diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 2096ed75f..7005bd738 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,6 +1,9 @@ Claimed in the coordination issue as: +Depends on: + ### What and why @@ -10,6 +13,8 @@ Claimed in the coordination issue as: +AI-assisted: + ### Checklist - [ ] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index abdc532eb..93065cd21 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -77,13 +77,19 @@ jobs: - name: Tests (standard library only, no game data) shell: bash run: | + # Run every file, then fail: stopping at the first failure would hide the files after it. + failed=() while IFS= read -r t; do if grep -Eq "$PYTEST_FILE_MARKERS" "$t" || ! grep -q '__main__' "$t"; then continue fi echo "== $t" - python -I "$t" || exit 1 + python -I "$t" || failed+=("$t") done < <(find tests -path 'tests/semantic' -prune -o -type f -name 'test_*.py' -print | LC_ALL=C sort) # pytest-based files run in the translator-tests job + if (( ${#failed[@]} )); then + for t in "${failed[@]}"; do echo "::error file=$t::$t failed"; done + exit 1 + fi - name: Build rpf9dump run: dotnet build tools/rpf9dump/rpf9dump.csproj -c Release - name: Test TTPF export retry diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 9ecc77a71..b5bb43f9d 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -3,11 +3,13 @@ name: Runtime on: - # What can break this build: the runtime and its vendored queue, the scripts the jobs run, this workflow, and - # everything the tools those scripts read depend on - their sibling imports, the data files they load by name - # (gfx10_formats.json is one a .py-only scan misses) and the hw_oracle directory. Any other file under tools/ - # used to start a full Windows and Wine build it cannot break (BUILD-856); paths-ignore cannot say "everything - # under tools/ except these", so the event lists what triggers it. + # What can break this build: the runtime and its vendored queue, the scripts the jobs run, this workflow, the + # line endings every checkout gets (.gitattributes), and everything the tools those scripts read depend on - + # their sibling imports, the data files they load by name (gfx10_formats.json is one a .py-only scan misses) and + # the hw_oracle directory. Any other file under tools/ used to start a full Windows and Wine build it cannot break + # (BUILD-856); paths-ignore cannot say "everything under tools/ except these", so the event lists what triggers + # it. tests/test_runtime_paths.py recomputes the tools/ part and fails when an entry is missing; keep the two + # lists identical. push: branches: [main] paths: @@ -15,6 +17,7 @@ on: - "third_party/**" - "scripts/**" - ".github/workflows/runtime.yml" + - ".gitattributes" - "tools/hw_oracle/**" - "tools/bary_fallback_gs.py" - "tools/cf_diff.py" @@ -32,6 +35,7 @@ on: - "tools/mc_command.py" - "tools/mesh_compute_vs.py" - "tools/rdna2spirv.py" + - "tools/report_paths.py" - "tools/shader_carve.py" - "tools/shader_disasm.py" - "tools/shader_ir.py" @@ -39,8 +43,10 @@ on: - "tools/shader_stage_manifest.py" - "tools/spirv_asm.py" - "tools/spirv_asm_tables.py" + - "tools/spirv_opt.py" - "tools/spirv_stubs.py" - "tools/vk_subgroup_info.py" + - "tools/wave64_emulate_opt.py" - "tools/wave64_halves.py" - "tools/xdxr_bvh.py" pull_request: @@ -49,6 +55,7 @@ on: - "third_party/**" - "scripts/**" - ".github/workflows/runtime.yml" + - ".gitattributes" - "tools/hw_oracle/**" - "tools/bary_fallback_gs.py" - "tools/cf_diff.py" @@ -66,6 +73,7 @@ on: - "tools/mc_command.py" - "tools/mesh_compute_vs.py" - "tools/rdna2spirv.py" + - "tools/report_paths.py" - "tools/shader_carve.py" - "tools/shader_disasm.py" - "tools/shader_ir.py" @@ -73,8 +81,10 @@ on: - "tools/shader_stage_manifest.py" - "tools/spirv_asm.py" - "tools/spirv_asm_tables.py" + - "tools/spirv_opt.py" - "tools/spirv_stubs.py" - "tools/vk_subgroup_info.py" + - "tools/wave64_emulate_opt.py" - "tools/wave64_halves.py" - "tools/xdxr_bvh.py" workflow_dispatch: diff --git a/README.md b/README.md index 7a085a59c..b9bc28ae0 100644 --- a/README.md +++ b/README.md @@ -53,11 +53,15 @@ work on booting can start as soon as one is available to a developer. | Shader translator checked on a real GPU | ⚠️ The hand-written GPU tests (vertex fetch, texture sampling, exports, ALU ops, partial-register ops, barycentrics, wave-uniform branches, compute LDS/barriers/buffer stores, wave64 masks) have been run on more than 30 GPU and driver combinations, with results in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): NVIDIA Turing, Ampere, Ada and Blackwell (Windows and Linux); AMD GCN3, RDNA1, RDNA2, RDNA3 and RDNA4 (Windows driver and RADV); Intel Gen9 (ANV); Apple M1 (MoltenVK, no geometry or mesh stages); and Mesa llvmpipe. Wave64 tests need 64-wide subgroups (AMD) or `LEONIDA_W64_EMULATE=1`. These are small test shaders: the game's own shaders are checked by `spirv-val` and by driver pipeline creation (`vk_pipeline_check`), not by their output | | Models (OBJ with real names, UVs, material references) | ✅ Exported. A ten-archive scan at decoder pin `e293917` recovered **382,781 models** with zero readback decode failures. This includes **343,327** models from `levels.rpf`. A full OBJ export of that archive is pending. See [recount and export scope](docs/models.md#full-archive-re-count-at-e293917). | | Texture dictionaries and world texture pools (DDS) | ✅ Exported. Pool entries stored as BCPack are still skipped by the export; a clean-room decoder (`tools/bcpack.py`) rebuilds BC1, BC3, BC4, BC5, BC6H and BC7 (most BC6H/BC7 chunks need a local history table, which the repo does not ship), and is not wired into `rpf9dump` yet ([notes](docs/textures.md)) | +| Models (OBJ with real names, UVs, material references) | ✅ Exported. Not all layouts are decoded yet | +| Texture dictionaries and world texture pools (DDS) | ✅ Exported. `rpf9dump` decodes BCPack BC1, BC3, BC4 and BC5 chunks in strict mode and skips BC6H, BC7 and chunks that need unconfirmed history; the assets stage then completes what it can with a clean-room decoder (`tools/bcpack.py`, run by `tools/ttpf_assets.py`) that rebuilds BC1, BC3, BC4, BC5, BC6H and BC7, and marks the rest as limited in `manifest.json` (most BC6H/BC7 chunks and the unconfirmed-history ones need a local history table, which the repo does not ship) ([notes](docs/textures.md)) | | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | | PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Controllers through a GameInput shim on SDL3 (any controller SDL supports, rumble, DualSense trigger effects and lightbar; built when SDL3 is installed or with `-DLEONIDA_SDL3_FETCH=ON`, [notes](docs/gameinput.md)). `--trace-d3d12` logs every D3D12 call and its outcome for the first boot. Untested against the real executable | | Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed, placed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube, 1D and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5, buffer SRVs — raw, structured and typed; they go into the bindless set), root signatures, pipelines and query heaps, and draws run on Vulkan. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. The console-shaped command-list proxy, the measured `PresentX` queue slots (30/32, layout-detected) wired to the presentation core, and `AllocateUploadMemory` (list slot 148, a mapped-upload arena whose addresses translate to buffer device addresses in root descriptors and IA/SO views) cover the console-ABI surface the package measures. Still open: the console list tail and the descriptor-table record model ([plan](docs/d3d12_vulkan.md), [console ABI](docs/d3d12_xs_console_abi.md)) | | Ray tracing (BVH) | ⚠️ In progress. `BuildRaytracingAccelerationStructure` builds BLASes and TLASes on the GPU in the console's XDXR BVH4 layout (the default; `LEONIDA_RT_AS=khr` uses Vulkan's own acceleration structures instead), which the translated shaders walk themselves through `image_bvh_intersect_ray` (all four triangle node types, TRI0-TRI3, with the barycentric remap byte); the GPU builder writes TRI0 leaves. Updates refit instead of rebuilding, and clone, compaction and the compacted/current postbuild sizes work; checked against a CPU reference on synthetic scenes. The build descriptions are recovered from the package's `XboxBvhBuilder.dll` ([notes](docs/xdxr.md)). The game's `*_bvh4.rpf` packs are measured: offline-built, dehydrated BLASes that rehydrate through that DLL with their geometry from the drawables in `levels.rpf` (measured on 8 of the 10 sampled BLAS; [notes](docs/bvh.md)). Not done in the builder: TRI1 pairing, BOX16 nodes, serialization. Open: whether the game rehydrates the packs or rebuilds them ([#313](https://github.com/ItsNotRexed/Leonida/issues/313)) | +| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists and bundles, fences, descriptor heaps, committed, placed and reserved resources (1D, 2D, 3D and cube textures), render-target and depth views, texture views, buffer UAVs and samplers (they go into the bindless set), root signatures, graphics (vertex, pixel, geometry) and compute pipelines, pipeline libraries, command signatures and query heaps. Draws (MSAA included), dispatches and indirect dispatches, barriers, clears, uploads, copies (BC included), colour and depth resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, as do DXGI swapchains and `PresentX` planes. Tested by contributors on NVIDIA, AMD and Intel GPUs ([#166](https://github.com/ItsNotRexed/Leonida/issues/166)). Not yet: mesh-shader draws, the draw state of indirect draws, stream output, and anything checked against the real executable ([plan](docs/d3d12_vulkan.md)) | +| Ray tracing (BVH) | ⚠️ In progress. `BuildRaytracingAccelerationStructure` builds BLASes and TLASes on the GPU in the console's XDXR BVH4 layout, which the translated shaders walk themselves (`image_bvh_intersect_ray`, TRI0/TRI1 leaves); `LEONIDA_RT_AS=khr` uses Vulkan's own acceleration structures instead. The build descriptions are recovered from the package's `XboxBvhBuilder.dll` ([notes](docs/xdxr.md)). The game's `*_bvh4.rpf` packs are measured: offline-built, dehydrated BLASes that rehydrate through that DLL with their geometry from the drawables in `levels.rpf` (measured on 8 of the 10 sampled BLAS; [notes](docs/bvh.md)). Not done in the builder: TRI1 pairing, BOX16 nodes, serialization. Open: whether the game rehydrates the packs or rebuilds them, and the XDXR-vs-KHR default ([#313](https://github.com/ItsNotRexed/Leonida/issues/313)) | The table above is written by hand. To measure it on your own checkout (unit and runtime tests, which rows of the translator contract were confirmed on a GPU, measured imports, your corpus counts and, with `--github`, CI diff --git a/docs/README.md b/docs/README.md index 39cd3da3f..674f5eeaa 100644 --- a/docs/README.md +++ b/docs/README.md @@ -71,15 +71,21 @@ method, scope and caveats. No game data is included. | [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | | [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | | [pipeline_check.md](pipeline_check.md) | Driver-level corpus check: 10/12 shards, 22,092 modules, 2,217 compute pipelines, 0 failures. | +| [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. | | [shader_validation.md](shader_validation.md) | Differential CPU/GPU validation design and the current CPU interpreter prototype. | | [isa_coverage.md](isa_coverage.md) | RDNA2 ISA coverage of the translator against AMD's machine-readable XML: which of its 1,153 instructions have a rule, and which matched names are not RDNA2. | | [buffer_bounds.md](buffer_bounds.md) | V# `OOB_SELECT` bounds measured natively: RDNA2 (gfx1036) follows Mesa's GFX11 column (729/732 cases), not GFX10; raw mode also counts `soffset`. | | [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. | | [fspx.md](fspx.md) | `FSPX`, the FidelityFX DLL's native compute programs (its shaders' `ACCC` part): directory as the DLL reads it, kind-0 dispatch state, the hash prologue, `gfx1030` for its `v_dot4` code; 13 of 29 translate with `tools/fspx_unpack.py`. | | [first_light.md](first_light.md) | The first draw of a real game model with its own translated VS/PS on a GPU: 4,213 vertices / 7,968 triangles, 78.1% coverage on an RTX 2060 SUPER; `tools/first_light.py`, the `vk_harness` mesh mode, and the same draw through the D3D12 layer (`d3d12_first_light`). | +| [material_pass_replay.md](material_pass_replay.md) | How one authored mesh writes packed draw indices, how six compute programs read the layout, and which sibling passes read the surface material. | | [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool and the one rule still missing. | | [shader_inputs.md](shader_inputs.md) | Inputs that specific game shaders need to be right, as a first check for a black frame or a device-lost: the studio-shot lighting shader's 512-byte light records, eight-light loop, plane count at +0x4C (#1892 said +0x40), profile table and shadow-strength byte; the ACES LUT bakes' two tone-curve splines (reference order at +0x00, points-first at +0x70 behind the +0x118 switch), the +0x13C luminance mode and the quasi-log addressing (#1896); the sky LUT order and the +0xD0 dword that picks RGB9E5 or float outputs (#1897). | +<<<<<<< HEAD | [hello_pixels.md](hello_pixels.md) | The package-free sibling: a synthetic quad drawn through the same `vk_harness` mesh mode, shaders hand-written in SPIR-V assembly; `tools/hello_pixels.py` checks coverage and probe pixels against a closed form. | +======= +| [sandbox.md](sandbox.md) | Placed world props through one translated VS/PS pair with a real camera, TTPF albedo and the game's sampler: 442 of 446 draws textured; fly/walk/drive window, `tools/sandbox.py --check`. | +>>>>>>> origin/main | [coder.md](coder.md) | The compressed mass in `story000_script.rpf`: entry framing (`align16(entry+8)` payload), the 32-value tag alphabet, deflate-shaped but proprietary, variable-length 7/8-bit LSB-first codes with no stored table, and the `n7 = 116..127` search that finishes it. | | [mission_logic.md](mission_logic.md) | Mission state tables: 0x20 record layout (band counter, byte offsets), the 64-byte pool element with world transforms, case-folding joaat keys, 53.5 % of states named, 113 state-set clusters covering 82.4 % of files. | | [gbuffer.md](gbuffer.md) | Deferred G-buffer targets (`PS_DeferredTextured` and all 2,989 `*Deferred*` pixel shaders, `PROC-146`): 5- and 6-target `OSG1`/`PSV0` signatures (`float32` + `exp ... compr` on all outputs), the 24-bit octahedral normal split across `mrt1.gba` (`2047.5` scale, `1/255` byte packing), sqrt-encoded `mrt2`, byte IDs in `mrt3.zw`, float motion in `mrt4`, and why binding `f16` targets mangles the normal bytes. | diff --git a/docs/animation.md b/docs/animation.md index 75e4b8648..018a6e6b3 100644 --- a/docs/animation.md +++ b/docs/animation.md @@ -149,6 +149,12 @@ The `SKEL__` shape is the conventional RAGE bone naming. The anima to the bones, but a skeleton carries its own names (`joaat32` at bone record `+0x1C`, name at `+0x30`, [character_skeleton.md](character_skeleton.md)), so the match is measured: see [Bone tables and motion matchers](#bone-tables-and-motion-matchers). +The `SKEL__` shape is the conventional RAGE bone naming. Measured across all `SKEL_*` streams in +`anim.rpf` (`177` streams, `118` distinct `SKEL_*` tokens) against the decoded skeleton name tables in +`packs.rpf` (`2,866` `SKEL_`-bearing streams, `691` distinct `SKEL_*` tokens) using `tools/anim_skeleton_match.py`: +`117` of `118` (`99.2%`) match by exact case and all `118` of `118` (`100%`) match case-insensitively (and by +lowercased `joaat32`, since `SKEL_HEAD` corresponds to `SKEL_Head`); `166` of `177` streams match all of their +tokens by exact case. The animation pages still carry no model name next to the bones. ### Type-hash containers @@ -622,8 +628,15 @@ fields are in the object table above. Measured on all 17,247 `.motion` clips: `.clip` in anim.rpf, the first float is bit-for-bit that `.clip`'s duration (`+0x78`): 111,948 of 111,948. - **Parameter node.** When `+0x58` is 1 the node is at `+0x138`; when it is 2, `+0x120` points at a block whose `+0x18` is the node. Every `.motion` has one, and it starts `{u64 0, u32 type, u32 0}`. By type: 3 on 10,171, 1 on - 3,557, 4 on 2,644, 5 on 482, 6 on 295, 8 on 98. Only type 3 is decoded here. -- **Type 3: one sampled axis.** It has one u32 name hash, then 1–16 `{u32 sample index, f32 value}` items and the + 3,557, 4 on 2,644, 5 on 482, 6 on 295, 8 on 98. +- **Axes by type.** Types 3, 4, 5, 6 and 8 have 1, 2, 3, 4 and 5 axes: `+0x10` is a `{ptr, count}` array of 8-byte + `{u32 name hash, u16, u16}` entries, with that count on every node of each type (the two u16 are not decoded). + Type 1 has no axis array and a sample count at `+0x20`: 1 on 3,552, 2 on 5. Types 4, 5, 6 and 8 keep their + sample count at `+0x90`, `+0x90`, `+0x50` and `+0xA0`: on all 2,281 of them that are a `.motion`'s only node, it + equals the number of `+0x90` sample lists below. The word list resolves 1,135 of their 8,404 axis names, the same + names as type 3 (`verticalheight`, `yawangle`, `surfaceincline` the most); `anim_clips.py` counts them as + `motion_node_axis_name::`. +- **Type 3: one sampled axis.** It has one axis entry, then 1–16 `{u32 sample index, f32 value}` items and the axis min and max. On all 10,171 (29,123 samples), the items are sorted by value, min and max are the first and last values, and the sample indices are 0..n−1 in some order. They are not child indices: the sample count equals the child count on 4,589 of them. The name hashes are `joaat32` of a lower-case name. 88 distinct hashes @@ -631,8 +644,21 @@ fields are in the object table above. Measured on all 17,247 `.motion` clips: `facingdirection` 638, `speed` 284, `surfaceincline` 271, `roll` 66, `verticalheight` 58, `pitch` 25, `pitchangle` 25, `height` 22. The ranges fit the names: `speed` is within [0, 1], `surfaceincline` within ±0.698 rad (40°), and `roll` within ±3.14. `anim_clips.py` reports every name as `motion_axis_name:`. -- Not decoded: parameter node types other than 3, how a type-3 sample index maps to the children, and the rest of - the object from `+0x80`, including the `{ptr, count}` lists at `+0x90`. +- **Samples to children (`+0x90`).** A `{ptr, count}` array of one `{ptr, count}` list per sample of the parameter + node; a list item is 12 bytes, `{u32 child index, f32, f32}`. On all 8,932 `.motion`s whose only node is at + `+0x138` (`+0x58` 1), the number of lists equals the node's sample count, every child index is below the child + count, and every child is played by at least one sample. So sample index k plays the child in list k: the type-3 + sample index is not a child index, it goes through this list. 8,903 have one item in every list; the other 29 + (types 5, 6 and 8) have lists of several children. On the 6,970 where the sample count equals the child count, + list k names child k; on the other 1,962 there are more samples than children and some children are played by + several samples. The first float is 1.0 on every item of types 1, 3 and 4 (36,830) and on all but 576 of the + 57,043 items of types 5, 6 and 8; the second is 1.0 on 76,604 of the 93,873 items. Neither is decoded. By type + (one-node motions, samples equal to children / more): 1: 1,176 / 0, 3: 4,545 / 930, 4: 1,009 / 479, 5: 154 / + 271, 6: 44 / 226, 8: 42 / 56. `anim_clips.py` counts these as `motion_samples::*`. +- Not decoded: where types 4, 5, 6 and 8 place their samples in parameter space (no array of theirs has one entry + per sample; most have a pointer at `+0x30`), the two u16 of an axis entry and the two floats of a sample item, how a + `.motion` with `+0x58` 2 (a block array at `+0x120` with several nodes) shares the `+0x90` lists among its + nodes, and the rest of the object from `+0x80`. The 180 `.motionmatcher` clips sit in 142 dictionaries that hold only `.motionmatcher` clips and no local pack. The three motion matcher streams in [Bone tables and motion matchers](#bone-tables-and-motion-matchers) @@ -716,7 +742,7 @@ or skeleton each non-humanoid clip dictionary drives remains open. ### Can the fragment bone names identify a clip's model? (ASSET-158) -Bone coverage alone identified **zero unique fragments** for the 8,393 dictionaries below the 90% humanoid +In the ASSET-158 scan, bone coverage identified **zero unique fragments** for the 8,393 dictionaries below the 90% humanoid threshold above. This comparison used the named fragment tables recovered from `packs.rpf` in Xbox 1.0.2.1. The threshold selects dictionaries for investigation; some may still animate humanoids. @@ -749,7 +775,7 @@ To reproduce the comparison: ### Explicit model-to-dictionary references in `levels.rpf` -The archetype metadata gives a direct association for **1,324 model asset names and 159 clip dictionaries** +The ASSET-158 scan of archetype metadata linked **1,324 model asset names and 159 clip dictionaries** in Xbox 1.0.2.1. Of those dictionaries, **63** carry local rotation or translation tracks below the humanoid coverage threshold. Their archetypes name **488 distinct model assets**. This identifies which dictionaries the archetypes reference; the per-bone mapping onto each model's skeleton still needs independent evidence. @@ -763,10 +789,10 @@ the archetypes reference; the per-bone mapping onto each model's skeleton still 2. Search **the same archive** for clip dictionary roots. At each 16-byte-aligned zlib stream start, check `anim_clips.is_root` and the dictionary hash at `+0x68` against those references. Join consecutive system pages as needed to parse the dictionary. Require a nonempty clip map and a name at `+0x38` - whose lowercase joaat equals the stored hash. This confirms 159 of the 161 referenced hashes. + whose lowercase joaat equals the stored hash. The scan confirmed 159 of the 161 referenced hashes. A direct hash comparison against the 52,752 bone-bearing dictionaries in `anim.rpf` found zero matches. Applying the same root and clip-map checks to the other 21 RPF archives (85,152,072,416 bytes) - yielded no additional matches. The two unresolved references appear in 43 and 64 archetype records, + yielded no additional matches. The two references unresolved by that scan appeared in 43 and 64 archetype records, covering two and 16 distinct asset names respectively. This search covers readable dictionary roots at aligned zlib stream starts. Other storage layouts remain possible. 3. Deduplicate the resulting `(assetName, clipDictionary)` pairs. Of the 159 confirmed dictionaries, diff --git a/docs/audio.md b/docs/audio.md index 3081cee98..e4141a706 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -59,7 +59,7 @@ is skipped. | Tag | Meaning | |---|---| -| `0x5a` | 20-byte-entry grid table (`12345678` marker; see [rsc8_audio.md](rsc8_audio.md#the-undocumented-0x5a0xd9-companion-tags)) | +| `0x5a` | 20-byte entries, a sample position and a pitch each (`12345678` marker; see [rsc8_audio.md](rsc8_audio.md#the-undocumented-0x5a0xd9-companion-tags)) | | `0xd9` | grouped ascending index runs into the sibling `0x5a` entries | Both appear only in `audio.rpf`, on 1,185 streams (32,000 Hz; 804 of them carry both). @@ -215,9 +215,26 @@ layout and the station-content references. The credited "Burn This Shit Down" is not a radio-station track. It is the song for the **Home Sweet Home** mission (Chapter 1, mission 21/25): Lucia at Jason's house in Key Lento during the house fire and the escape. The mission and its localized objective/fail strings are -present in `data.rpf`; the song audio is not. +present in `data.rpf`. -Measured coverage on the Xbox Series 1.0.2.1 package: +The song audio is in 1.0.2.1 too, as stems, not as one stream (found by @jefftern4 in the coordination thread, +PROC-178). It is the plain (not streamed) `audio.rpf` bank at offset `0x300695000`, 9,481,280 bytes, bank 5,573 of +7,162 in the exporter's `audio_manifest.json` order: + +| Field | Value | +|---|---| +| Streams | 73, all stereo, all codec `0x0B` (Opus, 48 kHz) | +| Common length | 47 streams declare 771,213 samples (16.067 s); the manifest's rounded `DurationSeconds` gives 771,213 for 32 of them and 771,214 for 15 | +| Other lengths | 6 × 1,156,820, 2 × 2,313,640 and 2 × 385,607 samples (1.5, 3 and 0.5 times the loop), and one 24,100-sample stream | +| Range | 0.439 s to 114.477 s, 1,297.2 s in total | + +The 47 equal-length streams are loop stems meant to play together (vocals, melodic, sub-bass and ad-lib layers per +slot, by the finder's listening), so no single stream is the song and a whole-file fingerprint of each stream +misses it. That is why the searches below came back empty. The bank's shape (field values above) was re-measured +from `audio_manifest.json` on a second 1.0.2.1 copy; the stem roles are the finder's and were not re-checked here. + +Measured coverage of the earlier search, which looked for the song as one stream. The `audio.rpf` all-banks row +is the one the stems fall under: | Container | Searched | Result | |---|---|---| @@ -226,7 +243,7 @@ Measured coverage on the Xbox Series 1.0.2.1 package: | `story000.rpf` Bink | 264 streams / 162 with audio / 165 tracks / 5,090 s | none | | `movies.rpf` Bink | 229 tracks / 12,401 s | none | | `audio.rpf` streamed cues under 30 s | 1,149 channels / 5.78 h | none | -| `audio.rpf` all banks | 7,162 banks, all streams | none | +| `audio.rpf` all banks | 7,162 banks, all streams | none as a single stream; the stems are bank `0x300695000` (above) | | loop/chunked banks | 1,099 banks / 118,180 streams | none | | `packs.rpf` inflated | 144,364 files / 9.74 GB | 0 AWC, 0 Bink2 | | `data.rpf` inflated | 28,509 files / 1.41 GB | mission text, 0 song strings | @@ -242,11 +259,21 @@ A `data.rpf` hash table contains 12 occurrences of `joaat("burn")`, but it is no config blob has none, no AWC stream ID matches its low 29 bits, and the table has no audio reference. -Residual uncertainty: `levels.rpf` (76 GB) was not fully inflated, and a custom RSC8 audio -resource is the only mission-side container not decoded; the retail track may be a third master -or patch content not covered by the public references; sub-30 s stings were not exhaustively +Residual uncertainty: `levels.rpf` (76 GB) was not fully inflated; the retail track may be a third +master or patch content not covered by the public references; sub-30 s stings were not exhaustively fingerprinted. No game audio is stored in the repository; the searches ran on a local copy and `radio-dump-v3` was not modified. +Residual uncertainty: how the game sequences the stems (which layers play in which slot, and the +order of the longer streams) is not decoded; the mission's audio config is the likely place (a +hypothesis, not measured). No game audio is stored in the repository; the searches ran on a local +copy and `radio-dump-v3` was not modified. + +This search first listed the `RSC8` resources of the story and minigame archives as the only +mission-side container not decoded. They are decoded in [rsc8_audio.md](rsc8_audio.md), and none of +them holds the song: all 641,428 raw `RSC8` headers in the package (225,281 in `story000.rpf`, 1,957 +in `shared_minigame000.rpf`, 9 in `story000_restofworld.rpf` and 414,181 in `audio.rpf`) are AWC tag +`0x5c` facial/lip-sync clips. Each sits in an `ADAT` bank next to the 48 kHz mono Opus dialogue line +it animates, none lies outside a bank, and none contains an `ADAT`, Ogg Opus or RIFF WAVE header. ## Stream names diff --git a/docs/buffer_bounds.md b/docs/buffer_bounds.md index 033e8c3e3..9326fe517 100644 --- a/docs/buffer_bounds.md +++ b/docs/buffer_bounds.md @@ -29,9 +29,20 @@ measured natively on AMD GPUs (SHADER-116). The translator reads this field and ([finding](https://github.com/ItsNotRexed/Leonida/issues/374#issuecomment-7072793165)). The RDNA2 result here agrees with it, plus the `soffset` rule. -**Open:** the console target is gfx1013 (GFX10.1); gfx1036 is GFX10.3. Mesa uses one GFX10 column for both, and -this measurement shows that column is wrong for GFX10.3. Whether GFX10.1 matches GFX10.3 here needs an RDNA1 card -(gfx1010–1012, RX 5000 series). +**RDNA1 measurement (SHADER-341):** the console target is gfx1013 (GFX10.1); gfx1036 is GFX10.3, and the +RDNA2 measurement above shows Mesa's GFX10 column is wrong for GFX10.3. A second native measurement through +`tools/hw_oracle` (Linux libdrm launcher, AMD clang 18) on an **AMD Radeon Pro V540, Navi 12 / gfx1011, RDNA1** +(`1002:7360`, bare metal, RADV Mesa 25.2.8, Ubuntu 24.04) found the same: `tools/buffer_bounds_probe.py` ran 12 +one-lane cases for a 4-byte `buffer_load_dword` at wave32 and wave64 (24 groups, 0 wave32/64 differences, 0 +launcher errors). Every case followed the RDNA2 / Mesa GFX11 column and **8 of 24 disagreed with Mesa's GFX10 +column**. The witnesses include mode 0 stride 16 at offset 13 (out of range on hardware, in range by the GFX10 +column), mode 3 `NUM_RECORDS` 18 at offset 16 (out of range), mode 3 `NUM_RECORDS` 3 at offset 0 (out of range), +and mode 3 offset 8 with `soffset` 8 and `NUM_RECORDS` 18 (out of range, confirming that `soffset` is part of the +RAW check). Swizzled V#s and unaligned addresses were not covered. This makes GFX10.1 follow GFX10.3 here in the +cases tried, but gfx1013 itself is still unmeasured: the card used was gfx1011 (Navi 12), not the console part. + +**Open:** measure the same table on gfx1013 (PS5) itself when a card with that ID is available, and extend the +probe to swizzled V#s and unaligned accesses. ## How it was measured diff --git a/docs/character_models.md b/docs/character_models.md index 9d030a7c8..adfb161da 100644 --- a/docs/character_models.md +++ b/docs/character_models.md @@ -248,13 +248,26 @@ silhouette is geometry, not a painted-on atlas. ## What is not decoded -- **Fragment children.** A raw child-array walk covers all 2,865 `packs.rpf` fragments: every one - has a single drawable and the flat 25-vertex / 32-triangle bounds grid, with **no child arrays**. - The four `gmt_mannequin*` fragments have no child arrays either; `ambient_femalebody` is a - 596-bone skeleton plus the same grid, with no skin mesh. The path is alive on world fragments +- **Fragment children.** A raw child-array walk (`tools/fragment_children.py`) covers every fragment + of `packs.rpf` and `levels.rpf`. The fragment header's u16 at `+0x30` is the number of drawables; + the records are 0x110 bytes apart, starting at the main drawable that `+0x18` points at, so + records 1 and up are the child drawables. All 2,865 `packs.rpf` fragments have a single drawable + and the flat 25-vertex / 32-triangle bounds grid, with **no child arrays**. The four + `gmt_mannequin*` fragments have no child arrays either; `ambient_femalebody` is a 596-bone + skeleton plus the same grid, with no skin mesh. The path is alive on world fragments (`bus2_frag_hi`: 14 model structs, 11 children, a 650 KB `model_parts.glb`), so the negative is - a property of the character files. The remaining 50,798 `levels.rpf` fragments are covered by - the main-drawable census but were not raw-walked for child arrays; that is the one bounded gap. + a property of the character files; those figures come from a different walk and were not + re-derived by this one. In `levels.rpf` the walk finds **50,802 fragments** (the exporter's + manifest counts 50,798): 50,068 have a single drawable and **734 have a child array**, 733 of + one child and 1 of two, **735 child drawables** in all. Every declared child record passes the + drawable-body test, and a scan of all other 16-byte offsets of those fragments' system pages + finds 0 further drawables. 10,097 of the 50,802 have a null `+0x10`, `+0x20` or `+0x28`, and 6 + have a main drawable that fails the embedded-drawable header test. For comparison `data.rpf` has + 1,758 fragments, all single-drawable. The other header counts are unrelated to children: the + `+0x28` array of 0x50-byte part records (the u16 at `+0x34`) has 153,028 records over + `levels.rpf` (13,871 fragments with more than one) and 27,778 over `packs.rpf` (2,605). The gap + is closed: every fragment in both archives was walked, and the only ones with child drawables + are 734 of the `levels.rpf` ones. - **A ped-variation table.** `common.rpf` contains `CPedVariationBodyTypeManager` (`0x226000`) and `CPedComponentSetManager` (`0x228000`), but neither maps a component variation index to a drawable plus texture. The first is height and body-shape presets @@ -289,8 +302,13 @@ silhouette is geometry, not a painted-on atlas. ```powershell rpf9dump models +python -I tools/fragment_children.py \levels.rpf --jobs 12 --json \levels_fragments.json ``` +The second command prints the fragment and child-drawable totals quoted under "Fragment children"; it +reads the archive in place (about 22 minutes for `levels.rpf` with 12 workers over a WSL mount of +the dump) and writes nothing else. + ```python import json diff --git a/docs/character_skeleton.md b/docs/character_skeleton.md index 7c8123cc0..18fede113 100644 --- a/docs/character_skeleton.md +++ b/docs/character_skeleton.md @@ -234,6 +234,11 @@ python -I tools/anim_glb.py \packs.rpf --coverage --skeleton \game_scarlett_master.exe --sites` (a few - minutes; it streams `dumpbin /disasm`). "UNCHECKED 0" means every inline write checks the cursor limit, so a - layer that keeps the cursor at the limit receives every command through the vtable; any unchecked site is a - write that layer never sees. The package's DLLs check at every site + minutes; it streams `dumpbin /disasm`; it exits 2 when it reads no instructions). "UNCHECKED 0" means every + inline write checks the cursor limit, so a layer that keeps the cursor at the limit receives every command + through the vtable; any unchecked site is a write that layer never sees. The package's DLLs check at every site ([d3d12_command_objects.md](d3d12_command_objects.md), "Every inline write in the package's DLLs checks first"). +4. **GDK runtime classes.** The exe imports no GDK function by name; `.gdk_calls.txt` lists the runtime classes + and vtable slots it calls through `xgameruntime.lib`'s thunks, and the classes `runtime/shims/xgameruntime.cpp` + doesn't serve yet ([runtime_imports.md](runtime_imports.md#measuring-which-runtime-classes-a-binary-calls)). Then `runtime\build\gta6rt.exe --dry-run ` maps the image and binds every import to the shim table without running any game code. It reports what it couldn't bind. @@ -122,7 +125,7 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b | Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**; the other archives measure **4,686 fragments**, **30,343 bone-bound**, **126,301,454 triangles** and 512 embedded textures, while the `levels.rpf` fragments/bone-bound/triangles/embedded cells are **not independently reproduced** (**†**) (no `levels.rpf` manifest; the count harness emits no such fields); 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,251 at `917e9b9` (159,486 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,530 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | | Texture dictionaries | Same tool: TXD resources become DDS per texture. | `\assets\\textures\` | | World textures (TTPF) | **Done (all 57 pools, 357,115 catalog entries, 0 failures):** the original exporter baseline exported **308,895** (98,603 complete, 210,292 partial) and skipped **48,220** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts (305,264 complete, 1,100,865 mips, 4.59 GiB), the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)), and DXGI 11 resolves the last 5 format skips, bringing the measured zlib/raw split to **305,959 complete, 16,423 partial, and 34,733 skipped** (0 remaining layout/format skips; all 34,733 are BCPack). Clean-room `tools/bcpack.py` decodes all six active BCPack modes (BC1, BC3, BC4, BC5, BC6H, BC7), giving a `tools/ttpf_mips.py scan` codec-availability projection of **357,115 complete / 0 partial / 0 skipped**; on full-corpus chunk decode with `--allow-provisional --history `, BC6H decodes 268 / 268 chunks (0 strict) and BC7 decodes 5,150 / 5,167 chunks (583 strict), while **17 / 5,167 BC7 chunks (0.33%)** still cleanly refuse in provisional mode. `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\\data\ttdb\**` (exported under `ttpf_pack\\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_`); models reference textures by asset key. Measured breakdowns and decode caveats are in [textures.md](textures.md). | `\assets\ttpf\\` + `manifest.json` | -| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `\anim-index\` | +| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). All 1,781 second pages labelled `clip-stream` begin at the parent `0DRP` auxiliary table (+0x40), with two or three tagged payloads followed by schema data. The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `\anim-index\` | | Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). `tools/awc_opus.py` repackages every Opus stream **losslessly** into a standard Ogg Opus file (no re-encode; PCM streams become .wav). The AWC framing is 2048-byte blocks of [u16 length][packet], with a zero length padding the block (as rpf9-explorer's OpusPreview reads it). The final granule is `pre-skip + declared samples`; the EOS page is emitted at the packet that reaches that target and later padding packets are dropped, so decoders stop at the declared end. Checked: 20 real streams at 48 and 32 kHz decode to exactly their declared counts; 300 random streams decode with ffmpeg with no errors. XMA2 streams (codec 5, 1,818) are written as RIFF XMA2 files by `rpf9dump xma` (rpf9-explorer's `AwcRecovery.WriteXmaWave`) and decoded to PCM WAV by ffmpeg: all 1,818 decode. Streamed music (tag 0x48: chunks with a per-channel record table, each channel's 2048-byte subblocks after the aligned header, and a repeated-prefix skip per chunk) becomes one Ogg Opus per descriptor channel (3,008 banks contain music). The Opus TOC stereo bit gives the packet channel count; a 1-channel descriptor can carry stereo packets, whose interleaved sample count is halved for the end granule. Checked: a 4-channel bank gives four 42.0 s mono channels; 1-channel stereo banks export at the config duration. Output: `\assets\audio\ogg\\.ogg`. **Done: 1,598,051 Opus streams + 3,116 music channels as Ogg Opus (22 GB), 19 PCM16 and 227 codec-2 streams (32-bit float PCM, 4 bytes per sample; values can exceed ±1) as WAV, 1,818 XMA2 as WAV. Every audio stream is converted; all WAVs decode.** `make_game.py --wav` also decodes the Ogg Opus output to 16-bit PCM WAV with `tools/audio_wav.py` (ffmpeg required; existing WAVs are skipped on resume). | `\assets\audio\awc\` | | World placement | **Full census of `levels.rpf`:** 23,535 map resources / 1,670,442 entities; all maps/entities exact, 36/36 shards, 98.32% stream coverage. Map files occupy a continuous band from ~7.5 to ~62.9 GiB; the earlier 9,918 / 680,228 sample was a 55% lower bound. `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/per-entity id/per-archetype key/LOD fields; names and most archetypes are hash-only. Archetype and map names are lower-cased joaat, confirmed by a MurmurHash3 x64 low-64 key; see [world_names.md](world_names.md). | `tools\world_index.py`, `tools\world_census.py`, `tools\world_names.py`; [world.md](world.md), [world_census.md](world_census.md), [world_names.md](world_names.md) | | Navmeshes | `navmeshes.rpf`: 90,295 zlib streams (6,540,238,392 stored / 20,551,068,624 inflated), 97.5% readable; 9,603 `0DRP` pages and 27,644 `0x00010015` pages, no `NAVM`/`CNavMesh`/`NVMS` magic. `0DRP` is generic RPF paging, not a navmesh container. | `tools\navmesh_index.py`; [navmesh.md](navmesh.md) | @@ -132,7 +135,7 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b | PSIN | `script.rpf`: 671 streams start with `PSIN`, 670 complete; sections `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`. `data.rpf`: 2,281 streams, 1,045 complete after joining. `LSCH` (type schema: structs and members) and `LENM` (enums) are decoded on all 17,664 / 17,641 whole sections across every archive, names as case-sensitive joaat. The instance data before `LSCH` is a block table plus 16-byte-aligned blocks with 20-bit-block pointers; read from the `LRSC` root through the schema, it reaches 129,100,004 of 129,117,812 block bytes on 17,507 containers. `LSNS` is a block table of 16-byte records (5,217 sections, 0 layout errors); the records are uniformly random, match no tested name hash and may be encrypted, so they stay unread. No plaintext scripts or names. Hash-typed members name other resources (u32: lower-cased joaat; u64: MurmurHash3 x64 low 64 bits): 228,427 values in 5,355 of 18,404 containers resolve against `rpf9_names.py` names, 299 control hits. | `tools/psin_index.py`, `tools/psin_data.py`, `tools/psin_names.py`; [psin.md](psin.md) | | Audio config | `audio.rpf` first 19.5 MiB: 837 zlib streams / 54,143,493 inflated bytes. 1,589 music records, 1,589 distinct ids, exact milliseconds; `hash & 0x1fffffff` is the AWC stream id. 1,584/1,589 durations match the AWC manifest / 2; no per-track start offsets. | `tools/audio_config.py`; [audio_config.md](audio_config.md) | | Page directory | `0DRP`: fixed 0x60-byte header, version 122; `q38` at +0x38 gives 16-byte records `{u32 hash, u32 size, u64 0x50000000 + target}`. `data.rpf`: 15,768 pages / 60,880 records; targets tile with zero overlaps. Names still need the TOC. | `tools/page_index.py`; [page_directory.md](page_directory.md) | -| Story / minigame | `story000.rpf` (18.65 GiB) is mixed: 264 Bink 2 streams (3.33 GB), 225,281 raw `RSC8` headers (v8001), 442 nested RPF9 headers and zlib resource pages. `story000_script.rpf` is 2,309 PSIN streams (2,118 complete), not a named script container; `shared_minigame000` mixes pages, PSIN and XML. | `tools/story_index.py`; [story.md](story.md) | +| Story / minigame | `story000.rpf` (18.65 GiB) is mixed: 264 Bink 2 streams (3.33 GB), 225,281 raw `RSC8` headers (v8001, AWC tag `0x5c` facial/lip-sync clips in its `ADAT` banks, see [rsc8_audio.md](rsc8_audio.md)), 442 nested RPF9 headers and zlib resource pages. `story000_script.rpf` is 2,309 PSIN streams (2,118 complete), not a named script container; `shared_minigame000` mixes pages, PSIN and XML. | `tools/story_index.py`; [story.md](story.md) | | Rest-of-world / script | Six archives, 1.57 GB total: `core_restofworld` 1.21 GB (11 Bink 2 streams / 1.24 GB, 37 decoded models, 958 graphics pages, 6 PSIN), `story000_restofworld` 189 MB, `story000_script` 74 MB (2,309 PSIN, 2,118 complete), small `appdata0`/licences. No maps; no validated script container. | `tools/restofworld_index.py`; [restofworld.md](restofworld.md) | | Audio stations | Audio config `0x762160`: 19 station blocks of `{station hash, u32 boundary, ordered u32 content ids}`; the boundary is a byte offset, not a count. VCRR content ids `0x28F2-0x2941` map exactly to records `0xBD73-0xBDC2` (80/80); other clusters are context-dependent or shared. Title-keyed stream ids resolve 702/800 resolved titles exactly and 746/800 with case/punctuation/feature variants. No per-track start offsets. | [radio_stations.md](radio_stations.md) | | D3D12 command objects | Measured command queue / command list / fence / `PresentX` surface, split into verified exports and slots, prior-art claims, and open questions. Queue/list/fence creation and barriers are scoped; `PresentX` signature/slot and exact swapchain/plane parameters remain open until the executable is available. | [d3d12_command_objects.md](d3d12_command_objects.md) | @@ -216,9 +219,20 @@ target and dumps the floats. Test shaders are in `\gputest`. (r,g,r,g). That's fixed. - After the export fix, 2 of the 400 smoke-test shaders (`PS_ImposterShadow` variants) gave non-finite red values. The cause was round-to-nearest `pkrtz` overflowing to inf, fixed with exact RTZ. One variant is now fully finite. - The other still has 1 inf and 4 NaN in red, and RTZ can't create those from finite values, so they come from the - shader's own maths on the synthetic test inputs (hardware would pass them through too). That's consistent with - hardware, but unconfirmed without a reference. + The other was reported with 1 inf and 4 NaN in red, put down to the shader's own maths on the synthetic inputs. + **That doesn't reproduce, and the shader has no maths to produce it** (TEST-643): both variants are the same + nine-instruction body, whose red is `v_cvt_pkrtz_f16_f32` of v2 and 1.0. Both read only `SV_Position.z` (input + signature rw mask 4), so v2 is POS_Z_FLOAT, which the translator maps to `gl_FragCoord.z`; red is f16(depth), + finite for every rasterized fragment. Redrawn with `vk_harness` (64×64, a full-screen triangle with depth 0, 0.5 + and 1 at its vertices, synthetic values on locations 0–15) on an AMD RDNA2 iGPU (gfx1036, driver 32.0.21043) and + an RTX 5090: 4,096 of 4,096 pixels written, 0 inf and 0 NaN in red, red in [0.0059, 0.744], for both variants as + translated by `main` and by the initial commit's translator; all eight images are bit-identical. **Measured on + the hardware** with the pixel-shader oracle (#3061's `ps_oracle.py`, not on `main` yet; same iGPU, wave64): with a + template PS that reads only `FragCoord.z` and front facing, the driver enables PERSP_CENTER, POS_Z_FLOAT and + FRONT_FACE, so v0/v1 are the barycentrics, v2 the depth and v3 the facing, as the translator assumes. The raw + body (its export made uncompressed, so the packed words come back as they are) over the same draw gives 0 inf + and 0 NaN in 4,096 of 4,096 pixels; each red half is the round-toward-zero f16 of that pixel's v2 (4,096 of + 4,096, checked on the CPU), and the translated shaders' red equals it bit for bit on both GPUs. ### Translator status and runtime contract @@ -230,31 +244,36 @@ How the generated SPIR-V expects the runtime to work: | Piece | Contract | |---|---| +| Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | | Execution model | One invocation = one lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). | -| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | -| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. A pixel lane that was inactive at the last `exp ... vm` it executed is discarded, and on a path without one, a lane inactive at the end (EXEC is kept at the export only where a path can write it afterwards). **The `vm` rule is from the RDNA2 ISA reference guide (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used), not measured on hardware**; checked on the CPU by `tests/semantic/test_export_valid_mask.py`. VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately.; also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately. | -| `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1`, `orn2`, `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). **Not GPU-verified** for the seven new kinds. | +| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | +| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases). Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. A pixel lane that was inactive at the last `exp ... vm` it executed is discarded, and on a path without one, a lane inactive at the end (EXEC is kept at the export only where a path can write it afterwards). **The `vm` rule is from the RDNA2 ISA reference guide (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used), not measured on hardware**; checked on the CPU by `tests/semantic/test_export_valid_mask.py`. VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), **not yet GPU-verified**. Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately.; also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately. | +| `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1`, `orn2`, `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | | Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound sits at 16. Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | | Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | | Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). Both checks for clean listings and re-anchoring use the parsed operand count to apply this exception only to unused sources. A used source encoded as 0 reads `s0` and is never treated as inline zero. `tests/semantic/test_printed_encoding.py` checks used `SRC1`/`SRC2` and an unused field with synthetic listings. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. | | Printed encodings | A listing is LLVM's text for what it decoded, not the bytes it read, so the translator checks the two against each other: the re-anchoring above for listings with undecodable words, and, for every other listing whose header names its code range and whose blob sits next to it (`fssm/`, or `fspx/` for FSPX), each instruction's printed encoding against the bytes at its offset, with the same exceptions (`same_encoding`). A difference is `Unsupported`, naming the instruction, its offset and both byte strings, instead of a translation of the field as 0. The case that prompted it: llvm-mc's gfx1013 decoder (LLVM 21.1.8) drops the VOP3 `op_sel` bits (word 0, bits 14:11) of a 16-bit VOPC compare: `0a 08 a9 d4 01 05 02 00` disassembles as `v_cmp_lt_u16_e64 s10, v1, v2` and re-encodes with the bits cleared (its assembler rejects `op_sel` on VOPC for gfx1013 and gfx1030 alike). Counted over the 1.0.2.1 corpus: the 25,030 clean listings hold 30,335,381 instructions, and none differs from its bytes beyond those exceptions (754); the 166 16-bit VOPC compares (154 shaders, all `f16`) have `op_sel` clear. Hand-written listings, `run_gpu_tests.py`'s `code 0x0..0x0 (synthetic)` listings and a blob that doesn't hold the listing's code range (the tests' header-only FSSM) are not checked. `tests/semantic/test_printed_encoding.py` (a dropped VOPC `op_sel`, a later instruction, the SRC2 exception, and the unchecked cases). | | Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). | -| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** || M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected). **Not GPU-verified.** | -| Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 | 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88). Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** | +| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** \|\| M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected). **Not GPU-verified.** | +| Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88). Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** | | 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** | -| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. | -| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ | dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). | +| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). | +| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). | | 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | | Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | | Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | | Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | | Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by `tests/test_desc_cache.py` (`test_lookup_result_is_broadcast_before_use`). | +| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# runs only that format's decode: `Gen.decode_any_format` is a binary search over the codes in `FORMATS` (`OpSelectionMerge` with `DontFlatten`, plain conditional branches), and a code outside the table gives zeros. The element size is selected from the format alone, and the per-lane byte offset is added once. Confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. Regression test: `tests/semantic/test_format_decode_branch.py`. | | 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | | `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | | Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). | +| Depth-compare samples with implicit LOD (`image_sample_c`, `image_sample_c_b`, and the `_o` forms) | In a pixel shader `image_sample_c` is `OpImageSampleDrefImplicitLod` and `image_sample_c_b` adds `Bias` (the LOD comes from the quad derivatives; the sampler is the comparison sampler `image_sample_c_lz` already uses, and the result is one value, f32 bits or with `d16` an f16 in the low half). The address order after the optional texel-offset dword is **bias, z-compare, coordinates** (GFX10 MIMG: offset, bias, zcompare, derivatives, coordinates, LOD, clamp): `image_sample_c_b` read the compare first until this change, the one place that order was wrong, which `ps_sample_c_b` catches (a bias of 1.0 read as the reference compares false everywhere). Outside the pixel stage there are no derivatives: `image_sample_c` samples LOD 0 (like `image_sample`), `image_sample_c_b` is `Unsupported`. `_o` takes the offset as the other `_o` forms do (`Offset`, or with `--texel-offset-fallback` the coordinate shift and a `Grad` sample of the unshifted coordinate's derivatives, scaled by `2^bias` for `_c_b`). Refused still: `_cl`, `_c_d`, `_c_cd` and the gradient forms of the compare samples; `image_sample_c_l` is #2685. GPU tests: `ps_sample_c`, `ps_sample_c_b` (`vk_texture_test dref_c`, `dref_c_b`: the D32 8x8 depth texture of `ps_sample_c_lz`, all 4096 pixels exact for the f32 result and the d16 one); semantic: `tests/semantic/test_sample_c.py` and the forms in `tests/test_texel_offsets.py`. `vk_texture_test` now takes the GPU `LEONIDA_VK_DEVICE` names, as the other harnesses do (it ignored it before). | +| Min-LOD clamp forms (`image_sample_cl`, `_b_cl`, `_c_cl`, `_c_b_cl`, and the `_o` forms) | The clamp is the component after the coordinates (address order: offset, bias, z-compare, coordinates, clamp), and becomes the `MinLod` image operand of the implicit-LOD sample (`OpImageSampleImplicitLod` / `OpImageSampleDrefImplicitLod`, with `Bias` and `Offset` before it in mask order), the same as the `image_sample_d_cl` that already existed; the module declares `MinLod` (`shaderResourceMinLod`, the harnesses skip a device without it). Outside the pixel stage there are no derivatives and the LOD is 0, so the clamp raises it: explicit `Lod = max(0, clamp)` and no `MinLod`. Under `a16` the clamp is packed with the coordinates (its own f16, with a pad after it in the last VGPR), as for `_d_cl`. With `--texel-offset-fallback` the Grad sample takes `Grad\|MinLod`. A clamp on a form that has no `_cl` instruction (`_l`, `_lz`, `_c_lz`) stays `Unsupported`. GPU tests: `ps_texture_cl` and `ps_texture_b_cl` on `vk_texture_test --two-mip` (coordinates / 4 so the unclamped LOD is -1; clamp 0.0 left of x = 32 reads mip 0 red, 1.0 from there on reads mip 1 cyan; dropping the MinLod operand turns the right half red); semantic: `tests/semantic/test_sample_cl.py` and the `_cl_o` forms in `tests/test_texel_offsets.py`. The compare forms (`_c_cl`, `_c_b_cl`) have no GPU test: the depth fixture has one mip level. Not translated: `_c_d`, `_c_cd`, `_d_cl` with compare, the g16 forms. | | Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). Reads of components the element doesn't declare (e.g. `.w` of an `xyz` position, 3 VS) are allowed: the fetch returns the format defaults (0, 0, 1), and Vulkan fills a `vec4` input from a narrower format the same way. Inputs are declared as `vec4`. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** | | PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | +| Partial pixel color exports | Each MRT retains channels from earlier exports when the current `exp` disables them. Uncompressed exports enable individual RGBA channels and compressed exports enable the RG and BA pairs. Partial MRT outputs start at zero so a channel the shader never writes keeps its existing translator default. The CPU test in `tests/semantic/test_export_valid_mask.py` checks the eight RGBA words from two interleaved targets in `partial_color_exports.asm`. [AMD RDNA 2 ISA, sections 11.1 and 11.2.1](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | Inputs and outputs | VS: **legacy (non-NGG) hardware VS, measured** over all 2,236 (`scripts/vs_input_survey.py`): no `exp prim`, no `s_sendmsg` (so no `GS_ALLOC_REQ`) and no `v_mbcnt` in any of them, and every one exports `pos0` and `param`. The input VGPRs are Mesa's GFX10 legacy-VS layout (`radv_shader_args.c`, `declare_vs_input_vgprs`, not `is_ngg`): `v0` = vertex id, `v1` unused, `v2` = primitive id, `v3` = instance id. On entry no VS reads `v1` or `v2`; 788 start with the fetch call (see *Vertex fetch*) and read the fetched attributes from `v4` up, and of the other 1,448, 1,052 read `v0` only, 386 `v0` and `v3`, and 10 neither (NGG would have put the VS inputs at `v5`/`v8`, after five GS VGPRs). **Both ids are zero-based on the hardware**: `v0` excludes the draw's base vertex and `v3` its first instance (Mesa `ac_nir_lower_intrinsics_to_args.c`: `vertex_id` is `load_vertex_id_zero_base`, `instance_id` is `load_instance_id`; the bases come in the `base_vertex` / `start_instance` SGPRs). Vulkan's `VertexIndex` / `InstanceIndex` include `firstVertex`/`vertexOffset` / `firstInstance`, so the translator seeds `v0 = VertexIndex - BaseVertex` and `v3 = InstanceIndex - BaseInstance` (`DrawParameters`, device feature `shaderDrawParameters`, in every VS's `features`). GPU-checked with `runtime/test/shaders/vs_base_ids.asm` (`VKH_DRAW=16,7`): `0x101` on every pixel, where `VertexIndex`/`InstanceIndex` alone gave `0x7111`. `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. | | 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. | | 16-bit SDWA result with `dst_sel:DWORD` | A 16-bit op in SDWA form (`v_add/sub/subrev/mul/min/max_f16_sdwa`, the f16 unary ops, `v_cvt_u16_f16`, `v_cvt_i16_f16`, `v_cvt_f16_u16`, `v_cvt_f16_i16`) with `dst_sel:DWORD` writes the whole VGPR: the 16-bit result zero-extended, **whatever `dst_unused` says**. The keep-the-high-half rule of the row above is for the non-SDWA forms only; with `dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE` the high half is kept as usual. **Until 2026-11-22 the translator kept the high half for `dst_sel:DWORD`** (`Gen.insn` marked an SDWA destination only for a `dst_sel` other than DWORD). Measured natively on an AMD Radeon iGPU (gfx1036, RDNA2, Windows driver 26.10.1) with `python -I tools/sdwa_diff.py --oracle hw` (#2113) and with the program of `runtime/test/shaders/ps_sdwa_dword_hi.asm` through `tools/hw_oracle`: destinations 0xdeadbeef give 0x00004000 (`v_add_f16`, PRESERVE), 0x00000003 (`v_cvt_u16_f16`, PAD), 0x00004700 (`v_cvt_f16_u16`, PRESERVE), 0x0000c000 (`v_mul_f16`, SEXT); the same ops with `dst_sel:WORD_0 UNUSED_PRESERVE` give 0xdead4000, 0xdead0003, 0xdead4700, 0xdeadc000. GPU-checked through Vulkan with `ps_sdwa_dword_hi.asm` on an RTX 5080 (driver 616.92) and the same Radeon iGPU (4096/4096 pixels each); CPU-checked in `tests/semantic/test_value_semantics.py`. | @@ -262,12 +281,13 @@ How the generated SPIR-V expects the runtime to work: | `v_fmamk_f16`, `v_fmaak_f16` | VOP2 with a literal K: `fmamk` computes `D = S0 * K + S1` (printed `vdst, src0, K, vsrc1`), `fmaak` computes `D = S0 * S1 + K` (printed `vdst, src0, vsrc1, K`). In print order both are `a[1] * a[2] + a[3]`, as for `v_fmamk/fmaak_f32`. K is the f16 in the literal's low 16 bits; a float literal is converted to f16 (`src_h`). One rounding to f16, as `v_fmac_f16` (SHADER-55). The GFX10 f16 VOP2 write puts the result in the low half and keeps the high half. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_fmamk_fmaak_f16.py`, against `v_fma_f16` with K in a VGPR (value grids, a float literal, the operand order, seeded values). **Not GPU-verified.** | | SDWA select on an f16 inline constant | In an `_sdwa` 16-bit float op, an inline float constant is first the f16 value over a zero high half (row above) and `src0_sel`/`src1_sel` then narrows those 32 bits like a register's, zero-extended, before neg/abs and the op: `1.0` under `WORD_1` reads +0.0, `2.0` under `BYTE_1` reads the f16 denormal `0x0040`. An SGPR source, and an integer op reading the f32 bits of a float constant (`v_cvt_f16_u16_sdwa d, 1.0 src0_sel:WORD_1` converts 0x3f80), are narrowed the same way. **Until 2026-11-22 the translator used the whole f16 constant** (`v_add_f16_sdwa d, 1.0, v src0_sel:WORD_1` with v = 0.5 gave 1.5). Measured on an AMD Radeon iGPU (gfx1036, Ryzen 9 9950X3D, driver 26.10.1) with `tools/hw_oracle` (raw HIP kernel, wave32): the four words of `runtime/test/shaders/ps_sdwa_f16_const.asm`; found with `python -I tools/sdwa_diff.py --oracle hw` (#2113). GPU test `ps_sdwa_f16_const`, 4096/4096 pixels on an NVIDIA GeForce RTX 5080 (driver 616.92) and the same Radeon iGPU through Vulkan; both fail without the fix. Also executed by `tests/semantic/test_value_semantics.py`. | | `v_pack_b32_f16` input `neg` | A VOP3 `neg` on an operand of this instruction flips the sign bit of **the 16-bit half that operand contributes**, not of the whole 32-bit source, and only that half: measured on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels, `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`. The translator moved the bits unchanged and refused every modifier; it now XORs `0x8000` into the selected half. `abs` is still refused, because its rule on this instruction is unmeasured (SHADER-260), and the mode-1 quieting of a signalling-NaN half is not modelled while SHADER-190 is open; under mode 0, where the bits move unchanged, the translation is exact. Checked on the CPU by `tests/test_values.py` and `tests/semantic/test_vop3_const_mods.py`; the gfx1036 measurement above is @Sanonymous01's, not repeated here. | -| Packed 16-bit integer ops (`v_pk_add/sub_u16/i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16/i16`, `v_pk_max/min_u16/i16`) | VOP3P: result half 0 takes each source's half from `op_sel[i]`, result half 1 from `op_sel_hi[i]` (defaults `[0,..]` and `[1,..]`), as for `v_pk_lshlrev_b16`. Each half is computed on its own and wraps to 16 bits. `clamp` (add, sub, mad) saturates the half to its type's range; the exact value fits in 32 bits. `neg_lo`/`neg_hi` are float-only and raise `Unsupported`, as does `clamp` on the other ops. A constant operand is treated as a 32-bit dword `C`: `op_sel[i] == 0` selects bits `[15:0]`, `op_sel[i] == 1` selects bits `[31:16]`. Positive inline constants zero-extend (`5` → `0x00000005`), negative inline constants sign-extend (`-1` → `0xFFFFFFFF`, `-16` → `0xFFFFFFF0`), and 32-bit literals retain their full dword (`0x12345678`). Lowered via `OpBitField*Extract` at `16 * sl[i]`. Until 2026-11-22 reading the high half of a constant raised `Unsupported`. A constant operand reads as its low 16 bits. Its high half under `op_sel`/`op_sel_hi` is **not measured** for integer ops (for f16 constants it reads +0.0, see the row above), so a constant whose high half would be read raises `Unsupported` instead of guessing; the compiler's usual form, `op_sel_hi:[1,0]` with the constant second, reads only the low half. Until 2026-11-22 all eleven ops raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, inline and literal constants, rejected forms). **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`, and independently on `gfx1036` desktop APU, Windows 11, driver `32.0.21045.29003`, across 380 raw compute kernels covering all 11 ops, constants under `op_sel`/`op_sel_hi`, `clamp`, and wave32/wave64 parity with 0 wave diffs and 0 mismatches): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and constant `op_sel`/`op_sel_hi`) match bit-for-bit. **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and `op_sel`/`op_sel_hi`) match bit-for-bit. | -| `v_sin_f32`, `v_cos_f32`, `v_sin_f16`, `v_cos_f16` | The operand is an angle in turns (the ISA says valid over +-256; the measurement below finds no such limit on gfx1030). `turn_angle` reduces it in turns first, `x - RoundEven(x)` (exact in binary32, in [-0.5, 0.5]), then scales by `2*pi` and calls `Sin`/`Cos`, so the angle stays in [-pi, pi], the only range where GLSL guarantees them (2^-11 absolute). Scaling first rounded the fractional turn away (about 1.2e-4 rad near 255 turns, #594); the first fix (#1283) reduced with `Fract`, which rounds `1 - | x | ` for a negative x and lost `-2^-26` (it returned +0; absolute errors up to ~1.7e-7 at -0.1 turns), so the reduction is `RoundEven`-centred. `RoundEven` rather than `Round` so +-0.5 turn reduce symmetrically. inf and NaN still give NaN, and a zero operand is passed through unreduced so `sin(-0)` stays -0. CPU-checked by `tests/semantic/test_alu_sincos.py` against `sin`/`cos(2*pi*x)` in double (large angles, tiny arguments, whole turns of either sign, +-0, inf/NaN, modifiers, f16) and `tests/semantic/test_valu_sin_cos_turns.py` (#1283). GPU test `cs_w32_sincos` (large angles within 1e-3, since the driver `Sin` is only good to 2^-11) is a regression guard, not proof the old form failed on a given driver. Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) by @shelbykb2 (#616): whole and half turns of either sign give +0 (only `sin(-0)` is -0, so no sign needs copying onto a zero result, as here); there is no +-256 limit on that card (any finite x reduces exactly: `sin(300.25)` = 1, `sin(2^24)` = +0); the f16 forms reduce the same way as the f32 ones; +-inf gives a NaN and a NaN passes through, quieted with IEEE mode on. Re-measured natively on gfx1036 (RDNA2, SHADER-134) for f32 and f16 over every quarter turn from 0.25 to 2^24 of either sign and around +-256: the same rules. At an odd half turn `sin`, and at an odd quarter turn `cos`, is exactly +0 (either sign of x), where `Sin`/`Cos` of the rounded 2*pi give about -+8.7e-8 (f32) or a +-1-ulp f16 denormal; since 2026-11-22 the translator selects +0 there (`Gen.trig_exact_zero`), checked against 500 measured words by `tests/semantic/test_alu_sincos_turns_hw.py`. Known differences from this translation: for Known differences from this translation: at half turns `Sin` of the rounded pi gives about -+8.7e-8 where the hardware returns exactly 0, likewise `cos` at quarter turns; for | x | <= 2^-12 the hardware multiplies by `0x40c90fd5`, not the rounded 2*pi; the inf/NaN words are whatever the host driver returns. Not checked on gfx1013. | -| `v_pack_b32_f16` source modifiers | A VOP3 `abs` or `neg` on an operand of this instruction acts on **the 16-bit half that operand contributes**, not on the whole 32-bit source, and only on that half: `abs` clears bit 15 and `neg` flips it, `abs` first, both as plain bit moves — the operand is not converted to a float. Until 2026-11-22 any such operand was rejected as `Unsupported`. **`neg` is measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels: `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`, so the sign move does not depend on the mode. **`abs` and `- **`neg`, `abs`, and `- **`abs` rests on the ISA's definition of ABS on a float operand as the sign clear, applied before `neg`; no hardware run of this instruction with `abs` exists yet**, and `abs` on a NaN half is therefore unmeasured too. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. | x src | ` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64): ` (neg+abs) are measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21045.29003) with 1,088 raw kernels across wave32 and wave64 (0 mismatches): `abs` clears bit 15 (`& 0x7FFF`), `neg` flips it (`^ 0x8000`), and `neg_abs` sets bit 15 across all normal numbers, zeros, infinities, subnormals, quiet NaNs, and signaling NaNs, in either half and with `op_sel`. Under IEEE mode 0, signaling NaN payloads are preserved untouched (`0x7c01` gives `0xfc01` under `neg` and `0x7c01` under `abs`); under IEEE mode 1, a signaling-NaN half is quieted (bit 9 set: `0x7c01` gives `0xfe01` under `neg` and `0x7e01` under `abs`). ` are hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels): `abs` clears bit 15 and applies before `neg` on `-1.0`, `-0.0`, `-qNaN` (`0xfe05` → `0x7e05`), and `-sNaN` (`0xfc01` → `0x7c01` under `ieee=0`), with and without `op_sel`. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. | +| Packed 16-bit integer ops (`v_pk_add/sub_u16/i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16/i16`, `v_pk_max/min_u16/i16`) | VOP3P: result half 0 takes each source's half from `op_sel[i]`, result half 1 from `op_sel_hi[i]` (defaults `[0,..]` and `[1,..]`), as for `v_pk_lshlrev_b16`. Each half is computed on its own and wraps to 16 bits. `clamp` (add, sub, mad) saturates the half to its type's range; the exact value fits in 32 bits. `neg_lo`/`neg_hi` are float-only and raise `Unsupported`, as does `clamp` on the other ops. A constant operand is treated as a 32-bit dword `C`: `op_sel[i] == 0` selects bits `[15:0]`, `op_sel[i] == 1` selects bits `[31:16]`. Positive inline constants zero-extend (`5` → `0x00000005`), negative inline constants sign-extend (`-1` → `0xFFFFFFFF`, `-16` → `0xFFFFFFF0`), and 32-bit literals retain their full dword (`0x12345678`). Lowered via `OpBitField*Extract` at `16 * sl[i]`. Until 2026-11-22 reading the high half of a constant raised `Unsupported`. A constant operand reads as its low 16 bits. Its high half under `op_sel`/`op_sel_hi` is **not measured** for integer ops (for f16 constants it reads +0.0, see the row above), so a constant whose high half would be read raises `Unsupported` instead of guessing; the compiler's usual form, `op_sel_hi:[1,0]` with the constant second, reads only the low half. Until 2026-11-22 all eleven ops raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, inline and literal constants, rejected forms). **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`, and independently on `gfx1036` desktop APU, Windows 11, driver `32.0.21045.29003`, across 380 raw compute kernels covering all 11 ops, constants under `op_sel`/`op_sel_hi`, `clamp`, and wave32/wave64 parity with 0 wave diffs and 0 mismatches): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and constant `op_sel`/`op_sel_hi`) match bit-for-bit. **Not GPU-verified.** **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and `op_sel`/`op_sel_hi`) match bit-for-bit. | +| `v_sin_f32`, `v_cos_f32`, `v_sin_f16`, `v_cos_f16` | The operand is an angle in turns (the ISA says valid over +-256; the measurement below finds no such limit on gfx1030). `turn_angle` reduces it in turns first, `x - RoundEven(x)` (exact in binary32, in [-0.5, 0.5]), then scales by `2*pi` and calls `Sin`/`Cos`, so the angle stays in [-pi, pi], the only range where GLSL guarantees them (2^-11 absolute). Scaling first rounded the fractional turn away (about 1.2e-4 rad near 255 turns, #594); the first fix (#1283) reduced with `Fract`, which rounds `1 - \| x \| ` for a negative x and lost `-2^-26` (it returned +0; absolute errors up to ~1.7e-7 at -0.1 turns), so the reduction is `RoundEven`-centred. `RoundEven` rather than `Round` so +-0.5 turn reduce symmetrically. inf and NaN still give NaN, and a zero operand is passed through unreduced so `sin(-0)` stays -0. CPU-checked by `tests/semantic/test_alu_sincos.py` against `sin`/`cos(2*pi*x)` in double (large angles, tiny arguments, whole turns of either sign, +-0, inf/NaN, modifiers, f16) and `tests/semantic/test_valu_sin_cos_turns.py` (#1283). GPU test `cs_w32_sincos` (large angles within 1e-3, since the driver `Sin` is only good to 2^-11) is a regression guard, not proof the old form failed on a given driver. Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) by @shelbykb2 (#616): whole and half turns of either sign give +0 (only `sin(-0)` is -0, so no sign needs copying onto a zero result, as here); there is no +-256 limit on that card (any finite x reduces exactly: `sin(300.25)` = 1, `sin(2^24)` = +0); the f16 forms reduce the same way as the f32 ones; +-inf gives a NaN and a NaN passes through, quieted with IEEE mode on. Re-measured natively on gfx1036 (RDNA2, SHADER-134) for f32 and f16 over every quarter turn from 0.25 to 2^24 of either sign and around +-256: the same rules. At an odd half turn `sin`, and at an odd quarter turn `cos`, is exactly +0 (either sign of x), where `Sin`/`Cos` of the rounded 2*pi give about -+8.7e-8 (f32) or a +-1-ulp f16 denormal; since 2026-11-22 the translator selects +0 there (`Gen.trig_exact_zero`), checked against 500 measured words by `tests/semantic/test_alu_sincos_turns_hw.py`. Known differences from this translation: for Known differences from this translation: at half turns `Sin` of the rounded pi gives about -+8.7e-8 where the hardware returns exactly 0, likewise `cos` at quarter turns; for \| x \| <= 2^-12 the hardware multiplies by `0x40c90fd5`, not the rounded 2*pi; the inf/NaN words are whatever the host driver returns. Not checked on gfx1013. | +| `v_pack_b32_f16` source modifiers | A VOP3 `abs` or `neg` on an operand of this instruction acts on **the 16-bit half that operand contributes**, not on the whole 32-bit source, and only on that half: `abs` clears bit 15 and `neg` flips it, `abs` first, both as plain bit moves — the operand is not converted to a float. Until 2026-11-22 any such operand was rejected as `Unsupported`. **`neg` is measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels: `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`, so the sign move does not depend on the mode. **`neg`, `abs`, and `neg_abs` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64, 0 mismatches): **`abs` and `- **`neg`, `abs`, and `- **`abs` rests on the ISA's definition of ABS on a float operand as the sign clear, applied before `neg`; no hardware run of this instruction with `abs` exists yet**, and `abs` on a NaN half is therefore unmeasured too. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. \| x src \| ` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64): ` (neg+abs) are measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21045.29003) with 1,088 raw kernels across wave32 and wave64 (0 mismatches): `abs` clears bit 15 (`& 0x7FFF`), `neg` flips it (`^ 0x8000`), and `neg_abs` sets bit 15 across all normal numbers, zeros, infinities, subnormals, quiet NaNs, and signaling NaNs, in either half and with `op_sel`. Under IEEE mode 0, signaling NaN payloads are preserved untouched (`0x7c01` gives `0xfc01` under `neg` and `0x7c01` under `abs`); under IEEE mode 1, a signaling-NaN half is quieted (bit 9 set: `0x7c01` gives `0xfe01` under `neg` and `0x7e01` under `abs`). ` are hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels): On `gfx1035`, `abs` clears bit 15 and applies before `neg` on `-1.0`, `-0.0`, `-qNaN` (`0xfe05` → `0x7e05`), and `-sNaN` (`0xfc01` → `0x7c01` under `ieee=0`), with and without `op_sel`. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. | +| Packed integer dot products (`v_dot2_i32_i16`, `v_dot2_u32_u16`, `v_dot4_u32_u8`, `v_dot8_i32_i4`, `v_dot8_u32_u4`, plus VOP2 accumulating `v_dot2c_i32_i16`, `v_dot2c_u32_u16`, `v_dot4c_u32_u8`, `v_dot8c_i32_i4`, `v_dot8c_u32_u4`), `v_dot2_f32_f16` / `v_dot2c_f32_f16`, and `v_pk_fmac_f16` | RDNA2 ISA: `v_dot2_i32_i16`/`u16` (2×16-bit), `v_dot4_u32_u8` (4×8-bit unsigned), and `v_dot8_i32_i4`/`u4` (8×4-bit) — and their VOP2 accumulating `v_dot*c_*` forms (reading old `vdst` as `acc`) — extract each element with `OpBitFieldSExtract`/`OpBitFieldUExtract`, sum the elementwise products with `S2` (or old `vdst`) wrapping at 32 bits, and saturate to `[INT32_MIN, INT32_MAX]` / `[0, UINT32_MAX]` under `clamp` (signed carry tracking handles the `v_dot2_i32_i16` `(-32768)^2 + (-32768)^2 + acc` overflow/cancellation edge). For VOP3P `v_dot*_*`, the hardware default `op_sel:[0,0,0]` and `op_sel_hi:[1,1,1]` is accepted and any other `op_sel`/`op_sel_hi`, `neg_lo`/`neg_hi`, DPP/SDWA, or source `neg`/`abs` raises `Unsupported`; for VOP2 `v_dot*c_*`, only optional `clamp` and VGPR `vdst` are accepted. `v_dot2_f32_f16` (VOP3P) and `v_dot2c_f32_f16` (VOP2) compute `a0*b0 + a1*b1 + acc` in f32 (`f16_in` per half, `flush_f32` on `acc`, optional `clamp`, and for `v_dot2_f32_f16` `op_sel`/`op_sel_hi`/`neg_lo`/`neg_hi` on the inputs and `neg_lo[2]` on `acc`). All 6 new `v_dot*c_*` ops mark `vdst` as read-before-write in `read_before_write_vgprs` and `reg_reads_writes`. (`v_dot4_i32_i8` and `v_dot4c_i32_i8` are covered separately in the Signed-byte dot products row, #1754.) `v_pk_fmac_f16` (VOP2) unpacks `src0`, `vsrc1` and `vdst` as `f16x2` (`Gen.src_h`, so inline float constants apply in the low half with `+0.0` high), computes `fma(src0[k], vsrc1[k], vdst[k])` per half with single f16 rounding (`Gen.fma_f16_odd`, SHADER-55), and packs with `Gen.f16_pack2`; any modifier outside `_dpp` or non-VGPR `vdst` raises `Unsupported`, and `v_pk_fmac_f16` marks `vdst` as read before write in `read_before_write_vgprs` and `reg_reads_writes`. **Hardware-confirmed on RDNA2** for the 5 VOP3P integer forms and `v_pk_fmac_f16`: on `gfx1036` (Ryzen 9 7950X3D iGPU, `tools/hw_oracle`, @aslan2142), all 60 integer dot-product sets and all 22 `v_pk_fmac_f16` default-MODE words match; independently confirmed on `gfx1035` (Radeon 680M, @Youssefrah16) across 18 cases × wave32/wave64 (36/36 bit-exact), pinned by `tests/semantic/test_alu_dot_pk_fmac.py`. The 5 VOP2 `v_dot*c_*` integer forms and `v_dot2_f32_f16` / `v_dot2c_f32_f16` are CPU-checked by `tests/semantic/test_alu_dot_complete.py` and not yet hardware-measured on RDNA2. Non-default f16 MODEs (denormal flush, RTZ) are not modelled on `v_pk_fmac_f16` while the translator has no MODE input. | | Packed integer dot products (`v_dot2_i32_i16`, `v_dot2_u32_u16`, `v_dot4_u32_u8`, `v_dot8_i32_i4`, `v_dot8_u32_u4`) and `v_pk_fmac_f16` | RDNA2 ISA: `v_dot2_i32_i16`/`u16` (2×16-bit), `v_dot4_u32_u8` (4×8-bit unsigned), and `v_dot8_i32_i4`/`u4` (8×4-bit) extract each element with `OpBitFieldSExtract`/`OpBitFieldUExtract`, sum the elementwise products with `S2` wrapping at 32 bits, and saturate to `[INT32_MIN, INT32_MAX]` / `[0, UINT32_MAX]` under VOP3P `clamp` (signed carry tracking handles the `v_dot2_i32_i16` `(-32768)^2 + (-32768)^2 + S2` overflow/cancellation edge). The hardware default `op_sel:[0,0,0]` and `op_sel_hi:[1,1,1]` (whether omitted or written explicitly) is accepted; any other `op_sel`/`op_sel_hi` (such as `op_sel_hi:[0,0,0]` or `[0,1,1]`, which select the low half for lane 1 on `v_dot2_*`), `neg_lo`/`neg_hi`, DPP/SDWA forms, and source `neg`/`abs` raise `Unsupported`. (`v_dot4_i32_i8` and `v_dot4c_i32_i8` are covered separately in the Signed-byte dot products row, #1754.) `v_pk_fmac_f16` (VOP2) unpacks `src0`, `vsrc1` and `vdst` as `f16x2` (`Gen.src_h`, so inline float constants apply in the low half with `+0.0` high), computes `fma(src0[k], vsrc1[k], vdst[k])` per half with single f16 rounding (`Gen.fma_f16_odd`, SHADER-55), and packs with `Gen.f16_pack2`; any modifier outside `_dpp` or non-VGPR `vdst` raises `Unsupported`, and `v_pk_fmac_f16` marks `vdst` as read before write in `read_before_write_vgprs` and `reg_reads_writes`. Until 2026-11-22 all six ops raised `Unsupported`. **Hardware-confirmed on RDNA2:** on `gfx1036` (Ryzen 9 7950X3D iGPU, `tools/hw_oracle`, @aslan2142), all 60 integer dot-product sets (plain, swapped/SGPR sources, and `clamp`) match bit-for-bit, all measured `op_sel`/`neg_*` variants are refused, and all 22 `v_pk_fmac_f16` default-MODE (`0x000003C0`: round-to-nearest-even, f16 denormals kept, IEEE and DX10_CLAMP on) words match in both source orders (all 34 non-NaN halves bit-exact; the 10 NaN halves yield quiet f16 NaN, as SPIR-V does not preserve NaN payload bits or sign); independently confirmed on `gfx1035` (Radeon 680M, `tools/hw_oracle`, @Youssefrah16) across 18 cases × wave32/wave64 (36/36 bit-exact). Pinned by `tests/semantic/test_alu_dot_pk_fmac.py` (all 82 `gfx1036` measured tables plus hand-written `.asm` fixture, boundary/clamp cases, default/non-default `op_sel`/`op_sel_hi`, `read_before_write_vgprs`/`reg_reads_writes`, DPP, seeded sweeps, and rejected forms). Non-default f16 MODEs (denormal flush, RTZ) are not modelled on `v_pk_fmac_f16` while the translator has no MODE input. | | `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. | -| `v_div_fmas_f32`, `v_div_fmas_f64` | Scaled FMA for IEEE-754 division (VOP3): `D = VCC[lane] ? (2^32 * fma(S0, S1, S2)) : fma(S0, S1, S2)` for f32 and `2^64` (`OpCapability Float64`) for f64. When `VCC` is set and the operands cannot overflow under pre-scaling (`\|S0\|, \|S1\| < 2^110` and `\|S2\| < 2^95` for f32; `< 2^990` and `< 2^958` for f64), the operands are pre-scaled before `Fma` (`S0·2^16, S1·2^16, S2·2^32` / `S0·2^32, S1·2^32, S2·2^64`) so tiny intermediates (e.g. `2^-75 · 2^-75 → 2^-118` in f32, `2^-540 · 2^-540 → 2^-1016` in f64) do not underflow before scaling; otherwise post-FMA scaling is used. VOP3 input (`abs`/`neg`) and output (`mul:2`/`mul:4`/`div:2`, then `clamp`) modifiers apply via `clamp_mods` / `clamp_mods_f64`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_DIV_FMAS_F32`, `V_DIV_FMAS_F64`) and LLVM `VOP3Instructions.td`. **Not measured on RDNA2 hardware** (translated GPU output checked on RTX 5070 by @duudiis). Checked on the CPU (`spirv_mini_interp` for f32 with VCC 0/1, tiny-intermediate fused scale, and modifiers) and with `spirv-val` (f32 and f64) by `tests/semantic/test_alu_div_fmas.py`; not run on the shader corpus. | +| `v_div_fmas_f32`, `v_div_fmas_f64` | Scaled FMA for IEEE-754 division (VOP3): `D = fma(S0, S1, S2)` when `VCC[lane] == 0`; when `VCC[lane] == 1`, `D = (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2)` where `(bias, S)` is `(127, 64)` for f32 and `(1023, 128)` for f64 (`OpCapability Float64`, no `Int64`), i.e. `\|S2\| >= 2.0` scales up and `\|S2\| < 2.0` scales down. Scale-up uses `fma(S0, S1, S2) * 2^S` (any non-zero cancellation residual against `\|S2\| >= 2.0` stays well above normal minimum). Scale-down pre-scales `S0`/`S1` only when `\|S0*S1\|` can overflow (`\|S0\| >= 2^S` and `\|S1\| >= 1`, symmetric, or both `>= 2^(S/2)`), with a raw-bit sticky value `copysign(min_normal, S2)` whenever `0 < \|S2\| < 2^(Emin + S)` so half-ULP tie-breaking stays exact; otherwise it post-scales `fma(S0, S1, S2) * 2^-S`, with a TwoSum + product-error half-ULP tie adjustment in f64 when `\|fma\|` falls in `[2^-947, 2^-894)` so f64 subnormal outputs single-round. For f32 under the game MODE (`denorm32=0`), subnormal inputs and intermediate products are kept while subnormal outputs flush to signed zero before (and after) output modifiers; for f64 (`denorm16_64=3`), subnormals are kept throughout. VOP3 input (`abs`/`neg`) and output (`mul:2`/`mul:4`/`div:2`, then `clamp`) modifiers apply via `clamp_mods` / `clamp_mods_f64`. **Until 2026-11-22 the translator scaled unconditionally by `2^32` (f32) / `2^64` (f64) whenever `VCC[lane] == 1`, omitting the `exp(S2) > bias` branch and using half the hardware exponent shift.** **Hardware-verified on RDNA2** (`gfx1036`, AMD Radeon Graphics, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64, game MODE `ieee=0`/`dx10_clamp=1`/`denorm32=0`/`denorm16_64=3`): 150/150 f32 and 153/153 f64 stress cases match bit-for-bit, including the `\|S2\| = 2.0` vs `nextbelow(2.0)` threshold, scale-down overflow prevention, sticky-bit tie-breaking, f32 output denormal flushing, and f64 subnormal single rounding. Checked bit-for-bit on the CPU (`spirv_mini_interp` for f32, SSA `%double` evaluator for f64) and assembled with `tools/spirv_asm.py` (plus `spirv-val` when present) by `tests/semantic/test_alu_div_fmas.py`; not run on the shader corpus. | | POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | | Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10–10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); every other `image_load` keeps the sampled path and needs no storage feature (SHADER-151). `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) or on a dimension without storage views (cube) is `Unsupported`. Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | | 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. | @@ -275,19 +295,20 @@ How the generated SPIR-V expects the runtime to work: | Implicit 2D pixel-shader integer samples | For `image_sample`, take the UV derivatives before branching on the T# format, then sample the matching float, UINT or SINT view with those gradients. In `ps_sample_implicit_sint` a 128×128 signed texture minifies onto 64×64 pixels. Clamping the sampler to level 0 returned four color quadrants; allowing level 1 returned cyan. All four signed D16 channels matched at every pixel on RTX 5080 and gfx1036. | | Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. The operand is always a run-time value: the translator extracts the fields from the register, also when the shader loaded the dword from an immediate, so every `_o` sample needs the extension. `image_gather4_lz_o` / `_l_o` read x and y the same way; a gather `Offset` needs `shaderImageGatherExtended`, not maintenance8. **GPU-tested** with `runtime/test/shaders/ps_texoff.asm` on `vk_texture_test` (in `check.py` and `scripts/run_gpu_tests.py`; SKIP on a device without the extension), on an AMD Radeon RX 6800, Windows driver 26.11.2, maintenance8 enabled: an 8×8 texture whose texels are all different, a point sampler that clamps to the edge, 2D targets, mip 0. `image_sample_lz_o` with an offset computed per pixel (all 64 pairs of x, y in −4..3, none clamped), `image_sample_l_o` with (−3, +2) and `image_sample_lz_o` with (+16, −32) from immediates, and `image_gather4_lz_o` of red and of green with the per-pixel offset gave, on all 4096 pixels, the texels worked out by hand from this rule (derivation in the `.asm` header). Run with a sabotaged translator, the test fails when the sample offset is dropped, has x and y swapped, takes y from bit 6, or uses 4-bit or 5-bit fields, and when the gather offset is dropped, has x and y swapped or takes y from bit 6; 4-bit and 5-bit gather fields pass, because the gather offsets stay in −4..3. What it shows is that the translated SPIR-V implements this rule on Vulkan; it does not measure the field layout on the hardware. **It cannot see the sign extension on this driver**: with the fields read unsigned the same texels come back: `Offset` 60..63 sampled as −4..−1 and +32 as −32 (the device reports texel offset limits −64..63, gather −32..31). The sign extension and the gather field width are therefore pinned by the structural test `tests/test_texel_offsets.py` (signed, bit 8k, 6 bits, for `_lz_o`, `_l_o`, `_o`, 3D and gather) and are not GPU-tested through Vulkan. **The x field is measured on hardware:** `image_sample_lz_o` run as a raw compute kernel on the same RX 6800 (gfx1030, wave32 and wave64), on a 64×1 `R32_FLOAT` image whose texel i holds i, with a point sampler that clamps to the last texel: from texel 40, offset dword `0x20` reads texel 8 and `0x3c` reads texel 36 (unsigned would clamp both to 63); from texel 10, `0x1f` reads 41 and `0x20` clamps to 0; `0x40`, `0x80` and `0xc0` read the centre texel (bits 6–7 are ignored); and a non-zero y field, z field or top byte leaves x alone. All 36 rows fit x = sign-extended bits [5:0]. **The y and z fields are measured too** (SHADER-337): `tools/texoff_probe.py --oracle hw` on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010), wave32 and wave64, samples a linear `R32_SFLOAT` texture whose texel holds its index (2D 64×64 for y, 3D 64×1×64 for z) with `image_sample_lz_o` and a point sampler that clamps to the last texel. From row 40, y = `0x20` reads row 8 and `0x3c` row 36, `0x21` row 9 (unsigned would clamp all three to 63); from row 10, `0x1f` reads 41 and `0x20` clamps to 0 (unsigned: 42); `0xc0` (bits 14–15 set, field 0) reads row 40 and `0x7f` row 39, so those bits are ignored; x −2 with y −4 in one dword reads both. The z field at bits [21:16] gives the same 7 results on the 3D image. All 15 rows fit each field = sign-extended 6 bits, the bits above it ignored, which is the translator's rule; `tests/test_texoff_probe.py` checks that every row with a negative field tells the signed reading from the unsigned one. The (+16, −32) sample is outside Vulkan's guaranteed −8..7 and is judged only where the device limits cover it. **`image_sample_o`, `image_sample_b_o` and `image_gather4_l_o` are GPU-tested** with `runtime/test/shaders/ps_texoff_forms.asm` (the same texture, sampler and per-pixel offset as `ps_texoff`, all 64 offset pairs in −4..3; in `check.py` and `scripts/run_gpu_tests.py`): 4096/4096 pixels exact on an NVIDIA GeForce RTX 4090 (driver 621.24) and on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, driver 32.0.21045.16010), both with maintenance8 enabled. Not GPU-tested: `_c_lz_o`, the z field (3D), 1D, 2D-array and cube targets (offset next to an array layer), wrap or mirror addressing, linear filtering, mips other than 0, other vendors' drivers, and a device without maintenance8 (the test skips there; the translator has no fallback for it). **Without maintenance8 (`--texel-offset-fallback`, NVIDIA Pascal for one):** an `image_sample*_o` gets no `Offset`; the offset is folded into the coordinate instead, as coordinate + offset ÷ the size of the sampled level. The level is 0 for `_lz` / `_c_lz`, the given LOD for `_l`, and `OpImageQueryLod`'s for implicit samples (plus the bias for `_b`), floored and clamped to the image's levels. A texel offset applies before wrapping and clamping, and an integer offset commutes with both, so the shift is exact for every address mode at that level. The one case that differs is a trilinear blend of two levels, where the coarser level moves by offset ÷ 2 of its texels. Implicit samples become `Grad` samples with the derivatives of the unshifted coordinate (× 2^bias for `_b`), so the LOD and anisotropy are those of the original sample even when the offset varies per pixel. Gathers keep their `Offset` (`shaderImageGatherExtended`). Only 4 of the 12,101 PS need it, all through `image_sample_o`. **GPU-tested** on an NVIDIA GeForce GTX 1060 6GB (no maintenance8; driver 560.94, Windows 10) with `LEONIDA_TEXOFF_FALLBACK=1`: `ps_texoff` and `ps_texoff_implicit` (the per-pixel sample as `image_sample_o`) are 4096/4096 pixels exact, with the +16/−32 sample judged too, since a coordinate shift has no device offset limit. Checked in `tests/test_texel_offsets.py`, including `spirv-val` without `--allow-offset-texture-operand`. | | A16 sample offsets | For the supported `image_sample*_o` forms, the first address VGPR retains the signed texel-offset fields. The following coordinates and any trailing LOD use packed binary16 halves, low half first. LLVM counts extra operands as whole words before packing coordinates and LOD ([getAddrSizeMIMGOp](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342)). On RTX 5080 and Radeon Graphics, `ps_texoff.asm` checked 64 distinct offsets applied to packed U/V at texel (3,5) against the expected texel for each of 4096 pixels. Swapping the halves or dropping the offset changed 4032 pixels per GPU. | +| A16 gather offsets | On GFX10, `image_gather4_lz_o` and `image_gather4_l_o` take the packed signed texel offset in a full VGPR before the packed binary16 coordinates and optional LOD. LLVM [counts the extra operand before packing coordinate words](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342). The synthetic `gather_offset_a16.asm` checks an offset of (−1,+1) with distinct U and V and a nonzero mip. | | Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti (and an RTX 2060 SUPER), and `runtime/test/vk_harness.cpp` enables them when available, as does the runtime's `create_vulkan_device_standalone`, each with its extension (`VulkanDeviceInfo::fragment_shader_barycentric`, `fragment_shader_interlock`, `maintenance8`; checked by `d3d12_vulkan_device_test`). All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. (It is guarded by the header macro `VK_KHR_MAINTENANCE_8_EXTENSION_NAME`, so older Vulkan headers build without it. `vk_texture_test` enables it too, and `shaderImageGatherExtended`.) A device without `fragmentShaderBarycentric` (NVIDIA Pascal) runs the raw-barycentric PS with `--bary-fallback` (below). Shaders translated with `--fma khr` need `VK_KHR_shader_fma` and its `shaderFmaFloat32` feature (`VkPhysicalDeviceShaderFmaFeaturesKHR`): `create_vulkan_device_standalone`, `runtime/test/vk_test_device.h` and the `vk_*` test programs enable it when the device offers it (`VulkanDeviceInfo::shader_fma`), and a test program refuses (exit 77) a module with `OpCapability FMAKHR` on a device without it. | -| Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | +| Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. | | Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | -| Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's Windows driver on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py`; all 185 hand-written GPU test shaders pass `spirv-val` with the flag (109 of them read the tail) with set-0 bindings unchanged. The GPU harnesses and the D3D12 layer that bind the block are the follow-ups. | -| Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (inferred from the code, not confirmed against the console's wave-size setting: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | +| Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | | Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | +| Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's Windows driver on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py`; all 185 hand-written GPU test shaders pass `spirv-val` with the flag (109 of them read the tail) with set-0 bindings unchanged. The GPU harnesses and the D3D12 layer that bind the block are the follow-ups. | | `v_add_nc_i16`, `v_sub_nc_i16` | GFX10 VOP3-only signed 16-bit add and subtract. Without `clamp` they are bit-identical to `v_add_nc_u16`/`v_sub_nc_u16` (the low 16 bits wrap) and take the same path: `op_sel:[s0,s1,dst]` picks each source's half and the destination half, and the other half of D is kept. With `clamp`, the exact sum or difference of the sign-extended halves saturates to [-32768, 32767] (`SClamp`), where the u16 forms saturate to [0, 0xFFFF]. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel` including the destination half, and equality with the u16 forms without `clamp`). **Not GPU-verified.** Measured on native gfx1100: `clamp` saturates the exact sign-extended sum to [-32768, 32767] and the other half of D is kept. | | Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). | | `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches, and the high product word and SCC retention confirmed across edge values. | | SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). | | Chained scalar constant folding (PERF) | Multi-step constant calculations on SGPRs (`s_mov_b32`, `s_lshl_b32`, `s_lshr_b32`, `s_mul_i32`, `s_add_u32`, `s_sub_u32`, `s_lshl1..4_add_u32`, `s_bfe_u32/i32`, `s_min/max_u32/i32`, `s_andn2/orn2/nand/nor/xnor_b32`, `s_abs_i32`, `s_absdiff_i32`, `s_sext_i32_i8/i16`, `s_pack_*_b32_b16`, `s_bfm_b32`) fold completely at translation time and record folded literal values in `self.sgpr_imm`, allowing downstream instructions within the basic block to propagate constants. `s_buffer_load` offset expressions computed via constant SALU fold statically into 64-bit addresses, and in-bounds reads eliminate runtime bounds check branches and Phi nodes. `s_bfe` with constant control words emits static offset/width operands directly. Checked by `tests/semantic/test_salu_chained_const_prop.py` and `tests/semantic/test_scalar_alu_and_smem_folding.py`. | -| Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. | +| Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. The `s_sub_u32 K; s_subb_u32 0` form is the backward jump (a loop back-edge), as is `s_add_u32 -K; s_addc_u32 -1`. K is a byte distance, so the fold needs the instructions' `; encoding:` bytes; a listing without them is `Unsupported` ("without encoding"), not a crash. GPU-checked by `ps_far_branch.asm` (two forward jumps, a `sub`/`subb` loop, an `add`/`addc -1` loop and a conditional one run twice, K and the expected words derived by hand; RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_far_branch.py`. | | No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | | Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint/sint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. A store with fewer components than its format writes the whole element, with 0 for the components it doesn't give (`_xy` into 32_32_32_32 leaves z = w = 0, `_xyz` into 16_16_16_16 leaves w = 0); into a one-channel format only x is written. Measured natively on a Radeon 680M (gfx1035, RDNA2), and GPU-checked by `cs_fmt_xy_xyz.asm` for 32_32_32_32, 16_16_16_16, 8_8_8_8 UNORM and UINT and 32 (TEST-185). Unsigned integer stores saturate to the destination channel width. On native gfx1036, RGBA8_UINT, RG16_UINT and RGBA16_UINT clipped overflowing inputs to 255 or 65535, with RGBA32_UINT as a full-width control. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero; native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. `tbuffer_store_format_*` is not translated. 8- and 16-bit SINT stores clamp the signed 32-bit value to [-2^(w-1), 2^(w-1) - 1] (300 stores 127 into 8_SINT, -129 stores -128), and the 8/16-bit UINT formats 5, 11 and 18 saturate like the others; measured natively on gfx1036 for x, xy, xyzw and d16_xyzw stores (a d16 half is read as a signed 16-bit integer for SINT, so 0xff80 stores -128) with the runtime's selectors (X001, XY01, XYZW) and checked by `tests/semantic/test_buffer_format_narrow_int.py` (until 2026-11-22 those formats stored nothing). `tbuffer_store_format_*` and its `_d16_*` forms take the instruction's format instead of the V#'s, as the tbuffer loads do: only that format is encoded, and its element size decides the bounds check (an 8_UNORM byte is stored where the V#'s 16-byte element would not fit; a 16-byte element is dropped where the V#'s 4-byte one would fit). A V# whose FORMAT is 0 (INVALID) still disables the store. No `format:` modifier is GFX10's default, BUF_FMT_8_UNORM; a format FORMATS has no encoder for stays `Unsupported`. Measured natively on a Radeon 680M (gfx1035, wave32 = wave64) and GPU-checked by `cs_tbuffer_store.asm` (13 stores: f32, f16, 8_8_8_8 UINT and UNORM, 2_10_10_10, d16, the default format, more and fewer components than the format has, both bounds cases, a V# with FORMAT 0; exact on an RTX 3050 and the 680M); CPU-checked by `tests/semantic/test_tbuffer_store.py`. | | No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | @@ -296,54 +317,57 @@ How the generated SPIR-V expects the runtime to work: | `s_lshl1..4_add_u32` | D = (S0 << N) + S1. SCC = the sum taken in 64 bits is ≥ 2³², so a bit shifted out of S0 sets it as well as a carry out of the add (RDNA ISA pseudocode: `tmp = (64'U(S0) << N) + 64'U(S1)`). Checked on the CPU by `tests/semantic/test_salu_lshl_add.py`. **Hardware-verified** on the same gfx1100 part through `tools/hw_oracle`: `s_lshl1_add_u32(0x80000000, 0)` = 0 with SCC = 1 (the bit shifted out of S0 sets it, with no carry out of the add), `s_lshl2_add_u32(5, 3)` = 0x17 with SCC = 0, `s_lshl4_add_u32(1, 0)` = 0x10. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches across shift amounts 1–4, confirming that bits shifted out of S0 set SCC as well as sum overflow. | | Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at the mip the "Gather sampler LOD" row chooses, in gather order. `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip `Floor(clamp(LOD, S# MIN_LOD, MAX_LOD) + 0.5)` (ties up, as native) in gather order. With `d16` those four taps round to binary16 and pack low half first into two consecutive VGPRs. The packed words and the first untouched VGPR were checked with `ps_gather_wrap.asm` on RTX 5080 and Radeon Graphics. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. The modulo is `OpSRem` plus the period when the remainder is negative, not `OpSMod`. On a Ryzen 5 7600's iGPU (RDNA2) with AMD's Windows driver 24.10.24, `OpSMod` of a negative coordinate came out with the dividend's sign: the three `ps_gather_wrap` cases whose wrap or mirror coordinate is negative (1, 2 and 6) fetched outside the image and read zeros, while the same module passed on an RTX 4070 SUPER. With `OpSRem` and the fix-up, all 4096 pixels are exact on both. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. A literal S# with a border mode (4-7: half-border, border colour) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4-7 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Modes 6 (clamp border) and 7 (mirror once border) give a tap whose coordinate, before the clamp, is outside [0, n-1] on either axis the S# border colour's channel instead of the fetched texel: BORDER_COLOR_TYPE = word 3 [31:30] (Mesa `gfx10-rsrc.json` `SQ_IMG_SAMP_WORD3`, `SQ_TEX_BORDER_COLOR_*` in `gfx6.json`), 0 transparent black, 1 opaque black (alpha 1), 2 opaque white; 1 for an integer format, as Vulkan's `INT_OPAQUE_*`. Type 3 (a colour from the border-colour table, `BORDER_COLOR_PTR`) is `Unsupported` on a literal S# and transparent black at run time (SHADER-348: since #1567 made the game's S# words literals, 16 of the corpus's mode-6 gathers failed as `Unsupported`; before that they ran as clamp-to-edge). A literal S# with a half-border mode (4, 5) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4 and 5 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two, and a table border colour (BORDER_COLOR_TYPE 3) on a run-time S#, which gives transparent black, are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070; the border modes with `runtime/test/shaders/ps_gather_border.asm` (two literal and two run-time S#s, opaque white and transparent black, modes 6 and 7) on NVIDIA RTX 4070 SUPER (driver 621.01), with `tests/test_translate.py`'s `test_gather4_l_*border*`. `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | | `v_mad_u64_u32`, `v_mad_i64_i32` | {sdst, D} = S0 × S1 + S2 as a 65-bit result (RDNA ISA pseudocode), the product unsigned or signed. sdst (a lane mask) gets bit 64 for active lanes and 0 for lanes off in EXEC (`EXEC[lane] ? bit64 : 0`, matching `v_cmp_*` and `*_co_*`): the carry out for u64, and for i64 the sign of the exact sum (bit 64 of a 65-bit two's-complement value), not a signed-overflow flag. `tools/lane_masks.py` tracks sdst as a lane mask (until 2026-11-22 it only matched `*_co_*`, so `s_bcnt1`/`s_ff1`/`v_mbcnt` on sdst read each lane's own mask word as plain data). `clamp` is rejected. Checked on the CPU by `tests/test_lane_masks.py`, `tests/semantic/test_alu_mad64.py` (including 64-lane `s_bcnt1_i32_b64`/`s_ff1_i32_b64` ballot tests), and `tests/semantic/test_carry_exec_mask.py` (EXEC masking on inactive lanes). **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): unsigned carry, signed positive overflow `(-2³¹)² + INT64_MAX` giving `sdst = 0`, negative sum giving `sdst = 1`, and inactive EXEC lane leaving D untouched with `sdst = 0` all match bit-for-bit. | -| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a). These two references agree; no game BVH is decoded yet to count over. A GPU can't confirm the rule either, because every GPU runs this emulation and none runs the native instruction. `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. | +| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, misses = `0xFFFFFFFF`, sorted when descriptor bit 63 (box_sort_enable) is set. **The box test is the native one, measured on RDNA2** (SHADER-650; RX 6900 XT, gfx1030, `tools/hw_oracle` raw kernels, 338 cases: BOX32 and BOX16, four rays including negative directions, NaN in every position, empty boxes, planes on the origin, and every tie order of four children; the translator now matches all 338 bit for bit, `main` before it 43): per axis, the near plane is min and the far plane max when the inverse direction (taken as given, not clamped) is ≥ 0, swapped otherwise; t = (plane − origin) × inverse direction, so `0 × inf` is NaN. tnear = max of the three near t, tfar = min of the three far t, **each skipping NaN**; all three near or all three far NaN is a miss. Hit when max(tnear, 0) ≤ tfar and tnear < extent (the extent boundary itself was not measured). So a lone NaN bound leaves its own plane open (a box with min.x = NaN is hit wherever x ≤ max.x), an empty box (min > max on any axis, ±inf or ±65504 included) is a miss without a separate check, and a plane exactly on the origin along a zero-direction axis is open. The sort key is max(tnear, 0), so boxes around the origin tie at 0, ordered by the network (0,2) (1,3) (0,1) (2,3) (1,2) with a strict `<` swap (all 88 measured tie orders). `tests/semantic/test_image_bvh_box_hw.py` holds measured words. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a). These two references agree; no game BVH is decoded yet to count over. The triangle rule has not been run natively yet; the box rule above has (`tools/hw_oracle` on an AMD RDNA2 card runs the instruction itself). `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (measured on gfx1030: the 32-bit form with a non-zero base and the 64-bit form with base 0 and the full address gave the same words in 71 cases). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact; its box with a NaN min.x is entered at t = 0 and sorts first (`0x68 0x48 0x40 0xffffffff`), as native gfx1030 returns for that scene. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. | | Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS (tier C of the *Wave64 graphics* row; tiers A and B are exact); compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | -| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. | -| v_interp operand guards (SHADER-177) | The single-lane model reads the attribute's own value for `v_interp_p1/p2`, which is only right when the VGPR source really holds the barycentric coordinate that op interpolates with — **p1 reads I = v0 and p2 reads J = v1, per op** — and `v_interp_mov_f32` models only the p0 provoking vertex. A p1/p2 (f32 and f16 forms) whose source is not its own coordinate — v0 for p1, v1 for p2, each either the hardware register or a plain `v_mov_b32` copy rooted at it (the copy's single write in the whole shader, defined before the use, copy chains followed, and its source v0/v1 itself unwritten up to the copy: a copy of an already-overwritten v0/v1 carries a computed value — zeroing the source before copying renders (0,0) on hardware — while a write after the copy is fine, the copy saved the value) — is **Unsupported**, naming the register and the role, so a swapped p1(v1)/p2(v0) pair, a both-v0 pair, or a copy of an overwritten source is refused rather than silently mistranslated; `v_interp_mov_f32` with p10/p20 is **Unsupported**, naming the select. A **direct** v0/v1 read stays accepted even when the shader overwrites v0/v1 first (evaluate-at-offset/snapped barycentrics; up to 213 PS, #1218): modelling that computed value is the separate provenance follow-up. Zero corpus cost: over the 26,503-shader corpus every f32 I/J source is v0/v1 (117,001 / 116,997) except one PS whose four `v_interp_p2_f32` read J through `v_mov_b32 v14, v1` (its v1 unwritten up to the copy; the later overwrites are the saved-copy case), which the copy rule keeps translating (bit-identical .spv), every f16 source is v0/v1 (58,950 / 58,950), and all 6,926 `v_interp_mov_f32` use p0. Confirmed by `tests/semantic/test_interp_guards.py` (refusals name the operand and its role, including swapped and both-v0 pairs, a wrong-root copy, and a copy of an overwritten source; the copy, copy-chain, matching-role and saved-from-later-zero cases translate and compute; a second write or a dpp copy no longer qualifies; a mutation check that the guard consults the copy analysis) and by re-translating a 200-shader corpus slice plus that PS before and after: translated/valid counts and every .spv unchanged. | +| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` with the p0 select is declared `Flat` (a location a p10/p20 mov reads is `PerVertexKHR`, next row). A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. | +| v_interp operand guards (SHADER-177) | The single-lane model reads the attribute's own value for `v_interp_p1/p2`, which is only right when the VGPR source really holds the barycentric coordinate that op interpolates with — **p1 reads I = v0 and p2 reads J = v1, per op** — and `v_interp_mov_f32` p0 is the provoking vertex (p10/p20 are the deltas of the vertex-delta row above). A p1/p2 (f32 and f16 forms) whose source is not its own coordinate — v0 for p1, v1 for p2, each either the hardware register or a plain `v_mov_b32` copy rooted at it (the copy's single write in the whole shader, defined before the use, copy chains followed, and its source v0/v1 itself unwritten up to the copy: a copy of an already-overwritten v0/v1 carries a computed value — zeroing the source before copying renders (0,0) on hardware — while a write after the copy is fine, the copy saved the value) — is **Unsupported**, naming the register and the role, so a swapped p1(v1)/p2(v0) pair, a both-v0 pair, or a copy of an overwritten source is refused rather than silently mistranslated; `v_interp_mov_f32` with p10/p20 was **Unsupported** until the vertex-delta row above; any other select still is, naming it. `v_interp_mov_f32` with p10/p20 is **Unsupported**, naming the select. A **direct** v0/v1 read stays accepted even when the shader overwrites v0/v1 first (evaluate-at-offset/snapped barycentrics; up to 213 PS, #1218): modelling that computed value is the separate provenance follow-up. Zero corpus cost: over the 26,503-shader corpus every f32 I/J source is v0/v1 (117,001 / 116,997) except one PS whose four `v_interp_p2_f32` read J through `v_mov_b32 v14, v1` (its v1 unwritten up to the copy; the later overwrites are the saved-copy case), which the copy rule keeps translating (bit-identical .spv), every f16 source is v0/v1 (58,950 / 58,950), and all 6,926 `v_interp_mov_f32` use p0. Confirmed by `tests/semantic/test_interp_guards.py` (refusals name the operand and its role, including swapped and both-v0 pairs, a wrong-root copy, and a copy of an overwritten source; the copy, copy-chain, matching-role and saved-from-later-zero cases translate and compute; a second write or a dpp copy no longer qualifies; a mutation check that the guard consults the copy analysis) and by re-translating a 200-shader corpus slice plus that PS before and after: translated/valid counts and every .spv unchanged. | | Pixel-shader interpolants | When a sidecar `fssm/.fssm` holds a pixel-input table (`tools/fssm_header.py`: 8-byte records from 0x138 while the first byte is 6; table position = `v_interp attr` number), every position 0..count−1 is declared as a fragment input at that Location, including positions the code never reads (the table overcounts the code's distinct `v_interp` attrs in 775 of 12,101 PS: 300 by one, 475 by two or more; only the 10 records starting with kind 7 undercount). A 32-bit `v_interp` read (`p1/p2/mov`) of a 16-bit-flagged position (flag bit 4; **measured natively on RDNA2**, AMD Radeon 680M `gfx1035` in wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430: the VINTRP unit reads the same LDS parameter-cache dwords at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}` with no hidden 16-bit unpacking, so `v_interp_mov_f32` returns the raw 32-bit parameter word and `v_interp_p1_f32`/`v_interp_p2_f32` interpolate those 32-bit words as binary32), and reads past the table still declare an input (the value is undefined on hardware). 11,199 such inputs corpus-wide, matching the `*_f16` interpolation opcodes in 99.7%) sees the value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, back to f32) via a single `OpQuantizeToF16` (a `PackHalf2x16`/`UnpackHalf2x16` round-trip is folded to a no-op by at least one Vulkan driver, RTX 5080); reads through the `*_f16` opcodes already narrow and are unchanged (on a location an f16 op also reads, the f32 read is of the per-vertex raw word, "16-bit interpolation"; on gfx1036 a 32-bit `p1/p2_f32` read of a packed channel takes the raw LDS words as f32 bits, one fma each (SHADER-430, `tools/interp_hw_probe.py`); what P10/P20 words the SPI stores for such a channel is unverified), and reads past the table still declare an input (the value is undefined on hardware). Without a sidecar, or with an empty table, the output is byte-identical to the code-driven path. Confirmed by synthetic fixtures plus mini-interpreter agreement (`tests/test_rdna2spirv_pixelinput.py`: an f32 read of a flagged slot with input 1.1 yields the f16-rounded 1.099609375; unflagged and table-less controls yield exact 1.1) and `tests/test_vinterp_hw_probe.py`. The `index.json` entry records `ps_interpolants` (count) and `ps_fp16_interpolants` (flagged positions). | -| PS interpolation modes (SHADER-181) | Every interpolated pixel input in this build is **perspective-correct at the pixel center**, and every other input is flat, so the single v0/v1 pair the code reads is `PERSP_CENTER`. The translator models exactly these two: Flat for `v_interp_mov_f32`, plain (perspective, center) inputs and `BaryCoordKHR` for `v_interp_p1/p2` and the f16 forms. Two records describe each input, and they state **different facts**: PSV0 (DXBC) stores the interpolation **mode**; the FSSM input record's flags byte (byte 7) stores the **read method** — bit 0 (0x01) marks `v_interp_mov_f32` (4,600 records), bit 1 (0x02) 32-bit `v_interp_p1/p2` (51,191; values 0 and 3 never occur), bit 3 (0x08) a Float16-typed parameter (11,619), bit 4 (0x10) the `*_f16` opcodes (11,199; 24 f16-read records lack it). The flag/usage cross-table over all 55,791 records has no contradiction: every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 positions), every bit-1 position only by `v_interp_p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). **The mode is in PSV0, not the FSSM**: `tools/ps_interp_modes.py` decodes it from the PSV0 signature elements (`DXIL::InterpolationMode`, "must match D3D_INTERPOLATION_MODE": 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, 5 LinearNoperspectiveCentroid, 6 LinearSample, 7 LinearNoperspectiveSample; the 16-byte elements carry row, cols, semantic kind, component type and the mode — layout in the Pixel-shader inputs section) and maps the modes onto the `SPI_PS_INPUT_ENA` barycentric-pair bits (Mesa `gfx103.json` register type SPI_PS_INPUT_ENA: PERSP_SAMPLE/CENTER/CENTROID = bits 0/1/2, LINEAR_SAMPLE/CENTER/CENTROID = bits 4/5/6; the same type serves `SPI_PS_INPUT_ADDR`). **No FSSM word stores ENA/ADDR**: every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the signature-reconstructed ENA and only constant coincidences matched, and the register addresses (0x286CC/0x286D0, or 0xA1B3/0xA1B4 as context-register indices) appear in no PS blob, so the v2.. position layout of "PS system inputs" (one enabled pair) is the only ENA witness. Census (12,101 PS; 101,024 declared / 77,245 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 4,529 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. 101,024 declared / 76,215 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 3,652 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. ISG1 has no mode field, and the DXIL part carries no bitcode. SV_Position is mode 4 (11,295 rows) or mode 5 (27) — noperspective by the D3D rule —. With packed-component read masks, the classifier assigns 10,260 shaders to the perspective-centre pair and 1,841 to no pair. It assigns none to a linear pair. This count measures input classification; it does not directly measure how the hardware delivers SV_Position; front face is a system input (1,984 rows, 345 read, at most one per shader). SV_Position is mode 4 (11,295 rows) or mode 5 (27) — noperspective by the D3D rule — and is delivered through the system VGPRs in every shader except **4**, which interpolate it through the parameter cache with the *linear* pair (`FragCoord` stays at the pixel center, which only differs at partly covered MSAA pixels); front face is a system input (1,984 rows, 345 read, at most one per shader). The code reads **one** barycentric pair per shader: v0/v1 in 10,259, none in 1,841, and one shader reads J from v14 (a copy of v1), so the perspective-centre assumption holds for every interpolated generic input. **Mode and read method disagree in thousands of rows** — the residual surface for modelling is: those 4 linear-pair position shaders, Constant rows read via `p1/p2` or `*_f16` (2,190 records at the matching table position; flat semantics in hardware, not modelled), and Linear rows read only by `v_interp_mov_f32` (3,197; already declared `Flat`). The translator's table check (`check_read_methods`, the row below) compares each read's opcode against the record's read-method bits (`fssm_header.read_methods`) — since the bits restate the read method, it rejects 0 of 12,101 PS: a consistency check between the two encodings of the read, not a mode check (a centroid/sample/noperspective input would still read `v_interp_p1/p2` and pass; that every interpolated input is perspective-centre is the PSV0 census result above, so keying a refusal on genuinely unmodelled modes means decoding PSV0, not reading these bits). Counted with `tools/ps_interp_modes.py` (stdlib; PSV0, FSSM and disassembly in one pass; #1301 removed the earlier #1246 census tool in favour of it) on the 1.0.2.1 corpus; tests `tests/test_ps_interp_modes.py`, `tests/test_fssm_header.py` and `tests/test_rdna2spirv_pixelinput.py` (synthetic). No GPU test: no shader needs centroid or sample interpolation. **Not covered:** bit 3 (0x08) is set in 11,619 records (all 11,199 16-bit ones, 396 flat, 24 linear). The 213 PS that overwrite v0/v1 before a `v_interp` (SHADER-178) compute their own barycentrics in code; PSV0 gives them no other mode. | +| PS interpolation modes (SHADER-181) | Every interpolated pixel input in this build is **perspective-correct at the pixel center**, and every other input is flat, so the single v0/v1 pair the code reads is `PERSP_CENTER`. The translator models exactly these two: Flat for `v_interp_mov_f32`, plain (perspective, center) inputs and `BaryCoordKHR` for `v_interp_p1/p2` and the f16 forms. Two records describe each input, and they state **different facts**: PSV0 (DXBC) stores the interpolation **mode**; the FSSM input record's flags byte (byte 7) stores the **read method** — bit 0 (0x01) marks `v_interp_mov_f32` (4,600 records), bit 1 (0x02) 32-bit `v_interp_p1/p2` (51,191; values 0 and 3 never occur), bit 3 (0x08) a Float16-typed parameter (11,619), bit 4 (0x10) the `*_f16` opcodes (11,199; 24 f16-read records lack it). The flag/usage cross-table over all 55,791 records has no contradiction: every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 positions), every bit-1 position only by `v_interp_p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). **The mode is in PSV0, not the FSSM**: `tools/ps_interp_modes.py` decodes it from the PSV0 signature elements (`DXIL::InterpolationMode`, "must match D3D_INTERPOLATION_MODE": 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, 5 LinearNoperspectiveCentroid, 6 LinearSample, 7 LinearNoperspectiveSample; the 16-byte elements carry row, cols, semantic kind, component type and the mode — layout in the Pixel-shader inputs section) and maps the modes onto the `SPI_PS_INPUT_ENA` barycentric-pair bits (Mesa `gfx103.json` register type SPI_PS_INPUT_ENA: PERSP_SAMPLE/CENTER/CENTROID = bits 0/1/2, LINEAR_SAMPLE/CENTER/CENTROID = bits 4/5/6; the same type serves `SPI_PS_INPUT_ADDR`). **No FSSM word stores ENA/ADDR**: every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the signature-reconstructed ENA and only constant coincidences matched, and the register addresses (0x286CC/0x286D0, or 0xA1B3/0xA1B4 as context-register indices) appear in no PS blob, so the v2.. position layout of "PS system inputs" (one enabled pair) is the only ENA witness. The #2735 packed-component census matched PSV0, FSSM and disassembly for all 12,101 indexed PS. Of 101,024 declared input rows, 77,245 have a nonzero read mask. Census (12,101 PS; 101,024 declared / 77,245 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 4,529 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. 101,024 declared / 76,215 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 3,652 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. ISG1 has no mode field, and the DXIL part carries no bitcode. SV_Position is mode 4 (11,295 rows) or mode 5 (27), both noperspective by the D3D rule. With packed-component read masks, the classifier assigns 10,260 shaders to the perspective-centre pair and 1,841 to no pair. None classify as linear-centre. Hardware delivery of SV_Position was not measured by this census. Front face is a system input (1,984 rows, 345 read, at most one per shader). It assigns none to a linear pair. This count measures input classification; it does not directly measure how the hardware delivers SV_Position; front face is a system input (1,984 rows, 345 read, at most one per shader). SV_Position is mode 4 (11,295 rows) or mode 5 (27) — noperspective by the D3D rule — and is delivered through the system VGPRs in every shader except **4**, which interpolate it through the parameter cache with the *linear* pair (`FragCoord` stays at the pixel center, which only differs at partly covered MSAA pixels); front face is a system input (1,984 rows, 345 read, at most one per shader). The code reads **one** barycentric pair per shader: v0/v1 in 10,259, none in 1,841, and one shader reads J from v14 (a copy of v1), so the perspective-centre assumption holds for every interpolated generic input. **Mode and read method disagree in thousands of rows** — the residual surface for modelling is: those 4 linear-pair position shaders, Constant rows read via `p1/p2` or `*_f16` (2,190 records at the matching table position; flat semantics in hardware, not modelled), and Linear rows read only by `v_interp_mov_f32` (3,197; already declared `Flat`). The translator's table check (`check_read_methods`, the row below) compares each read's opcode against the record's read-method bits (`fssm_header.read_methods`) — since the bits restate the read method, it rejects 0 of 12,101 PS: a consistency check between the two encodings of the read, not a mode check (a centroid/sample/noperspective input would still read `v_interp_p1/p2` and pass; that every interpolated input is perspective-centre is the PSV0 census result above, so keying a refusal on genuinely unmodelled modes means decoding PSV0, not reading these bits). Counted with `tools/ps_interp_modes.py` (stdlib; PSV0, FSSM and disassembly in one pass; #1301 removed the earlier #1246 census tool in favour of it) on the 1.0.2.1 corpus; tests `tests/test_ps_interp_modes.py`, `tests/test_fssm_header.py` and `tests/test_rdna2spirv_pixelinput.py` (synthetic). No GPU test: no shader needs centroid or sample interpolation. **Not covered:** bit 3 (0x08) is set in 11,619 records (all 11,199 16-bit ones, 396 flat, 24 linear). The 213 PS that overwrite v0/v1 before a `v_interp` (SHADER-178) compute their own barycentrics in code; PSV0 gives them no other mode. | +| `v_interp_mov_f32` p10 / p20 | The VINTRP mov returns one of the three values the hardware keeps per attribute for the p1/p2 pair, {P10, P20, P0}[S] (RDNA2 ISA, VINTRP; P = P0 + i·P10 + j·P20). p0 stays the provoking vertex (`Flat`, exact bits). p10 and p20 read the location `PerVertexKHR` (the per-vertex path the `*_f16` interps use, so the PS needs `fragmentShaderBarycentric`) and return P1 − P0 and P2 − P0 as one f32 `OpFSub` of the producer's words, vertices ordered as in the f16 row (BaryCoordKHR .y/.z weight vertices 1/2). Refused (`Unsupported`) under `--bary-fallback` and `--f16-interp-fallback` (no per-vertex inputs) and on a 16-bit-flagged interpolant (FSSM table), where whether the hardware forms the delta in f16 is unmeasured. Until 2026-11-22 both selects were refused; all 6,926 `v_interp_mov_f32` in the corpus use p0, so the corpus translation is unchanged. Confirmed on the CPU by `tests/semantic/test_interp_mov_delta.py` (distinct per-vertex words give the deltas, and P0 + i·P10 + j·P20 from the three movs matches the p1/p2 pair bit for bit). **Unverified:** a GPU run, and AMD's rounding of P10/P20 for denormal or NaN words. | | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. | -| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. There is no f64 fused multiply-add in the translator yet (`v_add_f64` only). | +| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. There is no f64 fused multiply-add in the translator yet (`v_add_f64` only). | | `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | | `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | | MoltenVK fast-math (SHADER-234, NaN compares) | MoltenVK compiles every shader's MSL with Metal's fast-math on by default (`MVK_CONFIG_FAST_MATH_ENABLED`, default 1), and with it Metal folds an f32 compare of a NaN with itself as if the NaN were an ordinary number: `v_cmpx_eq_f32` and `v_cmpx_le_f32` on (NaN, NaN) give true where the ISA, AMD and NVIDIA give false (`ps_vcmpx_forms`, #1374: word 1 `0xf05e8e16`, want `0xf05e8a12`, bits 2 and 10; found by @zneel and @DomasUrbonas). The translation is not involved: the compare is `OpFOrdEqual` / `OpFOrdLessThanEqual`, and the MSL MoltenVK generates (`MVK_CONFIG_SHADER_DUMP_DIR`) is byte-identical with fast-math on and off, so it is Metal's compile option. `MVK_CONFIG_FAST_MATH_ENABLED=2` (on demand) does not help, because translated modules don't declare an execution mode that asks for IEEE behaviour; 0 does. The test tools (`runtime/test/vulkan_loader.h`, which every Vulkan test program uses to load MoltenVK) set `MVK_CONFIG_FAST_MATH_ENABLED=0` before MoltenVK reads its configuration, unless the variable is already set, so a user's own value still wins; the variable also reaches MoltenVK through the Vulkan loader. A runtime that loads MoltenVK on a Mac must do the same. Fast-math off does **not** remove the `[[clang::optnone]]` `spvFAdd`/`spvFSub`/`spvFMul` helpers SPIRV-Cross emits for `NoContraction` (11 calls in `ps_ops`'s MSL either way: their cost is the other part of SHADER-234), and it does not fix the row above (SHADER-182): `valu_fuzz.py --family f16 --seed 1` gives the same `v_mul_f16` +0 mismatch with fast-math on and off. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_vcmpx_forms` fails on all 4,096 pixels with fast-math on and matches all 4,096 with it off, natively and with wave64 emulation; no other `run_gpu_tests.py` result and none of the 25 `ctest` tests changes. | | Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). | -| f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for |x| > 1 is bit-exact, and for |x| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). `v_exp_f16`/`v_log_f16` give the same counts on gfx1036 (RDNA2, AMD Windows driver; SHADER-135). **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. | +| f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for \|x\| > 1 is bit-exact, and for \|x\| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). `v_exp_f16`/`v_log_f16` give the same counts on gfx1036 (RDNA2, AMD Windows driver; SHADER-135). **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. | | f64 literal sources | For `v_cvt_f32_f64` and either source of `v_add_f64`, a literal dword supplies bits 63:32 and bits 31:0 are zero. Inline integers are sign-extended and inline floats use their binary64 value. For example, gfx1030 `llvm-mc` encodes 1.5 as the literal word `0x3ff80000`. The synthetic `tests/semantic/fixtures/f64_literals.asm` checks both source words in the translated SPIR-V, including the distinction between the printed literal `0x1` and inline `1`. [LLVM AMDGPU operand conversions](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#integer-literals) | | `v_cvt_f32_f64` output modifiers | Convert to f32, apply `mul:2`, `mul:4`, or `div:2` if present, then apply `clamp` to [0, 1] if requested. [LLVM GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/main/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s#L3044-L3054) confirm the modifier encodings. `tests/test_f64_conversion.py` checks the resulting SPIR-V data flow. | | `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). | | `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64` | Double-precision reciprocal (`OpFDiv %double 1.0 x`), inverse square root (`GLSL.std.450 InverseSqrt`), and square root (`GLSL.std.450 Sqrt`), requiring `Float64` (`shaderFloat64`). VOP3 input modifiers (`abs`, `neg`) apply to the double operand, and output modifiers (`mul:2`, `mul:4`, `div:2`, then `clamp` to [0, 1]) apply via `clamp_mods_f64` (LLVM `VOP1Inst` / `VOP_F64_F64` in `VOP1Instructions.td`, `HasClamp` and `HasOMod` via `VOPProfile`). Special-value edge cases (`±0`, negative inputs, NaN) follow the driver's SPIR-V `OpFDiv`/`InverseSqrt`/`Sqrt` rules, as for the f32 forms. Checked by `tests/test_f64_transcendentals.py` (SPIR-V data flow and `spirv-val`). | | `v_trunc_f64`, `v_ceil_f64`, `v_rndne_f64`, `v_floor_f64` | Round binary64 toward zero, positive infinity, nearest-even, or negative infinity respectively; the result stays binary64. The translator maps these to GLSL.std.450 `Trunc`, `Ceil`, `RoundEven`, and `Floor` with `shaderFloat64` (no intermediate f32). Register pairs are low word first, literal dwords fill bits 63:32 with a zero low word, and inactive lanes keep both destination words. VOP3 applies source modifiers before rounding and the existing f64 scale/clamp path afterwards. Sources: AMD [RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §6.2.1 and §12.8 (VOP1 opcodes 23–26), and LLVM's [GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/1a7ece827ab3543387ee1adf1eb4c8878905b577/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s). Value and SPIR-V checks: `tests/semantic/test_f64_round.py`. Hardware-confirmed natively on RDNA2 (`gfx1036` iGPU, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case) by @timelery: exact IEEE-754 rounding that keeps signed zeros and binary64 subnormals (`ceil(+sub)` = +1.0, `ceil(-sub)` = -0.0, `floor(+sub)` = +0.0, `floor(-sub)` = -1.0, `trunc(±sub)` = ±0.0, `rndne(±0.5)` = ±0.0, `rndne(±1.5)` = ±2.0, `rndne(±2.5)` = ±2.0, ±inf stays ±inf, and ±qNaN/±sNaN pass through unchanged under IEEE=0), where `sub` is the smallest binary64 subnormal; the hex literal dword populates bits 63:32 with a zero low word (`v_floor_f64 v[4:5], 0x3ff80000` -> `0x3ff0000000000000`); and the VOP3 output modifiers behave as for `v_add_f64`/`v_sqrt_f64`: applied on hardware under `denorm16_64=0` and ignored under `denorm16_64=3` (IEEE=0), while the translator applies them through `clamp_mods_f64` as those rows do. | -| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). VOP3 `abs` and `neg` on `src0` are applied as raw sign-bit moves on the 32-bit integer bits (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`) rather than `FAbs`/`OpFNegate`, so signalling NaNs stay signalling (class bit 0) and subnormals are never flushed. **Hardware-measured natively on RDNA2 (`gfx1036`)** via `tools/hw_oracle` (Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM): 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, `|v|`, `-|v|`) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). Corpus count (26,503 shaders): `v_cmp_class_f32` appears 37,026 times in 7,101 shaders (0 with VOP3 `abs`/`neg` on `src0`). Checked on CPU + `spirv-val` by `tests/semantic/test_cmp_class_f32_mods.py` and `tests/semantic/test_valu_f32_class_rndne.py`; `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive (GPU-checked on RTX 4070 SUPER driver 616.92 and AMD RX 9070 XT RADV Mesa 26.2.6, plus direct Vulkan compute verification of modified sNaNs on RX 9070 XT and Radeon 610M `gfx1036`). | +| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). VOP3 `abs` and `neg` on `src0` are applied as raw sign-bit moves on the 32-bit integer bits (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`) rather than `FAbs`/`OpFNegate`, so signalling NaNs stay signalling (class bit 0) and subnormals are never flushed. **Hardware-measured natively on RDNA2 (`gfx1036`)** via `tools/hw_oracle` (Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM): 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, ` `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). \| v \| `, `- \| v \| `) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, `\|v\|`, `-\|v\|`) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). Corpus count (26,503 shaders): `v_cmp_class_f32` appears 37,026 times in 7,101 shaders (0 with VOP3 `abs`/`neg` on `src0`). Checked on CPU + `spirv-val` by `tests/semantic/test_cmp_class_f32_mods.py` and `tests/semantic/test_valu_f32_class_rndne.py`; `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive (GPU-checked on RTX 4070 SUPER driver 616.92 and AMD RX 9070 XT RADV Mesa 26.2.6, plus direct Vulkan compute verification of modified sNaNs on RX 9070 XT and Radeon 610M `gfx1036`). | | Float controls (NaN, ±inf, −0) (SHADER-99) | RDNA2 float ops return NaN, ±inf and −0 as computed, and Vulkan lets the driver assume none of them occur unless the module says otherwise. Every module therefore declares `OpExecutionMode %main SignedZeroInfNanPreserve 32` (capability `SignedZeroInfNanPreserve`, core since SPIR-V 1.4). Its index entry lists `"float_controls": ["shaderSignedZeroInfNanPreserveFloat32"]`, the device property it needs; `vk_pipeline_check` skips the shader where that property is false, and `--no-float-controls` leaves the mode out. Measured on AMD Radeon RX 9070 XT (driver 26.11.2). Without the mode, `runtime/test/shaders/cs_signed_zero_nan.asm` gets 0 in out[4..7]: the `x != x` NaN checks fold to false and a NaN `v_cvt_f16_f32` is lost. The f16 fuzzer (`tools/valu_fuzz.py --family f16`) also saw `v_pk_mul_f16` −0 products come back +0, and, with integer f16 narrowing (#575), NaN results that were never stored. With the mode, the test and those programs match. Other drivers, from testers in #664: RADV (RX 7800 XT) folds the f16 NaN check (out[6]) without the mode; NVIDIA and Intel Arc keep all three either way. Apple GPUs (MoltenVK) report the property, and the mode fixes their NaN checks, but −0 products (out[0], out[2], out[3]) still come back +0 with or without it (#1203, SHADER-182). `check.py` and `scripts/run_gpu_tests.py` don't judge those three words on an Apple device. Mesa's llvmpipe, where the CI runs these tests, returns 0 for the `0 × inf` NaN check (out[5]) with or without the mode, while its other NaN checks give 1 (#664), so out[5] isn't judged there (`UNJUDGED_WORDS` in `check.py`). f64 (`SignedZeroInfNanPreserve 64`) isn't declared yet. | | Float controls (f16 denormals) (SHADER-526) | RDNA2 keeps f16 denormals, so every module also declares `OpExecutionMode %main DenormPreserve 16` (capability `DenormPreserve`, core since SPIR-V 1.4 like `SignedZeroInfNanPreserve`, so no extension at `--target-env vulkan1.2`). The translator models f16 arithmetic in f32 with integer narrowing (`Gen.f16_bits`), so an f16 denormal is an ordinary f32 value in the module and no f32 denormal is involved: the 16-bit mode is what governs the f16→f32 conversion the driver emits for an f16 source. NVIDIA flushed that conversion without it: in `runtime/test/shaders/ps_sdwa_f16_const.asm` the y lane (`src0_sel:BYTE_1` of `2.0` is the denormal 0x0040 = 2^−18, × 1024.0 = 2^−8 = 0x1c00) read 0x0000, 4096/4096 pixels wrong, while x, z and w matched; with the mode the test is 4096/4096 exact (RTX 4070 SUPER, driver 610.88, Windows 11, validation layers on). The same lane read 0x0000 on an RTX 3090 (driver 610.88, found by @Rainmaker33). Assembling the same module with only the two `DenormPreserve` lines removed reads 0x0000 again, so it is the mode the driver honours, not a change in the translated code. Not every NVIDIA build flushes it: on `main` without the mode an RTX 4060 Ti (621.24), an RTX 5070 Ti (620.73.04, Linux) and an RTX 5080 (616.92) pass the test. The index entry lists `"shaderDenormPreserveFloat16"` after `"shaderSignedZeroInfNanPreserveFloat32"`; `vk_pipeline_check` skips the shader where the device reports that property false, and `--no-float-controls` leaves both modes out. Where the property is false the module has no f16 denormal guarantee, so an f16 denormal read can come back +0 exactly as in that lane above (NVIDIA's default without the mode); that is a value difference in the shader, and the GPU test's y lane is then expected to fail. The AMD Radeon iGPU (RDNA2, driver 24.10.24, Vulkan 1.3.280) reports `shaderDenormPreserveFloat16` true with `denormBehaviorIndependence` `32_BIT_ONLY`, and `vk_pipeline_check` builds the module and its pipeline there (`ps_sdwa_f16_const`: 1 module ok, 1 pipeline ok, wave32 and wave64); the GPU test itself skips on that device, which has 128 push-constant bytes where the test needs 144. `tests/semantic/test_f16_denorm_preserve.py` pins the mode, the index property and the four words. | +| `v_mul_legacy_f32` default-mode f32 denormal flushing | Under the inferred game `MODE` (`IEEE=0`, `denorm_mode_32=0`), the DX9 legacy multiplication reads f32 denormal operands as signed zeros, then its zero-operand override produces **+0** even when an operand was negative or the other is infinity/NaN. A nonzero subnormal product flushes to a zero retaining its sign, *before* VOP3 `mul:2`/`mul:4`/`div:2`; with IEEE off an output multiplier converts a resulting -0 to +0 on native RDNA2. The translated result is flushed after the modifier. This uses software f32 bit tests (`Gen.flush_f32`) rather than driver-specific denormal controls. Native gfx1031 (39,101 programs) and gfx1036 (38,858 programs) measured the MODE and DX9 mul rule (see the output-modifier rows below); the previous translator allowed f32 denormal operands and products through raw `OpFMul`. Synthetic regression: `tests/semantic/test_valu_mul_legacy_denorm.py`, `ps_mul_legacy_denorm.asm` and `ps_mul_legacy_denorm_mods.asm` (CPU, spirv-val and Vulkan GPU). This models the inferred game mode, not all possible dynamically changed MODE configurations. | | Multiply-add with a literal | `v_fmamk_f32`/`v_madmk_f32` are D = S0 × K + S1 and `v_fmaak_f32`/`v_madak_f32` are D = S0 × S1 + K, K being the 32-bit literal. LLVM prints them `vdst, src0, K, vsrc1` and `vdst, src0, vsrc1, K`, so in print order all four are a[1] × a[2] + a[3] (fused for fmamk/fmaak). **Until 2026-11-21 fmamk and madmk computed S0 × S1 + K.** Source: RDNA2 ISA (V_FMAMK_F32, V_MADMK_F32) and the operand fields of the llvm-mc encoding. Checked by `tests/semantic` and GPU-checked with `runtime/test/shaders/ps_fma_literal.asm` on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact, and 4096/4096 differ with the old translator. | | Multiply-add and output modifiers | `v_mac_f32` is the VOP2 form of `v_mad_f32`, **not** of `v_fma_f32`: the product is rounded before the add (`OpFMul` + `OpFAdd`, both `NoContraction`). It used to emit `Fma`, one ULP off on some inputs. Source: LLVM `SIInstrInfo.cpp` `getNewFMAInst` (`V_MAC_F32` -> `V_MAD_F32_e64`, `V_FMAC_F32` -> `V_FMA_F32_e64`). VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` now apply to `v_cvt_f32_i32`/`u32`/`ubyte0..3`, `v_cvt_f32_f16` and `v_rcp_iflag_f32` (they were dropped). Source: LLVM `VOPProfileI2F` (`Ins64 = $src0, $clamp, $omod`) and the float-source profiles. Found by `tools/f32_fuzz.py` (FUZZ-3: an exact-arithmetic model against the translated SPIR-V; 0 mismatches over 10,000 seeded programs after the fix) and pinned by `runtime/test/shaders/ps_f32_mods.asm` (`tests/semantic/test_f32_valu.py`); **GPU-checked** (TEST-298): `ps_f32_mods` gives the expected four words (`0xc0256a01 0x3f800000 0x41e00000 0x3fc00000`, so the `v_mac_f32` product is not fused and the `clamp`, `mul:4` and `div:2` on `v_cvt_f32_ubyte1`/`u32`/`f16` and `v_rcp_iflag_f32` apply) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 615.78.08); `mul:2` on the conversions is not in that fixture. **not yet GPU-verified**. Still open: on some inputs the ISA defines a result but the emitted SPIR-V is undefined: `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative. `v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp` (see "Float-to-byte pack"). `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative (`v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp`, see "Float-to-byte pack"). | -| Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. RDNA2 does the same: gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D; RDNA2, but not the console's gfx1013), seeds 1 to 6, 38,858 programs, 0 mismatch and 56 omod -0 → +0 deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | | Output modifiers on hardware (gfx1150, RDNA2) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). **RDNA2 does the same, rule for rule** (SHADER-353): on an RX 6700 XT (gfx1031, a discrete RDNA2 part, not the console's gfx1013; AMD Windows driver 26.11.2), seeds 1 to 6, 39,101 programs, 0 mismatch and 66 omod -0 → +0 deviations. Per MODE, counting only the programs where the omod changes the result: with IEEE off and f32 denormals flushed (the game's mode) it is applied every time (2,680, and the 66 -0 results become +0); with denormals kept it is ignored by the ALU ops (1,811) and applied by `v_rcp/rcp_iflag/rsq/sqrt/exp/log_f32` and the four cube ops (869, -0 → +0 only there); with IEEE on it is ignored (2,650) and a -0 result stays -0. Earlier, gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D) gave seeds 1 to 6, 38,858 programs, 0 mismatch and 56 such deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | | Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. Measured natively on gfx1036 (RDNA2) in the MODE inferred for the game (IEEE 0, f32 denormals flushed): `v_floor_f32`, `v_ceil_f32` and `v_fract_f32` read a denormal operand as a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0), fract(±inf) is exactly `0xffc00000`, and a NaN operand comes back unchanged, a signalling one too. The translator flushes the operand and selects those words itself (`Gen.round_f32_flushed`) instead of leaving them to the driver's f32 denormal handling, which Vulkan does not fix; until 2026-11-22 a driver that keeps denormals gave -1.0, +1.0 and 0x3f7fffff there. `v_cvt_flr_i32_f32` likewise returns 0 for a negative denormal (the translator gave -1). Checked against 119 measured words by `tests/semantic/test_alu_floor_ceil_fract_hw.py`. For `v_fract_f16`, either infinity gives the gfx1036 word `0xfe00`, or +0 with the DX10 clamp. The translator selects these results explicitly. The hand-written `ps_fract_f16_infinity.asm` fixture checks both signs, the preserved destination bits and a color channel computed from the result sign in the CPU interpreter (`tests/semantic/test_fract_f16_infinity.py`). A source `neg` on a signalling NaN operand still quiets it in the translator. Not changed: f16 fract(±inf) is `0xfe00` on the hardware and a quiet positive NaN in the translator, and `neg` on a signalling NaN operand quiets it in the translator. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `NMin(NMax(z, NMin(x, y)), NMax(x, y))` (until 2026-11-22 this used `FClamp(z, lo, hi)`, which was GLSL.std.450 undefined whenever `z` was NaN or both `x` and `y` were NaN), and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead; all 1-, 2-, and 3-NaN operand positions for both `v_med3_f32` and `v_med3_f16` were hardware-verified on RDNA2 (`gfx1035`, wave32 & wave64). `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (the `clamp` bit, LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged. Not modelled: signalling NaNs under IEEE mode; NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the payload when all operands are NaN in the f16 or three-source forms (`NMin` and `NMax` only promise a NaN). The binary `v_min_f32` and `v_max_f32` forms explicitly select the first operand when the second is NaN, preserving the first quiet NaN's sign and payload when both are quiet NaNs, as measured on the RX 6800. The CPU test `tests/semantic/test_minmax_f32_payload.py` checks both operand orders using finite color exports. Also, without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the NaN payload when both operands are NaN (`NMin` only promises a NaN); and without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. | | `ds_swizzle_b32` | An active destination reads the selected source lane's VGPR. If EXEC disables that source, the read returns zero; a disabled destination keeps its prior value. The [hardware measurements](shader_validation.md#hardware-oracle-for-the-lds-programs---oracle-hw) confirm the disabled-source result on gfx1036 and gfx1150. In the seven-invocation CPU fixture, lane 6 selects lane 7, which is absent. The translator returns zero in that case; the corresponding result on hardware is unverified. The fixture exercises `QUAD_PERM` and `SWAP` in `test_ds_permute.py`. | +| Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. RDNA2 does the same: gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D; RDNA2, but not the console's gfx1013), seeds 1 to 6, 38,858 programs, 0 mismatch and 56 omod -0 → +0 deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | | Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). Wave size comes from the sidecar `fssm/.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (FSPX programs or synthetic listings). Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | | Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. | | First active lane in a vertex shader (`v_readfirstlane_b32`, MoltenVK) | A native `v_readfirstlane_b32` is a ballot of the EXEC lanes, its lowest set bit, and a shuffle from that lane (lane 0 when no lane is on). **In a vertex shader the lowest bit is taken with `FindILsb` over the ballot's four words** (the lowest non-zero word wins), not with `OpGroupNonUniformBallotFindLSB`. The two give the same lane, because a ballot has no bit at or above the subgroup size. Other stages keep `BallotFindLSB`; the `--wave64-emulate` form already used `FindILsb` on its two mask words. Why: MoltenVK lowers `BallotFindLSB`, like the `SubgroupSize` built-in, to Metal's `threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for input declaration in a vertex function"), so every VS with a readfirstlane failed to compile there. **Confirmed on an Apple M4 (MoltenVK 1.4.2):** hand-written VS with `subgroupBallotFindLSB` or `gl_SubgroupSize` fail, and ballot, shuffle, broadcast-first, elect, votes, and ballot + `findLSB` + shuffle (32- and 64-lane forms) create. Corpus (1.0.2.1, translated from `4eb6155d`): 572 of the 2,236 VS contain `v_readfirstlane_b32`, and exactly those 572 modules change; all 2,236 stay `spirv-val`-valid. VS pipelines on the M4 go from 667 to 672 of 2,236 on main (the rest fail on the subgroup lane built-in, #1784), and from 1,662 to 2,233 with #1784's vertex-subgroup workaround (its flag is not on main) (the 571 `threads_per_simdgroup` failures are gone). `tests/semantic/test_vs_readfirstlane.py` runs it on the wave interpreter with the first EXEC lane in word 0 and word 1. | | Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. Under `--wave64-emulate`, `tools/wave64_emulate_opt.py` runs three exact CFG/dataflow passes to eliminate redundant scheduler rounds and global `OpSwitch` blow-up (#884): (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, no live-out scalars, and for each memory domain (`mem`/`lds`) either read-only accesses or an acyclic single write/atomic behind `if (%active)` (issuing any uniform `x_memory_order` split/barrier before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), and (3) structured emulation (`plan_structured_emulation`, `control_flow = "emulated wave64 structured"`) removes the global round-loop `OpSwitch` on multi-superblock reducible CFGs without non-uniform 32-bit half-mask SCC: single-wave workgroups (`<= 64` threads) run 100% inline structured SPIR-V with direct workgroup barriers (`0` `OpSwitch`, `0` `x_spill`, strictly monotone GEN/KILL 4-bit `dirty_in` memory ordering across blocks and loop back-edges), while multi-wave workgroups (`> 64` threads, without divergent `s_barrier`) emit post-dominating spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, `EXEC`-widening, and read-only loops) inline and isolate any remaining wave-divergent barrier regions into local mini-schedulers (or a tail scheduler at early `s_endpgm`). Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (40/64/128/256-thread workgroup interpreter with strict uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, single-store WAR/RAW ordering, single-wave `inline_all` loop-carried WAR, monotone `dirty_in` regression after `x_round`, multi-wave `structured_hybrid` + local `mini_scheduler`, divergent `s_barrier` fallback, `cs_w64x_saveexec_b64.s` fixture, and negative controls; **not yet GPU-verified** for the structured emulation pass). (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), and (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no memory/LDS writes, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, and no live-out scalars behind `if (%active)` (issuing any uniform `x_memory_order` split before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), keeping all 64 lanes of each wave in the same scheduler round. Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (64-thread and 128-thread workgroup interpreter with uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, internal loop, `cs_w64x_saveexec_b64.s` fixture, RAW memory/scalar-load ordering, and negative controls for live-out scalars, stores, cross-lane ops, and EXEC-widening). `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | -| Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | +| Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | | Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one). The raw pair a PS reads ("PS system inputs": 321 PS) comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module then needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. The stage before the PS writes (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices: `tools/bary_fallback_gs.py` writes that pass-through geometry shader from the index (Position and the PS's input locations copied unchanged). Default (perspective) interpolation of those weights is the perspective-correct barycentric, the value `BaryCoordKHR` has, so `.y`/`.z` stay AMD's i/j; shaders that don't read the pair translate to the same module either way. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal, no barycentric extension; driver 560.94, Windows 10) with `LEONIDA_BARY_FALLBACK=1`: `ps_bary` 4096/4096 pixels exact, and `ps_uniform_branch` and `ps_scc_mask32` pass, through `run_gpu_tests.py` and `build.py` + `check.py`, with zero Khronos validation messages. Checked in `tests/semantic/test_bary_fallback.py`. For a known VS/PS pair, `python -I tools/bary_fallback_gs.py DIR --pair VS PS` builds `PS.bary_gs.clipN.spv`. It copies the producer’s `ClipDistance[N]` at each emitted vertex, using the VS index field `clip_distance_count`. On RTX 5080 and Radeon integrated graphics, two independently shifted clip planes yielded 512, 1024, 2048 or 4096 covered pixels, matching the native barycentric path. For a cull-only VS the pair writes `PS.bary_gs.cullN.spv` from `cull_distance_count`. A two-plane synthetic draw on the same GPUs covered 0 pixels when every vertex was negative for either plane and all 4096 when each plane had a nonnegative vertex. The helper rejects mixed clip/cull arrays. The runtime building that GS per pipeline is the follow-up (it needs the graphics pipelines of #291). | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. This was checked against what all 2,689 CS read before writing: 2,281 match exactly, and the rest overshoot only through loop-carried registers in the straight-line check. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). | -| Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | -| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | +| Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | +| Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | +| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | | `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`; GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11), and measured on native gfx1100 through `tools/hw_oracle` (hit, miss and hit-to-zero), where GFX11 spells it `ds_cmpstore_b32` with the store value before the compare value. **Not GPU-verified.** GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11). | | LDS ADDTID (`ds_read_addtid_b32`, `ds_write_addtid_b32`) | The LDS forms address one dword at `M0[15:0] + offset + 4 * lane`, where `offset` is an unsigned 16-bit byte offset and `lane` is the invocation index within the RDNA wave. The Workgroup array supplies LDS_BASE. The compute/mesh path uses the ordinary LDS addressing and EXEC guard. The GDS form raises `Unsupported`. Source: RDNA2 ISA §10.4 and §12.13 (opcodes 176/177), LLVM GFX1030 assembly syntax. `tests/semantic/test_lds_addtid.py` compares the two forms with ordinary LDS reads/writes over two waves, including partial EXEC and emulated wave64. | | `ds_add_f32`, `ds_add_rtn_f32` | `M = M + DATA` as binary32 on the LDS dword (RDNA2 ISA, `DS_ADD_F32`); the `_rtn_` form returns the old M. No core SPIR-V atomic adds floats on Workgroup memory, so it is an `OpAtomicCompareExchange` loop with an `OpFAdd` (round to nearest even, `NoContraction`). That is exact under contention: every update is one successful exchange of the value it read. **Not measured:** how the LDS adder treats denormals and NaN payloads; the result is `OpFAdd`'s IEEE sum. The f32 min/max forms are #2495's. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_add_f32.py` (a value grid, the non-returning form, `offset:`, ties to even, -0 + +0, overflow to ±inf, seeded values, against a once-rounded double sum). **Not GPU-verified.** | -| `ds_mskor_b32`, `ds_mskor_rtn_b32` | `tmp = M[A]; M[A] = (tmp & ~DATA) | DATA2`; the `_rtn_` form returns `tmp` (RDNA2 ISA, DS). Emitted as an atomic AND with `~DATA`, whose result is `tmp`, then an atomic OR with `DATA2`, so the returned value is exact. DATA2 bits outside DATA are ORed in too, as the formula says; it isn't a masked insert. **Approximation:** the memory ends as the single op leaves it unless another lane's op on the same dword lands between the two atomics. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_mskor.py` (a value grid, the non-returning form, DATA2 outside DATA, `offset:`, seeded values). Measured on native gfx1100, including DATA2 bits outside DATA being ORed in, so it is not a masked insert. **Not GPU-verified.** | -| `ds_{inc,dec,rsub}_u32`, `ds_{min,max}_f32` (and `_rtn_`) | 32-bit LDS atomics lowered inside `Gen.lds_op` via a Workgroup-scope `OpAtomicCompareExchange` CAS loop (no shader float atomic extension needed): `ds_inc_u32` gives `(M >= DATA) ? 0 : M + 1` (unsigned), `ds_dec_u32` gives `(M == 0 || M > DATA) ? DATA : M - 1` (unsigned), `ds_rsub_u32` gives `DATA - M` (wrapping), and `ds_{min,max}_f32` use GLSL.std.450 `NMin`/`NMax` (NaN returns the non-NaN operand, `-0.0 < +0.0`, matching `global_atomic_fmin`/`fmax`). The `_rtn_` forms return the pre-op word in `vdst`; inactive lanes skip the op and preserve `vdst`. Source: AMD RDNA2 ISA DS encoding. CPU-checked by `tests/semantic/test_lds_atomics_cas.py` (edge value grids, NaN/±0/±inf, `offset:`, `vdst` aliasing, inactive lanes, sequential wraparound, Workgroup CAS loop structure, outside-compute and bad-operand rejections). **Not GPU-verified.** | +| `ds_mskor_b32`, `ds_mskor_rtn_b32` | `tmp = M[A]; M[A] = (tmp & ~DATA) \| DATA2`; the `_rtn_` form returns `tmp` (RDNA2 ISA, DS). Emitted as an atomic AND with `~DATA`, whose result is `tmp`, then an atomic OR with `DATA2`, so the returned value is exact. DATA2 bits outside DATA are ORed in too, as the formula says; it isn't a masked insert. **Approximation:** the memory ends as the single op leaves it unless another lane's op on the same dword lands between the two atomics. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_mskor.py` (a value grid, the non-returning form, DATA2 outside DATA, `offset:`, seeded values). Measured on native gfx1100, including DATA2 bits outside DATA being ORed in, so it is not a masked insert. **Not GPU-verified.** | +| `ds_{inc,dec,rsub}_u32`, `ds_{min,max}_f32` (and `_rtn_`) | 32-bit LDS atomics lowered inside `Gen.lds_op` via a Workgroup-scope `OpAtomicCompareExchange` CAS loop (no shader float atomic extension needed): `ds_inc_u32` gives `(M >= DATA) ? 0 : M + 1` (unsigned), `ds_dec_u32` gives `(M == 0 \|\| M > DATA) ? DATA : M - 1` (unsigned), `ds_rsub_u32` gives `DATA - M` (wrapping), and `ds_{min,max}_f32` use GLSL.std.450 `NMin`/`NMax` (NaN returns the non-NaN operand, `-0.0 < +0.0`, matching `global_atomic_fmin`/`fmax`). The `_rtn_` forms return the pre-op word in `vdst`; inactive lanes skip the op and preserve `vdst`. Source: AMD RDNA2 ISA DS encoding. CPU-checked by `tests/semantic/test_lds_atomics_cas.py` (edge value grids, NaN/±0/±inf, `offset:`, `vdst` aliasing, inactive lanes, sequential wraparound, Workgroup CAS loop structure, outside-compute and bad-operand rejections). Measured on native gfx1100 (single thread, 28 cases): `ds_inc_u32` gives `M + 1` until `M >= DATA` and 0 from there, `ds_dec_u32` gives `M - 1` or `DATA` when `M == 0` or `M > DATA`, `ds_rsub_u32` wraps, the `_rtn_` forms return the pre-op word, and `ds_{min,max}_f32` take the non-NaN operand and rank `-0.0` below `+0.0`. **Not GPU-verified.** | | `ds_wrxchg2_rtn_b32`, `ds_wrxchg2st64_rtn_b32` | Two atomic exchanges, addressed as `ds_write2_b32` addresses its dwords: `vaddr + offset0 * 4` and `vaddr + offset1 * 4` (times 64 for st64). `M[A0] = data0` and `M[A1] = data1`, and `vdst` (a VGPR pair) gets the two old words. Both exchanges run before either result is written, so `vdst` may alias the address or data VGPRs. When both offsets name one dword, the second exchange returns `data0`. Each exchange is atomic on its own, not the pair together, as on hardware (two DS operations). Until 2026-11-22 both ops raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg2.py` (offsets, st64 = 256-byte steps, the same dword twice, aliasing, a single-VGPR `vdst` rejected). Measured on native gfx1100: with `vaddr` 16 the offsets 0/4 read `vaddr + 0` and `vaddr + 16`, the `_st64_` form's offsets 1/2 read `vaddr + 256` and `vaddr + 512` (64 dwords per step), `vdst` takes the two old words, and with both offsets on one dword the second exchange returns `data0`; `vdst` may alias the address or the data pair, which still lands both data words in LDS and leaves the old words in `vdst`. **Not GPU-verified.** | | `ds_wrxchg_rtn_b64`, `ds_wrxchg2_rtn_b64`, `ds_wrxchg2st64_rtn_b64` | 64-bit LDS exchanges (two dwords, low first): `M[A] = DATA`, and `vdst` gets the old 64 bits. `wrxchg_rtn_b64` has one element at `vaddr + offset`. The `2` forms have two, at `vaddr + offset0/offset1 * 8` (times 64 for st64), as `ds_write2_b64` addresses them, and `vdst` is four VGPRs. Each dword is its own 32-bit `OpAtomicExchange`, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **Approximation:** two lanes exchanging into one element at once can tear it, leaving one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), which a 64-bit exchange never does; and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Until 2026-11-22 these three raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg_b64.py` (values, `offset:`, `vdst` aliasing the data, both 2 forms, st64 = 512-byte steps, bad operands rejected). Measured on native gfx1100: `M[vaddr]` takes the data pair and `vdst` gets the old pair, the `2` form's offsets 0/2 read `vaddr + 0` and `vaddr + 16` with four old dwords in `vdst`, and the `_st64_` form's offsets 1/2 read `vaddr + 512` and `vaddr + 1024` (64 pairs per step). **Not GPU-verified.** | | `ds_and_b64`, `ds_or_b64`, `ds_xor_b64` (and `_rtn_`) | `M = M op DATA` on the 64-bit LDS element at `vaddr + offset` (two dwords, low first); the `_rtn_` form returns the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so it is emitted as one 32-bit `OpAtomicAnd/Or/Xor` per dword. That leaves exactly the memory a 64-bit atomic would, without Int64 atomics on Workgroup memory (optional in Vulkan). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done; the memory result is exact. The other 64-bit LDS atomics (`add/sub/min/max_u64`, `wrxchg_b64`, `cmpst_b64`) carry between dwords or need the pair to move together, and still raise `Unsupported`. Until 2026-11-22 these three were rejected as well. CPU-checked by `tests/semantic/test_lds_bitwise_b64.py` (all six forms, offsets, `vdst` aliasing the data, seeded values). **Not GPU-verified.** Measured on native gfx1100 for all six forms, both dwords of each pair, with the returning forms giving the old pair. | @@ -354,69 +378,74 @@ How the generated SPIR-V expects the runtime to work: | Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. | | Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The synthetic translator tests check the four address registers and the RGBA32 format selection. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) | -| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. | AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. | +| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. \| AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. | | Half-precision coordinates for LOD queries | For `image_get_lod a16` on 2D and 2D-array images, the low and high halves of the first address VGPR supply U and V. The array layer is excluded from `OpImageQueryLod`; the selected clamped and raw LOD outputs are f32. `tests/semantic/fixtures/get_lod_a16.asm` assembles for gfx1030 and checks the query operands and output components through `tests/test_image_load_typed.py`. [AMD RDNA2 ISA, MIMG](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) | | Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off leaves memory alone: cmpswap is skipped, the others run with the operand that changes nothing. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (1) and the level count in VGPRs 0..3 (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). The translator still differs in the first three: it writes 1 for the 2D depth word and the full layer count for a 2D array, and `OpImageQuerySizeLod` past the last level is undefined. `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: resinfo's depth word on hardware (1 is what the T#'s DEPTH field says for a 2D image), the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. | | Hand-written short assembler forms | `llvm-mc` accepts `v_add_co_ci_u32 vD, src0, src1` (also `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with the carry out and in left to VCC, and a modifier list shorter than the operands (`op_sel_hi:[0,0]`, `neg_lo:[1,0]` on a three-source op), whose missing entries are 0; it prints them as `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo` and `[0,0,0]`. The GPU runner assembles through `llvm-mc -show-encoding`, so it sees the printed form; `tests/semantic/regen_fixtures.py` copies the `.asm` text as written, so the translator takes the source spelling too (it used to raise `IndexError` for these: the carry forms, `v_pk_fma_f16`, `v_fma_mix_*`). A probe of 42,000 operand and modifier variations of 302 ALU mnemonics, in the source spelling and as `llvm-mc` prints them, found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_short_asm_forms.py`. | | SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. A byte or word destination with PRESERVE reads its incoming VGPR on first use. The synthetic `sdwa_bary_input.asm` checks this with two raw fragment weights, following the [LLVM SDWA destination rules](https://llvm.org/docs/AMDGPUModifierSyntax.html#dst-unused). VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. **Measured natively on RDNA2** (gfx1036 iGPU, `tools/hw_oracle`, the game's MODE): all 172 distinct SDWA forms of the 26,503 listings (79,307 instructions: opcode, operand kinds, sels, `sext`, neg/abs, `dst_unused`, omod), 12 operand words per source, 21,204 cases. 18,885 give the translator's word. The rest are: a 16-bit result with `dst_sel:DWORD`, where the hardware zeroes the high half and the translator keeps it (1,888, #2187); a NaN result, where the hardware keeps the input's sign and payload (826 counting those also in the first group, as in the f16 transcendentals row); `div:2` on -0, which gives +0 (1, as in the output-modifier rows); and 160 cases whose translation is undefined in SPIR-V (`FClamp`/`FDiv`/`Sqrt` on NaN, zero or negative operands). `tests/semantic/test_alu_sdwa_hw.py` replays 624 of the matching words, up to four per form. | | VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). | | Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. When S2 is a literal or a currently known SGPR constant, the translator emits fixed byte extracts/inserts (including sign replication), folds the zero and 0xff bytes, and uses the selected source directly for a whole-word identity. `tests/semantic/test_perm_known_selector.py` checks the resulting words and that selector dispatch only remains for a clobbered SGPR. | -| Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ | S0 − S1\ | + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. | +| `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | The six remaining 32-bit MIMG image atomics on 2D (binding 4) and 3D (binding 7) `r32ui` storage images (including `a16` packed coordinates and optional `glc` return), guarded by `active_b` so inactive lanes skip memory access and preserve `vdata`. `image_atomic_swap` emits `OpAtomicExchange`; `inc`/`dec`/`fmin`/`fmax`/`fcmpswap` emit `OpAtomicLoad` (valid on `OpImageTexelPointer` `Image` pointers) followed by a Device-scope `OpAtomicCompareExchange` CAS loop (`inc`: `(M >= D) ? 0 : M + 1`; `dec`: `(M == 0 \|\| M > D) ? D : M - 1`; `fmin`/`fmax`: GLSL.std.450 `NMin`/`NMax`, no float-atomic extension required; `fcmpswap`: integer IEEE-754 binary32 ordered equality on raw 32-bit words — equal iff neither is NaN and `(cur == cmp) \|\| (both ±0.0)`, preserving subnormals even on Vulkan drivers reporting `shaderDenormPreserveFloat32 = false`, exiting without writing on mismatch or NaN; native RDNA2 subnormal behavior under denormal flush is unmeasured). Source: AMD RDNA2 ISA MIMG `IMAGE_ATOMIC_*`. CPU-checked structurally (including `spirv_mini_interp.check_structure` CFG validation) by `tests/semantic/test_image_atomics_32.py` (all 6 ops on 2D and 3D images, `a16`, `glc` and non-`glc`, no `AtomicFloat` capability, rejected widths/coords/dims). **Not GPU-verified on RDNA2.** | +| Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ \| S0 − S1\ \| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. | | Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `test_alu_qsad.py` and `test_alu_mqsad_u32.py`. | | `v_mqsad_u32_u8` | Four masked byte-SADs with full 32-bit accumulators: D[k] = S2[k] + `v_msad_u8` of the 32-bit window S0[8k+31:8k] of the 64-bit S0 against S1, wrapping at 32 bits (S2 and D are four VGPRs). Every source is read before the first write; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mqsad_u32.py`. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across 64-bit sliding window and masked byte values against the 32-bit accumulators: bit-exact with the ISA reference. **Not GPU-verified.** | | `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py (500 programs, --oracle translator,hw): 500 pass, 0 mismatches against the reference; confirmed s_flbit_i32 gives 0xFFFFFFFF for 0 and -1. | -| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across byte edge values and rounding bit variations: 0 mismatches against the ISA reference. | -| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination stays `Unsupported`, #210). `s_cmov_b64`: D[63:0] = SCC ? S0[63:0] : D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask stays `Unsupported` (#210). D[63:0], SCC read and not written, on plain 64-bit data pairs (SGPR pair, immediate or `null`); any dword that is or has been a lane mask (EXEC, VCC or a mask SGPR) makes the pair `Unsupported` — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask (#210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU [SOPInstructions.td](https://github.com/llvm/llvm-project/blob/2bfedf3338162e2c841a73cd7cd9e98d00add608/llvm/lib/Target/AMDGPU/SOPInstructions.td) (`S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`). CPU-checked by `tests/semantic/test_salu_cmov.py`, `tests/semantic/test_salu_cmov_b64.py` and `test_salu_pack.py`; **not GPU-verified, no corpus count**; the translated shaders were run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: **no corpus count**; GPU-checked for `s_cmov_b32` (`cs_w32_salu64.asm`, SCC = 1 selects S0) and `s_pack_lh_b32_b16` (`cs_w32_int_ext.asm`) on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92); `s_cmovk_i32`, `s_cmov_b64` and the other `s_pack_*` forms have no GPU test on main; the translated shaders were also run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Also **measured on RDNA2 gfx1036** (Radeon iGPU of a Ryzen 9 9950X3D, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher, rocm-sdk-core clang): `tools/int_hw_probe.py --oracle both --wave both` gives the same words as the translator for all five `salu_cmov_pack` cases in wave32 and wave64, and the 14 `s_cmov_b64` cases of the `salu_cmov_b64` group (`python -I tools/int_hw_probe.py --oracle both --wave both --group salu_cmov_b64`; SCC 0 and 1; source an SGPR pair, the inline constants -1, -16 and 64, the literal 0x89abcdef, `null`, and the destination itself; SCC preset and read back after) match the translator in wave32 and wave64: SCC = 1 takes S0 (a literal zero-extended, an inline constant sign-extended, `null` gives 0), SCC = 0 keeps D, SCC is never written. Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py: s_cmov_b32 verified under SCC=0 and SCC=1 (preserving destination and updating respectively); s_pack_ll/lh/hh_b32_b16 verified bit-exact on 500 random programs with 0 mismatches (--oracle translator,hw). **Not measured on RDNA2.** | +| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The translator uses the per-byte identity `x + y = 2*(x & y) + (x ^ y)`. It clears each byte's low bit before shifting, then adds the rounding bit only to an odd sum. Each result fits in one byte, so the packed additions do not carry across bytes. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. The synthetic `tests/semantic/fixtures/lerp_packed_bytes.asm` gives exact words across a 64x64 draw on an RTX 3070 (NVIDIA 591.86). Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across byte edge values and rounding bit variations: 0 mismatches against the ISA reference. | +| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination stays `Unsupported`, #210). `s_cmov_b64`: D[63:0] = SCC ? S0[63:0] : D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask (EXEC, VCC or a mask SGPR) stays `Unsupported` (#210) — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask. D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask stays `Unsupported` (#210). D[63:0], SCC read and not written, on plain 64-bit data pairs (SGPR pair, immediate or `null`); any dword that is or has been a lane mask (EXEC, VCC or a mask SGPR) makes the pair `Unsupported` — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask (#210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU `SOPInstructions.td` (`S_CMOV_B64 : RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU [SOPInstructions.td](https://github.com/llvm/llvm-project/blob/2bfedf3338162e2c841a73cd7cd9e98d00add608/llvm/lib/Target/AMDGPU/SOPInstructions.td) (`S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`). CPU-checked by `tests/semantic/test_salu_cmov.py`, `tests/semantic/test_salu_cmov_b64.py` and `test_salu_pack.py`; no corpus count; **not GPU-verified, no corpus count**; the translated shaders were run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: **no corpus count**; Hardware: on native `gfx1036` (Ryzen 9 9950X3D iGPU, Windows 11, driver 26.10.1) `tools/int_hw_probe.py --oracle both --wave both` matches the translator in wave32 and wave64 for all five `salu_cmov_pack` cases and for the 14 `s_cmov_b64` cases (`--group salu_cmov_b64`: GPU-checked for `s_cmov_b32` (`cs_w32_salu64.asm`, SCC = 1 selects S0) and `s_pack_lh_b32_b16` (`cs_w32_int_ext.asm`) on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92); `s_cmovk_i32`, `s_cmov_b64` and the other `s_pack_*` forms have no GPU test on main; the translated shaders were also run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept), and on native gfx1036 (AMD Radeon Graphics, Windows 11, driver 26.10.1) through `tools/hw_oracle`: all five `salu_cmov_pack` cases and the 14 `s_cmov_b64` cases match the translator in wave32 and wave64 (SCC 0 and 1; an SGPR pair, the inline constants -1/-16/64, the literal 0x89abcdef, `null` and the destination itself; SCC = 1 takes S0, 0 keeps D, SCC is never written), `s_cmov_b32` matches under SCC=0 and SCC=1, and `s_pack_ll/lh/hh_b32_b16` is bit-exact on 500 random programs with 0 mismatches (`--oracle translator,hw`). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Also **measured on RDNA2 gfx1036** (Radeon iGPU of a Ryzen 9 9950X3D, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher, rocm-sdk-core clang): `tools/int_hw_probe.py --oracle both --wave both` gives the same words as the translator for all five `salu_cmov_pack` cases in wave32 and wave64, and the 14 `s_cmov_b64` cases of the `salu_cmov_b64` group (`python -I tools/int_hw_probe.py --oracle both --wave both --group salu_cmov_b64`; SCC 0 and 1; source an SGPR pair, the inline constants -1, -16 and 64, the literal 0x89abcdef, `null`, and the destination itself; SCC preset and read back after): SCC preset and read back after) match the translator in wave32 and wave64: SCC = 1 takes S0 (a literal zero-extended, an inline constant sign-extended, `null` gives 0), SCC = 0 keeps D, SCC is never written. Also on `gfx1035` via `int_hw_probe` (SHADER-137, SCC kept), and on `gfx1036` and an RTX 5080 through the fixtures `cs_w32_salu64.asm` (`s_cmov_b32`) and `cs_w32_int_ext.asm` (`s_pack_lh_b32_b16`). `tools/hw_oracle` + `tools/salu_diff.py` verify `s_cmov_b32` under SCC 0/1 and `s_pack_ll/lh/hh_b32_b16` bit-exact on 500 random programs with 0 mismatches. Reviewers ran `s_cmov*` on an RTX 5090, an RTX 4050 and a Radeon 740M (#613) and `s_pack_*` on an RTX 5090 (#449). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py: s_cmov_b32 verified under SCC=0 and SCC=1 (preserving destination and updating respectively); s_pack_ll/lh/hh_b32_b16 verified bit-exact on 500 random programs with 0 mismatches (--oracle translator,hw). **Not measured on RDNA2.** | +| `v_bfi_b32` | `(S0 & S1) \| (~S0 & S2)` (RDNA2 ISA, VOP3 opcode 330). A literal or known same-block SGPR mask of zero or all ones selects S2 or S1 directly. A contiguous mask uses `OpBitFieldInsert` with S1 shifted down by the field offset, since RDNA2 reads the bits in place. For sparse constant masks the translator precomputes the complement. Runtime masks use the full bitwise expression. Checked by the hand-written `bfi_known_mask.asm` and `tests/semantic/test_bfi_known_mask.py`. | | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | | 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Not GPU-verified.** **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | | `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by `tests/test_int_hw_probe.py` (`ValuBfeMeasuredOnRdna2`). | | `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | -| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ | D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. | +| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| +| Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). | | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | -| Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). Not covered here: Not covered: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). | | Vector integer additions (`v_mul_hi_u32_u24`/`v_mul_hi_i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`) | `v_mul_hi_*24`: the high 32 bits of the 48-bit product of the low 24 bits, zero-extended (u24) or sign-extended from bit 23 (i24); the high halves of `v_mul_u32_u24` / `v_mul_i32_i24`. `v_lshrrev_b64` / `v_ashrrev_i64`: the pair (or a 64-bit constant) shifted right by S0 & 63, logically or arithmetically, through the `v_lshlrev_b64` code. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8`: D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31:8k] against S1) & 0xFFFF; the m form skips bytes where S1's byte is 0; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mul_hi_24.py`, `test_alu_shift_b64.py`, `test_alu_qsad.py`; run on NVIDIA by reviewers (`v_mul_hi_*24`: RTX 5090 and RTX 5070 in #440; `v_qsad`/`v_mqsad`: 24 cases bit-exact on an RTX 3060 in #623). **Not measured on RDNA2.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137), and on native `gfx1036` (AMD Radeon Graphics) with 0 mismatches across signed/unsigned products, shifts, and sliding windows. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | | 64-bit constant vector compares | For `i64`, `u64` and `f64`, V_CMP writes the predicate to VCC or the named scalar mask, with inactive lane bits cleared. V_CMPX ANDs the predicate into EXEC and preserves VCC. Both predicates ignore the source values, including NaNs. The 12 instructions in `tests/semantic/fixtures/vopc_constant_64.asm` assemble for gfx1030 and are CPU-checked with active and inactive lanes in `test_vopc_const_ordered.py`. [AMD RDNA 2 ISA, VOPC](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. All 16 f16 predicates (`v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16`, e32 and e64) are GPU-checked on quiet and signalling NaN, +-0, +-inf, denormals and junk high halves by `ps_vcmp_f16.asm` and `ps_vcmp_f16_e64.asm` (RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_vcmp_f16.py`. The 16 `v_cmpx_*_f16` forms (e32 and e64) are GPU-checked the same way by `ps_vcmpx_f16.asm` and `ps_vcmpx_f16_e64.asm` (EXEC result on every case, VCC kept, EXEC only narrowed; RTX 5080 and Radeon gfx1036), CPU side `tests/semantic/test_vcmpx_f16.py`. | -| Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \ | 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). | -| `v_swaprel_b32` | GFX10 VOP1 opcode 104: swap `VGPR[D + M0[25:16]]` and `VGPR[S0 + M0[9:0]]`, the two M0 fields `v_movrelsd_2_b32` uses; the other M0 bits are ignored (RDNA2 ISA opcode description). Both registers are read before either is written. When both name one register it keeps its value. Inactive lanes keep both registers (`OpSelect` on `active`). As for `v_movrel*`, the hardware's range check against the VGPR allocation is not modelled. A non-VGPR operand raises `Unsupported`. Until 2026-11-22 the op raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_swaprel.py` (both fields, ignored M0 bits, a self-swap, a register-file model). **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_swaprel`): M0[25:16] & M0[9:0] offsets, ignored upper M0 bits (`0xfc01fc02`), self-swap, and inactive EXEC lanes all match bit-for-bit. | +| Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \ \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). | +| `v_swaprel_b32` | GFX10 VOP1 opcode 104: swap `VGPR[D + M0[25:16]]` and `VGPR[S0 + M0[9:0]]`, the two M0 fields `v_movrelsd_2_b32` uses; the other M0 bits are ignored (RDNA2 ISA opcode description). Both registers are read before either is written. When both name one register it keeps its value. Inactive lanes keep both registers (`OpSelect` on `active`). As for `v_movrel*`, the hardware's range check against the VGPR allocation is not modelled. A non-VGPR operand raises `Unsupported`. Until 2026-11-22 the op raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_swaprel.py` (both fields, ignored M0 bits, a self-swap, a register-file model). **Not GPU-verified.** **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_swaprel`): M0[25:16] & M0[9:0] offsets, ignored upper M0 bits (`0xfc01fc02`), self-swap, and inactive EXEC lanes all match bit-for-bit. | | Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. An SGPR that `lane_masks.py` marks as a lane mask (a saved EXEC, a `v_cmp` result) holds only this lane's bit, so the whole wave's mask word is collected for each such SGPR (as for `s_bcnt1`) and read instead when the index lands on it; D then holds the mask as data (SHADER-284, CPU-checked by `tests/semantic/test_salu_movrels_lane_mask.py`, wave32 and wave64). **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept; lane-mask SGPR collection is CPU-checked only). **Not GPU-verified.** | | d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer ops (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`: to nearest even, except the typed-buffer float conversions, which round toward zero (below). AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). Packed MUBUF and MTBUF loads clamp unsigned 32-bit channels to 65535 before writing each half. On native gfx1036, values 65534 and 65535 survived, while 65536, 65537 and 0xffffffff all produced 0xffff, across all four load widths in wave32 and wave64. Packed `buffer_load_format_d16_x` and `_xyz` write only the low 16 bits of the final VGPR. Its upper half survives even when the load is out of bounds. Native gfx1036 wave32 and wave64 confirmed this with RGBA8_UINT and RGBA8_UNORM, two destination seeds, and both even-component loads as full-write controls. Full pairs are packed by `pack_f16_pair_int` and an odd final buffer component is narrowed with `f16_bits` for float/normalized formats. These memory conversions do not use `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). **Typed buffer floats are narrowed toward zero (SHADER-358).** Measured natively on gfx1036 (RDNA2, wave32 and wave64, `tools/hw_oracle`): `buffer_store_format_*` into `16_FLOAT`/`16_16_FLOAT`/`16_16_16_16_FLOAT` and `buffer_load_format_d16_*` from `32_FLOAT`/`32_32_FLOAT`/`32_32_32_32_FLOAT` round an f32 toward zero, give ±65504 for a finite value past the f16 range (65520 stores 0x7bff, not infinity), flush an f32 denormal to a signed zero, keep infinities, and keep a NaN's sign and top 10 payload bits without quieting it (1 if those are 0: 0x7fa00000 gives 0x7d00, 0x7f800001 gives 0x7c01); gfx1150 does the same for the stores (#1548). The translator does that with `Gen.mem_f16`; until 2026-11-22 it rounded these to nearest even and overflowed to infinity. UNORM/SNORM d16 loads keep the rounding above (nearest even of the exact quotient, re-measured on gfx1036 for every 8-bit value and a 16-bit sample). Checked by `tests/semantic/test_buffer_f16_narrowing_hw.py` (45 measured values in four forms). Image d16 results are still inferred to round to nearest even (SHADER-308). #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. For typed buffer loads the rounding is measured (BUILD-161, `tools/d16_format_probe.py`). On an RX 6700 (gfx1031, AMD Windows driver 32.0.21045.29003), every UNORM8, SNORM8, UNORM10, UNORM16 and SNORM16 value was loaded through `buffer_load_format_d16_x` and `tbuffer_load_format_d16_x`, in wave32 and wave64. The hardware rounds the exact quotient once, straight to f16, to nearest even, with f16 denormals kept (65,536 of 65,536 UNORM16 and SNORM16 values). It does not round to f32 first: that double rounding is 1 ulp high on exactly four values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009). Over every width from 1 to 16 bits, only two f32 quotients land on an f16 halfway point: 0x3f7ff000 (16379/16383, 32759/32767, 65519/65535) and 0x3f7fb000 (65455/65535). `Gen.d16_norm_f16` takes the f16 below for those two, for normalized formats only; a 32_FLOAT 0x3f7ff000 is a real tie and still rounds to even. `buffer_load_format_x` without d16 returned the correctly rounded f32 quotient for all of them, the decode `norm_bits` builds. A 16_FLOAT d16 load returned its own bits for all 65,536 encodings. MUBUF and MTBUF agreed everywhere. For d16 image results, round to nearest even is still inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). | -| `v_div_fixup_f16`, `v_div_fixup_f64` | Final IEEE-754 special-case fixup for division (VOP3, `S0` quotient, `S1` denominator, `S2` numerator): `sign_out = sign(S1) ^ sign(S2)`; `NaN(S2)` → quieted `S2`; `NaN(S1)` → quieted `S1`; `(0/0)` or `(±inf/±inf)` → canonical negative qNaN (`0xFE00` for f16, `0xFFF80000_00000000` for f64); `(x/±inf)`, `(±0/y)`, or guaranteed exponent underflow (`exp(S2) - exp(S1) <= -25` for f16, `<= -1075` for f64) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or guaranteed exponent overflow (`exp(S2) - exp(S1) >= 16` for f16, `>= 1024` for f64) → `±inf` with `sign_out`; otherwise `copysign(S0, sign_out)` (including `NaN(S0)` keeping its payload with `sign_out`). Computed bit-exactly on integer words (no `OpCapability Float64` for plain `v_div_fixup_f64`); VOP3 input modifiers (`abs`/`neg`, plus `op_sel:[s0,s1,s2,dst]` on f16 with the unwritten half preserved) and output modifiers (`mul:2`/`mul:4`/`div:2`/`clamp`, enabling `Float64` on f64) apply. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_DIV_FIXUP_F16`, `V_DIV_FIXUP_F64`). **Not measured on RDNA2 hardware** (translated GPU output checked on RTX 5070 by @duudiis). Checked bit-for-bit on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_div_fixup.py`; not run on the shader corpus. | +| `v_div_fixup_f16`, `v_div_fixup_f64` | Final IEEE-754 special-case fixup for division (VOP3, `S0` quotient, `S1` denominator, `S2` numerator) under the game's `MODE` (`ieee=0, denorm16_64=3, dx10_clamp=1`): `sign_out = sign(S1) ^ sign(S2)`; `NaN(S2)` → quieted `S2`; `NaN(S1)` → quieted `S1`; `NaN(S2)` → `S2` unchanged (sNaN not quieted under `IEEE=0`); `NaN(S1)` → `S1` unchanged; `(0/0)` or `(±inf/±inf)` → canonical negative qNaN (`0xFE00` for f16, `0xFFF80000_00000000` for f64); `(x/±inf)`, `(±0/y)`, or guaranteed exponent underflow (`exp(S2) - exp(S1) <= -25` for f16, `<= -1075` for f64) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or guaranteed exponent overflow (`exp(S2) - exp(S1) >= 16` for f16, `>= 1024` for f64) → `±inf` with `sign_out`; otherwise `copysign(S0, sign_out)` (including `NaN(S0)` keeping its payload with `sign_out`). `(x/±inf)` or `(±0/y)` (plus `exp(S2) - exp(S1) <= -1076` on f64 only; f16 has no exponent-difference cutoff) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or `NaN(S0)` → `±inf` with `sign_out` (no exponent-difference overflow cutoff on either f16 or f64); otherwise `copysign(S0, sign_out)`. Computed bit-exactly on integer words (no `OpCapability Float64` for plain `v_div_fixup_f64`); VOP3 input modifiers (`abs`/`neg`, plus `op_sel:[s0,s1,s2,dst]` on f16 with the unwritten half preserved) and output modifiers (`mul:2`/`mul:4`/`div:2`/`clamp`, enabling `Float64` on f64) apply. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_DIV_FIXUP_F16`, `V_DIV_FIXUP_F64`). **Not measured on RDNA2 hardware** (translated GPU output checked on RTX 5070 by @duudiis). **Hardware-measured on RDNA2** (`gfx1036`, Windows driver `32.0.21042.62`, `tools/hw_oracle`, `ieee=0, denorm16_64=3, dx10_clamp=1`, wave32, by @timelery): `NaN(S0)` → `±inf`, f16 has no exponent-difference underflow/overflow check, f64 has underflow cutoff `e2 - e1 <= -1076` with no overflow check, and sNaN passes through unchanged under `IEEE=0`. Checked bit-for-bit on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_div_fixup.py`; not run on the shader corpus. | +| Image instruction without a VGPR data operand | `llvm-mc` accepts `off`, an SGPR or a constant where an `image_*` instruction names the VGPR range of its result or data (`image_sample off, v[1:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D`); no compiler emits it (the texels would have nowhere to go). The translator raises `Unsupported` (` destination` for `image_op` and `image_get_lod`, ` data` for the `image_misc` group: `image_load_mip`, `image_get_resinfo`, `image_store`, the atomics) instead of the `KeyError` it gave when it wrote the result. A probe of about 60,000 DS, MUBUF, MTBUF, MIMG, SMEM and FLAT/GLOBAL/SCRATCH operand and modifier variations (glc, slc, dlc, lds, tfe, d16, a16, unorm, dmask, dim, offset, idxen, offen, addr64, format; as written and as `llvm-mc` prints them; pixel and compute stages) found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_mem_crash_forms.py`. | | Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | | `v_cvt_f16_u16`, `v_cvt_f16_i16`, `v_cvt_u16_f16`, `v_cvt_i16_f16` | Conversions of the low 16-bit half (`op_sel:[src,dst]` picks the high half of the source / of the destination in the VOP3 form where supported; GFX10 does not accept `op_sel` on these opcodes); the other half of the destination is kept, like the other 16-bit-result ops (see *16-bit results*). `v_cvt_f16_u16` / `v_cvt_f16_i16` convert the unsigned / sign-extended half and narrow with the usual f16 rounding (65520 and above give +infinity for the unsigned form). `v_cvt_u16_f16` / `v_cvt_i16_f16` truncate toward zero, saturate to [0, 65535] / [-32768, 32767] (an f16 infinity too) and give 0 for NaN, as the 32-bit conversions do (*Float-to-int saturation*). `clamp` and the output multipliers are rejected as `Unsupported` rather than guessed. Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode. Checked on the CPU by `tests/semantic/test_alu_cvt_16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all four `_e64` forms keep the high half of the destination, `v_cvt_u16/i16_f16` give 0 for ±qNaN and saturate ±inf, and `v_cvt_f16_u16(65520)` gives +inf (`0x7c00`). Not run on the shader corpus. | -| `v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16` | Normalized f16-to-16-bit integer conversions: `round_even(clamp(S0, -1, 1) * 32767)` (`i16`, snorm16) and `round_even(clamp(S0, 0, 1) * 65535)` (`u16`, unorm16), with NaN giving `0`, source `neg`/`abs` and SDWA `WORD_1` supported, and the unwritten half of the destination preserved (matching `v_cvt_i16_f16`/`v_cvt_u16_f16`; GFX10/LLVM does not accept VOP3 `op_sel` on these opcodes). For `\|cl\| >= 0.25`, `cl * (scale + 1)` is an exact even integer in f32, so `cl * (scale + 1) - RoundEven(cl)` rounds the exact product once without binary32 double-rounding ties near `±0.5`. `clamp` and output multipliers (`mul:*`/`div:*`) are rejected as `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_CVT_NORM_I16_F16`, `V_CVT_NORM_U16_F16`). **Hardware-verified on RDNA2** (AMD Radeon RDNA2 iGPU `gfx1036`, Windows 11, driver `32.0.21043.5001`, wave32 and wave64 via `tools/hw_oracle`, @Pierre-Kookis): 655,360 / 655,360 exact words across all 65,536 f16 inputs in five forms (`_e32`, `_e32 ieee=1`, `_e64 -v1`, `_e64 \|v1\|`, `_sdwa WORD_1`), including NaN → 0, ±inf clamps, denormals, single-rounding ties near ±0.5, and the untouched destination half. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py`; not run on the shader corpus. | +| `v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16` | Normalized f16-to-16-bit integer conversions: `round_even(clamp(S0, -1, 1) * 32767)` (`i16`, snorm16) and `round_even(clamp(S0, 0, 1) * 65535)` (`u16`, unorm16), with NaN giving `0`, source `neg`/`abs` and SDWA `WORD_1` supported, and the unwritten half of the destination preserved (matching `v_cvt_i16_f16`/`v_cvt_u16_f16`; GFX10/LLVM does not accept VOP3 `op_sel` on these opcodes). For `\|cl\| >= 0.25`, `cl * (scale + 1)` is an exact even integer in f32, so `cl * (scale + 1) - RoundEven(cl)` rounds the exact product once without binary32 double-rounding ties near `±0.5`. VOP3 `clamp`, `mul:2`, `mul:4`, `div:2` (and combinations) and SDWA `clamp` are hardware no-ops on these integer-destination conversions and are accepted without changing output semantics; unsupported modifiers or invalid form/modifier pairs (e.g., `mul:8`, `_sdwa mul:*`, `_e32`/`_dpp` output modifiers) still raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_CVT_NORM_I16_F16`, `V_CVT_NORM_U16_F16`). **Hardware-verified on RDNA2** (AMD Radeon RDNA2 iGPU `gfx1036`, Windows 11, driver `32.0.21043.5001`, wave32 and wave64 via `tools/hw_oracle`, @Pierre-Kookis): 655,360 / 655,360 exact words across all 65,536 f16 inputs in five forms (`_e32`, `_e32 ieee=1`, `_e64 -v1`, `_e64 \|v1\|`, `_sdwa WORD_1`), including NaN → 0, ±inf clamps, denormals, single-rounding ties near ±0.5, and the untouched destination half; **output modifiers additionally verified natively on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 and wave64 via `tools/cvt_norm_mods_probe.py --hw-arch gfx1036`): exhaustive 65,536/65,536 f16 sweeps across VOP3 `plain`, `clamp`, `mul:2`, `mul:4`, `div:2`, `clamp mul:2`, `clamp div:2`, plus `MODE.FP_ROUND=RTZ` (`0xCC`), `IEEE=1` (`0x2C0`), `_e64` high-half preservation, and `_sdwa clamp` (`WORD_0`/`WORD_1`, `UNUSED_PRESERVE`/`UNUSED_SEXT`/`UNUSED_PAD`) all match with 0 mismatches and 0 wave diffs (`1,050,708` total word evaluations across the four probe ops). **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 20 `v_cvt_norm_*` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py` and `tests/semantic/test_cvt_norm_mods.py`; not run on the shader corpus. | | `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Measured natively** on an RDNA2 iGPU (gfx1036, `tools/hw_oracle`): under the MODE inferred for the game (IEEE 0, f32 denormals flushed) the hardware gives the translator's word for all 30 special inputs of each frexp op and 741 ldexp cases (denormal inputs, results in and below the denormal range, every exponent clamp edge, NaN payloads). With f32 denormals kept the hardware normalizes denormal inputs and returns denormal ldexp results, and with IEEE 1 it quiets signalling NaNs; neither is modelled, since the game runs with both off. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. | | `v_mad_u16`, `v_mad_i16` | `D = S0 * S1 + S2` on the low 16-bit halves (VOP3 only). The product and sum are formed in 32 bits, so nothing overflows, and the low 16 bits are the result. `op_sel` bits 0..2 read the high half of a source and bit 3 writes the high half of the destination; like the other opsel-capable 16-bit VOP3 ops the other half of the destination is kept (see *16-bit results*). `clamp` saturates the full-width result to [0, 65535] (`v_mad_u16`) or [-32768, 32767] (`v_mad_i16`). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode and Mesa ACO's `can_use_opsel`. Checked on the CPU by `tests/semantic/test_alu_mad_u16_i16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): full-width `clamp`, `op_sel` and the untouched destination half match bit-for-bit. Not run on the shader corpus. | | `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | The binary16 versions of `v_frexp_mant_f32`, `v_frexp_exp_i32_f32` and `v_ldexp_f32`, computed on the f16 word of the low half with no float arithmetic (`op_sel` picks the high half of a source; the last `op_sel` bit sends the result to the high half of the destination; the other half of the destination is kept). A normal input has a biased exponent of 1..30. `v_frexp_mant_f16` returns the input with its exponent set to 14 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i16_f16` returns the biased exponent minus 14 as a 16-bit integer, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. Zero gives a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. f16 denormals are kept, as in the MODE inferred for the game (`denorm_mode_16_64` = 3): a denormal input is normalized (`v_frexp_mant_f16(0x0001)` = 0.5 with exponent -23, `0x03ff` gives `0x3bfe` and -14). `v_ldexp_f16` is S0 × 2^S1 with S1 the low 16 bits of the source read as a signed integer: S1 is clamped to [-64, 64] and added to the exponent field; a new field above 30 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. S1 is clamped to [-64, 64]; a result above the f16 range gives ±infinity, and one below the smallest normal is a denormal rounded to nearest even (1.0 × 2^-15 = `0x0200`, 1.5 × 2^-24 = `0x0002`, 1.0 × 2^-25 = 0, 65504 × 2^-30 rounds up to `0x0400`); zero, infinities and NaNs ignore S1. Source neg/abs apply to the float operand. `clamp` and the output multipliers are rejected as unsupported rather than guessed. VOP3 `clamp` clamps the FP16 result of `v_frexp_mant_f16` and `v_ldexp_f16` to [0.0, 1.0] (negative values and NaNs clamp to +0.0, values > 1.0 and +Inf clamp to 1.0, [0.0, 1.0] kept; hardware-verified on gfx1036 with 302 kernels across wave32 and wave64). Output multipliers and clamp on `v_frexp_exp_i16_f16` raise `Unsupported`. Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling, the NaN payload, and whether `v_frexp_exp_i16_f16` keeps the high half of its destination (it is modelled like the other 16-bit ops here, which keep it) are the translator's choice. **Measured natively** on an RDNA2 iGPU (gfx1036, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`) under IEEE 0, DX10_CLAMP 1, f32 denormals flushed and f16 denormals kept: the translated rule gives the hardware's word for every one of the 65,536 f16 inputs of both frexp ops and of `v_ldexp_f16` under 16 exponents (1,048,576 cases), and the high half of the destination is kept by all three. Until 2026-11-22 the translator read f16 denormals as zero and flushed denormal ldexp results, which the hardware does only with `denorm_mode_16_64` = 0. Not modelled (the game runs with IEEE 0): with IEEE 1 a signalling NaN is quieted (`0x7c01` gives `0x7e01`). Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp_f16.py`, which holds measured words (including VOP3 clamp); not run on the shader corpus. | | `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` | Binary64 versions of `v_frexp_mant_f32` and `v_frexp_exp_i32_f32`, computed bit-exactly on the `(lo, hi)` dword pair without requiring `OpCapability Float64` or `Int64` unless VOP3 output modifiers are used. A normal input has biased exponent `1..2046` (bits `[62:52]`): `v_frexp_mant_f64` sets the biased exponent to `1022` (`0x3FE00000`, mantissa in `[0.5, 1)` with sign and low mantissa bits kept), and `v_frexp_exp_i32_f64` returns `e - 1022` as a 32-bit signed integer so `mantissa × 2^exponent == input`. Under the default f16/f64 denormal mode (`denorm_mode_16_64` = 3, matching `v_frexp_mant_f16`/`v_frexp_exp_i16_f16`), non-zero subnormals (`e == 0`, 52-bit fraction `≠ 0`) are normalized into `[0.5, 1)` with sign preserved and exponent `msb − 1073` (`-1073..-1022`; e.g. `0x0000000000000001` → `0x3FE0000000000000` / `-1073`, `0x000FFFFFFFFFFFFF` → `0x3FEFFFFFFFFFFFFE` / `-1022`). Zero and denormals give signed zero and exponent `0`; infinities and NaNs pass through unchanged with exponent `0`. VOP3 source `abs`/`neg` flip/clear bit 31 of `hi`; VOP3 output modifiers (`mul:2`/`mul:4`/`div:2`, then `clamp`) apply to `v_frexp_mant_f64` via `clamp_mods_f64` (`OpCapability Float64`) and are rejected on `v_frexp_exp_i32_f64`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_FREXP_MANT_F64`, `V_FREXP_EXP_I32_F64`) and LLVM `VOP1Instructions.td`. **Measured natively** on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case): under `IEEE=0, denorm_mode_16_64=3, DX10_CLAMP=1` all 71 cases (all 52 single-bit subnormal positions `0..51`, lo/hi boundary-crossing multi-bit subnormals, negative subnormals, `±0`, normals, `±inf`, `qNaN`, `sNaN`, plus VOP3 `abs`/`neg`/`clamp`) matched bit-for-bit. Until 2026-11-22 the translator flushed binary64 subnormals to `±0` / exponent `0`, which the hardware does only under `denorm_mode_16_64=0`. Not modelled (the game runs with `IEEE=0, denorm_mode_16_64=3`): `IEEE=1` quieting signalling NaNs (`0x7FF0000000000001` → `0x7FF8000000000001`), `denorm_mode_16_64=0` flushing subnormals, and `denorm_mode_16_64=3` ignoring `omod`. **Not measured on hardware** (denormal input handling and NaN payload follow the f32 rule). Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_f64.py`; not run on the shader corpus. | | `v_min3_f16`, `v_max3_f16`, `v_min3_i16`, `v_min3_u16`, `v_max3_i16`, `v_max3_u16`, `v_med3_i16`, `v_med3_u16` | Three-operand 16-bit min/max/median (VOP3 only). `op_sel` bits 0..2 read the high half of S0..S2, bit 3 writes the high half of D, and the unwritten half of D is kept (see *16-bit results*). `v_min3_f16` and `v_max3_f16` read each selected f16 half through `Gen.f16_in` (`neg`/`abs` apply to the selected half), fold with `NMin`/`NMax` (so a NaN operand yields the other operand and −0 orders below +0, matching `v_min3_f32`/`v_max3_f32` and `v_med3_f16`), then apply VOP3 `omod`/`clamp` and `Gen.f16_out`. The 16-bit integer ops zero-extend (`u16`) or sign-extend (`i16`) the selected 16-bit halves, evaluate `UMin`/`UMax`/`UClamp` or `SMin`/`SMax`/`SClamp`, and write the low 16 bits into the selected half of D; `clamp` is supported on integer min3/max3/med3 as an identity no-op on the 16-bit container (hardware-verified on gfx1036 across wave32 and wave64); non-VGPR `op_sel` destinations raise `Unsupported`. `clamp` and non-VGPR `op_sel` destinations raise `Unsupported`. Until 2026-11-22 all eight raised `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) VOP3 opcodes `0x351`–`0x356`, `0x359`–`0x35A`, and Mesa ACO's `can_use_opsel`. **Hardware-verified on RDNA2** (gfx1036 iGPU, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`, IEEE 0 with f16 denormals kept): 6,092 cases (every triple of ±0, a denormal, 1.0, -1.0, 2.0, ±inf, a quiet and a signalling NaN for each f16 op; every triple of 8 edge values for the i16/u16 ops; `op_sel` on each source and the destination; a 0xabcd high half on every source) give the translator's word, the kept destination half included, except one: with all three operands NaN the hardware returns src0's NaN bits unchanged (`0x7c01` stays a signalling NaN under IEEE 0), the translator a quiet NaN, as for the 32-bit ops (*Float min/max/med3 with NaN*). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words, and `ALL_NAN_SRC0_SIGNALLING` there holds the 8 all-NaN min3/max3 rows with a signalling src0 (an `expectedFailure` until the translator keeps src0's bits). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words. **Not GPU-verified.** CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`. CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`; also **hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_min3_max3_med3_16`): all eight ops (`op_sel`, untouched destination half, NaN, −0/+0 ordering, and `v_max3_f16` `clamp`) match bit-for-bit. | | `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. `sat_i32(floor(S0))` and exact `sat_i32(floor(S0 + 0.5))` (computed via `f = Floor(x); (x - f >= 0.5) ? f + 1 : f`, with no binary32 rounding of `S0 + 0.5`: `0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`). Out-of-range values (±2³¹ and beyond, ±inf) and NaNs all saturate by the sign bit of the operand (`+NaN` → `0x7FFFFFFF`, `-NaN` → `0x80000000`, unlike `v_cvt_i32_f32` which returns `0` for NaN); the sign is read from `x` before `Floor` so driver NaN canonicalization cannot flip it. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. **Until 2026-11-22 the translator rounded `S0 + 0.5` in binary32 and returned `0` for NaN.** Hardware-verified natively on RDNA2 (AMD Radeon 680M `gfx1035`: 82/82 wave32 and 82/82 wave64 via `tools/hw_oracle`, plus `gfx1036` confirmation in #1746) and CPU-checked by `tests/semantic/test_alu_cvt_flr_rpi.py`. | -| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does: **measured** on an RDNA2 iGPU (gfx1036, SHADER-339), 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept (`tools/pknorm_probe.py --oracle hw`). **The rounding differs:** the hardware rounds the exact product x · 32767 (or 65535) once, while the translator rounds the f32 `OpFMul` product and then `RoundEven`, so it is one off where the f32 product lands exactly on k + 0.5 (28 of 28 such near-tie inputs, both directions; `docs/shader_validation.md`, "`v_cvt_pknorm_*` NaN and rounding on RDNA2"). On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Not fixed here. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. `clamp` raises `Unsupported`. Until 2026-11-22 both ops were rejected. **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg) and `tests/test_pknorm_probe.py`. **Not checked through Vulkan on a GPU.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): ±qNaN → 0, ±inf saturation, and round-to-nearest-even ties at ±0.5 match bit-for-bit (the near-tie rounding above is a separate case). **Not GPU-verified.** | -| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). | +| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does: **measured** on an RDNA2 iGPU (gfx1036, SHADER-339), 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept (`tools/pknorm_probe.py --oracle hw`). **The rounding differs:** the hardware rounds the exact product x · 32767 (or 65535) once, while the translator rounds the f32 `OpFMul` product and then `RoundEven`, so it is one off where the f32 product lands exactly on k + 0.5 (28 of 28 such near-tie inputs, both directions; `docs/shader_validation.md`, "`v_cvt_pknorm_*` NaN and rounding on RDNA2"). On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Not fixed here. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. VOP3 `clamp` is a hardware no-op on RDNA2 and is accepted without changing the result; other modifiers (`mul:*`/`div:*`, `op_sel:*`) raise `Unsupported`. `clamp` raises `Unsupported`. Until 2026-11-22 both ops were rejected. CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg). **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; additionally, `tools/cvt_norm_mods_probe.py --hw-arch gfx1036` verified `plain` vs VOP3 `clamp` across 40 edge/near-tie/NaN/±inf/subnormal pairs + 3 source-modifier cases across 6 `HW_REG_MODE` configurations and wave32/wave64 on `gfx1036` driver `32.0.21045.29003`: 2,064/2,064 words exact with 0 clamp diffs and 0 wave diffs). CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg, `clamp`), `tests/semantic/test_cvt_norm_mods.py`, and `tests/test_pknorm_probe.py`. **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 8 `v_cvt_pknorm_*` plain & `clamp` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. **Not checked through Vulkan on a GPU.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): ±qNaN → 0, ±inf saturation, and round-to-nearest-even ties at ±0.5 match bit-for-bit (the near-tie rounding above is a separate case). **Not GPU-verified.** | +| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). It depends on the driver: `ps_sdwa_f16_const` failed this way on `main` with NVIDIA 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99 (RTX 5090, Linux) and 580.173 (RTX 3060 Ti, Linux), and passed with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop) (#3220). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). | +| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` | VOP3 packed normalized conversion from two f16 sources (`D[15:0]` from `S0.f16`, `D[31:16]` from `S1.f16`): each selected f16 half (`op_sel[0..1]`, with `neg`/`abs` source modifiers and inline f16 constants via `Gen.f16_in`) is clamped to `[-1, 1]` (`i16`) or `[0, 1]` (`u16`), scaled by `32767` or `65535`, and rounded once to nearest even (`NaN → 0`). Uses `cl * (scale + 1) - RoundEven(cl)` for `\|cl\| >= 0.25` to avoid binary32 double-rounding at near-tie f16 inputs (e.g. `0x3801` = `0.5 + 2^-11`). Output modifiers (`clamp`, `mul:*`, `div:*`), `op_sel` destination bit, and VOP3P modifiers raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOP3 `v_cvt_pknorm_i16_f16` / `v_cvt_pknorm_u16_f16`) and LLVM AMDGPU `VOP3Instructions.td`. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py`; **not GPU-verified** and not run on the shader corpus. | | `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions in `test_scalar_noop_waitcnt.py` check both modes in one shader. | | f16 narrowing size | `Gen.f16_bits` leaves out or shares steps where that can't change the result. In nearest-even mode there is no separate infinity select: infinity is already at or above the overflow threshold (65520), which gives 0x7C00. For `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_pk_add_f16` without omod (`exact_tiny`), the range below 2^-14 is neither rounded nor tested for underflow: a sum of two f16 values is a multiple of 2^-24, so there it is already an f16 value, and clamp keeps that true. With an omod the rounding stays, since `div:2` can create a tie. No range has an underflow test: below 2^-25 the shift is 25, which moves the mantissa (plus the rounding bias) out to 0. The subnormal range rounds like the normal one, by adding half - 1 + the kept low bit before the shift. When the program writes MODE, `Gen.f16_res` makes one pass: toward zero selects a bias of 0, the 65536 overflow threshold and 0x7BFF, and keeps the infinity select. Confirmed by running the emitted integer sequences before and after on all 2^32 f32 inputs (both roundings) and on all 2^32 f16 operand pairs (both roundings, with and without clamp): no difference. Regression test: `tests/semantic/test_f16_sum_narrowing.py`. | -| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` | VOP3 packed normalized conversion from two f16 sources (`D[15:0]` from `S0.f16`, `D[31:16]` from `S1.f16`): each selected f16 half (`op_sel[0..1]`, with `neg`/`abs` source modifiers and inline f16 constants via `Gen.f16_in`) is clamped to `[-1, 1]` (`i16`) or `[0, 1]` (`u16`), scaled by `32767` or `65535`, and rounded once to nearest even (`NaN → 0`). Uses `cl * (scale + 1) - RoundEven(cl)` for `|cl| >= 0.25` to avoid binary32 double-rounding at near-tie f16 inputs (e.g. `0x3801` = `0.5 + 2^-11`). Output modifiers (`clamp`, `mul:*`, `div:*`), `op_sel` destination bit, and VOP3P modifiers raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOP3 `v_cvt_pknorm_i16_f16` / `v_cvt_pknorm_u16_f16`) and LLVM AMDGPU `VOP3Instructions.td`. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py`; **not GPU-verified** and not run on the shader corpus. | | `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator narrows the f32 sum) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Still unverified:** what the SPI writes into LDS for a packed channel in a real draw (P10/P20 as f32 differences of the raw words, or per-half f16 differences under `FP16_INTERP_MODE`), which needs a pixel-shader harness; also f16 inf/NaN halves and `p1lv_f16`. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | -| 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 29 − 2N and high halves at 30 − 2N, below MoltenVK's 31 locations (124 components); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(29 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. **Unverified:** devices with fewer than 124 vertex output components. **Unverified:** devices with fewer than 31 output locations. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2· **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 124 vertex output components. Not combined with `--bary-fallback`'s geometry shader. | F | <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Not combined with `--bary-fallback`'s geometry shader. | +| 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 29 − 2N and high halves at 30 − 2N, below MoltenVK's 31 locations (124 components); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(29 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. **Unverified:** devices with fewer than 124 vertex output components. **Unverified:** devices with fewer than 31 output locations. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2· **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 124 vertex output components. Not combined with `--bary-fallback`'s geometry shader. \| F \| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Not combined with `--bary-fallback`'s geometry shader. | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | | `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. | -| 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. **Measured natively on RDNA2** (gfx1036, AMD Ryzen 7000 iGPU, driver 26.11.2) across wave32 and wave64: `v_cmp` writes 0 for inactive lanes in `sdst` (`s4` in wave32, `s[4:5]` in wave64); `v_cmpx` kills inactive lanes in EXEC; inline float constants (`1.0`, `-2.0`, `0.5`, `4.0`) read f16 in low half with `op_sel=0` and +0.0 with `op_sel=1`; inline integer constants (`1`, `-1`) read low half with `op_sel=0` and high half with `op_sel=1` (`0` for `1`, `0xFFFF` for `-1`); 32-bit literals read `[15:0]` (`op_sel=0`) and `[31:16]` (`op_sel=1`, including signed negative high halves in `i16`); SGPR high halves as src0 and src1 with modifiers (`neg`, `abs`); and f16 ordered vs unordered relations on `qNaN`/`sNaN`. Probed natively with zero divergences by `tools/probe_gfx1036_vcmp16.py`, and checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations, spirv-val compliance, wave32/wave64 EXEC updates and inactive-lane 0 writes in `sdst`). Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); **not GPU-verified**. | +| 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Measured (TEST-650) with `tools/vcmp16_opsel_probe.py --oracle hw`, which writes `v_cmp_{lt,eq,gt}_{f16,u16,i16}_e64` as raw words with OPSEL set by hand in word 0 [12:11]: llvm-mc rejects `op_sel` on these compares and drops the bits when disassembling, so no listing carries it. On an RDNA2 iGPU (gfx1036), with the Windows HIP launcher (AMD 26.10.1) and independently with the Linux DRM launcher (#3329), all 50 rows read the low halves in wave32 and wave64, including the 20 where the selected halves would answer differently (f16 with and without `neg`, u16, sign-extended i16). The same hand-set bits on `v_add_nc_u16_e64` do select the high halves, so the encoding is right. The translator still honours `op_sel` here (from the ISA text and Mesa ACO `can_use_opsel`), which only a hand-encoded word can reach: #3487, which made it read the low halves as TEST-650 measured, was reverted because the constant, literal and SGPR-high-half checks below (row 403, measured natively) expect `op_sel` to select; the two measurements disagree and are open. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. **Measured natively on RDNA2** (gfx1036, AMD Ryzen 7000 iGPU, driver 26.11.2) across wave32 and wave64: `v_cmp` writes 0 for inactive lanes in `sdst` (`s4` in wave32, `s[4:5]` in wave64); `v_cmpx` kills inactive lanes in EXEC; inline float constants (`1.0`, `-2.0`, `0.5`, `4.0`) read f16 in low half with `op_sel=0` and +0.0 with `op_sel=1`; inline integer constants (`1`, `-1`) read low half with `op_sel=0` and high half with `op_sel=1` (`0` for `1`, `0xFFFF` for `-1`); 32-bit literals read `[15:0]` (`op_sel=0`) and `[31:16]` (`op_sel=1`, including signed negative high halves in `i16`); SGPR high halves as src0 and src1 with modifiers (`neg`, `abs`); and f16 ordered vs unordered relations on `qNaN`/`sNaN`. Probed natively with zero divergences by `tools/probe_gfx1036_vcmp16.py`, and checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations, spirv-val compliance, wave32/wave64 EXEC updates and inactive-lane 0 writes in `sdst`). Not measured: `v_cmpx`, `abs`, RDNA1. **not GPU-verified**. | | `v_cmp_class_f16`, `v_cmpx_class_f16`, `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 floating-point class tests against the 10-bit class mask (`0: sNaN, 1: qNaN, 2: -inf, 3: -normal, 4: -denormal, 5: -0, 6: +0, 7: +denormal, 8: +normal, 9: +inf`), writing VCC/SGPR or narrowing EXEC (`v_cmpx`). Computed bit-exactly on integer words (so `sNaN` is never quieted by float ops and `v_cmp(x)_class_f64` does not require `OpCapability Float64`): `f16` reads the selected half (`op_sel[0]`, inline f16 constants via `src_h`) and applies `abs`/`neg` on bits `[15:0]`; `f64` reads the `(lo, hi)` pair (32-bit literals placed in the upper word with `lo = 0` per RDNA2 ISA) and applies `abs`/`neg` on `hi`. Output modifiers (`clamp`, `mul:*`, `div:*`) and unsupported `op_sel` bits raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOPC `V_CMP_CLASS_F16/F64`, `V_CMPX_CLASS_F16/F64`). Checked bit-for-bit across all 10 classes on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cmp_class_f16_f64.py`; **not GPU-verified** and not run on the shader corpus. | | Float-to-byte pack | `v_cvt_pk_u8_f32` rounds to nearest even (the default MODE round mode; the hardware follows the MODE register's f32 round mode, which the translator ignores, see #358), clamps to [0, 255], and gives 0 for NaN and negative values, then inserts the byte at `src1[1:0]` of `src2` and keeps the other three. NaN is replaced by +0 before `FClamp`, which is undefined for a NaN operand. **Measured natively** on RDNA2 (gfx1036, the Ryzen 7 9800X3D iGPU, AMD driver 25.10, the instruction run through inline assembly): all 256 inputs k + 0.5 round to even, 0.5 gives 0, 0x3f000001 gives 1, +inf and 300.0 give 255, -inf, -1.0, ±0, denormals and quiet, signalling and negative NaNs give 0 (#358). `cs_cvt_pk_u8.asm` holds eight of these words, checked by `check.py`/`run_gpu_tests.py` and bit-for-bit by `tests/semantic/test_cvt_pk_u8.py`. | -| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (below; `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); the translator does that in both modes through `Gen.fma_mix_odd`; the ALU ones follow a MODE toward-zero write (below; `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); toward zero the translator does that already, while in nearest-even mode it still narrows an f32 `Fma`, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036, finding 7079901079; an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( | a x*y | >= < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each, see the f16 transcendentals row; independently confirmed by an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, as `Gen.fma_mix_odd` produces (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"). In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | b | `, `FastTwoSum`: `bb = r - a`, `e = b - bb`) and steps back one ulp when the rounding error shows it rounded away from zero; finite overflow gives the largest finite value (unordered `TwoSum` `r - x` can overflow to `±inf` and yield `NaN` error for opposite-sign finite operands with ` | x | < | y | ` near `±DBL_MAX`, e.g. `0x7fdd9bb47daa1333 + 0xffefffffffffffff` found by `@Jolymmiles`; GPU-checked with `runtime/test/shaders/ps_f64_round.asm` on NVIDIA GeForce RTX 5060 Ti, 4096/4096 pixels exact). The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( | x*y | < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | -| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits ` | x | < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and (via `Gen.flush_f32_mods`) both before and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). **Measured natively on RDNA1** (`AMD Radeon RX 5600 XT`, `gfx1010`, Windows driver `32.0.21045.29003`, `tools/mad_denorm_probe.py --oracle hw`, SHADER-340): 48 of 48 cases match in wave32 and wave64 across `game` (`IEEE=0`, `denorm32=0`), `dx10_clamp=0` and `denorm32=3` (`v_mul_f32(FLT_MIN, 0.5)` confirms `denorm32=3` keeps subnormals on the GPU while the mad/mac ops still flush them), and all 40 non-`omod` cases match under `IEEE=1` (where hardware ignores `mul:2`/`mul:4`/`div:2` as for other f32 VALU ops). Before SHADER-340 the translator ran `flush_f32` only after `clamp_mods`, which gave `FLT_MIN` (`0x00800000`) instead of `+0` (`0x00000000`) on `(1.5*2^-126 - 2^-126) mul:2` (and `0x01000000` on `mul:4`), whereas hardware flushes the sum before `omod` (`+0`) as well as after (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, pre- and post-`omod` cases, NaN/inf/zero pass-through, and a sabotaged pass-through that fails) and `tests/test_mad_denorm_probe.py`. **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | -| 16-bit high-half reads (`Gen.u16_half` / `Gen.i16_half`, #1506) | Reading the high 16 bits of a 32-bit word emits `OpShiftRightLogical %uint u 16` (`u16_half`) or `OpShiftRightArithmetic %int (as_int(u)) 16` (`i16_half`) alone, without a trailing `OpBitwiseAnd ... 0xFFFF` or `OpBitFieldSExtract ... 0 16` (used for the low half only). On 32-bit inputs `>> 16` already zero- or sign-extends bits 31..16, and AMD's Windows LLPC compiler (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24 on Ryzen 5 7600 iGPU) miscompiles both `(u >> 16) & 0xFFFF` and `OpBitFieldSExtract (u >> 16) 0 16` after two partial-half writes to `u` by dropping the `>> 16` when the result feeds `OpIAdd`, `OpIMul`, or `OpShiftLeftLogical` (e.g. `(0x41b1 << 1) & 0xFFFF` became `0x0000` instead of `0x8362` in `cs_f16fuzz_s2_163_w64`, `s_bitreplicate`'s `((0x41b1 << 8) | 0x41b1) & 0x00ff00ff` became `0xb10000` instead of `0x4100b1`, and `SExtract(0x91b1138b >> 16, 0, 16) + 1` became `0x91b10001` instead of `0xffff91b2`). Applies across all 16-bit half readers (`v_*_b16`/`u16`/`i16`, `v_mad_{u,i}16`, `v_min3/max3/med3_{u,i}16`, `v_cvt_f16_{u,i}16`, `v_pack_b32_f16`, `v_frexp_*_f16`, `v_ldexp_f16`, `s_bitreplicate_b64_b32`, and `buffer_store_format_d16_*`). Checked by `tests/test_u16_high_half.py` and `tools/valu_fuzz.py --family f16 --seed 2 --programs 200 --wave both` on AMD Ryzen 5 7600 iGPU (driver 24.10.24: 400/400 native, up from 399/400; 200/200 wave64 emulated on both AMD and NVIDIA). | +| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (see the f16 rounding row). `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); the translator does that in both modes through `Gen.fma_mix_odd`; the ALU ones follow a MODE toward-zero write (below; `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); toward zero the translator does that already, while in nearest-even mode it still narrows an f32 `Fma`, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036, finding 7079901079; an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| a x*y \| >= < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each, see the f16 transcendentals row; independently confirmed by an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, as `Gen.fma_mix_odd` produces (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"). In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). \| b \| `, `FastTwoSum`: `bb = r - a`, `e = b - bb`) and steps back one ulp when the rounding error shows it rounded away from zero; finite overflow gives the largest finite value (unordered `TwoSum` `r - x` can overflow to `±inf` and yield `NaN` error for opposite-sign finite operands with ` \| x \| < \| y \| ` near `±DBL_MAX`, e.g. `0x7fdd9bb47daa1333 + 0xffefffffffffffff` found by `@Jolymmiles`; GPU-checked with `runtime/test/shaders/ps_f64_round.asm` on NVIDIA GeForce RTX 5060 Ti, 4096/4096 pixels exact). The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| x*y \| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | +| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits ` \| x \| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and (via `Gen.flush_f32_mods`) both before and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). **Measured natively on RDNA1** (`AMD Radeon RX 5600 XT`, `gfx1010`, Windows driver `32.0.21045.29003`, `tools/mad_denorm_probe.py --oracle hw`, SHADER-340): 48 of 48 cases match in wave32 and wave64 across `game` (`IEEE=0`, `denorm32=0`), `dx10_clamp=0` and `denorm32=3` (`v_mul_f32(FLT_MIN, 0.5)` confirms `denorm32=3` keeps subnormals on the GPU while the mad/mac ops still flush them), and all 40 non-`omod` cases match under `IEEE=1` (where hardware ignores `mul:2`/`mul:4`/`div:2` as for other f32 VALU ops). Before SHADER-340 the translator ran `flush_f32` only after `clamp_mods`, which gave `FLT_MIN` (`0x00800000`) instead of `+0` (`0x00000000`) on `(1.5*2^-126 - 2^-126) mul:2` (and `0x01000000` on `mul:4`), whereas hardware flushes the sum before `omod` (`+0`) as well as after (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, pre- and post-`omod` cases, NaN/inf/zero pass-through, and a sabotaged pass-through that fails) and `tests/test_mad_denorm_probe.py`. **not GPU-verified** — a native measurement still needs an RDNA1 part (gfx1010-gfx1013): no RDNA2 part has these opcodes, and on gfx103x the encodings of `v_mad_legacy_f32` (VOP3 0x140) and `v_mac_legacy_f32` (VOP2 0x06) are the fused `v_fma_legacy_f32` / `v_fmac_legacy_f32`, so a raw-encoding run on the gfx1036 oracle would measure a different instruction (see the GFX10.1/GFX10.3 opcode row). **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | +| 16-bit high-half reads (`Gen.u16_half` / `Gen.i16_half`, #1506) | Reading the high 16 bits of a 32-bit word emits `OpShiftRightLogical %uint u 16` (`u16_half`) or `OpShiftRightArithmetic %int (as_int(u)) 16` (`i16_half`) alone, without a trailing `OpBitwiseAnd ... 0xFFFF` or `OpBitFieldSExtract ... 0 16` (used for the low half only). On 32-bit inputs `>> 16` already zero- or sign-extends bits 31..16, and AMD's Windows LLPC compiler (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24 on Ryzen 5 7600 iGPU) miscompiles both `(u >> 16) & 0xFFFF` and `OpBitFieldSExtract (u >> 16) 0 16` after two partial-half writes to `u` by dropping the `>> 16` when the result feeds `OpIAdd`, `OpIMul`, or `OpShiftLeftLogical` (e.g. `(0x41b1 << 1) & 0xFFFF` became `0x0000` instead of `0x8362` in `cs_f16fuzz_s2_163_w64`, `s_bitreplicate`'s `((0x41b1 << 8) \| 0x41b1) & 0x00ff00ff` became `0xb10000` instead of `0x4100b1`, and `SExtract(0x91b1138b >> 16, 0, 16) + 1` became `0x91b10001` instead of `0xffff91b2`). Applies across all 16-bit half readers (`v_*_b16`/`u16`/`i16`, `v_mad_{u,i}16`, `v_min3/max3/med3_{u,i}16`, `v_cvt_f16_{u,i}16`, `v_pack_b32_f16`, `v_frexp_*_f16`, `v_ldexp_f16`, `s_bitreplicate_b64_b32`, and `buffer_store_format_d16_*`). Checked by `tests/test_u16_high_half.py` and `tools/valu_fuzz.py --family f16 --seed 2 --programs 200 --wave both` on AMD Ryzen 5 7600 iGPU (driver 24.10.24: 400/400 native, up from 399/400; 200/200 wave64 emulated on both AMD and NVIDIA). | | `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | -| `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** | -| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | -| `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. Each dword is its own 32-bit `OpAtomic*`, so no Int64 atomics are needed; a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** | -| Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried. `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave32; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. | -| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | -| Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | +| `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Measured on native gfx1100 (single thread, 116 cases): all 16 predicates return IEEE-754 results (`eq` on `NaN` is 0 while `neq`/`nlt`/`nge`/`ngt` are 1, `lg` is 0 for `NaN` with `o`/`u` splitting on it, `eq(+0.0, -0.0)` is 1, `inf` compares equal to itself) and `v_cmpx_*_f64` narrows `EXEC` instead of writing `VCC`. | +| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | +| `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. A bitwise op or an exchange leaves the same memory done one dword at a time, so each dword is its own 32-bit `OpAtomic*` and no Int64 atomics are needed. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. Each dword is its own 32-bit `OpAtomic*`, so no Int64 atomics are needed; a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** | +| Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. | +| GFX10.1 (console gfx1013) / GFX10.3 (gfx1030, gfx1036 oracle) opcode differences | Found by disassembling every opcode of every GFX10 encoding (SOP1/SOP2/SOPK/SOPC/SOPP, SMEM, VOP1/VOP2/VOPC/VOP3/VOP3P, DS, FLAT/GLOBAL/SCRATCH, MUBUF/MTBUF, MIMG) with LLVM 21 `llvm-mc` for `-mcpu=gfx1013` and for `gfx1030`/`gfx1036` (the two gfx103x lists are identical). Every other opcode slot decodes to the same mnemonic on both, so the hardware-oracle rows measured on gfx1036 are about the same instructions the console runs (the microarchitectures still differ, which no opcode table shows). **On gfx1013 only:** `v_mac_f32`/`v_mad_f32` (VOP2 0x1f, VOP3 0x11f/0x141) and `v_mac_legacy_f32`/`v_mad_legacy_f32` (VOP2 0x06, VOP3 0x106/0x140), translated (rows above; not measurable on gfx103x, where 0x06/0x106/0x140 are the fused `v_fmac_legacy_f32`/`v_fma_legacy_f32`); `v_mul_lo_i32` (VOP3 0x16b; `Unsupported` until #3504 translates it); `s_get_waveid_in_workgroup` (SMEM 0x2a), translated in compute and mesh shaders; scalar stores (`s_store_dword*`, `s_buffer_store_dword*`), scalar atomics (`s_atomic_*`, `s_buffer_atomic_*`, 32- and 64-bit), scalar scratch (`s_scratch_load/store_dword*`), `s_dcache_wb`, `s_dcache_discard(_x2)` and the 31 LDS `ds_*_src2_*` forms, all `Unsupported`. **On gfx103x only:** `v_dot2c_f32_f16`, `v_dot4c_i32_i8`, the VOP3P `v_dot2_f32_f16`, `v_dot2_i32_i16`/`u32_u16`, `v_dot4_i32_i8`/`u32_u8`, `v_dot8_i32_i4`/`u32_u4`, `v_fmac_legacy_f32`/`v_fma_legacy_f32`, `global_load/store_dword_addtid`, `global_atomic_csub`, `buffer_atomic_csub`. The console's code can't contain these; the translator handles the integer dot products (rows above, measured on gfx1036) and refuses the rest, so a listing disassembled for the wrong target (VOP2 0x06 printed as `v_fmac_legacy_f32`) fails loudly instead of being translated as a fused multiply-add. Not covered by the sweep: opcodes whose operand template did not decode on either target, and behaviour that differs without an opcode change. | +| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **RDNA1 (gfx1011, Navi 12) follows the same RDNA2/GFX11 column**: `tools/buffer_bounds_probe.py` ran 12 one-lane 4-byte `buffer_load_dword` cases at wave32 and wave64 through `tools/hw_oracle` (24 groups, 0 wave32/64 differences); all matched the measured column and 8 disagreed with Mesa's GFX10 column (SHADER-341, results in `docs/buffer_bounds.md`). **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | +| Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | | Null mask source | The scalar register `null` supplies zero when read as a lane mask. The wave64 fixture in `tests/semantic/fixtures/null_mask_source.asm` checks a high-bit test, a zero-bit count, a first-set-bit search and a masked vector write after `s_and_saveexec_b64`. LLVM 21.1.8 assembles each instruction for gfx1030. [LLVM GFX10 null operand](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#null) | | Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, `s_bfm_b64` bitfields, `_b64` copies of immediates into `vcc`, and `_b64` bitwise/select ops combining a lane mask or `vcc` destination with immediates; 32-bit mask + non-0/-1 immediate into an SGPR stays plain data, #1792). Split wave64 SGPR pairs whose two dwords hold separately written half-masks or a half-mask paired with a 0/-1 `EITHER` constant (`include_either=True`) are recognized by `holds_lane_mask` and read `s[r]` for lanes 0–31 and `s[r+1]` for lanes 32–63 in `mask_src`, and `--wave64-emulate`'s `x_mcache` keys `wave_mask` on every dword of an SGPR operand so rewriting `s[r+1]` invalidates a cached 64-bit exchange. `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, `s_bitcmp0/1_b32/b64`, and `v_mbcnt_lo/hi_u32_b32` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops (including `v_mbcnt_lo/hi_u32_b32` on `vcc_hi`/`vcc_lo`/`exec_lo` via `mask_half`) and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py`, `tests/semantic/test_scalar_alu_shifts.py`, `tests/semantic/test_loop_ballot_barrier.py`, and `tests/test_lane_masks.py` (split SGPR pairs, dual-dword `x_mcache`, `_b64` mask+imm, and `v_mbcnt` half selection CPU-checked, not yet GPU-verified). GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | -| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `|...|`, `-|...|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-|1.0|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `|0x...|` / `-|0x...|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). | +| 64-bit mask equality (SHADER-551) | `s_cmp_eq_u64` / `s_cmp_lg_u64` compare both exact 32-bit words and set a uniform SCC. Canonical full-wave masks (`exec`, mask-valued `vcc`, or a wave64 `MASK_LO`/`MASK_HI` SGPR pair) compared with another full mask or zero may use a whole-wave equality vote. Other SGPR pairs materialize each mask half separately and retain scalar data and constant words, including split, swapped, duplicated, mixed mask/data and wave32 pairs. Comparing with all ones also materializes words, so unlaunched lanes remain zero bits in partial waves. CPU-checked by `tests/semantic/test_scmp_u64_mask_pairs.py` with full and partial wave64, wave32, and wave64-emulation cases; independent synthetic Vulkan readback is reported in [PR #3007](https://github.com/ItsNotRexed/Leonida/pull/3007). No native RDNA2 instruction oracle was run for this rule. | +| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `\|...\|`, `-\|...\|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-\|1.0\|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `\|0x...\|` / `-\|0x...\|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). | | `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 binary64 numeric class test against the 10-bit mask (`0` sNaN, `1` qNaN, `2` `-inf`, `3` `-normal`, `4` `-subnormal`, `5` `-0`, `6` `+0`, `7` `+subnormal`, `8` `+normal`, `9` `+inf`), lowered in `Gen.cmp_class_f64` using pure 32-bit `%uint` bit extraction on `(lo, hi)` with no `Float64` capability required. Supports VGPR/SGPR pairs, float inline constants (`fimm`), sign-extended inline integers (`-16..64`), 32-bit literals placed in bits `[63:32]` (as on RDNA2), and VOP3 `abs`/`neg` sign-bit modifiers on `src0` (`abs` clears bit 63, `neg` flips bit 63 without quieting sNaN). Inactive lanes produce 0 for `v_cmp_class_f64` and stay inactive for `v_cmpx_class_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 `V_CMP_CLASS_F64` / `V_CMPX_CLASS_F64`. CPU-checked by `tests/semantic/test_cmp_class_f64.py` (all 10 classes with low- and high-word payload bits, mask combinations and high-bit ignores, SGPR pairs, `fimm`/inline/literal constants, `abs`/`neg`/`-\|x\|`, `v_cmpx_class_f64` EXEC narrowing, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** | | Mesh/compute input registers (historical measurement) | An early read-before-write analysis over all compute and mesh shaders found **compute** v0 (880), v0–v1 (614), v0–v2 (50), consistent with AMD's local thread ID x/y/z in v0/v1/v2, and scalar inputs centred on a pointer at s[4:5] and s6/s7. **Mesh:** every one of 2,969 reads exactly **v5**, plus s3 (always arithmetic), s[16:17] and s19–s23. The early pass also read FSSM 0x13C as the group width and compared the first SGPR multiply against it (82 match, 151 don't, 1,447 no simple multiply) and wrongly concluded that 0x13C was not the group width; the matching register varied by shader (s6/s10/s7/s9…). PSV0 gave the real thread-group sizes (32×1×1 for 1,253, 8×8×1 for 416, …). **Superseded:** 0x13C/0x140/0x144 are the thread-group size, `COMPUTE_PGM_RSRC2` at 0x138 gives the per-shader user-SGPR count and enabled workgroup IDs, and mesh takes NumThreads, limits and topology from PSV0 with `v5 = linearGroupIndex * NumThreads + LocalInvocationIndex`. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). | | Formerly untranslated | Mesh (9,282), geometry (195) and compute (2,689) now translate; `s_swappc_b64` is replaced by Vulkan vertex inputs (see *Vertex fetch*) and the `tbuffer_load_format_*` forms use the instruction's format. Packed `tbuffer_load_format_d16_{x,xy,xyz,xyzw}` load two 16-bit components per VGPR, with the same final partial write as MUBUF. Native gfx1036 wave32/64 confirmed all four widths for RGBA8_UINT and RGBA8_UNORM with a conflicting 32_UINT V# format. Both packed and ordinary MTBUF loads ignore the V# channel selectors and use identity for the instruction format, zero-filling missing channels. Native gfx1036 measurements compared multiple V# permutations with MUBUF as a control. An INVALID V# format (0) suppresses the MTBUF fetch even at a valid address inside its bounds. Native gfx1036 wave32/64 returned zero components at all four widths and preserved the untouched half of an odd D16 destination, as specified for unbound resources in the [RDNA2 ISA, §8.1.4](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). A translated vertex fetch on RTX 5080 and Radeon Graphics also followed a change to the instruction format between two draws with identical vertex records and V#. Fixed UNORM and SNORM loads share the exact integer quotient for each magnitude width across instructions and channels (checked against rationally rounded binary32 values on RTX 5080 and Radeon Graphics). The gfx1013 disassembler omits `format:` for the [GFX10 MTBUF default](https://llvm.org/docs/AMDGPUModifierSyntax.html#ufmt), `BUF_FMT_8_UNORM` (code 1). A few rare ops are still reported by name rather than guessed. | @@ -424,6 +453,7 @@ How the generated SPIR-V expects the runtime to work: | `v_dot2c_i32_i16`, `v_dot8c_i32_i4` | VOP2/VOP3 accumulating forms of `v_dot2_i32_i16` and `v_dot8_i32_i4` (`D = sum(S0.elem[k] * S1.elem[k]) + D`, signed 2×16-bit and 8×4-bit). Wraps at 32 bits by default and saturates to `[INT32_MIN, INT32_MAX]` with VOP3 `clamp` (sharing the `v_dot2_i32_i16`/`v_dot8_i32_i4` signed-carry path); `op_sel`, `neg`/`abs`, and DPP/SDWA are refused. Registered in read-before-write VGPR tracking alongside `v_dot4c_i32_i8`. Source: LLVM AMDGPU `VOP2Instructions.td` (`HasDot4Insts` / `HasDot3Insts`, `gfx908` VOP2/VOP3 syntax; not in the default `gfx1013`/`gfx103x` feature set). **Not measured on AMD hardware** (translated Vulkan lowering checked on RTX 5070 by @duudiis: 40,960/40,960 exact words across wave32 and emulated wave64). Checked bit-for-bit on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_dotc.py`; not run on the shader corpus. | | Out-of-bounds typed buffer loads and `DST_SEL=1` | When a MUBUF `buffer_load_format_{x,xy,xyz,xyzw}` or `buffer_load_format_d16_{x,xy,xyz,xyzw}` is out of bounds (`OOB_SELECT` 0–3, `num_records == 0`, partial-element spill, or swizzled OOB), memory is not accessed and raw data channels (`DST_SEL` 4..7) read 0, while the V# `DST_SEL` swizzle still runs: `DST_SEL=0` returns 0 and `DST_SEL=1` returns `1.0f` (`0x3F800000`, `d16` `0x3C00`) iff V# `FORMAT[6:0]` is a valid float, normalized or scaled buffer format (`1..77` ending in `_UNORM`, `_SNORM`, `_USCALED`, `_SSCALED`, or `_FLOAT`), and integer `1` (`0x00000001`, `d16` `0x0001`) for `UINT`/`SINT`, `INVALID` (`0`), and reserved codes (`78..127`). `d16_x` and `d16_xyz` preserve the unaddressed upper 16 bits of the final destination VGPR, and MTBUF `tbuffer_load_format_*` ignores V# `DST_SEL` on both out-of-bounds and `FORMAT=0` loads (returning 0 in addressed channels). Until 2026-11-22 `Gen.buffer_load_format` clamped the post-swizzle result to 0 when `in_b` was false (`SHADER-429`), dropping `DST_SEL=1` on out-of-bounds loads and returning `1.0f` instead of `1` for `DST_SEL=1` with `FORMAT=0`. **Hardware-verified on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21042.62`, wave32 and wave64, 746 kernels via `tools/hw_oracle`: all 41 `Gen.FORMATS` across `xyzw`/`d16_xyzw`/`d16_xyz`/`d16_x`, all 128 7-bit `FORMAT` codes `0..127` for both `f32` and `d16`, `OOB_SELECT` 0–3, partial spill, swizzled OOB, MTBUF controls, and inactive EXEC lanes), Vulkan GPU-checked across all 128 7-bit `FORMAT` codes (`xyzw`, `d16_xyzw`, `d16_xyz`, `d16_x`) and the `cs_fmt_*`/`cs_oob_*`/`cs_bounds`/`cs_buf_*` fixtures on NVIDIA GeForce RTX 5090 (driver `32.0.16.1088`) and AMD Radeon Graphics (`gfx1036`, driver `32.0.21042.62`), and CPU/`spirv-val`-checked by `tests/semantic/test_buffer_oob_dst_sel.py`. | | `v_div_fixup_f32` | Measured natively on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case: 256 seeded triples across 4 MODEs plus 73 targeted special-case/modifier rows, 0 mismatches). Computes `div_fixup_f32(S0=quotient, S1=denom, S2=numer)` with pure integer SPIR-V ops under the game's inferred MODE (`IEEE=0`, `denorm32=0`, `DX10_CLAMP=1`): VOP3 `abs` (clear bit 31) then `neg` (flip bit 31) apply bitwise to `S0`/`S1`/`S2` before classification (including NaN payloads); `S1`/`S2` subnormals flush to signed zero (`exp == 0`) while `S0` subnormals are preserved; priority order is (1) `NaN(S2) → S2`, (2) `NaN(S1) → S1` (signalling NaNs pass unchanged under `IEEE=0`, quieted only when `IEEE=1`), (3) `0/0` or `±inf/±inf → 0xFFC00000` (`-qNaN`), (4) `zero(S2) ∨ inf(S1) → ±0.0`, (5) `zero(S1) ∨ inf(S2) → ±inf`, (6) `exp(S2) − exp(S1) ≤ −151 → ±0.0` (pure biased-exponent check, beats `NaN(S0)` and `inf(S0)`; no overflow check), (7) `NaN(S0) → ±inf`, (8) `copysign(S0, sign(S1) ⊕ sign(S2))`. Output modifiers `mul:2`/`mul:4`/`div:2` apply before `clamp`, and `clamp` maps NaN to `+0.0` (`DX10_CLAMP=1`) before `FClamp` to `[0, 1]`. Not modelled: `IEEE=1` sNaN quieting, `denorm32=3` keeping `S1`/`S2` subnormals, and the hardware `omod` `-0 → +0` quirk (same as the other f32 ops). Checked bit-for-bit against 73 measured `gfx1036` words in `tests/semantic/test_alu_div_fixup_f32.py`. | +| Atomic natural alignment, 64-bit bounds, and `buffer_atomic_{fmin,fmax}` | Measured natively on RDNA2 (AMD Radeon(TM) Graphics, `gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle/`): **natural alignment** is enforced on every 32-bit and 64-bit buffer/global atomic (`buffer_atomic*`, `buffer_atomic*_x2`, `global_atomic*`, `global_atomic*_x2`), even under `OOB_SELECT = 2` (DISABLED). A 32-bit atomic requires `(addr & 3) == 0` (`offset = 1, 2` and `base + 2, offset = 0` are dropped; `base + 2, offset = 2` succeeds) and a 64-bit `_x2` atomic requires `(addr & 7) == 0` (`offset = 2, 4` and `base + 4, offset = 0` are dropped; `base + 4, offset = 4` succeeds). When dropped (OOB or unaligned), memory is untouched, an active `glc` lane receives `0` (32-bit) or `(0, 0)` (64-bit) in `vdst`/`vdata`, and an inactive lane (`EXEC = 0`) preserves `vdst`/`vdata`. Independently confirmed on a second `gfx1036` (driver `24.10.24`): without the alignment guard, an unaligned SPIR-V `OpAtomicAdd` corrupts the aligned dword (`100 -> 0xDEADBEF3`), whereas with the guard memory stays untouched and `0` is returned. `Gen.atomic_aligned` guards all six atomic emitters on `addr & 3 == 0` / `addr & 7 == 0`, merges `0` via `OpPhi` on skipped paths, and writes through `Gen.dst` so inactive lanes keep their prior register value while active unaligned/OOB lanes receive `0`. **64-bit partial bounds (`buffer_atomic*_x2`)**: the same `gfx1036` wave32/wave64 measurements confirm the all-or-nothing 8-byte bounds rule (`fixed_fmt = 62`) across all four `OOB_SELECT` modes (answering the unmeasured note in the `buffer_atomic_{and,or,xor,swap}_x2` row): mode 3 (RAW) requires `offs + 8 <= num_records` (`0/8` and `8/16` succeed; `0/7`, `0/5`, `0/4`, `8/15`, `8/12` drop cleanly); mode 0 (STRUCTURED_WITH_OFFSET) requires `idx < num_records` and `off + 8 <= stride` (`stride = 8, off = 0`, `stride = 16, off = 8`, `stride = 12, off = 0` succeed; `stride = 7, off = 0` and `stride = 12, off = 8` drop); mode 1 (STRUCTURED) checks `idx < num_records`; mode 2 (DISABLED) checks `num_records != 0`. **`buffer_atomic_{fmin,fmax}`**: lowered via `Gen.buffer_atomic_float` sharing `Gen._emit_atomic_fminmax_cas` (relaxed Device-scope `OpAtomicLoad` seed + `OpAtomicCompareExchange` + `GLSL.std.450` `NMin`/`NMax` CAS loop, no float-atomic extension required), enforcing V# bounds, 4-byte alignment, and `glc` return (`lds` and non-1-VGPR `vdata` raise `Unsupported`). On `gfx1036`, normal floats, `±inf`, `-0` vs `+0` (`fmin(-0, +0) = -0`, `fmax(-0, +0) = +0`), and `qNaN` (returns the non-NaN operand) match `NMin`/`NMax`; **known approximation**: the `gfx1036` L2 atomic unit quiets `sNaN` (`0x7f800001 -> 0x7fc00001`) regardless of `MODE`, while f32 subnormal handling follows the wave's `MODE.denorm32` and preserves sign (independently verified on a second `gfx1036`, wave32/wave64: under `denorm32 = 0`, subnormals flush to signed zero — `fmax(0x80000001, 0x80000002) -> 0x80000000 (-0)`, `fmax(0x00000001, 0x00000002) -> +0` — whereas under `denorm32 = 3`, subnormals are preserved and `NMin`/`NMax` is exact); `NMin`/`NMax` does not model `sNaN` quieting or `denorm32 = 0` subnormal flushing. CPU-checked by `tests/semantic/test_buffer_atomic_fminmax_and_align.py` (value grid, multi-lane CAS contention, OOB/partial-bounds matrix, inactive vs active-unaligned distinction across all six atomic families, and SPIR-V structural checks). | ### System values confirmed on the corpus (SHADER-4) @@ -498,6 +528,12 @@ Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 b last `s_endpgm`. Use `--mcpu gfx1013`. On 300 random shaders it decoded 284 cleanly (134 invalid words in total), against 201 clean and 6,560 invalid for gfx1030 and 283 clean for gfx1010–1012. +Some blobs end with a constant-data block after the real code: `s_endpgm`, a dword count N, N dwords of data, a +closing `s_endpgm`, then `s_code_end` padding. The data is not code, so the tool ends the range at the count +(`data_block_start`) and no longer reports those words as invalid. Over a 26,503-blob build, 1,473 blobs had such a +block (N from 0 up to several hundred); with the block excluded all 1,473 decode with no invalid word, and none of +the other 25,030 blobs matches the pattern. + ## Pixel-shader inputs `tools/fssm_header.py` decodes the FSSM input table: 8-byte records from 0x138 while the first byte is 6. diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md index 8e0766993..24f0b9971 100644 --- a/docs/embedded_shaders.md +++ b/docs/embedded_shaders.md @@ -82,6 +82,13 @@ order of section 3; `CopyAndCompactBVH` is #52, not the first): | #14-#29 | `BitonicPreSortCS`, `BitonicOuterSortCS`, `BitonicInnerSortCS`, `BitonicPreSort64CS`, `BitonicOuterSort64CS`, `BitonicInnerSort64CS`, `RadixReset`, `RadixCount`, `PrefixSum64`, `PrefixSum128`, `PrefixSum256`, `PrefixSum512`, `PrefixSum1024`, `PrefixSum2048`, `PrefixSum4096`, `RadixAlloc` | | #30-#46 | `RearrangeTriangles`, `RearrangeBVHs`, `LoadInstances`, `SplitInstances`, `LoadTriangles`, `LoadProceduralGeometry`, `ReloadTriangles`, `ReloadProcedurals`, `PT_ConstructBVH4`, `ConstructBVH4`, `RefitBVH4`, `BuildBVHSplits`, `BuildBVHSplits64`, `FindTreelets`, `ResetKDOP`, `BuildKDOP`, `BuildApexPointMap` | | #47-#53 | `GetBVHCompactedSize`, `DecompressHeader`, `LeafRehydration`, `Box16Rehydration`, `Box32Rehydration`, `CopyAndCompactBVH`, `GetBVHCompactedSize` (again) | +container is created twice: **`GetBVHCompactedSize`** (RT-182). With `LEONIDA_BVH_RECORD62=1` the test prints each +creation's container with its `ILDN` module name and the first bytes of its digest: creations 1 to 51 are 51 +distinct containers, `GetBVHCompactedSize` (5,284 bytes, 0x14a4) among them at 47; creation 52 is +`CopyAndCompactBVH` (4,404 bytes, 0x1134); creation 53 is `GetBVHCompactedSize` again, with the same digest and +size. So the 0x14a4-byte container `FUN_18001d400` passes for `XDXR PostBuildInfoQuery` is the +`GetBVHCompactedSize` module, and the PSO for it is created twice. Measured on 1.0.2.1 with an RTX 5080 (driver +621.01): all 53 creations return `S_OK`. ## 3. The 52 modules @@ -121,7 +128,7 @@ When this page was first written, 42 translated and 10 stopped at four rules. Th | `PT_LoadInstances` | `global_atomic_fmin` | translates | | `Box32Rehydration`, `ReloadTriangles` | `buffer_load_ushort` | translate | | `LeafRehydration` | `tbuffer_load_format_x GFX10_FORMAT_8_UINT` | translates | -| `Box16Rehydration` | `buffer_load_ushort` | stops at `buffer_store_short` (#1864, open) | +| `Box16Rehydration` | `buffer_load_ushort` | stops at `buffer_store_short` (#1864) | The disassembly count is unchanged: the same 42 programs have no invalid word, and 10 have invalid words in the code. All 10 of those translate; `Box16Rehydration` is one of the 42 clean ones. @@ -176,9 +183,43 @@ python -I tools/rdna2spirv.py /embedded/dxbc/disasm --out /embedded/ output. Which of them the game actually creates is a call-site question (RT-5). The module-to-pipeline order above comes from `ILDN`, not from a runtime trace. The `STAT` metadata-only shape is consistent with reflection, but whether the builder consumes it has not been measured. +* **They run on a GPU (TEST-594).** `tools/bvh_gpu_smoke.py` translates them from the package and runs each through + `vk_compute_test`. Each program reads its root arguments from a table at `s[0:1]`, the heap base there, which the + tool seeds with `VKC_HEAP_INIT`: every table word points past the table into zeros. **All 49 that aren't + rehydration programs pass**: exit 0, no Khronos validation error, and the same heap bytes on a second run (AMD + Radeon RX 9070, Windows 11, `--max-shared-memory 32768`, package 1.0.2.1). With these inputs only seven change any + heap word (`InitHeaders`, `InitPartitionedHeaders`, `LoadInstances`, `LoadProceduralGeometry`, `LoadTriangles`, + `PT_BeginPass`, `PT_WriteInstances`); the others leave early. So this alone shows that the translated programs + run cleanly, not that their output is right. **Six are checked byte for byte** (`--checked`), the ones whose effect + reads straight off their code. `RadixReset`, `ResetKDOP`, `ResetToIndexBuffer`, `CopyCounters` and + `ResetCounterValues` get their root-table fields (an output address, a count of 20, a value or a source), and the + tool compares all 20 entries they write and the bytes after them, which must stay untouched. `PrefixSum64` scans 64 + words in place into their exclusive prefix sum through five `ds_swizzle_b32` broadcast steps and stores the group's + total; the input wraps past 2^32. All six match exactly. Negative controls: with the translator made to skip + `v_add_nc_u32`, `ResetToIndexBuffer` fails (entries hold `base+4i` and zeros); with it skipping `ds_swizzle_b32`, + `PrefixSum64` fails from element 2 on. So the check sees a wrong translation. Two things found on the way: + * the wave64 bitonic sorts (`BitonicPreSort64CS`, `BitonicInnerSort64CS`) declare 32,780 bytes of workgroup memory + with the translator's default cap, 12 over the 32 KiB AMD's Windows driver allows + (`VUID-RuntimeSpirv-Workgroup-06530`). Their highest LDS offset is 8192, and `--max-shared-memory 32768` shrinks + the array to what they use; + * with every table word 0 instead, the descriptors point at the table itself, and `RadixCount` then writes into the + table that other waves are reading, so its output differs between runs. That is the test input, not the + translator; the tool's default avoids it. +* **What is still open.** The other programs' outputs (the sorts, prefix sums, builders, refit and loaders) are not + checked against a reference yet; the rehydration trio has one in TEST-376 (`tools/bvh_rehydrate.py`); `LeafRehydration` does not finish within 60 s with either table described + above. Which of them the game actually creates is a call-site question (RT-5). The module-to-pipeline order + above comes from `ILDN`, not from a runtime trace. The `STAT` bitcode and the `0x07 NOBC` record are not + explained. ## 6. Tool and tests +`tools/bvh_gpu_smoke.py --game-dir [--max-shared-memory N] [--checked] [--json report.json]` reproduces the +GPU run above: the extraction and translation of §4, then two dispatches per program, and with `--checked` the six +byte-exact cases. Its report holds module names, statuses +and counts only. `tests/test_bvh_gpu_smoke.py` checks the heap image, the word count and the judging of runs with a +fake `vk_compute_test`, and the checked cases' inputs and judging (a fake that does what each case describes passes, +one wrong byte fails), without a GPU or game files. + `tools/pe_shader_containers.py` is standard library only and reads the file, never runs it. It accepts a container only when the chunk table is sorted, 4-byte aligned, entirely inside the declared total and its last chunk ends exactly at that total; that is what rejects the FSR DLL's `DXBC` immediate. The synthetic tests in diff --git a/docs/first_light.md b/docs/first_light.md index 6f15a134e..654665c6c 100644 --- a/docs/first_light.md +++ b/docs/first_light.md @@ -1,7 +1,7 @@ -# First light: a real game model with its own translated shaders +# First light: a game model's UVs drawn with translated game shaders **Status: measured** on the 1.0.2.1 package and an NVIDIA RTX 2060 SUPER (driver 620.73.04, Vulkan 1.4.357, -CachyOS). This is the first draw of a real game model with its own translated VS and PS on a real GPU. The image +CachyOS). The fixture draws a model from the package with a vertex and pixel shader chosen to display its UVs. The image stays in the user's work folder; this note records the counts and the recipe, not the model, the shaders or a screenshot. @@ -21,6 +21,13 @@ The shaders are two ordinary containers from `shaders.rpf`, carved and translate | VS | `128867d3233a97ba5b203c313a24ab8a77df20c2a308091a5595bb9f669677f4` | forwards POSITION and TEXCOORD from the vertex fetch to clip space and a varying | | PS | `ed4147a5f7514947c2eb8d79255bd80f72761ac1ba2205dd811d3e050cf1b495` | writes the interpolated TEXCOORD as the colour; no bindings, no texture | +The model's authored shader assignment can be checked separately. In the model export manifest for the OBJ +above, `MeshShaders[0]` selects material slot 0, the only slot. Looking up its `Materials[0].Shader` in the +native shader database yields one effect with one technique and four compute-only passes. The VS and PS +in the table are the fixture's chosen pair. The model's use during gameplay remains unverified. +See the [effect lookup](https://github.com/ItsNotRexed/Leonida/pull/3036) and the +[Windows reproduction of the UV draw](https://github.com/ItsNotRexed/Leonida/pull/2893#issuecomment-7084947193). + Both disassemble with no invalid word, translate, and pass `spirv-val`; `tools/shader_link_check.py check` reports the pair compatible. At 128×128 the draw covers **12,804 of 16,384 pixels (0.781)** and the centre pixel is `(0.498, 0.496, 0.0, 1.0)`: the model is the disc its geometry projects to, and the colour is its own UV map. The @@ -71,6 +78,11 @@ indices), writes `manifest.json` with the counts and FSSM hashes, and runs `vk_h other names from the carve index; `--no-fit` keeps a model that is already in NDC (the sky dome is). The test is package-gated: without `LEONIDA_FIRST_LIGHT_DIR` it skips, and it writes its image to that folder. +Each run stages its pair in `/first_light/dxbc` and translates it into `/first_light/spirv`. Both folders +are removed at the start of a run, so they hold that run's two shaders and nothing an earlier run selected; do not +keep files there. The output folder (`first_light/out` or `--out`) and `/shaders` are not emptied. If either +folder is a symlink or a junction, or a file in it cannot be removed, the run stops and names it. + ## 4. The harness mode `runtime/test/vk_harness.cpp` gained two environment options, inert when unset (the existing three-vertex and diff --git a/docs/fssm_crosscheck.md b/docs/fssm_crosscheck.md index c3994a19f..cb87011cd 100644 --- a/docs/fssm_crosscheck.md +++ b/docs/fssm_crosscheck.md @@ -25,11 +25,17 @@ The short version: contain no numeric encodings apart from the standard VOP3 base-plus-offset convention. - SCARAB's family classifier is sound; its VOP1/VOP2/SOP1 **mnemonic tables and length model** are not. Leonida's `llvm-mc` path is the better decoder. +<<<<<<< HEAD - **Leonida bug found and fixed:** `xdat_entries` keyed by tag, so a container with two `0x0D` entries silently kept only the last. 195/26,503 containers have two distinct `XBCH` payloads. `xdat_entries_all` now preserves every entry in directory order, `xdat_entries` keeps the last-wins view for old callers, and `unpack(payload="first"|"last")` / `--payload` selects which one is written. The repro tests are in `tests/test_fssm_crosscheck.py`. +======= +- **Leonida bug found, since fixed:** `xdat_entries` kept only the last of a container's two + `0x0D` entries. 195/26,503 containers have two distinct `XBCH` payloads. #2479 added + `xdat_entries_all` and a `payload=` choice; `tests/test_fssm_crosscheck.py` pins both. +>>>>>>> origin/main ## 1. Container and unwrap @@ -42,7 +48,11 @@ The short version: | The unwrap is a full chain `.dxbc -> DXIL chunk -> XBCH -> zlib -> FSSM`. | `fssm_lib.fssm_from_dxbc()` | `fssm_unpack.unpack()` does the same, but selects the `XBCH` by XDAT tag and checks the decompressed length. SCARAB scans for `XBCH` (the extractor additionally requires version 3) and does not check the length. | **Equivalent in result, different in mechanism** | | A bare `FSSM` blob is accepted as input. | `fssm_to_rdna2.unwrap()` | `fssm_unpack.unpack()` accepts only `.dxbc`; the rest of Leonida (`shader_disasm.py`) accepts a bare `.fssm`. | **Minor input-form gap** | | `FSSM` magic is asserted after decompression. | `fssm_lib.fssm_from_dxbc()` | `fssm_unpack.unpack()` also rejects a payload that doesn't start with `FSSM` (`ValueError`, counted as a problem, nothing written). All 26,503 are `FSSM`, so there is no corpus failure. | **Verified** | +<<<<<<< HEAD | **Duplicate XDAT tag `0x0D`.** | `fssm_lib` / `fssm_to_rdna2` pick the **first** version-3 `XBCH` | `xdat_entries` is a dict, so the **last** tag-`0x0D` entry wins; `xdat_entries_all` exposes both in directory order and `unpack` selects first or last (`payload=`, `--payload`). 195/26,503 containers (all `$VS_*` VoxelizeGeneric) have **two different** tag-`0x0D` payloads; the two FSSM payloads differ in code size and content. | **Corrected — was a real Leonida bug, now fixed** | +======= +| **Duplicate XDAT tag `0x0D`.** | `fssm_lib` / `fssm_to_rdna2` pick the **first** version-3 `XBCH` | `xdat_entries` was a dict, so the **last** tag-`0x0D` entry won. 195/26,503 containers (all `$VS_*` VoxelizeGeneric) have **two different** tag-`0x0D` payloads; the two FSSM payloads differ in code size and content. Since #2479 `xdat_entries_all` returns every entry in directory order and `unpack(payload=…)` picks one; `xdat_entries` keeps the last-wins view for old callers. | **Corrected — real Leonida bug, fixed in #2479** | +>>>>>>> origin/main ### The duplicate-XBCH exception (the important one) @@ -65,6 +75,7 @@ In the measured pair the first is 3,679 bytes and starts with a GS/ES-like prolo instructions. The 24-byte descriptor at `code_off + 0x10` is identical in the measured pairs, so they belong to the same container record. +<<<<<<< HEAD Leonida writes the second (last) payload as `.fssm` by default; `unpack(payload="first")` and the CLI's `--payload first` select the first, matching SCARAB's scan-from-the-start choice. The two projects therefore extract **different payloads by default** for these containers. The @@ -73,6 +84,18 @@ authoritative mapping (which payload the game's pipeline uses) is not establishe Repro: `tests/test_fssm_crosscheck.py::DuplicateXbchTest` covers the fixed behaviour — `xdat_entries_all` returns both payloads in order, `xdat_entries` keeps the old last-wins view, and `unpack` selects `first` or `last`. +======= +Leonida writes the second payload as `.fssm` by default; `fssm_unpack.py --payload first` +writes the first instead, which is the one SCARAB takes when it scans from the start. The +default is unchanged, so the two projects still extract **different payloads** for these +containers unless that flag is passed. The authoritative mapping (which payload the game's +pipeline uses) is not established here. + +Covered by `tests/test_fssm_crosscheck.py::DuplicateXbchTest`: +`test_xdat_entries_all_preserves_both_payloads_in_order` pins the directory order, +`test_xdat_entries_keeps_the_last_payload_per_tag` the compatibility view, and +`test_unpack_selects_first_or_last_payload` the `payload=` choice. +>>>>>>> origin/main ## 2. FSSM header and code range @@ -104,6 +127,22 @@ Leonida's rule is `u32[0xC0] + 0x28` to the last `s_endpgm` (also `docs/design.m "Disassembling shaders"). The 17 `code_end = DEAD` blobs are handled because the last `s_endpgm` is used instead of `code_end`. +### Initial float mode (SHADER-190) + +The 1.0.2.1 scan tested 88 aligned little-endian words in each of the 26,503 indexed FSSM blobs as possible +packed `PGM_RSRC1` registers carrying `FLOAT_MODE`, `DX10_CLAMP` and `IEEE`. It covered 78 word starts at +FSSM offsets `0x00` through `0x134` and 10 at `code_off + 0x00` through `code_off + 0x24`, inclusive. + +The VGPR allocation field provides an independent check on that interpretation. Of 2,689 compute shaders, 1,675 +had zero reported invalid words and at least one explicit VGPR in the instruction listing. For each of these, +the minimum allocation must cover the highest numbered VGPR, including range endpoints. The tested capacity was +the low six bits of the candidate word plus one, multiplied by 8 for wave32 or 4 for wave64 (FSSM flag at +`0xD4`, bit 5). Graphics stages can share register allocations across merged stages and were excluded from this check. + +Of the 88 positions, 63 gave too little capacity for at least one qualifying compute shader. Each of the other 25 +exceeded the minimum whole-granule allocation in all 1,675. Over-allocation is possible, and the mode fields could +be stored separately or supplied by pipeline state. The initial float mode remains unresolved. + ## 3. ISA, RDNA2 classification and the "XBSC" notes | Claim | SCARAB source | Leonida behaviour / measurement | Verdict | @@ -128,9 +167,16 @@ Adopt: 1. **Keep `+0x28`.** Leonida already does. The regression test in `tests/test_fssm_crosscheck.py` pins it, including the `code_end = DEAD` case. +<<<<<<< HEAD 2. **Preserve duplicate XBCH payloads.** Done: `xdat_entries_all` keeps every entry in directory order, `xdat_entries` keeps the last-wins view for old callers, and `unpack(payload="first"|"last")` / `--payload` selects which payload is written. +======= +2. **Preserve duplicate XBCH payloads.** This is the one real Leonida bug found, and #2479 + did it: `xdat_entries_all` keeps every entry for a tag in directory order, + `unpack(payload="first"|"last")` and the CLI's `--payload` choose between them, and + `xdat_entries` keeps the last-wins view for old callers. +>>>>>>> origin/main 3. **Treat `0xDEADBEEFDEADBEEF` as an unset `code_end`** (and `meta_ptr`). If a future tool reads `0xE8`, it must fall back to `code_off + code_size` or the last `s_endpgm`. Leonida's last-`s_endpgm` rule already does this implicitly; document it. diff --git a/docs/gamedata.md b/docs/gamedata.md index dd91439d2..5aa880df4 100644 --- a/docs/gamedata.md +++ b/docs/gamedata.md @@ -257,6 +257,15 @@ fallback names match an item name or its joaat hash, and ten `prefix + x + y + s 2,112 tiles match nothing in three atlases and one hash in the fourth. The tile textures are therefore either outside the scanned archives or named another way; this is unresolved. +In the 1.0.2.1 exports, one content change set lists four grid metadata registrations and three candidate +archive paths as siblings. The list gives no per-grid archive assignment. The two fog grids share a tile +prefix, while the shore-wave and water-height grids each have a distinct prefix. A case-insensitive search +of the 30,516 other plain export blobs (30,520 total, excluding the four grid documents) found none of the +three prefixes or the grids' global or sector fallback names in ASCII or UTF-16LE. None of the three +archive filenames appeared as a loose file in the local package. The single catalog hash match above +remains uncorroborated. The tile payloads and the mapping from tile coordinates to archive entries remain +unverified. + A fifth grid uses the same base fields: one `TextureGridInfo` document has `origin`, `width`, `height`, `tileSize`, `streamRadius` and `zInflation`, plus a low- and a high-detail fallback name, but no sector overrides. It is 32,768 x 32,768 units with the same 512 tile, so **64 x 64 tiles**, the same 512 stream @@ -925,6 +934,9 @@ Four representative roots in the world/navigation/map category (826,397 B across - `InteriorNames/Item` × 1,358, holding `2,280` nested `` records with `{Name, Pos}`. Their 2,280 3D positions span `x = -9,673.0..4,705.3`, `y = -7,308.0..8,589.9`, `z = -78.0..820.9` — 100% inside the world bounds of the `PAMH` heightmap and `GridAtlasInfo` grids above. + span `x = -9,673.0..4,705.3`, `y = -7,308.0..8,589.9`, `z = -78.0..820.9` — their 2D `x`/`y` coordinates fall 100% + inside the `x`/`y` extent of the `PAMH` heightmap (`-13,312..5,120`, `-9,728..11,264`) and `GridAtlasInfo` grids + above, while `z` reaches `820.9` (above the `PAMH` `404` m ceiling). - `RoadNames/Item` × 409 (`Name` on all 409) and `RiverNames/Item` × 66. - **`PathingStyleData` (1 document, 5,993 B, 1 stream):** `StyleProfiles/Item` × 12 (`key=`), each defining `CurvatureStyle`, `CorneringStyle`, `ApproachStyle`, `ContinuityStyle`, `SlowdownStyle`, `SplineConfig`, and diff --git a/docs/gameinput.md b/docs/gameinput.md index fa216a2ee..90e0a3d2e 100644 --- a/docs/gameinput.md +++ b/docs/gameinput.md @@ -8,7 +8,12 @@ the lightbar colour can be set. Without the shim the loader would bind `GameInputCreate` to the host's `GameInput.dll` if there is one ([#279](https://github.com/ItsNotRexed/Leonida/pull/279)). That works for Xbox pads only, and gives no DualSense -features. The game executable is not available yet, so whether it imports GameInput this way, and under which +features. That path is tested without the game: `gameinput_host_test` (ctest `gameinput_host`) maps a synthetic DLL +built against the SDK's `gameinput.lib` and checks that its `GameInput.dll` import binds to the host's copy, that +`GameInputCreate` and `GetCurrentTimestamp` work from mapped code, and that `GetCurrentReading` answers; with a pad +attached, `GetGamepadState` must succeed on the reading. It passes on Windows 11 build 26300 (GameInput 0.2309) without +a pad attached. The test skips only where Windows cannot load `GameInput.dll`; with the DLL present, an import that binds to nothing fails it. The game executable is not available yet, +so whether it imports GameInput this way, and under which module, is unverified (see [VERIFY](#verify)). ## Building @@ -240,6 +245,39 @@ sensors are enabled when the pad is opened, at SDL's requested rate, and every p reading history cap bound the cost. - `gameinput_probe` prints the accel and gyro fractions when the pad has sensors (a resting pad shows ~0.5 g). +## Active input + +The title is told that every pad is an Xbox One pad, so it cannot know what the player is holding. The shim keeps +that record itself, for the runtime's own use, such as button prompt glyphs that follow the device in use: +`rt::gameinput::active_input()` returns the family of the device used last, a generation that goes up by one with each +change, and whether `LEONIDA_PROMPTS` forced it. It needs no lock and can be read from any thread, every frame. + +| SDL gamepad type | family | +|---|---| +| `PS5` (DualSense, DualSense Edge) | PlayStation 5 | +| `PS4` (DualShock 4) | PlayStation 4 | +| `PS3` (DualShock 3) | PlayStation 3 | +| `NINTENDO_SWITCH_PRO`, the Joy-Con types | Nintendo | +| the [keyboard pad](#keyboard-pad) | keyboard and mouse | +| everything else (Xbox One/Series, Xbox 360, generic, unknown) | Xbox | + +SDL takes the type from the pad's vendor and product id. Only deliberate input changes the answer +(`runtime/src/active_input.h`, tested by `active_input_test` without SDL): + +- an edge: a button going down (any of SDL's, the DualSense touchpad included), a trigger rising past 0.3, or a stick + leaving a radius of 0.35. A held button, trigger or stick, stick drift inside the radius and analog noise never + count. The mouse moves the keyboard pad's right stick, so a real mouse movement counts through the same rule and a + jitter of a count or two does not; +- a pad's first reading after it connects is its baseline, so connecting a pad with a button held, or with a worn + stick resting past the radius, changes nothing; +- after a change, the next one waits `LEONIDA_PROMPTS_SWITCH_MS` (300 ms by default). Input from another family inside + that time is ignored, not queued, so two devices used at once cannot make the answer flicker; +- input from a second device of the family already in use changes nothing. + +Before the first deliberate input the answer is Xbox. Each change logs one line, for example +`input in use: PlayStation 5 (DualSense Wireless Controller, button press)`. `LEONIDA_PROMPTS` forces a family (a +line is logged when it takes effect); tracking goes on underneath, so clearing it returns at once to the device in use. + ## Environment variables | variable | default | effect | @@ -249,6 +287,8 @@ sensors are enabled when the pad is opened, at SDL's requested rate, and every p | `LEONIDA_DS_TRIGGER_FREQ` | `30` | vibration frequency of the `rumble` mode, 1..255 | | `LEONIDA_DS_LIGHTBAR` | unset | `RRGGBB` (hex) sets the DualSense/DualShock 4 lightbar when the pad connects; `off` turns it dark; unset keeps SDL's player colour | | `LEONIDA_RUMBLE` | `1` | `0` turns all rumble, trigger and force-feedback output off | +| `LEONIDA_PROMPTS` | `auto` | forces the [active input](#active-input) family: `xbox`, `playstation` (or `ps5`), `ps4`, `ps3`, `nintendo` or `keyboard`; `auto` follows the devices | +| `LEONIDA_PROMPTS_SWITCH_MS` | `300` | shortest time between two changes of the active input family, 0..2000 ms | | `LEONIDA_GAMEINPUT_THREAD` | `1` | `0` stops the background poll thread; only `rt::gameinput::poll()` then reads the pads (tests) | | `LEONIDA_KEYBOARD_PAD` | `off` | `1` adds the [keyboard pad](#keyboard-pad), read while this process has focus; `always` reads keys whatever has focus | | `LEONIDA_MOUSE_SENSITIVITY` | `1` | scales how far the mouse moves the keyboard pad's right stick, 0.1..10 | @@ -276,6 +316,8 @@ The API surface: | `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state, raw report (pads opened through HID, see [Raw HID](#raw-hid)) | keyboard, mouse, touch, arcade/flight stick, racing wheel (all return nothing) | | `IGameInputDevice` | device info, status, battery, `SetRumbleState`, force-feedback motors with `CreateForceFeedbackEffect`/`IGameInputForceFeedbackEffect`, `IsForceFeedbackMotorPoweredOn`, `SetForceFeedbackMotorGain`, haptic trigger motors with `SetHapticMotorState`, `CreateRawDeviceReport`, `GetRawDeviceFeature`, `SetRawDeviceFeature`, `SendRawDeviceOutput` (pads opened through HID) | `SendRawDeviceOutputWithResponse`, `ExecuteRawDeviceIoControl`, exclusive raw access, power off, input synchronization (no-ops) | | `IGameInputRawDeviceReport` | device, report info (kind, id, size), raw data size, get and set raw data | item values (`Get/Set/ResetItemValue`, `ResetAllItems` answer false: no item tables) | +| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state | raw report, keyboard, mouse, touch, arcade/flight stick, racing wheel (all return nothing) | +| `IGameInputDevice` | device info, status, battery, `SetRumbleState`, force-feedback motors with `CreateForceFeedbackEffect`/`IGameInputForceFeedbackEffect`, `IsForceFeedbackMotorPoweredOn`, `SetForceFeedbackMotorGain`, haptic trigger motors with `SetHapticMotorState` | raw device I/O, power off, input synchronization (no-ops) | | `IGameInputDispatcher` | `Dispatch` (with its quota), `OpenWaitHandle` | | `CreateAggregateDevice` takes exactly one of the keyboard, mouse, gamepad, arcade stick, flight stick or racing wheel @@ -391,6 +433,12 @@ rests on a transcription rather than on a side-by-side compile. ## Tests +- `active_input_test` (CTest, no SDL): the [active input](#active-input) tracker's rules on synthetic samples with + its own clock. `gameinput_test` runs them on a DualSense, a DualShock 4 (Sony `054c:09cc`), an Xbox pad and the + keyboard pad: no change when pads connect (one with a button held) or a held button is let go, each family by a + button, the touchpad, a trigger or a stick, stick drift and a one-count mouse jitter ignored, a real mouse movement + counted, the 300 ms window on the real clock, and `LEONIDA_PROMPTS` forcing, changing, ignoring an unknown value + and clearing. - `gameinput_test` (CTest, no controller): turns SDL's real backends off and drives the shim through `rt::shims::find` with SDL virtual joysticks, an Xbox-style pad with trigger motors, a DualSense (Sony `054c:0ce6`) and a pad without trigger motors. It checks enumeration and device callbacks, the button, stick, @@ -446,6 +494,9 @@ These need the game executable or a test on hardware: `GameInputMotionAccuracyUnknown`; whether a title wants a synthesised quaternion there is unknown. - **Device family**: every pad is reported as `GameInputFamilyXboxOne`; a title that filters on family sees only that. +- **Active input behind Steam Input**: when Steam turns a PlayStation pad into a virtual Xbox pad, SDL may report the + virtual one's type, and the active input then says Xbox; `LEONIDA_PROMPTS` is the way round it until that is + checked on a real setup. - **Identical pads at start**: twins are numbered in the order the shim opens them. For pads already connected when it starts, that is SDL's enumeration order, not measured on Windows for identical pads; if it varies between runs, so does which pad gets which id. diff --git a/docs/gbuffer.md b/docs/gbuffer.md index e8a3347df..eae783c60 100644 --- a/docs/gbuffer.md +++ b/docs/gbuffer.md @@ -4,6 +4,8 @@ Reported by @Silliana in [#1891](https://github.com/ItsNotRexed/Leonida/issues/1 checked here across all **2,989 `*Deferred*` pixel shaders** (and all **1,703 six-target pixel shaders**) in the 1.0.2.1 `shaders.rpf` corpus. Counts, target masks, numeric constants and format requirements only; no shader text or disassembly. +checked here across the `*Deferred*` pixel shaders and six-output pixel shaders in the 1.0.2.1 `shaders.rpf` corpus. +Counts, target masks, numeric constants and format requirements only; no shader text or disassembly. ## 1. Corpus census of deferred pixel-shader output signatures (`OSG1` / `PSV0`) @@ -41,6 +43,45 @@ Confirming #1891 against the 5-target (`mrt0..mrt4`) and 6-target (`mrt0..mrt5`) | `mrt5` (`SV_Target5`) | `0xF` (`RGBA`, 1,690 deferred PS) | `R8G8B8A8_UNORM` | **Sixth deferred target** on the 6-target permutations (`rgb` material terms + clamped alpha). | ## 3. The 24-bit octahedral normal in `mrt1.gba` and why binding `f16` targets breaks lighting +semantic_index, component_type, mask, min_precision}` per declared output element. (The FSSM header dword at `+0x0FC` +holds `5` and `6` on the two sampled `PS_DeferredTextured` blobs below, but holds `16` and `18` on two stock vehicle +deferred passes, so target counts must be read from `OSG1` rather than FSSM `+0x0FC`.) + +Depending on whether container names are matched case-insensitively on raw RPF entry names (`2,989` pixel shaders) or +case-sensitively on `Deferred` in the carved `.dxbc` file stems (`3,004` pixel shaders, including `807` +`PS_DeferredTextured` variants: 380 five-target, 371 six-target and 56 three-target): + +| `OSG1` outputs declared | `*Deferred*` PS (entry match / `.dxbc` stem match) | `PS_DeferredTextured` count | Corpus-wide PS (entry / `.dxbc` stem) | `OSG1` component type on all colour targets | Per-target `OSG1` write masks (`SV_Target0..N-1`) | +|---|---:|---:|---:|---|---| +| 6 colour (`SV_Target0..5`) | 953 / 949 | 371 | 955 / 955 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3, 0xF` (`SV_Target4` mask is 2-component `RG`) | +| 6 colour (`SV_Target0..5`) | 737 / 735 | 0 | 747 / 747 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF, 0xF` (all six `RGBA`) | +| 5 colour + `SV_Depth` | 0 / 0 | 0 | 1 / 0 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` + `SV_Depth` (`0x1`) | +| 5 colour (`SV_Target0..4`) | 1,160 / 1,160 | 380 | 1,168 / 1,166 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` (`SV_Target4` mask is 2-component `RG`) | +| 5 colour (`SV_Target0..4`) | 2 / 2 | 0 | 20 / 20 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF` | +| 3 colour (`SV_Target0..2`) | 125 / 125 | 56 | 248 / 248 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0x3` (`SV_Target2` mask is 2-component `RG`) | +| other (`0..4` outputs) | 12 / 33 | 0 | — | `float32` (3 single-target `uint32`) | depth-only, discard, or reduced passes | + +The two six-colour-target rows total **1,702** pixel shaders corpus-wide (`955 + 747`; plus 1 five-colour-target + +`SV_Depth` shader with 6 `OSG1` rows = 1,703 six-row `OSG1` tables). In the compiled RDNA2 code across the `*Deferred*` +pixel shaders, **16,306 of 16,306 (100%)** `exp mrtN` instructions use compressed half-float export (`compr`, +`EXP_FORMAT_FP16_ABGR`), fed by `v_cvt_pkrtz_f16_f32`. + +## 2. G-buffer target layout (`mrt0..mrt5`) + +Comparing #1891 against the 5-target (`mrt0..mrt4`) and 6-target (`mrt0..mrt5`) `PS_DeferredTextured` programs (note +that the RTV format column below is **inferred from the shader-side encoding and #1891**, not declared by `OSG1` or a +captured PSO): + +| Target | `OSG1` mask | Inferred RTV format class (from shader encoding / #1891) | Channel layout and shader-side encoding in `PS_DeferredTextured` | +|---|---|---|---| +| `mrt0` (`SV_Target0`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Albedo + alpha/material byte:** `rgb` holds base colour/albedo; in the sampled 6-target variant `a` packs a byte extracted from an integer register (`ubyte0`) and scaled by `1.0 / 255.0` (`0x3b808081`). | +| `mrt1` (`SV_Target1`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Scalar in `r` + 24-bit octahedral world normal split across `g`, `b`, `a`:** see section 3 below. | +| `mrt2` (`SV_Target2`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Square-root encoded channels:** producer applies hardware square root (`sqrt(x)` or `sqrt(1.0 - sqrt(x))`) before `v_cvt_pkrtz_f16_f32` export; #1891 notes that the lighting consumer squares `mrt2` back (tentatively specular / $F_0$ material terms, pending lighting-consumer verification). | +| `mrt3` (`SV_Target3`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Flags + byte IDs:** `x` and `y` carry clamped `[0, 1]` values biased by a dither term (`scale = 2.0 / 255.0` = `0x3c008081`, `offset = -1.0 / 255.0` = `0xbb808081`); `z` and `w` carry two 8-bit integer IDs extracted with byte-to-float conversion (`ubyte0`, `ubyte1`) and multiplied by `1.0 / 255.0` (`0x3b808081`). | +| `mrt4` (`SV_Target4`) | `0x3` (`RG`, 2,113 / 2,109 deferred PS) or `0xF` (`RGBA`, 739 / 737 deferred PS) | Float format (e.g. `R16G16_FLOAT`) | **Motion vectors:** unscaled signed float screen-space motion offset (`xy`; in the sampled 5- and 6-target `PS_DeferredTextured` disassembly with `mask = 0x3`, exported as `exp mrt4, vN, vN, off, off compr`). | +| `mrt5` (`SV_Target5`) | `0xF` (`RGBA`, 1,690 / 1,684 deferred PS) | `R8G8B8A8_UNORM` | **Sixth deferred target** on the 6-target permutations (`rgb` material terms + clamped alpha). | + +## 3. The 24-bit octahedral normal in `mrt1.gba` and `UNORM8` vs `FLOAT16` storage `PS_DeferredTextured` does not store a 3-channel `(nx, ny, nz)` normal in `mrt1`. Instead: @@ -71,3 +112,24 @@ Confirming #1891 against the 5-target (`mrt0..mrt4`) and 6-target (`mrt0..mrt5`) - The runtime must always bind the PSO's declared `RTVFormats[]` (`R8G8B8A8_UNORM` for the byte-packed G-buffer targets and a float format for `mrt4`) and must never infer `R16G16B16A16_FLOAT` for all G-buffer attachments from `OSG1` or `exp ... compr`. +### Arithmetic across all 256 byte values and consequence for the runtime + +- **Declared signatures do not separate `UNORM8` from `FLOAT16`:** because `OSG1` and `PSV0` declare `float32` on all + six `SV_Target0..5` outputs and the RDNA2 code uses `exp mrtN ... compr` (`EXP_FORMAT_FP16_ABGR`) for all of them, + neither the DXBC signature nor the FSSM export opcode indicates which G-buffer targets are `R8G8B8A8_UNORM` and which + target (`mrt4`) is a float motion target. +- **`UNORM8` vs `SFLOAT16` round-trip across `b = 0..255`:** `v_cvt_pkrtz_f16_f32(float32(b) * 0x3b808081)` rounds + **toward zero** (`RTZ`) to binary16, placing all **254 intermediate bytes (`b = 1..254`)** slightly *below* `b / 255.0` + (with a maximum shortfall of `0.1240234375` of a byte before integer conversion): + - When the attachment is `R8G8B8A8_UNORM`, the render-target output stage quantizes with nearest-integer rounding + ($\lfloor x \cdot 255.0 + 0.5 \rfloor$) and stores **256 of 256** bytes exactly in every channel. + - When the attachment is `R16G16B16A16_SFLOAT`, the stored binary16 RTZ value is kept verbatim. How a downstream + lighting shader recovers each byte from `x * 255.0` determines whether a 1-LSB error occurs: **nearest-integer + rounding** recovers **256 of 256** bytes, whereas **integer truncation** (`uint32(x * 255.0)`) recovers only + **2 of 256** bytes (`0` and `255`) and yields `b - 1` on all **254** intermediate values `1..254` across all three + byte positions (`ubyte0`, `ubyte1`, `ubyte2`). When `ubyte1` (bits `[15:8]`, straddling the 12-bit boundary between + $q_u$ and $q_v$) or `ubyte2` (bits `[23:16]`) drops by 1 under a truncating consumer, the reassembled 24-bit + octahedral normal shifts by large steps (#1891; actual lighting-consumer decode and PSO formats remain to be + verified against the lighting pass). +- The runtime must therefore bind the PSO's declared `RTVFormats[]` rather than inferring `R16G16B16A16_FLOAT` for all + G-buffer attachments from `OSG1` or `exp ... compr`. diff --git a/docs/i18n/README.md b/docs/i18n/README.md index f2901e650..021bd233b 100644 --- a/docs/i18n/README.md +++ b/docs/i18n/README.md @@ -13,7 +13,7 @@ A language is added when a contributor volunteers to maintain it and keeps the s | Language | File | Synced commit | Maintainer | |---|---|---|---| | Français (`fr`) | [`fr/quickstart.md`](fr/quickstart.md) | `e7584c52` | `@Urban225` | -| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `16282101` | `@Andretuta` | +| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `f847748c` | `@Andretuta` | | 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `003e7812` | `@liang-kai-shui` | | Polski (Polish) (`pl-PL`) | [`pl-PL/quickstart.md`](pl-PL/quickstart.md) | `c0ac5fd6` | `@Dom-in` | | Türkçe (`tr`) | [`tr/quickstart.md`](tr/quickstart.md) | `f85582e` | `@emirhan-karaca` | diff --git a/docs/i18n/pt-BR/quickstart.md b/docs/i18n/pt-BR/quickstart.md index bbc0f2bf6..e528154fe 100644 --- a/docs/i18n/pt-BR/quickstart.md +++ b/docs/i18n/pt-BR/quickstart.md @@ -4,6 +4,7 @@ > A documentação em inglês ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) e > [`docs/README.md`](../../README.md)) é a **referência oficial**. Este guia reúne apenas instruções estáveis de > configuração e compilação (sincronizado com o commit `16282101`). Para o status diário do projeto, consulte o +> configuração e compilação (sincronizado com o commit `f847748c`). Para o status diário do projeto, consulte o > [`README.md`](../../../README.md). ## O que é o Leonida @@ -56,6 +57,9 @@ ferramentas de extração de assets, e `--wav` adiciona várias vezes o tamanho podem apontar para outro disco; se o pacote do jogo estiver em uma unidade somente leitura, use `--overlay` em um disco gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm`: apagá-los mantendo a pasta faz o estágio parecer concluído com zero shaders, e um link simbólico em `disasm` é recusado. +podem apontar para outro disco; se o pacote do jogo estiver em uma unidade somente leitura, use `--overlay` (no +`gta6rt`) em um disco gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm`: apagá-los mantendo a pasta faz +o estágio parecer concluído com zero shaders, e um link simbólico em `disasm` é recusado. ## Como compilar @@ -72,6 +76,12 @@ O script procura automaticamente sua cópia (Downloads, Desktop, Documentos, Gam discos até dois níveis), valida os pré-requisitos e o espaço livre e grava o resultado em `Documents\Leonida`. Se o build for interrompido, basta rodar novamente para retomar de onde parou. +**Espaço em disco baixo:** o valor de ~350 GB é para o build completo. Para *rodar* o port, `--stages check,shaders,runtime` +precisa de cerca de 30 GB; o estágio `assets` (~300 GB) é apenas para as ferramentas de assets, e `--wav` adiciona +várias vezes o tamanho do Ogg Opus. `--work` e `--out` podem ficar em outro disco; uma unidade de pacote somente leitura +precisa de `--overlay` em uma gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm` no lugar: apagá-los +mantendo a pasta faz o estágio parecer concluído com zero shaders, e um `disasm` com symlink é recusado. + ### Pelo terminal (`make_game.py`) ```powershell @@ -104,6 +114,10 @@ python -I make_game.py --stages check,shaders,runtime O estágio `assets` serve às ferramentas de extração e ocupa cerca de 300 GB. A opção `--wav` aumenta ainda mais o espaço usado pelos áudios. Você pode apontar `--work` e `--out` para outro disco. Se o disco do pacote for somente leitura, passe `--overlay` ao iniciar o runtime e aponte para uma pasta em um disco gravável. +- **`--wave64-emulate`**: emula shaders compute/mesh wave64 em GPUs com subgrupos de 32 lanes (NVIDIA e Intel). O padrão `auto` consulta `vulkaninfo` e ativa a emulação se alguma GPU não tiver subgrupos de 64 lanes ou se o tamanho for desconhecido, verificando também se a GPU do runtime suporta compute e mesh em 64 lanes (com `--mesh-compute`, apenas o suporte em compute é necessário). No driver Windows da AMD, `auto` usa wave64 nativo em GPUs RDNA1 e RDNA2 quando a GPU do runtime suporta (para placas RDNA1 sem suporte a mesh shaders, a decisão usa o estágio compute), mesmo que outra GPU seja de 32 lanes ou que `vulkaninfo` não esteja disponível, pois o compilador desse driver pode falhar em código LDS emulado (#857). O modo escolhido fica salvo junto aos shaders traduzidos; use `--wave64-emulate on` para forçar a emulação ou `--wave64-emulate off` para forçar wave64 nativo. +- **Flags de fallback do tradutor**: `--no-float-controls` (omite `SignedZeroInfNanPreserve`), `--bary-fallback` (lê baricêntricas de um input interpolado sem `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (incorpora offsets `image_sample*_o` na coordenada sem `VK_KHR_maintenance8`) e `--mesh-compute` (traduz mesh shaders como compute sem `VK_EXT_mesh_shader`) são repassadas ao tradutor e salvas junto aos shaders; alterá-las retraduz os shaders (veja [`docs/design.md`](../../design.md)). +- **`--work`**: recomenda-se apontar para um disco com pelo menos 350 GB livres para o build completo (ou ~30 GB com `--stages check,shaders,runtime`); o estágio `shaders` é o mais demorado e usa metade das threads da CPU por padrão (ajustável com `--jobs`). +- **`--wav`**: fica desativado por padrão porque WAV PCM de 16 bits é várias vezes maior que Ogg Opus; quando ativado, decodifica os streams Ogg Opus para `work\assets\audio\wav` e pula arquivos WAV já existentes ao retomar um build. ### Diagnóstico do Vulkan no Linux diff --git a/docs/material_pass_replay.md b/docs/material_pass_replay.md new file mode 100644 index 000000000..8e9b13590 --- /dev/null +++ b/docs/material_pass_replay.md @@ -0,0 +1,30 @@ +# Following a mesh from its material to a pixel shader + +A stored effect can offer several ways to draw the same mesh. On one Xbox 1.0.2.1 drawable, the first geometry selects material slot 0. Its effect has 45 techniques. One vertex/pixel pair writes a packed integer target. Two other techniques each pair a mesh shader with a pixel shader that declares textures. The first of those pixel shaders directly reads the drawable's stored material constants. The active technique for a particular frame remains unknown. + +## Identify the draw + +To locate the example in a local 1.0.2.1 copy, filter the decoded `data.rpf` drawables to three meshes and three material slots. The first mesh has 1,656 vertices and 809 triangles. Its slot declares five textures and 46 numeric members. Select stored technique 2, pass 0, then confirm the pixel stage declares one constant buffer, one structured SRV and one four-component unsigned output. These checks distinguish the input used here from the UV example in [first_light.md](first_light.md). + +Follow the geometry's material-slot index to the effect, then follow the technique and pass selectors to the original program records. Use their archive offsets to distinguish programs and verify the native shader hashes before replay. On the selected vertex shader's packed-index branch, the mesh's original buffers reproduced 2,427 triangle corners in order and 1,656 object-space positions bit for bit. Swapping the first and third corner changed 1,618 indices. Changing the position-axis field eliminated every exact position match. The replay ends before the object-to-clip transform. [Effect lookup and geometry check](https://github.com/ItsNotRexed/Leonida/pull/2519#issuecomment-7085667975) · [Effect and pass reader](https://github.com/ItsNotRexed/Leonida/pull/3036) + +## Follow the integer target through its reader + +For this pixel shader the first dword of `b501, space0` supplies a row index. The paired vertex shader uses that index to write three more incoming dwords into one 12-byte structured record. The pixel shader also reads a word at byte offset 20 in a separate structured SRV. Three other shader programs use that field to address records 48 bytes apart in a second table. + +Before its compressed export, the pixel shader forms the second component as `((word & 0xffff) << 16) | ((row + 1) & 0xffff)`. Six compute programs load a four-component image under the same resource key and interpret that layout. Each tests the second component for zero. Each subtracts one from the low half to index the 12-byte table and uses the high half to index the other table. The different stages identify the tables by matching resource keys even where the register numbers differ. Connecting this particular draw and dispatch still requires the actual image binding and execution order. + +To check the handoff, vary just the row and read back the **whole second component**. The following synthetic inputs were supplied to the selected translated pixel shader. A synthetic vertex shader supplied constant interpolants. Both pixel shaders used the same descriptor contents and `R32G32B32A32_UINT` target. [Tested translator revision](https://github.com/ItsNotRexed/Leonida/commit/4f0c41fb3241870230483c02918f99e901c3a5fe) + +| Buffer word | Row | Before the half conversion | Selected shader readback | Direct 32-bit control | +|---:|---:|---:|---:|---:| +| `0x3f80` | 6 | `0x3f800007` | `0x00003c00` | `0x3f800007` | +| `0x3f80` | 7 | `0x3f800008` | `0x00003c00` | `0x3f800008` | + +Two further cases varied the buffer word and crossed a half-precision quantization boundary. All four pixels of each of eight 2×2 draws matched their expected values on an NVIDIA GeForce RTX 5070, driver 621.01, Intel Core Ultra 7 265K, Windows 11 build 26200.9974. A typed output alone does not preserve these two indices through the selected translation. The Xbox frame's export configuration and render-target view remain open. + +## Find the surface inputs + +Compare pixel-stage declarations across the same material's passes. The packed pass has no texture or sampler declaration. The textured sibling declares a 272-byte material constant buffer. Of its 46 authored members, 45 match the program by hash and byte offset. For the last member, the effect's parameter record supplies both the authored and compiled name hashes at the same offset. A different material slot gave only 11 direct matches. The textured shader reads the stored values and uses the first texture handle for a 2-D RGB sample. The drawable supplies four texture references across five declarations. The live handle table, sampler, and the descriptor used for the empty declaration still need independent verification. + +Both tested color techniques' mesh and pixel programs translated and passed Vulkan 1.2 SPIR-V validation, including the translator's 32-lane emulation of the mesh stages' 64-lane waves. The stage-interface checker also found compatible mesh outputs and pixel inputs for each original pair in both modes. Reproducing final appearance still requires their draw constants, descriptors, transforms, and the frame's pass selection. diff --git a/docs/models.md b/docs/models.md index 793ac5b0b..bebdfecd6 100644 --- a/docs/models.md +++ b/docs/models.md @@ -443,9 +443,22 @@ records. No unhandled layout tag appears: - **Sentinels.** On each surface, 11 entries have every estimate 0 and 10 more have zero speeds with an infinite time (`inf`). `inf` occurs in 38 road and 99 offroad blocks overall, so a parser must accept `inf` in these fields (it reads as "never reaches the test speed or distance"). +- **`fOverallRating` is a weighted mean of the other four ratings** (measured, confirmed to float noise). Over the + 504 rating blocks, `fOverallRating` = 0.21 `fSpeedRating` + 0.38 `fHandlingRating` + 0.40 + `fAccelerationRating` + 0.01 `fBrakesRating`: the four weights sum to 1, so handling and acceleration weigh + about twice speed and brakes is 1%. The residual is at most 7e-5 on the 345 rating blocks whose four parts are + all above 10, and differencing a key's road and offroad blocks gives the same 0.2100 / 0.3800 / 0.4000 / + 0.0100 on the 139 keys that are above 10 on both surfaces, so the weights do not depend on the surface. +- **The same 10 floor is on the overall** (likely). 24 blocks whose four parts run 10.0 to 11.97 carry an + `fOverallRating` of exactly 10; and the other 159 rating blocks, which have at least one part at exactly 10, + sit up to 4.1 below the weighted mean, as parts raised to 10 from a lower value would, while no block without + a part at 10 deviates. +- **Scale.** The ratings are continuous floats, not a 0-1 or 0-100 score: 342 to 451 distinct values per field + over the 504 blocks, a floor of exactly 10, and `fAccelerationRating` the only field past 1,000 (22 blocks, + maximum 1,327). -Not measured here (hypothesis): the rating scale and how `fOverallRating` weights its parts, and whether the -estimates are precomputed from handling data or measured by simulation. +Not measured here (hypothesis): whether the estimates are precomputed from handling data or measured by +simulation, and what fixes the top of the rating scale. ## Character skeletons @@ -521,18 +534,90 @@ file names), so the effect is recoverable from them. Measured on a 1.0.2.1 copy, | Materials whose hash is the joaat of a carved effect name | 3,211 (96%), 8 of the 18 hashes | | Materials whose hash is the joaat of a native effect record's name (both SGD5 databases, below) | 3,340 (100%), 18 of the 18 hashes, one record each | -So a material leads to its effect and that effect's ray-tracing resolve programs. It does **not** lead to the -draw (VS/PS/MS) programs from the package alone: +So a material leads to its effect. Through the carved compute names it reaches only 8 of the 18 hashes; the +effect records' own names reach all 18 (@jeremygold02, `tools/sgd5_effects.py` in #3036). The draw (VS/PS/MS) +programs are not reachable through the carved programs' names, order or suffixes: -- None of the 23,619 graphics programs (VS/PS/MS) carries an effect name; they are named `__<8 hex>`. +- None of the 23,619 graphics programs (2,236 VS, 12,101 PS, 9,282 MS; the 195 GS are left out here) carries an + effect name; they are named `__<8 hex>`. - `shaders.rpf` stores programs grouped by kind, not by effect (the 1,004 `RaytracingResolve` programs sit next to each other), so position doesn't group an effect's programs either. -- The graphics programs' 8-hex suffix groups them (1,226 suffixes over 23,016 programs, the largest shared by - 1,775) but is not the joaat of the program name, and only 1 of the 896 suffixes on the effect-named CS programs - appears on any graphics program. +- Every one of the 23,619 has an 8-hex suffix. The suffixes group them: there are 1,228 distinct ones, the largest + shared by 1,806 programs and 53 used once. The suffix is not the joaat of the program name, and only 1 of the + 896 suffixes on the effect-named CS programs appears on any graphics program. -The effect → technique → VS/PS table is therefore not in the carved programs' names, order or suffixes; it is -presumably in the executable (RT-5). Until then, a real model is drawn with a chosen pair ([first_light.md](first_light.md)). +They are reachable through the **effect records** in `shaders.rpf` (found by @jeremygold02, #2519). All fields +are little-endian: + +1. **The effect record.** It starts with a one-byte name length and the name, including its terminator, then a + u32 (below). Six stage lists follow, each a u32 count and that many u32 ordinals. + + The u32 is a size computed from the record's own counted fields (@jeremygold02). Let G be the ordinals in the + six lists, T the techniques, P the passes, and W the post-pass word count. Let A and B be the two block + lengths after them, E the post-pass entry count, I the payload bytes of the entries whose tag is a length + (not `0x80000000`), and S the string-pool length. Lengths don't count their own prefixes. Then, with + `x = 4W + A + B`: + + ```text + word = 48 + 8(G + T + E) + 32P + I + S + (round_up(x, 8) if E else x) + ``` + + This holds for all 932 records of this build (910 + 22, recomputed here). The value never equals the record's + serialized length (0 of 932), so the next record is found by the sequential walk, not by this word. What the + runtime uses it for is unknown. Groups 3 and 4 are empty here, so their share of it is unmeasured. + + `shaders.rpf` holds **two shader databases** (SGD5), and an ordinal counts within one of them (found by + @jeremygold02). Each database stores six program groups, each a u32 count followed by its programs. A program + is a u8-length label including its NUL, one tag byte, a u32-length payload, 152 fixed bytes and a u32-length + trailer. The u32 after group 5 is the database's effect count. An ordinal is the zero-based position in the + group of the effect's own database, so a lookup needs the database, the group and the ordinal. + + | Database (group walk starts at) | 0: VS + MS | 1: PS | 2: GS | 3 | 4 | 5: CS | Effects declared | + |---|---:|---:|---:|---:|---:|---:|---:| + | `0x10E39` | 11,018 | 10,944 | 195 | 0 | 0 | 2,647 | 910 | + | `0x10289C81` | 500 | 1,157 | 0 | 0 | 0 | 42 | 22 | + + The two databases add up to the whole carve: 11,518 VS + MS, 12,101 PS, 195 GS and 2,689 CS. Groups 3 and 4 are + empty and their stages are not identified. The first database's programs come first in the archive, so for its + effects the ordinal also equals the program's position among the carve index's programs of that group, sorted + by `offset`. The three records here are all in the first database: the wiper's 11017 is the last entry of its + group 0. + + On the rim and the tire, list 5's three entries are exactly the effect's own `:RaytracingResolve` + programs, the ones the material hash leads to in the table above. In the second database all 42 group-5 + references resolve to programs that carry their effect's name; resolved against the archive-wide CS list + instead, none of them do (@jeremygold02). +2. **The technique table.** A u32 count, then one 4-byte entry per technique: the low 15 bits of its first u16 are + the name's offset in a string block, and byte 3 is the pass count. A u32 pass total follows, then 24-byte pass + records. Where the table and its string block sit relative to the record is not derived yet: the three + tables were located by offset. +3. **The pass records.** The first six bytes of each pass select an entry of each stage list: 0 is unused, + otherwise `stage_list[selector - 1]`. + +The group walk and its counts above were reproduced on a 1.0.2.1 copy (the same `shaders.rpf`, SHA-256 +`0bc16345…`). So was @jeremygold02's census of both databases' effects with `tools/sgd5_effects.py +--list-effects` (#3036, `0029eba7`): 932 effect records with 932 distinct name hashes, 913 of them with a +technique table, 25,037 techniques and 28,798 passes. Since `c0439966` the tool also **walks** the records +forward from each database's effect count, using only stored lengths: every record's string pool, the next +record, and at the end the terminal word and zero padding. Its tests, run against this package +(`LEONIDA_GAME_DIR` set, `tests/test_sgd5_effects.py`), pass: the walk and the earlier search agree on every +record, technique and pass. The record and pass format below was also checked by hand on three records: + +| Record | Stage list sizes | Techniques | Passes (total = sum of counts) | First pass list 0 / list 1 ordinal | +|---|---|---:|---:|---| +| windshield wiper mask | 1, 1, 0, 0, 0, 0 | 1 | 1 | 11017 / 10943 | +| stock rim | 41, 53, 0, 0, 0, 3 | 106 | 108 | 9143 / 8925 | +| stock tire | 41, 53, 0, 0, 0, 3 | 106 | 108 | 9089 / 8835 | + +Two things are still open: + +- **The u32 after an effect's name.** It is reproduced from the record's fields; how the runtime uses it is + still unknown. +- **Which technique and pass the game draws with.** That is a run-time choice; it is presumably made in the + executable (RT-5). + +Until both are settled, a real model is drawn with a chosen pair ([first_light.md](first_light.md)). The effect +records already give that choice a pair that can be checked independently. So a material leads to its effect. Through the carved compute names it reaches only 8 of the 18 hashes; the effect records' own names reach all 18 (@jeremygold02, `tools/sgd5_effects.py` in #3036). The draw (VS/PS/MS) @@ -628,9 +713,16 @@ vehicle models to far-away light recipes. Counts only; no model names. this build the document is an index from model and variant to recipe with the light positions absent, so distant vehicle lights cannot be reconstructed from it. -Not measured here (hypothesis): what the secondary tokens name (per-model parts or liveries would fit the -model-name substrings), and where the light positions are generated at runtime (for example from the model's -own light bones). +The sampled `CPaletteIndexedRecipeTintsArray` document reuses 746 of the 780 distinct distant-light +secondary tokens in its own `secondaryRecipes` field. Of the 1,668 distant-light rows with at least one +token, 1,339 match a palette recipe on both vehicle name and the complete token list, ignoring case and +token order. Replacing each vehicle name with the next of the 319 lowercased names in sorted order +(wrapping at the end) and keeping its tokens fixed gives 56 matches among the same 1,668 rows. + +In the 34-row `CVehicleBoneOffsetsArray` document, 0 of the 780 distinct tokens match a whole text or +attribute value case-insensitively. In the 2,447-row document of the same type, 178 of the 780 match +`boneOffsets/Item/name`. These comparisons establish recipe reuse across the light and palette documents. +Which physical parts or liveries a token selects, and where the runtime obtains light positions, remain open. ## Skinned GLB export diff --git a/docs/movies.md b/docs/movies.md index f318a1069..06a24f7f9 100644 --- a/docs/movies.md +++ b/docs/movies.md @@ -1,8 +1,9 @@ # Movies (`movies.rpf`) -**Status: indexed. All 515 Bink 2 streams have been enumerated and their fixed headers read; representative -frames decode with the package's own Bink 2 library. The RPF9 table of contents is encrypted, but the streams can be -named from the game's mount lists ([section 8](#8-names-from-the-mount-lists)). Nothing here is a playback path yet.** +**Status: indexed. All 515 Bink 2 streams have been enumerated and their fixed headers read; the first two frames +of every stream, and the start of every audio track, decode with the package's own Bink 2 library. The RPF9 table +of contents is encrypted, but the streams can be named from the game's mount lists +([section 8](#8-names-from-the-mount-lists)). Nothing here is a playback path yet.** Every number below was measured on the Xbox Series 1.0.2.1 package on 2026-11-21. The archive is read-only. No game video, audio, frames, carved streams or reports that quote them are in this repository; the tools write only @@ -26,6 +27,7 @@ offsets and header facts. Commands are at the end. | Total duration at 30 fps | 14,181.3 s (3 h 56 min) | | Audio tracks (header field) | 319 streams with 0, 165 with 1, 30 with 2, 1 with 4; 229 tracks total | | Decoded samples | 9 streams, 14 frames, both revisions, 512x512 to 3840x2160 | +| Decode test over the archive | 515 of 515 streams: frames 0 and 1; 229 of 229 audio tracks: PCM for the first 60 frames ([below](#decode-coverage-over-the-whole-archive)) | | ffprobe decode result | 0 of 515 (`decodes=no` with a forced `-f bink` probe) | `8,831,336,892 + 1,094,744 + 22,812 = 8,832,454,448`, the span from the RPF header's data start to EOF. Readable @@ -175,6 +177,23 @@ build dependency. With that copy: - `BinkGetSummary` with a guessed `BINKSUMMARY` layout crashed with an access violation. The `HBINK`, `BINKSUMMARY`, `BINKTRACK` and related struct layouts are not established. +### Decode coverage over the whole archive + +The two package-gated runtime tests were run on every stream of `movies.rpf`, one at a time: each stream is copied +from its `bink_index.py` offset and size to one temp file, the test runs on it, and the file is overwritten by the +next. Both tests map the package's `Bink2Scarlett.dll` with `rt::Loader` and bind its two `xmem.dll` imports to the +runtime's shim, so no patched copy of the DLL is involved. + +| Test | Scope | Result | +|---|---|---| +| `bink_decode_test` | all 515 streams | 515 exit 0: `BinkOpen` returns a handle, and frames 0 and 1 each replace the sentinel buffer with more than one byte value | +| `bink_audio_test`, `LEONIDA_AUDIO_FRAMES=60` | all 229 tracks of the 196 streams that have audio (`LEONIDA_AUDIO_TRACK` 0..n-1) | 229 `RESULT PASS`, 0 `FAIL` lines: track id, type and maximum size match the header, `BinkOpenTrack` returns a track, and `BinkGetTrackData` returns a non-empty, whole number of 16-bit samples on every track | + +Measured at `main` `16282101` and again at `f847748c`, with the same counts, on Windows 11 (MSVC 14.44, +RelWithDebInfo). This is a decode check of the start of +each stream. It does not decode every frame, compare pixels with a reference, or look at the frames (none was +viewed), so it says the library accepts all 515 streams and all 229 tracks, not that every frame is correct. + The nine sampled streams (all at 30 fps): | Revision | Resolution | Frames | Duration | Audio tracks | @@ -203,8 +222,9 @@ The raw buffer and PNG stay in temp. FFmpeg is only the raw-to-PNG step here; it the mount lists ([section 8](#8-names-from-the-mount-lists)), and the folder names group the streams by use. What the game does with each folder at run time is not established. - **Audio association.** The header gives a track count, sample rate, flags and track IDs, but not which audio - belongs to which video frame beyond the interleaving described by the Bink format. No Bink Audio packet was - decoded, and no track was matched to a movie. `BinkOpenTrack`/`BinkGetTrackData` were not called successfully. + belongs to which video frame beyond the interleaving described by the Bink format. `BinkOpenTrack` and + `BinkGetTrackData` return 16-bit PCM for all 229 tracks (`runtime/test/bink_audio_test.md`, + [coverage above](#decode-coverage-over-the-whole-archive)), but no track was matched to a language or a mix. - **Playback integration.** The executable is not in the package. Where the game calls `BinkOpen`, which flags it passes, whether it uses `BinkDoFrameAsync`, `BinkGoto`, subtitles or the GPU path, and how it schedules movies against streaming are all unknown. @@ -214,9 +234,10 @@ The raw buffer and PNG stay in temp. FFmpeg is only the raw-to-PNG step here; it Xbox semantics, not necessarily `malloc`. - **Why 22,812 bytes at the end are unread.** They are not a `KB2` stream and not zero. They may be an RPF footer or leftover table data; the encrypted TOC prevents a name-level answer. -- **Whether all 515 streams are playable by the game.** Nine were decoded as a sample; the other 506 were only - header-validated. A full decode pass would need the same DLL experiment for every stream and is not part of the - index. +- **Whether every frame of all 515 streams decodes correctly.** All 515 open and decode their first two frames + through the package's DLL ([coverage above](#decode-coverage-over-the-whole-archive)); nine were decoded as a + sample with frames viewed. No stream was decoded from its first frame to its last, and nothing compares the + output with a reference. ## 6. No-sharing rule diff --git a/docs/multi_gpu_validation.md b/docs/multi_gpu_validation.md new file mode 100644 index 000000000..dbea4da09 --- /dev/null +++ b/docs/multi_gpu_validation.md @@ -0,0 +1,79 @@ +# Multi-GPU validation on identical cards + +A small box with several identical GPUs is useful for **parallel sharding**, not for inventing several independent +hardware results. This page records the setup used for the eight-card RDNA1/RADV farm and the rules that kept its +numbers meaningful. Counts and pass/fail lines only: no shader corpus, game files, keys or private paths belong +here or in any report generated from it. + +## Hardware used + +Eight AMD Radeon Pro V540 cards, Navi 12 / gfx1011 (RDNA1, PCI `1002:7360`, subsystem `1002:1a34`, VBIOS +`113-D3020100-103`), on bare metal (no VM passthrough), each bound to `amdgpu` and reachable through a render node. +RADV Mesa 25.2.8, Vulkan device 1.4.318, loader 1.3.275, subgroup range 32..64. Ubuntu 24.04.4, kernel +7.0.0-31-generic, GCC 13.3.0, Python 3.12.3, CMake 3.28.3, llvm-mc 21.1.8 with the AMDGPU target, SPIRV-Tools +2026.1 (2025.1 is too old for the `FMAKHR` capability used by `LEONIDA_FMA=khr`). + +| PCI BDF | Render node | Shard label | +|---|---|---| +| `0000:1c:00.0` | `renderD128` | gpu0 | +| `0000:1f:00.0` | `renderD129` | gpu1 | +| `0000:55:00.0` | `renderD130` | gpu2 | +| `0000:58:00.0` | `renderD131` | gpu3 | +| `0000:8e:00.0` | `renderD132` | gpu4 | +| `0000:91:00.0` | `renderD133` | gpu5 | +| `0000:c7:00.0` | `renderD134` | gpu6 | +| `0000:ca:00.0` | `renderD135` | gpu7 | + +## Pinning one device per process + +Use the PCI BDF, never an index, and exclude software drivers explicitly: + +```sh +lspci -Dn -d 1002:7360 +DRI_PRIME='pci-0000_1c:00.0!' VK_LOADER_DRIVERS_SELECT='*radeon*' vulkaninfo --summary +``` + +For every BDF in the table, that check must show **exactly one** RADV NAVI12 device. If it shows none or several, +stop and report the blocker; do not substitute llvmpipe. The ICD file on this box is `radeon_icd.json`, so +`VK_LOADER_DRIVERS_SELECT='*radv*'` matches nothing and makes `vkCreateInstance` fail with `-9`. + +## Shard discipline + +- Split work into **disjoint** units: different seeds for the fuzzers, different `--start`/`--count` ranges for a + translated index, or different test names. Eight processes running the same full suite are eight copies of one + result, not a validation farm. +- Run one process per card, keep logs per card, and aggregate counts afterwards. +- Each PR verification used a clean worktree at the PR head and, where a base was named, a second worktree at that + base with its own freshly built programs. Mixing a script from one commit with binaries from another produces + false failures (see "Known problems" in [testing.md](testing.md)). +- When a shard fails, rerun the *same* shard on two or three other cards. Failing everywhere points to a driver or + corpus issue; failing on one card points to that card. Re-run single failing tests in isolation before calling a + result reproducible. +- A transient single-card anomaly must be reported as such. On this box `0000:ca:00.0` intermittently produced a + few mismatching pixels in different fragment tests on different full-suite runs, while each failing test passed + 3/3 in isolation and the other seven cards were clean. It was never counted as a PR regression. + +## Results already collected + +These are aggregate results from this box; the full per-command counts are in the linked #166 entries, not in this +page. No game-derived data was used for any of them. + +- Single-card RDNA1/RADV baseline suite and TEST-71 fuzz matrix: [#166 entry](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7078373329). +- Eight-card fallback matrix and extended fuzz campaign (seeds 4–11, 200 programs, both waves): [#166 entry](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7079130604). +- Native MUBUF `OOB_SELECT` measurement on gfx1011 with `tools/hw_oracle` and `tools/buffer_bounds_probe.py`: 12 cases + at wave32 and wave64 (24 groups), all following the measured RDNA2/GFX11 column, 8 disagreements with Mesa's + GFX10 column, 0 wave32/wave64 differences (SHADER-341; results in [buffer_bounds.md](buffer_bounds.md)). + +Two failures recur on these cards at the tested commits and were confirmed on clean base worktrees, so they are +driver-version limitations rather than regressions from the PRs tested here: `cs_w32_salu64` (wrong high word of +an `s_bfe_i64` field) and `cs_signed_zero_nan`. The latter is the signed-zero class tracked in #1203. A real +regression was found on PR #2715: two wave64 pixel fixtures returned the clear value on all three cards tested while +the PR's base passed them. + +## Using a translated corpus + +If a private translated shader directory containing `index.json` and `stubs/` is available, shard the *sorted* index +with `vk_pipeline_check --start`/`--count` and one pipeline cache per shard. Record ok/skipped/failed by stage and +generic error category only: never post shader names, contents or private paths. RDNA1 legitimately skips mesh, +barycentric and maintenance8 shaders; report those separately from passes. If no such directory exists, do not run +this phase and do not report pipeline counts as if you had. diff --git a/docs/navmesh.md b/docs/navmesh.md index a12a239a7..fa6f1bca0 100644 --- a/docs/navmesh.md +++ b/docs/navmesh.md @@ -186,17 +186,49 @@ layout, fixed `0xF0`-byte header, `14.36 GiB` / `15,420,757,856` bytes inflated | `+0xA0` | 8 | `ptr64` | Spatial quadtree root (`96` B nodes, `32` B leaves) | Full tree (`2,337,904` nodes, `1,760,339` leaves, max depth `9`) valid & all leaf indices `< u32@0xC4` on `27,644 / 27,644` | | `+0xA8` | 8 | `ptr64` | Nullable special-link array (`32` B, count `u32@0xD4`) | Non-null iff `flags & 2` (`8,817` pages); in-bounds `27,644 / 27,644` | | `+0xB0` | 8 | `ptr64` | Nullable special-link index table (`u16`, count `u32@0xD8`) | Non-null iff `flags & 2`; in-bounds & all entries `< u32@0xD4` on `27,644 / 27,644` (`2` tiles have `d8 < d4`) | -| `+0xB8` | 8 | `ptr64` | Nullable 96-byte geometric/volume array (count `u32@0xDC`) | Present on `9,425` pages (`6,246,890` records); in-bounds `27,644 / 27,644`; semantics **open** | +| `+0xB8` | 8 | `ptr64` | Nullable 96-byte obstacle footprint array (count `u32@0xDC`) | Present on `9,425` pages (`6,246,890` records = `3,123,445` outer/inner contour pairs); in-bounds & valid `27,644 / 27,644` | | `+0xC0` | 4 | `u32` | Vertex count | Min `4`, max `52,608`, sum `138,041,746` | | `+0xC4` | 4 | `u32` | Polygon count | Min `1`, max `71,803`, sum `124,768,148` | | `+0xC8` | 4 | `u32` | 512 × 512 sector ID (`0` if `flags & 4`) | `0` iff `flags & 4` (`162` pages); exact `136 × 180 = 24,480` static grid | | `+0xCC` | 4 | `u32` | Core mesh data byte size | `6*c0 + 14*pool + 44*c4 + 32*d4 == u32@0xCC` with **0 residual** on `27,644 / 27,644` | | `+0xD4` / `+0xD8` / `+0xDC` | 12 | `u32[3]` | Special-link, link-index, and `+0xB8` record counts | Sums `26,679,246` / `26,903,247` / `6,246,890` | -| `+0xE8` | 4 | `u32` | Build stamp (`0` if `flags & 4`) | `7` distinct values (`0` on `162`, `0x09090516` on `24,474`, `0x160e3132` on `3,003`, 4 rare on `5`); encoding **open** | +| `+0xE8` | 4 | `u8[4]` | Build stamp (`0` if `flags & 4`): second, minute, hour, day of month | `7` distinct values (`0` on `162`, `0x09090516` on `24,474`, `0x160e3132` on `3,003`, 4 rare on `5`); see [Build stamp](#build-stamp-0xe8) | Reserved slots `+0x18..+0x1f`, `+0x6c..+0x6f`, `+0x78..+0x7f`, `+0x94..+0x97`, `+0xd0..+0xd3`, `+0xe0..+0xe7`, and `+0xec..+0xef` are zero on `27,644 / 27,644` pages. +### Build stamp (`+0xE8`) + +Read as four bytes from the lowest address, every nonzero value is a second, a minute, an hour and a day of month, +the first four fields of C's `struct tm` in their order. No month or year is stored. The numbers are for the +1.0.2.1 package (ASSET-282): + +| `u32@0xE8` | Bytes | Reads as | Tiles | Grid positions | +|---|---|---|---:|---| +| `0x09090516` | 22, 5, 9, 9 | day 9, 09:05:22 | 24,474 | 24,474 of 24,480: 23,536 alone, 938 shared | +| `0x160e3132` | 50, 49, 14, 22 | day 22, 14:49:50 | 3,003 | 940, never alone | +| `0x0f0e1b37` | 55, 27, 14, 15 | day 15, 14:27:55 | 2 | 2 adjacent, alone | +| `0x1d07151c` | 28, 21, 7, 29 | day 29, 07:21:28 | 1 | alone | +| `0x18101739` | 57, 23, 16, 24 | day 24, 16:23:57 | 1 | shared with 2 day-22 tiles | +| `0x0b0a2f1a` | 26, 47, 10, 11 | day 11, 10:47:26 | 1 | alone | +| `0` | | not a grid tile | 162 | the `flags & 4` meshes | + +- **Only the date and time reading fits all six nonzero values.** In each one, the low two bytes are below 60, the + third is below 24 and the top byte is 1 to 31. Six independent random words land in those ranges with a + probability of about 6 × 10⁻²⁰. The low two bytes could in principle be the other way round (minute first). The + `struct tm` order is the natural reading, but the data can't tell them apart. +- **The day-22 stamp marks tiles added on top of the base grid.** The 27,482 static tiles sit on 24,480 grid + positions (the `u32@0xC8` sector, above). The 3,002 extra tiles are all on 940 positions that hold 2 to 40 tiles, + and every one of those positions has day-22 tiles. 2,984 of the 3,003 day-22 tiles share their position with a + day-9 tile, and on all 938 positions with both, the day-22 tiles come later in the archive. The other 19 are on two + positions without a day-9 tile: 17 at sector (255, 248), and 2 with the day-24 tile at (248, 246). On 450 of the 938, the first day-22 tile has the same vertex and polygon + counts as the day-9 tile. What the stacked tiles are for is not measured. +- **Neighbouring tiles share a stamp.** Of the 48,644 pairs of grid neighbours (one tile per position), 98.12% have + the same stamp, against 92.58% for stamps placed at random with the same frequencies. + +Method: `tools/navmesh_decode.py`'s own scan of `navmeshes.rpf`, with each tile's `u32@0xE8`, `u32@0xC8`, flags, +counts and archive offset recorded per tile. No geometry was kept. + The `+4` word of a polygon packs `(index start << 4) | count`; the runs tile the index pool in order (`tools/navmesh_decode.py --deep` checks it on all `124,768,148` polygons, 0 failures), which caps a polygon at 15 vertices. 6stars independently reads the same packing. Its polygon `+0x28` bit 17 and `+0x18` bit 27 @@ -224,6 +256,40 @@ world_min_y = (sector_y - 256) * 128.0 # -9,856 .. +13,056 m (max +13,184 m) The `24,480` unique static sector IDs form a complete, gap-free `136 × 180` rectangle (`Z ∈ [-78.55, +403.84]` m). +### Adjacent-polygon edges (`+0x88`, `493,024,188` records) and special links (`+0xA8`/`+0xB0`, `26,679,246` records) + +- **12-byte adjacent-polygon edges (`+0x88`, count `u32@0x90`, `493,024,188` records across `27,644` tiles):** + Each record is `{u32 adj_sector, u16 adj_poly, u16 edge_meta, u32 edge_flags}`. Across all `493,024,188 / 493,024,188` + records (`0` exceptions): + - **`458,728,869`** (`93.04%`) are intra-tile neighbors with `adj_sector == u32@0xC8` and `adj_poly < u32@0xC4` + (`0` out-of-bounds polygon indices); + - **`34,295,319`** (`6.96%`) are open or tile-border edges with `adj_sector == 0xFFFFFFFF` and `adj_poly == 0xFFFF` + (cross-tile border stitching is performed at runtime rather than serialized in `+0x88`). +- **Polygon `+0x20` special-link prefix-sum chain (`124,768,148` polygons across `27,644` tiles):** + In every 44-byte polygon at `+0x98`, `u32@0x20` packs `link_count = w20 & 0x3F` (bits `0..5`, range `0..63`), + `link_start = (w20 >> 6) & 0x1FFFF` (bits `6..22`, up to `17,459`), and a 9-bit polygon flag field `w20 >> 23` + (bits `23..31`). Across all `27,644 / 27,644` tiles (including polygons with `link_count == 0` and linkless tiles + with `u32@0xD8 == 0`), `link_start` equals the exact running prefix sum of `link_count` across preceding polygons, + and the tile total after polygon `u32@0xC4 - 1` equals `u32@0xD8` (`0` failures). +- **32-byte special links (`+0xA8`, count `u32@0xD4`, `26,679,246` records across `8,817` tiles) and `+0xB0` index table + (`u16[u32@0xD8]`, `26,903,247` entries):** + Each 32-byte record at `+0xA8` is `{u16[3] pos0, u16[3] pos1, u16 poly0, u16 poly1, u32 sector0, u32 sector1, + u16 flags0, u16 flags1, u16 heading, u16 pad}`: + - `+0x00..+0x05` (`u16[3]`) and `+0x06..+0x0B` (`u16[3]`): quantized 3D link endpoints `pos0` and `pos1`. + - `+0x0C..+0x0F` (`u16 poly0, u16 poly1`) and `+0x10..+0x17` (`u32 sector0, u32 sector1`): endpoint polygon indices + and sector IDs. Across all `26,679,246 / 26,679,246` links, at least one endpoint sector equals the owning tile's + `u32@0xC8` (`26,398,281` intra-tile with `sector0 == sector1 == u32@0xC8`; `143,913` cross-tile with + `sector0 == u32@0xC8`; `137,052` cross-tile with `sector1 == u32@0xC8`; `0` with neither). Whenever + `sector0 == u32@0xC8`, `poly0 < u32@0xC4` (`26,542,194 / 26,542,194`); whenever `sector1 == u32@0xC8`, + `poly1 < u32@0xC4` (`26,535,333 / 26,535,333`). + - `+0x18..+0x1B` (`u16 flags0, u16 flags1`): link attribute and traversal type words (`flags1` top values: `0x0050` + on `11,492,614`, `0x0040` on `9,705,698`, `0x0030` on `4,281,168`, `0x0060` on `425,369`). + - `+0x1C..+0x1D` (`u16 heading`): 8-bit quantized heading angle (`0..254`, `< 256` on `26,679,246 / 26,679,246`). + - `+0x1E..+0x1F` (`u16 pad`): zero padding (`0` on `26,679,246 / 26,679,246`). + - Across all `26,903,247 / 26,903,247` entries of `+0xB0`, every entry `li = u16@(b0 + 2*k)` in polygon `pi`'s slice + `[link_start .. link_start + link_count)` indexes a 32-byte link at `+0xA8` satisfying + `(poly0 == pi or poly1 == pi) and (sector0 == u32@0xC8 or sector1 == u32@0xC8)` (`0` failures). + ### Split arrays and quadtree layout - Each `aiSplitArray` descriptor (`48` B: `{u64 vtable, u64 total, ptr64 blocks, ptr64 starts, u64 nblocks, u64 0}`) @@ -234,6 +300,22 @@ The `24,480` unique static sector IDs form a complete, gap-free `136 × 180` nullable leaf pointer (`+0x2C`), four 4-byte-aligned child pointers (`+0x34..+0x53`), and 12 trailing zero bytes (`+0x54..+0x5F`). Each `32`-byte leaf holds `{u64 0, ptr64 poly_indices, u64 0, u64 num_polys}`. +### Paired 96-byte obstacle footprint records (`+0xB8`, `6,246,890` records) + +On all `9,425` tiles where `u32@0xDC > 0`, `u32@0xDC` is even (`9,425 / 9,425`) and the array at `+0xB8` holds +`3,123,445` consecutive `(outer, inner)` pairs (`6,246,890` 96-byte records). Every pair `(rec[2*p], rec[2*p + 1])` +shares the identical 20-byte prefix `+0x00..+0x13` (`3,123,445 / 3,123,445`): + +| Offset | Size | Type | Verified meaning (`6,246,890 / 6,246,890` records) | +|---:|---:|---|---| +| `+0x00` | 8 | `u64` | 64-bit obstacle/object UID (identical across `rec[2*p]` and `rec[2*p + 1]` on `3,123,445 / 3,123,445` pairs; repeated across adjacent tiles when a footprint crosses a 128 m tile border) | +| `+0x08` | 12 | `f32[3]` | Finite 3D world-space anchor `(x, y, z)` (`6,246,890 / 6,246,890`, identical across each pair) | +| `+0x14` | 1 | `u8` | Contour role/flags: `0x00` (`2,750,542`) or `0x04` (`372,903`) on `rec[2*p]` (expanded outer contour), and `0x08` (`3,123,445`) on `rec[2*p + 1]` (inner core contour) on `3,123,445 / 3,123,445` pairs | +| `+0x15` | 1 | `u8` | 2D polygon vertex count `N` (`4` on `3,123,878` records, `8` on `3,123,012` records). `(rec[2*p].N, rec[2*p + 1].N)` is `(8, 4)` on `3,123,012` pairs (chamfered octagon around an inner quad, typically expanded by `128` fixed-point units) and `(4, 4)` on `433` pairs | +| `+0x16` | 64 | `i16[32]` | Up to 16 relative 2D `(dx, dy)` footprint vertices in signed 16-bit fixed point around `(x, y)`; trailing unused slots `+0x16 + 4*N .. +0x55` are zero on `6,246,890 / 6,246,890` | +| `+0x56` / `+0x58` | 4 | `i16`, `u16` | Vertical/extent words (`u16@0x56` range `0..65,535`, high bit set on `1,846,885`; `u16@0x58` range `3..65,534`, high bit set on `13,629`) | +| `+0x5A` | 6 | `u8[6]` | Trailing zero padding (`0` on `6,246,890 / 6,246,890`) | + ## Band-3 `grid` resources (`27,482` resources) The final 433 MiB of `navmeshes.rpf` holds `27,482` `pgBase` resources (`+6` continuations) paired **1-to-1** with all @@ -251,8 +333,23 @@ The final 433 MiB of `navmeshes.rpf` holds `27,482` `pgBase` resources (`+6` con Reserved slots `+0x38..+0x3f`, `+0x4c..+0x4f`, and `+0x54..+0x5f` are zero on `27,482 / 27,482`. Each 272-byte group at `+0x60` is a 16-way SwissTable block (`16` control bytes where `0x80` = empty and `< 0x80` = occupied tag, followed by `16 × {u64 key, u64 value}`). Across all `27,482 / 27,482` resources, occupied slots equal `N` and their `value` fields -form an exact bijection onto `[0 .. N - 1]`. The engine subsystem name, `u64` key encoding, and `u32[N]` bit semantics -remain **open**. +form an exact bijection onto `[0 .. N - 1]`: `value` indexes the `u32[N]` payload. + +**Keys (ASSET-287).** The `u64` keys are sentinel-bit linear octree keys over the cubic volume: `1` is the root and a +child is `(parent << 3) | octant`, so the highest set bit sits at bit `3 × depth`. Measured on `27,482 / 27,482` +resources: the root is present, no key appears in two slots, every key's highest set bit is a multiple of 3, and every non-root key's parent (`key >> +3`) is in the same table. Octant bit 2 is the vertical axis (cells stack on it); which of bits 0/1 is x and where the +cube sits against the sector are **open**. Depths run `0..10` (`53,835,068` keys). The cell size at a resource's deepest +level (`extent >> depth`) is 16 m on `12,694` resources (`12,693` 128 m tiles at depth 3, one 256 m tile), 8 m on `859` +and 4 m on `13,929`. + +**`u32[N]` words.** `51` distinct values over the whole package. Every inner node (a key with at least one child: +`8,617,353`) holds `0x0000ff00`. Leaves (`45,217,715`) hold `0x0000ff00` (`1,791,096`, never at a resource's deepest +level), a word with low byte `0x01` (`26,659,574`; bits `8-11` take `0, 5, 7, 9, B, D, F`; bits `17-18` are a 2-bit +field), or a word with low byte `0x03` (`16,767,045`; bit 8 is a flag, bits `11-14` a 4-bit value `0..15`). What the two +leaf kinds and their fields mean, and the engine subsystem name, are **open**. `navmesh_decode.py --deep` checks the key +and inner-word rules (`keys_octree`, `inner_payload_ff00`) and reports `key_depth`, `inner_nodes` and `leaf_payload` +counts. ## Remaining unknowns @@ -264,10 +361,12 @@ remain **open**. 3. **`0DRP` unnamed structs and fields.** Several `0x7a` struct/member hashes (including `0x4712787b`, `0x57ad0b12`, `0xdd53676a`, `0xf2dd6348`, `0xde5f1345`, and 3 of the 4 singletons) are not yet matched to engine names. 4. **Per-record bitfields inside `0x00010015` tiles.** `u32@0x10` bit 3's secondary trigger on `289` tiles and bit 6's - name, `u32@0xE8` build-stamp encoding, polygon/adjacent-edge/special-link flag bitfields, and the C++ type of the - 96-byte `+0xB8` records remain open. -5. **Band-3 `grid` subsystem and EOF `PSIN` v79.** The Band-3 subsystem identity, `u64` key encoding and `u32[N]` - payload bits are open, as is why the final `PSIN` (version `79`) terminates before `LSNS` ends. + name, `u32@0xE8` build-stamp encoding, polygon/adjacent-edge/special-link flag bitfields, and the exact C++ class name + and `+0x56/+0x58` vertical unit of the paired 96-byte `+0xB8` footprint records remain open. +5. **Band-3 `grid` subsystem and EOF `PSIN` v79.** The Band-3 subsystem identity, the x/y order of the octree key's + octant bits 0/1, the cube's placement against its sector and the meaning of the `u32[N]` leaf fields are open + (the key encoding and the inner-node word are decoded above), as is why the final `PSIN` (version `79`) + terminates before `LSNS` ends. ## Vehicle navmesh settings (`CVehiclePoints`, `common.rpf`) @@ -307,12 +406,16 @@ stored elsewhere, and which vehicles the 31 are (wagons, boats and trains would - `tools/navmesh_decode.py` (stdlib-only) decodes all four resource classes (`0DRP`, `0x00010015`, `grid`, `PSIN`), joins continuations (including tiny `< 64`-byte continuations), validates structural invariants, and writes aggregate JSON and optional numeric CSV metadata. It never writes payload bytes and never touches the TOC. +- `tools/navmesh_links.py` (stdlib-only) decodes and verifies the 12-byte `+0x88` adjacent-polygon edges, the polygon + `+0x20` special-link prefix-sum chain, and the 32-byte `+0xA8` special links and `+0xB0` index table. ```powershell python -I tools/navmesh_decode.py \navmeshes.rpf --out /navmesh-decode.json --csv /navmesh-decode.csv python -I tools/navmesh_decode.py \navmeshes.rpf --deep --out /navmesh-decode-deep.json python -I tools/navmesh_decode.py --out /carved-decode.json +python -I tools/navmesh_links.py \navmeshes.rpf --out /navmesh-links.json python -I -W error::ResourceWarning tests/test_navmesh_decode.py -v +python -I tests/test_navmesh_links.py -v python -I tests/test_navmesh_index.py ``` @@ -321,8 +424,8 @@ For both tools, `--start` must be 0 or more and `--limit` at least 1; anything e Validation on the full real archive (`navmeshes.rpf`, `6,707,512,496` bytes) with `--deep`: `90,295` carver streams + `10` tiny continuations; `9,603` `0DRP` (`15,629,979` cover nodes), `27,644` `0x00010015` navmesh tiles (`138,041,746` vertices, `124,768,148` polygons, `2,337,904` quadtree nodes), `27,482` `grid` resources (`53,835,068` entries, `0` -sector mismatches), `22` `PSIN` (`21` complete), **0 check failures**, in 236 s. Both test suites build synthetic -archives in memory/tempdir and need no game files. +sector mismatches, `keys_octree` and `inner_payload_ff00` pass on all), `22` `PSIN` (`21` complete), **0 check +failures**, in 236 s. Both test suites build synthetic archives in memory/tempdir and need no game files. ## No-sharing rule diff --git a/docs/page_directory.md b/docs/page_directory.md index 1a301a592..5e9334609 100644 --- a/docs/page_directory.md +++ b/docs/page_directory.md @@ -11,11 +11,11 @@ payload, carved stream or name list is in this document or the repository. | Question | Measured answer | |---|---| | Where is the header? | `0DRP` at +0x10, version 122 at +0x14, fixed header length **0x60**. | -| Is there a 64-bit key at +0x60? | **No.** The first resource payload starts at +0x60 on 29,297 of 29,298 measured pages. The bytes called a key are payload. | +| Is there a 64-bit key at +0x60? | **No.** The first resource payload starts at +0x60 on 29,297 of 29,298 measured pages, and on 48,193 of the 48,194 pages of the three archives read whole. The bytes called a key are payload. | | What does +0x38 point to? | A table of **16-byte `{u32 hash, u32 size, u64 self-pointer}` records**, one per resource segment. The count is `u16@0x4c`. | | What does a record map? | A virtual offset and exact byte size inside the logical resource. The offset is `pointer - 0x50000000`, not an archive offset. | -| Do the records cover the page? | Yes on 15,767 of 15,768 `data.rpf` pages and all sampled navmesh/animation pages: sorted by target they tile from +0x60 with **zero overlaps**. The 14.8 MB, 89-count page starts with the +0x40 table at +0x60; its `q38` records still tile with zero overlaps. | -| Can a resource span zlib streams? | **Yes.** When a table or target crosses the inflated stream end, the next zlib stream in archive order continues the same resource. All 29,298 core pages resolved with at most **one** continuation stream; the 107 sampled `levels.rpf` pages did the same. | +| Do the records cover the page? | Yes on 15,767 of 15,768 `data.rpf` pages and on every navmesh and animation page (all 9,603 and all 22,823, see *Whole-archive pass*): sorted by target they tile from +0x60 with **zero overlaps**. The 14.8 MB, 89-count page starts with the +0x40 table at +0x60; its `q38` records still tile with zero overlaps. | +| Can a resource span zlib streams? | **Yes.** When a table or target crosses the inflated stream end, the next zlib stream in archive order continues the same resource. All 29,298 core pages resolved with at most **one** continuation stream; the 107 sampled `levels.rpf` pages did the same, and so did all 48,194 pages of `data.rpf`, `navmeshes.rpf` and `anim.rpf` read whole. | | Are resource boundaries available without the TOC? | **Yes for offsets, sizes and stream membership; no for names or asset identity.** The TOC is still required for paths and the hash-to-name mapping. | ## Method and coverage @@ -45,6 +45,56 @@ The BVH samples are a negative control. `core_bvh4.rpf` is RPF9, but none of the format; their streams are BVH payloads and descriptors (see `docs/bvh.md`, PR #109), not directory pages. The "generic" claim in this note covers `data.rpf`, `levels.rpf`, `navmeshes.rpf` and `anim.rpf`. +## Whole-archive pass + +The `navmeshes.rpf` and `anim.rpf` rows above stop at 64 MiB and 256 MiB. `tools/page_index.py pages.json` +without `--limit`, on the same 1.0.2.1 package, reads both archives to the end (counts only; every row is taken from +the report's `summary` or counted over its `pages`): + +| | `data.rpf` | `navmeshes.rpf` | `anim.rpf` | +|---|---:|---:|---:| +| zlib streams | 28,509 | 90,295 | 130,470 | +| `0DRP` pages, all version 122, all complete | 15,768 | 9,603 | 22,823 | +| `q38` records | 60,880 | 54,898 | 527,439 | +| a `q38` record targets +0x60 | 15,767 | 9,603 | 22,823 | +| pages with overlapping `q38` records | 0 | 0 | 0 | +| gap runs / gap bytes between sorted records | 27,377 / 8,411,848 | 11,461 / 5,058,136 | 136,013 / 10,259,744 | +| pages with one continuation stream (none has more) | 158 | 2,170 | 11,760 | +| `q38` table wholly in the continuation (none is split) | 2 | 270 | 10,218 | +| span (target + size): minimum / median / maximum | 296 / 21,760 / 14,848,448 | 360 / 186,208 / 2,985,724 | 2,732 / 189,072 / 5,634,144 | +| `+0x20` | 1-3, 89 | 1-6 | 1-5, 13-41 | +| `n28` / `n30` / `n38` / `u16@0x4e` | 2-182 / 0-38 / 2-186 / 0-1,077 | 2-12 / 0-4 / 2-6 / 0-602 | 25-103 / 11-57 / 7-79 / 0-1,382 | +| `q28` records declared (`sum n28`) | 60,901 | 108,890 | 1,015,222 | +| `q28` records read | 60,897 | 106,202 | 952,850 | +| `q28` records with a null pointer | 0 | 0 | 3,672 (on 3,511 pages) | +| pages whose `q28` table ends past the streams read | 1 | 225 | 1,355 | + +The stream and page totals agree with the other whole-archive readers: 90,295 streams and 9,603 directory pages in +`docs/navmesh.md`, 130,470 streams in `docs/animation.md`. What the samples said about the layout holds on all +48,194 pages: version 122, the first payload at +0x60 (one `data.rpf` exception), `q38` tables 16-byte aligned, +`q28` tables 8-byte aligned, no overlap between `q38` records, at most one continuation stream, and a `q28` +`hash_a` that matches a `q38` hash on every page where both tables were read (15,767, 9,378 and 21,468 pages). + +What the samples did not show: + +- **Header ranges are wider.** `+0x20` reaches 6 in `navmeshes.rpf` (1: 1 page, 2: 779, 3: 7,650, 4: 932, 5: 22, + 6: 219) and 41 in `anim.rpf` (1: 1,883, 2: 7,571, 3: 9,241, 4: 2,022, 5: 70, 13-41: 2,036); `n30` reaches 57 and + `u16@0x4e` 1,382, both in `anim.rpf`. +- **A `q28` pointer can be null.** 3,672 `anim.rpf` records on 3,511 pages have a zero pointer with `hash_a`, + `count_or_size` and the flags set; 116,277 ordinary records follow them in the same tables. The tool used to stop + a table at the first one. It now keeps the record with `target` null and reads on; a pointer with any other + non-`0x50000000` value still ends the table with `q28_error`. `data.rpf` and `navmeshes.rpf` have none. +- **A `q28` table can lie past the resource's `q38` boundary.** The tool reads only the continuation streams the + `q38` table and its records need. On 1,355 `anim.rpf`, 225 `navmeshes.rpf` and 1 `data.rpf` pages the `q28` + table ends beyond those streams. Such a page reports no `q28` records and names the reason in `q28_error` + (`q28_tables_unread` in the summary) instead of looking like a page without the table. Whether the next stream + holds the table was not followed up. +- **The navmesh type hashes are not on every page.** `0xde5f1345` is in 8,412 of the 9,603 pages (every page of the + first 64 MiB has it); the most common hash, `0x0bcb00e4`, is in 9,585 records. + +The per-archive tables further down (common sizes, common hashes, payload classes) are still the 64 MiB and 256 MiB +slices where they say navmesh or animation; the `data.rpf` columns were complete from the start. + ## Fixed header (0x60 bytes) The core sample is 15,768 `data.rpf` pages plus 1,132 navmesh and 12,398 animation pages = **29,298 pages**. @@ -60,16 +110,16 @@ sample; the meaning column separates decoded fields from unresolved ones. | +0x10 | 4 | `30 44 52 50` | `0DRP` | | +0x14 | 4 | 122 in all 29,298 | version | | +0x18 | 8 | zero in all pages | unused | -| +0x20 | 4 | 1-89 in `data.rpf`, 2-3 in navmesh, 1-38 in anim | presumed page count; **unit unresolved** | +| +0x20 | 4 | 1-89 in `data.rpf`, 2-3 in navmesh, 1-38 in anim (whole archives: 1-6 and 1-41) | presumed page count; **unit unresolved** | | +0x24 | 4 | zero in all pages | high half of the +0x20 qword | | +0x28 | 8 | `0x5000xxxx`, 8-byte aligned | pointer to the `q28` table | | +0x30 | 8 | zero or `0x5000xxxx` | pointer to the `q30` table | | +0x38 | 8 | `0x5000xxxx`, 16-byte aligned in all pages | pointer to the `q38` resource table | | +0x40 | 8 | `0x5000xxxx` | pointer to the `q40` table; layout unresolved | | +0x48 | 2 | 0-182 | `n28`: number of +0x28 records | -| +0x4a | 2 | 0-38 | `n30`: number of +0x30 records | +| +0x4a | 2 | 0-38 (0-57 over whole `anim.rpf`) | `n30`: number of +0x30 records | | +0x4c | 2 | 2-186 | `n38`: number of +0x38 records | -| +0x4e | 2 | 0-305, varying | **unresolved**; not a dense count | +| +0x4e | 2 | 0-1,382, varying | **unresolved**; not a dense count | | +0x50 | 16 | zero in all pages | unused | | +0x60 | ... | first payload, or the `q40` table on one page | not header | @@ -107,7 +157,8 @@ used as a name or asset id. Names still require the TOC. ## Pointer arithmetic -Every measured `q28` and `q38` pointer is a zero-extended 32-bit value in a 64-bit field: +Every measured `q38` pointer, and every `q28` pointer that is not null (3,672 `anim.rpf` records have a zero +pointer, see *Whole-archive pass*), is a zero-extended 32-bit value in a 64-bit field: ```text d0 86 01 50 00 00 00 00 -> 0x000000005000186d0 -> 0x186d0 @@ -230,6 +281,35 @@ These are 32-bit hashes; whether they are type ids is open. Repeated values are No name or type string is present in the page; these hashes remain opaque until the TOC or the executable supplies a mapping. +### One page lacks the recurring `0x00000007` tag + +The Xbox Series 1.0.2.1 export identifies `story000.rpf` as its source and contains 16,977 complete +directory pages. A bounded source check used 17 evenly spaced rows (including the first and last) and +the six-record exception described below. At the recorded compressed spans, the inflated length, page +signature and both record lists (`q38` and `q28`) matched for 18/18 rows in `story000.rpf` and 0/18 in +`data.rpf`. The counts below apply only to this export. Each selected tag occurred once per page that contained it. + +| Selected `q38` tag | Pages containing it | +|---|---:| +| `0xa90b7f7e`, `0x0000004a`, `0x64e8ac67` | 16,977 each | +| `0x00000007` | 16,976 | +| `0x00000100` | 16,519 | +| `0x00000101` | 593 | +| `0x00000010` | 19 | +| `0xde5f1345` | 0 | + +The one complete page without tag 7 had six `q38` records. The six nearest pages by record count had 10–12 +records and carried tag 7 in positions 2–7 (counting from one). Four shared five of the exceptional page's tags +and two shared all six. Across the export, all 81 other pages containing all six tags also contained tag 7. +None preserved the relative order of all six. Tag 7 is therefore optional in this sample. There is no second +six-record table for a comparison that could distinguish omission from substitution. + +Of the 15,775 pages with exported `q28` records, all had at least one `hash_a` equal to a same-page `q38` +tag. None had a matching `hash_b`. The export also reported 131 pages with `q28_error`. On the exceptional +page, five of the 26 readable `q28` records each matched a different local tag through `hash_a`. Neither +field equalled 7. On the six nearest pages, `hash_a` also never equalled 7 even though `q38` contained it. +These comparisons establish equality of field values. Their role at runtime and the meaning of the tags remain open. + ## The `q28` table (layout measured, semantics partial) `n = u16@0x48`; table at `q28 = u64@0x28 - 0x50000000`; each record is 32 bytes: @@ -239,7 +319,7 @@ No name or type string is present in the page; these hashes remain opaque until | +0x00 | 4 | measured | `hash_a`; at least one record on every page matches a `q38` hash | | +0x04 | 4 | unresolved | `hash_b`; no match to a `q38` hash observed | | +0x08 | 8 | unresolved | `field_08`; observed `0`, `0x100`, `0x200`, `0x300`, `0x30c`, `0x400`, `0x424`, ...; not a measured byte range | -| +0x10 | 8 | measured | self-pointer; 60,862 of 60,897 `data.rpf` targets resolve in the first stream | +| +0x10 | 8 | measured | self-pointer, or zero on 3,672 `anim.rpf` records; 60,862 of 60,897 `data.rpf` targets resolve in the first stream | | +0x18 | 4 | unresolved | `count_or_size`; small values, not consistently the linked `q38` size | | +0x1c | 4 | measured | flags; only high 16 bits are set, observed `0x10000`-`0x6b0000` | @@ -257,7 +337,8 @@ The table points at hash-table-like records of 16 bytes, `{u32 hash, u32 0, u32 dictionaries. The exact meaning of `field_08`, `count_or_size` and `hash_b` is not decoded, so the tool exports them under those names and does not use them for boundaries. -Counts: 60,897 records in `data.rpf`, 13,090 in the navmesh slice, 511,435 in the animation slice. `hash_a` +Counts: 60,897 records in `data.rpf`, 13,090 in the navmesh slice, 511,435 in the animation slice (106,202 and +952,850 over the whole archives). `hash_a` matched a `q38` hash on 15,767/15,767 `data.rpf` pages, 1,103/1,103 navmesh pages and 11,558/11,558 animation pages where both tables were present. @@ -268,7 +349,7 @@ pages where both tables were present. - `q40` points at a table whose common prefix is `01 00 00 00 01 01 00 00 20 00 00 00 ...` (1, 0x101, 32, then hash words). The 89-count page starts `05 00 00 00 01 01 00 00 40 46 4e 00 0f 01 ...`. It is not used for resource boundaries and its fields are unresolved. -- `u16@0x4e` ranges 0-305 and does not match any table count. It is left raw in the tool JSON as `counts[3]`. +- `u16@0x4e` ranges 0-1,382 (0-1,077 in `data.rpf`) and does not match any table count. It is left raw in the tool JSON as `counts[3]`. ## What a page maps @@ -352,11 +433,16 @@ path or resource type is present in a `0DRP` page. tables it points at look like `{hash, 0, index, 0}` records, but the index semantics are not proven. 4. **`q30`/`q40`.** Both contain hash-like tables and are not needed for boundaries. Decode them only with a consumer. -5. **Type-hash semantics.** The same hashes recur across pages (`0xde5f1345` in every sampled navmesh page, +5. **Type-hash semantics.** The same hashes recur across pages (`0xde5f1345` in every sampled navmesh page and 8,412 of all 9,603, `0x00000101` in 14,482 `data.rpf` records). Whether they are class ids, schema hashes or builder tags is **open**. 6. **Full-corpus runs.** The tool is bounded by `--limit`; run it on a whole archive before quoting a count for - that archive. The samples here are complete for `data.rpf` and bounded for the other two. + that archive. `data.rpf`, `navmeshes.rpf` and `anim.rpf` are read whole in *Whole-archive pass*; `levels.rpf` + is still the 64 MiB sample here (its full pass is `docs/world_census.md`), and the common-size, common-hash and + payload-class tables are still slices for navmesh and animation. +7. **`q28` tables past the `q38` boundary.** 1,581 pages declare a `q28` table that ends beyond the streams the + `q38` records need. Reading the following stream for it would settle whether a resource can be longer than its + `q38` records say. ## Tool @@ -376,7 +462,8 @@ error and exit code 2, before anything is scanned or written. An empty archive, header, gives an index with no pages. JSON has a `summary` and one object per page: offset, stored/inflated size, version, `page_count` (`u32@0x20`), -the four counts, table offsets, `q38_records`, raw `q28_records`, continuation streams, `span`, +the four counts, table offsets, `q38_records`, raw `q28_records` (`target` is null for a null pointer; `q28_error` +names a table that was cut short or not read), continuation streams, `span`, `payload_at_0x60`, `complete`, and a `resource` group (its `streams` with offsets and inflated sizes, `bytes`, `page_units` at 64 KiB, `declared_pages` and `declared_matches_units`). CSV is one row per `q38` record: `page_offset,stored,inflated,version,page_count,q28_count,q30_count,q38_count,span,complete,record_index,hash,size,target,target_stream`. @@ -390,9 +477,15 @@ Validation on the package used here: | `levels.rpf` first 64 MiB | 142 | 107 | 871 | 107 | 14 | 1.1 s | | `navmeshes.rpf` first 64 MiB | 1,378 | 1,132 | 6,645 | 1,132 | 210 | 1.6 s | | `anim.rpf` first 256 MiB | 24,232 | 12,398 | 269,320 | 12,398 | 7,865 | 25 s | +| `navmeshes.rpf` full | 90,295 | 9,603 | 54,898 | 9,603 | 2,170 | 2.8 min | +| `anim.rpf` full | 130,470 | 22,823 | 527,439 | 22,823 | 11,760 | 2.5 min | + +The summary also counts the `q28` side: `q28_declared` (the sum of `n28`), `q28_records` (read), `q28_null_targets` +and `q28_tables_unread`. The synthetic test builds its own RPF9 header and pages. It covers an in-page resource, a payload in the next -stream, a `q38` table that itself straddles the stream boundary, the carved-directory mode, and the CSV shape. +stream, a `q38` table that itself straddles the stream boundary, the carved-directory mode, the CSV shape, a +`q28` record with a null pointer in the middle of a table, and a `q28` table past the streams read. ## No-sharing rule diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 856d675d4..ef90efbd5 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -19,6 +19,27 @@ For an index entry with `lds_bytes`, the checker compares the reported workgroup limit counts as a module failure before Vulkan receives the shader. Older indexes without this field still use the normal driver check. Mesh pipelines on devices without mesh shader support still use the existing feature skip. +## Options + +`vk_pipeline_check [cache.bin] [options]` + +| Option | Meaning | +|---|---| +| `cache.bin` | Optional positional pipeline cache. Loaded first if it exists, saved every 10 minutes and at the end, so a stopped run resumes. | +| `--jobs N` | Compile on N threads (default: half the hardware threads). | +| `--start I`, `--count N` | Check only the sorted index entries `[I, I+N)`. | +| `--stage all\|cs\|graphics` | Which stages to check. `--compute-only` and `--graphics-only` are aliases. | +| `--slow SEC` | Print pipelines slower than SEC (default 30); compiles past 60 s are named while running. | +| `--max-bytes N` | Skip `.spv` files larger than N bytes (0 = no limit); every skip is named. | +| `--large-module-bytes N` | Compile modules larger than N bytes alone (default 4 MiB; 0 disables isolation). | +| `--stats FILE` | Write the driver's per-shader statistics as CSV rows `name,stage,statistic,value`. Needs `VK_KHR_pipeline_executable_properties`; use it without `cache.bin`, because a cached pipeline may come without statistics. | +| `--cache-feedback` | Group successful pipeline creations by `VkPipelineCreationFeedback`: cache hits, no hit reported, and unavailable. | +| `--isolate` | POSIX only: check in child processes, `--isolate-batch N` modules at a time (default 256), so a crashing module is recorded as `MODULE CRASH` and the pass continues. Not compatible with `--stats`. | +| `--inflight-file F` | Keep the modules currently in the driver in F as `namephase` lines. It is rewritten by the watchdog and when a large module enters or leaves, and emptied at the end; `make_game.py`'s pipelines stage reads it. | +| `--skip-file F` | Do not compile modules named one per line in F; each is reported as `MODULE CRASH` and counted as a failed pipeline. `make_game.py` writes F after a crash so the next run checks the rest. | + +`--isolate-child` is internal to the parent/child protocol and is not meant to be passed directly. A module with a missing partner stub is skipped; without `--isolate`, a driver crash ends the run. + ## Check user-defined interfaces between stages `tools/shader_link_check.py` compares the binary SPIR-V declarations of the shaders you plan to put in the @@ -62,6 +83,38 @@ and error classes, keeping the local shader files and reports that identify them [interfaces]: https://docs.vulkan.org/spec/latest/chapters/interfaces.html#interfaces-iointerfaces-matching +## Audit wave fidelity for the target GPU + +The subgroup audit combines the translator's wave-width and partition-invariance metadata with +the target device's Vulkan stage capabilities. A device can require 64 lanes for a fragment +shader without being able to require 64 for a vertex or geometry shader. Audit the whole graphics +index or use the same manifest as the interface check. + +```powershell +python -I tools/wave64_pipeline_audit.py /index.json +python -I tools/wave64_pipeline_audit.py /index.json --manifest pairs.json --strict --report wave64-summary.json +``` + +The audit checks the Vulkan device selected on this PC and respects `LEONIDA_VK_DEVICE`. To assess +another device, save `python -I tools/vk_subgroup_info.py --stage-caps` as UTF-8 JSON on that system and pass the file +with `--device-info`. The report counts each shader once and each pipeline by its worst stage. It +contains aggregate counts, capability masks and reason categories. Shader and pipeline names are +excluded from the report. + +| Result | Meaning | +| --- | --- | +| `exact` | Fixed or explicitly requestable translated width, or workgroup exchange in compute/mesh | +| `partition-invariant` | A 32-wide graphics subgroup can run a tier A/B wave64 shader. Tier B atomic slot order can differ. | +| `default-width` | The reported device default matches, with no per-stage width guarantee | +| `approximate` | A tier C wave64 VS, PS or GS depends on cross-half behaviour on the 32-wide device | +| `unknown` | The index or device lacks the information for a decision | +| `unsupported` | The translated width, stage support or execution model does not fit the target | + +In strict mode, exit 1 means at least one result other than `exact` or `partition-invariant`. +Invalid inputs or an unavailable Vulkan probe exit 2. This checks width fidelity from metadata. +Vulkan pipeline creation and drawing still need their own tests. See [Wave64 graphics in the +translator contract](design.md) for how the tiers are assigned. + ## Corpus The translated corpus is 26,503 entries: 2,236 vertex, 12,101 pixel, 2,689 compute, 9,282 mesh and @@ -122,13 +175,36 @@ acceptance only. ## Limiting concurrent compilation of large modules -By default, a SPIR-V module larger than 4 MiB compiles alone. Smaller modules continue to use -`--jobs`. The gate covers module creation and both compute and graphics pipelines. The size -cutoff is a heuristic for [#884](https://github.com/ItsNotRexed/Leonida/issues/884), where several -compiles that each needed gigabytes of host RAM ran at the same time. The pipeline cache still -checkpoints during the run, and isolated modules count towards the regular results. +A SPIR-V module larger than 4 MiB is "large". [#884](https://github.com/ItsNotRexed/Leonida/issues/884) +showed why that matters: several compiles that each needed gigabytes of host RAM ran at the same time. Large +modules now share a memory budget (`runtime/test/large_module_gate.h`): each one reserves 512 bytes of RAM per +SPIR-V byte, and they enter the driver while their reservations fit three quarters of the memory available when +the run starts, up to `--jobs` of them. One large module always gets in when none is compiling, so a module +bigger than the whole budget still compiles, alone among the large ones. Small modules are never held back. On +Linux the budget is the smaller of `MemAvailable` and the room under the cgroup v2 `memory.max` of the process and +every cgroup above it (a container, or `systemd-run -p MemoryMax=...`); on Windows it is `ullAvailPhys`. Where +neither can be read, every large module compiles alone, as before. After each large module, glibc builds call +`malloc_trim(0)`: the driver's compiler frees its memory into the arena of the thread it ran on, and glibc kept it +there. -`--large-module-bytes N` changes the cutoff in bytes. Set it to `0` to disable isolation. +Measured on an RX 9070 XT (RADV GFX1201, Mesa 25.3.6, Mesa shader cache off), on 40 consecutive translated +compute modules of which 27 are over 4 MiB: + +| Large modules | Threads | Wall time | Peak RAM | +|---|---|---|---| +| one at a time (`--large-parallel 1`, the old default) | 6 | 297 s | 7.1 GB | +| memory budget (default) | 6 | 83 s | 8.3 GB | +| memory budget (default) | 12 | 56 s | 15.1 GB | + +One 5.7 MB ray-tracing compute module alone: 12.4 s and 1.96 GB peak (about 330 bytes per SPIR-V byte, hence the +512 estimate); a 0.36 MB one: 0.13 s and 94 MB. The process grew past one module's peak even one at a time because +of the arenas (16 modules, 6 threads: 6.2 GB; with `MALLOC_ARENA_MAX=1`: 2.1 GB). + +- `--large-module-bytes N` changes the cutoff in bytes. `0` disables the gate. +- `--large-parallel N` caps how many large modules compile at once: `0` (default) by the budget, `1` alone with + the other threads waiting (the behaviour before), `N` at most N without a budget. +- `--inflight-file` names every module in flight when a large one enters or leaves the driver, so with several + large modules in flight it names all of them; the `pipelines` stage of `make_game.py` checks each alone. ## Skipping huge modules @@ -147,6 +223,34 @@ The report above therefore states the limit and the skip count; a later run on a completed the full 26,503-entry set without them (`docs/design.md`). `--max-bytes` remains a visibility tool, not a pass: a skipped module has not been validated. +## Build-stage batches (BUILD-1030) + +`make_game.py` runs the pipelines stage in fresh checker processes over at most **500 index entries** each, on +Windows and POSIX. The ranges partition the same name-sorted index as `--start` / `--count`, including the final +short range. Each finished process saves to the same `pipeline_cache.bin`, and the next loads that checkpoint. +This bounds each invocation to a range that can be split further if concurrent heavy compiles exceed available +memory. A work folder with at most 500 entries keeps the single invocation. An older checker without the range +options keeps the older invocation; rebuild the runtime to get batching. + +If a batch crashes, its in-flight modules are checked alone in fresh processes. A module that reproducibly crashes +is recorded as failed, and the rest is checked. If none crashes alone, the entire failed range is retried in +smaller processes, down to one entry; healthy modules are not added to the crash list. An unrecoverable crash, +an interrupted check or a setup error stops the stage. A validation failure in one batch remains a failure even +when subsequent batches succeed; it does not prevent those later batches from being checked. + +The native checker returns 1 for initialization failures as well as validation failures. A completed shader pass +writes/clears its in-flight report even when validation fails. Exit 1 without a new report stops the stage instead +of repeating failed setup for the remaining batches; diagnostic probes use the same distinction. Each process +starts with a cleared report path, so an earlier process's report cannot hide an initialization failure. + +The batch size limits the index range, **not total memory usage**. Concurrent heavy modules, loading a large +saved cache or compiling one large shader can still exceed a process's available memory; a range that +cannot complete even alone fails with a diagnostic rather than being counted as checked. + +`tests/test_make_game_pipeline_batches.py` runs the real build-stage orchestration against scripted child processes: +bounded coverage and cache checkpoints, collective memory-crash recovery, a genuinely crashing module, validation +failures, interruptions, setup failures and compatibility with older checkers. It needs no game files or GPU. + ## Crash isolation (`--isolate`) A driver that dies while compiling one module (for example the RADV `SIGFPE` in @@ -223,9 +327,16 @@ in between. **One process per chunk.** A single `vk_pipeline_check --jobs 4` run over the emulated corpus reached 21,000 of 26,503 pipelines with no failures. Then the driver's compiler ran out of memory (`LLVM ERROR: out of memory`). With 2 jobs, one process later grew past 100 GB of committed memory. -Driver compiler memory isn't returned between pipelines, so the build now runs as one checker -process per 300–500 entries. Each process seeds from and saves to the same cache file, so the chunks -resume. Since #903 the checker also compiles modules over 4 MiB alone. +In those earlier runs, compiler allocations were reported to persist between pipelines; the original workaround +used one checker process per 300–500 entries. The build stage now uses at most 500 per process, with smaller +retries when needed (above). +Each process seeds from and saves to the same cache file, so the chunks resume. Since #903 the checker also +compiles modules over 4 MiB alone. + +For BUILD-1030, [the reporter's later measurements](https://github.com/ItsNotRexed/Leonida/pull/3623#issuecomment-7085912874) +found no accumulation over a 1,500-entry range and cheap loading of the full cache; the large peaks came from +individual heavy modules. The recovery therefore splits the failed range until fewer such modules compile at +once, without treating the initial cache-growth hypothesis as established. **The ScreenProbes shaders.** `indirect_diffuse_lighting`'s ScreenProbes_ActivateProbes, ActivateProbesTarget and ActivateRays compute shaders were 60, 60 and 32 MB of SPIR-V. Their 3,281 diff --git a/docs/rbf0.md b/docs/rbf0.md index 404594a5e..43ad49762 100644 --- a/docs/rbf0.md +++ b/docs/rbf0.md @@ -454,11 +454,16 @@ the last byte. The corpus has 0 bad, 0 truncated and 0 trailing resources. `tools/rbf0_encode.py` writes a tree document back to bytes with the grammar of section 3. It emits each descriptor name at its first use, then the element header words `0, 0, attribute count`, the attributes, and the content in tree order. Text and strings keep their recorded bytes and terminating NUL. `--check` decodes every resource of a carve, -joining continuations as `rbf0_tree.py` does, encodes it, and compares the result with the original bytes. +joining continuations as `rbf0_tree.py` does, encodes it, and compares the result with the original bytes. It exits 0 +only when every resource is byte-identical: a resource that encodes to different bytes or is refused makes it exit 1, +as `rbf0_tree.py` does for a resource that is not `ok`. The encoder fails closed: it refuses a tree that cannot hold the original bytes instead of writing other bytes. A refusal is one of these: an incomplete parse, invalid UTF-8 that the decoder replaced, a NaN float (infinities are -exact), an attribute after content, a descriptor out of order, or a string or text whose byte length changed. +exact), an attribute after content, a descriptor out of order, a string or text whose byte length changed, or a +value the record cannot hold: an integer out of range for the layout, a float that overflows it, an unknown type, or +an element with more attribute records than its attribute count. An element short of its attribute count with a +value in its content is refused as an attribute after content, because that value would decode as an attribute. Measured on the same 1,263 `data.rpf` resources: @@ -471,7 +476,7 @@ Measured on the same 1,263 `data.rpf` resources: | Narrow layout, exact | 3 of 3 | The 23 refused resources are exactly those that hold the 26 invalid UTF-8 text payloads in 9.5. No other reason -occurs. So the tree loses no byte anywhere else: element words, attribute counts, descriptor order, value widths, +occurs, and with them `--check` exits 1 on this corpus. So the tree loses no byte anywhere else: element words, attribute counts, descriptor order, value widths, float bits and NUL terminators all survive. The encoder also writes an edited tree, for example a JSON report changed by hand. It then checks each string and text against the recorded byte length when one is present, so a change that alters a length needs that field dropped or updated. diff --git a/docs/restofworld.md b/docs/restofworld.md index 7f6b0474b..e069e6025 100644 --- a/docs/restofworld.md +++ b/docs/restofworld.md @@ -423,16 +423,38 @@ descriptor supplies meshlet, triangle and reference counts that must agree with pointed-to group's header. This check also validates the packed triangles, vertex reference bounds and padded index-buffer length. -All 311 target blocks have one distinct validated group address under this check. -Geometry records reached through resource-root model lists account for 303. For -the other eight, a search of aligned system records found the same pointer layout -and a primary-LOD geometry list containing the record. The path from the resource -root to that list is still unknown. The pointer search reproduced the addresses -without selecting on the proposed vertex count. The layout count and the group's -dense range subsequently agreed in all 311. This includes the six uniquely paired -page walks and seven walks with a repeated target block count. +The original check found one distinct validated group address for each of the +311 target blocks. The regular drawable LOD lists reached 303. For the other +eight, a search of aligned system records found the same pointer layout and a +geometry list containing the record. The layout count and the group's dense range +agreed in all 311. This includes the six uniquely paired page walks and seven +walks with a repeated target block count. -| Pointed-to group start relative to the target stream | Blocks | +**The eight auxiliary root paths (ASSET-273).** An independent scan of all 22 +archives reproduced 311 outliers and verified all 311 draw bindings. The regular +drawable lists reached 264 blocks through LOD 0 and another 39 through LODs 1–3. +The eight records reached through auxiliary paths each have a verified geometry +record and graphics-group address: + +- **Seven standalone drawables:** follow the root drawable's pointer at `+0xD0`. + In the auxiliary header, `+0x30` points to a table of system pointers and + `+0x38` holds its 16-bit count, which matched capacity in these cases. Each + relevant table entry points to a record whose `+0x68` field leads to the + structure with the geometry list at `+0x50`. +- **One fragment:** start with the fragment root's pointer at `+0x90`, then + follow pointer fields at `+0x130`, `+0x20` and `+0x70`. In that table, entry 1 + (zero-based) reaches the record whose `+0x68` pointer leads to the structure + with the geometry list at `+0x50`. These offsets are one measured route. + +One regular LOD 0 binding needs a compressed final system page that inflates to +48 bytes. The diagnostic scan's 64-byte minimum excluded that page. When the +first page's map declares the final system continuation, the archive diagnostic +accepts a nonempty short page at the next 16-byte boundary with zero padding +and a valid zlib checksum. That restores the normal draw binding. Both the +diagnostic and the pinned model reader recover the containing dictionary's 11 +children. + +| Pointed-to group start relative to the target stream (original survey) | Blocks | |---|---:| | Preceding stream | 68 | | Same stream | 228 | @@ -444,9 +466,10 @@ different group even with an exact match in hand. For an already separated system/graphics resource pair, the following command walks the primary LOD from the drawable offset reported by the model manifest. -Use `--geometry-offset` for a known individual geometry record. Both offsets -are relative to the start of the system segment. Unsupported or inconsistent -bindings are reported as unresolved. +Use `--lod 1`, `--lod 2` or `--lod 3` with the same drawable offset to select a +lower LOD, or use `--geometry-offset` for a known individual geometry record. +Both offsets are relative to the start of the system segment. Unsupported or +inconsistent bindings are reported as unresolved. ```powershell python -I tools/meshlet_page.py --draw-system --drawable-offset @@ -529,6 +552,31 @@ edges, so none of the conclusions below depend on it. | Position header (bias, scale) finite, scale >= 0 | 60,442 / 60,442 | | Every triangle edge no longer than the block extent | 48,150 / 60,442 | +**Slots 6/7 (tag `0x26`) and 8/9 (tag `0x25`) are skin weights and joint indices.** Where slot 8 holds tag +`0x25`, each `0x25` slot comes with a `0x26` slot two below it (slot 6 with 8, slot 7 with 9), and no block in +the sample has one without the other. Read as four unorm8 weights per `0x26` slot and four joint indices per +`0x25` slot, `skin_checks` in `tools/vertex_types.py` counts, per vertex over all weight slots +(core_restofworld, first 500 streams: 612 blocks, 212,564 vertices; 454 blocks with two pairs, 158 with one): + +| Check | Vertices | +| --- | --- | +| Weights sum to 255 | 203,243 (95.6%) | +| Weights sum to 247-255 | 204,758 (96.3%) | +| Weights in descending order | 211,902 (99.7%) | +| No joint repeated among the non-zero weights | 212,564 (100%) | +| Every zero weight has joint index 0 | 156,808 (73.8%) | +| Control: slot 1 colour bytes sum to 255 | 0 | + +The `0x25` bytes are small: the highest joint used by a non-zero weight is below 16 in 488 blocks, 16-31 in +117 and 48-63 in 7. So the indices point into a short per-block (or per-mesh) joint list, not a whole +skeleton; which list was not traced here. + +Of the 9,321 core_restofworld vertices whose weights do not sum to 255, the twelve most common sums (254 +down to 233) all come from one-pair blocks: a four-influence vertex whose weights fall short, as +`tools/skin_streams.py` also finds for one packed four-influence population of the drawable skin streams. +levels (first 400 streams) has 9 skinned blocks (3,910 vertices), all one pair, and every vertex there +passes: one weight of 255 on joint 0. The colour control never sums to 255 in either sample. + Slot usage (block counts): slot 0 tag `0x42` in all 60,442; slot 2 `0x21` in 57,925; slot 1 `0x26` in 57,873; slot 3 `0x28` in 49,294 and slot 4 `0x28` in 29,379; then slot 12 `0x26` (25,239), slot 6 `0x26` (24,876), slot 8 `0x25` (21,519), slot 13 `0x26` (17,928), slot 11 `0x27` (11,120) and 21 rarer slot/tag @@ -579,6 +627,28 @@ than 0x8000 between neighbouring vertices occurs 1,597,530 times when the values half floats, 1,391,311 slot 3 values are NaN or infinite. So the stream is a pair of `int16`s, continuous across the surface, which fits the `x / 32767 * f32@0x7C` texture-coordinate reading. +**Tag `0x27` is a second tangent frame: a unit tangent along `u` of another `0x28` stream, with a sign.** +The mesh shaders fetch it with `tbuffer_load_format_xyzw ... BUF_FMT_2_10_10_10_UNORM` (one of the +four typed vertex formats they use, in 2,162 of the 9,282 mesh shaders) and map every component by +`v * 2 - 1`. They transform xyz by the same matrix as the normal and cross it with the normal, scaled by +w. `tangent_0x27` in `tools/vertex_types.py` is that read: xyz = bits 0-9, 10-19, 20-29 over 1023, and +w = bits 30-31 over 3. Per `0x27` slot, `tangent27_checks` counts unit length over all vertices; over +the sampled triangles it counts vectors perpendicular to the face normal (`|cos| < 0.2`) and, for each +`0x28` stream, vectors within `cos > 0.8` of `dP/du` and the w side: + +| Sample | Slot | Vertices | Unit | w = 3 / 0 | Perpendicular to face | Best `0x28` stream: along u | w > 0 exactly when `cross(face normal, xyz)` runs along `-v` | +| --- | --- | --- | --- | --- | --- | --- | --- | +| levels (400 streams) | 11 | 637,604 | 100% | 634,431 / 3,173 | 86.1% | slot 4: 96.7% (slot 3: 69.5%) | 99.8% | +| core_restofworld (500 streams) | 18 | 182,208 | 100% | 180,282 / 1,926 | 40.3% | slot 14: 79.3% (slot 4: 73.6%, slot 3: 21.0%) | 99.2% | +| core_restofworld | 19 | 12,679 | 100% | 12,445 / 234 | 61.7% | slot 14: 69.0% (slot 3: 54.1%) | 98.5% | + +The w side is counted among the along-u vertices of that stream. The w field only ever holds 0 or 3 in +these samples. Against the vertex normal of tag `0x21` (read as the mesh shaders read it) instead of the +face normal, the slot-18 vectors are perpendicular (`|cos| < 0.1`) for 174,942 of 182,208 (96.0%) and the +slot-19 and levels slot-11 vectors for all of them. Where the face-normal column is low, the face normals +disagree with the vertex normals, as for tag `0x21`. The tangent matches the `0x21` tangent (`cos > 0.99`) +for only 10-17% of vertices, so it is a different frame, the one for a second texture-coordinate stream. + **Tag `0x26` (slot 1) is four bytes with an alpha-like byte 3.** Byte 3 is 255 on 62.4% of the 137.9 million vertices and 0 on 17.2%; each of bytes 0-2 is constant within a block in 36,544 to 38,854 blocks. The bytes change smoothly over edges (block-weighted median edge/random difference ratio 0.18 to 0.27), as a colour or @@ -642,9 +712,15 @@ Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` rec `RSC8` headers, the nested RPF9 payloads, and the whole `appdata0` data area. Across the 971 core graphics blocks, final-slot widths remain unresolved (`0x21`, the last unread component type, is decoded above). The stride check +Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` record contents, the nested RPF9 +payloads, and the whole `appdata0` data area. The bodies of the nine `RSC8` headers are decoded in +[rsc8_audio.md](rsc8_audio.md): facial/lip-sync clips. Across the 971 +core graphics blocks, final-slot widths remain unresolved, and of the component types the non-normal +bits of `0x21` (see above). The stride check also leaves 436 blocks unclassified, including 18 with a validated following meshlet group. "Unread" in the tables above is not a claim that those bytes are empty: in -`story000_restofworld` the 9.33 MB unread gap contains nine `RSC8` headers and nested RPF9 headers, and +`story000_restofworld` the 9.33 MB unread gap contains 15 `ADAT` (AWC) banks (8,908,216 bytes), which hold the +nine `RSC8` headers as tag `0x5c` clips, and nested RPF9 headers, and in `story000_script` the 53 MB unread region contains four nested RPF9 headers. ## Likely format family @@ -663,10 +739,13 @@ The bytes support the existing **RPF9/RAGE family**, not a new container: big-endian length chain are measured; the `LSNS` block layout is decoded, its record contents are not. - `RBF0` records carry schema names (movie subtitles, VFX texture-atlas metadata); XML records carry content definitions. -- `RSC8` appears only as raw headers in the story-rest unread gap. No `RSC7` was found. +- `RSC8` appears only in the story-rest unread gap, as the tag `0x5c` facial/lip-sync clips of its 15 + `ADAT` (AWC) banks ([rsc8_audio.md](rsc8_audio.md)). No `RSC7` was found. Models are present (37 decoded in core, plus 924 name-bearing pages), but the measured bytes do not -support a claim that these archives hold map placement, compiled scripts, audio banks or UI layout. +support a claim that these archives hold map placement, compiled scripts or UI layout. Their only audio banks +are those 15 in story-rest, with 76 streams: 13 carry a streamed-music `0x48` tag and 9 are dialogue lines with +a clip. A raw `tools/rsc8_audio.py` scan of the other five archives finds no `ADAT` bank. The only UI-adjacent evidence is content-manifest XML and text; there is no UI container signature. ## Content-definition reader (ASSET-149) @@ -763,6 +842,51 @@ not raw stream-start images. Measured on the 1.0.2.1 package, they live in two p | `pack/core_restofworld/data/ttdb/vfx/ttdb_vfx.ttpf` | 3,129,600 | 17 | `BC7_UNORM_SRGB` 5, `BC1_UNORM` 5, `BC5_UNORM` 5, `BC4_UNORM` 1, `BC3_UNORM_SRGB` 1 | | `pack/core_restofworld001/data/ttdb/ui/ttdb_ui.ttpf` | 38,656 | 5 | `BC7_UNORM` 3, `BC3_UNORM` 2 | +### Which source the drawables' texture references reach + +The drawables name textures by the 64-bit texture IDs in their shader parameter records +([textures.md](textures.md)). Measured over the 1,732 `.ydr`/`.yft`/`.ydd` entries of the two core archives in +a local RPF9 index (all decoded; 17,208 texture references to 675 distinct IDs), against the ID tables of all 57 +`.ttpf` pools in the package and against the two sources above: + +| Where the ID is | Distinct IDs | References | +|---|---:|---:| +| a pool under `pack/core_restofworld*/data/ttdb/` | 285 | | +| a shared pool under `data/ttdb/` | 258 | | +| subtotal: in a pool | 543 | 6,403 | +| a key of an embedded `pgDictionary`, or any u64 inside the 145 embedded-texture streams | 0 | 0 | +| nowhere | 132 | 10,805 | + +The 144 embedded dictionaries hold 166 keys; 119 of them have a zero high half, and none equals a referenced ID +or either 32-bit half of one. So these 64-bit IDs reach the pools only; how a drawable binds the embedded +`0x980` textures was not traced here. + +The unresolved share is not spread over the materials. By shader texture slot (slots named by role where the +material's own textures show it; the others are unnamed and listed by size): + +| Slot | References in a pool / nowhere | Distinct IDs in a pool / nowhere | +|---|---:|---:| +| colour | 1,818 / 136 | 166 / 15 | +| normal | 1,758 / 223 | 145 / 14 | +| specular | 1,675 / 306 | 149 / 19 | +| a fourth material slot | 1,049 / 931 | 52 / 24 | +| five slots with one fixed ID each | 0 / 1,463 to 1,568 each | 0 / 1 each | +| a sixth such slot | 6 / 1,517 | 1 / 2 | +| one slot that never resolves | 0 / 184 | 0 / 57 | + +The per-asset material textures resolve for about nine references in ten (colour 93%, normal 89%, specular 85%). +Most unresolved references come from six slots that each use one fixed ID on 1,463 to 1,568 shaders: textures +shared by the whole engine and bound at run time rather than stored with an asset (hypothesis: lookup tables, +noise or environment maps). + +Pool entry formats of the 543 resolved IDs (DXGI numbers): 71/72 (BC1) 391, 98/99 (BC7) 120, 83 (BC5) 14, +78 (BC3) 14, 80 (BC4) 3, 65 (A8) 1; 22 are 4 x 4 placeholders. + +Method: drawables decoded with a local RPF9 model decoder (the shader parameter layout of textures.md); pool ID +tables read from each pool's `ETPF` section (count at +8, 16-byte records, then the sorted u64 IDs); embedded +streams found with `tools/restofworld_index.py`'s `find_rage_textures` / `is_pg_tex_dictionary` (keys at the +`+0x20` pointer, count at `+0x28`). Counts only; no IDs, names or texture data. + ## What a future decoder needs 1. The RPF9 table-of-contents key/schema for names, paths and exact entry boundaries. This project diff --git a/docs/rpf.md b/docs/rpf.md index b0f48dbf2..a72fc55d6 100644 --- a/docs/rpf.md +++ b/docs/rpf.md @@ -15,6 +15,47 @@ are offset-based (`recovered/...`), not the original paths. `story000.rpf` and `shared_minigame000.rpf` is non-zlib. Unread bytes are recorded as ranges (the `unread` list in `rpf9_carve.py`'s `index.json`), never guessed. +## Whole-package name coverage (reported in #1790) + +The recovery view names streams by offset, but some original paths can be read from the payload itself: +mount XMLs and similar text in the data area list them in plain text, directory form included. #1790 ran one +name-recovery walker over all 22 archives of a retail package (150.2 GiB) and reports how far that gets. These +counts are as reported there; they were not re-run for this page. + +| | Count | +|---|---:| +| Streams | 1,489,677 | +| Streams with a name | 177,087 (11.89%) | +| Unique paths | 155,214 | +| Unique identifiers | 200,184 | +| Path mentions | 526,581 | + +| Stream type (walker's classes) | Named / streams | Share | +|---|---:|---:| +| `sgd5_shader_dxbc` | 25,043 / 25,043 | 100.00% | +| `xml` | 191 / 332 | 57.53% | +| `rsc50` | 123,889 / 531,370 | 23.32% | +| `xml_chunk` | 109 / 504 | 21.63% | +| raw | 26,766 / 690,003 | 3.88% | +| `PSIN` | 465 / 15,380 | 3.02% | +| `0DRP` | 624 / 227,045 | 0.27% | + +Three findings from the same run: + +- The paths come from the payload, not the TOC. One 8 KB stream in `common.head.bin` declares 473 `.bk2` paths on its + own. +- Stream alignment is not universal. Inflated streams sit on 4 KiB boundaries in `data.rpf` (295 of 301 checked) + but not in `levels.rpf` (8 of 26), `packs.rpf` (0 of 301) or `textures.rpf` (0 of 3), so a walker that assumes + 4 KiB steps misses most streams in three of those four. `tools/rpf9_carve.py` does not assume an alignment: it + continues after the bytes each stream consumed. +- `anim.rpf` is the richest archive for names (64,785 named streams, 367,190 path mentions, almost all `.clip`). + `movies.rpf` produced no zlib streams, and `script.rpf` and `story000_script.rpf` no names. + +The 11.89% is the ceiling of this method, not a progress figure: the rest of the names are in the encrypted TOC, +which this project does not decode. #1790 also confirms the TOC is not ECB (no duplicate 16-byte blocks in 62,487). +The full name index is not published; the issue offers salted hashes of the paths and identifiers so that another +run can be compared without publishing a name. + ## Stream roles In the measured carve indexes, a resource's system prefix can be separated from its graphics pages without diff --git a/docs/rsc8_audio.md b/docs/rsc8_audio.md index d57e1ce56..68a1b70d1 100644 --- a/docs/rsc8_audio.md +++ b/docs/rsc8_audio.md @@ -1,6 +1,6 @@ # `RSC8` audio-bank resources (AWC tag `0x5c`) -**Status: decoded at container, object-graph, property, animation-block and track-directory level; stdlib decoder in [`tools/rsc8_audio.py`](../tools/rsc8_audio.py).** +**Status: decoded at container, object-graph, property, animation-block, track-directory and keyframe level; stdlib decoder in [`tools/rsc8_audio.py`](../tools/rsc8_audio.py).** [story.md](story.md) measured 225,281 raw `RSC8` (version `8001` / `0x1F41`) headers in `story000.rpf` (plus 1,957 in `shared_minigame000.rpf` and 9 in `story000_restofworld.rpf`), and the mission-music @@ -63,30 +63,33 @@ zero-stream bank, so only `audio.rpf`'s bank and byte counts changed (banks 7,16 them per stream in its scan tallies (`grid20_*`, `indexrun_*` summary keys): over the whole archive **387,233 `0x5a` entries / 0 invalid** and **4,853 `0xd9` groups / 0 invalid / 0 index overruns**. Every invariant below was measured on that full population; the field names describe structure, and the meaning of -`value`, `s`, `t` and the last entry's tail float stays a labelled hypothesis. +`p`, `z`, `s`, `t` and the trailer stays a labelled hypothesis. -`0x5a` — `{u32 12345678; u32 unknown; N × 20-byte entries}` (`(size − 8) % 20 == 0` always): +`0x5a` — `{u32 12345678; N × 20-byte entries; f32 trailer}` (`(size − 8) % 20 == 0` always). The framing is +@kotorvr's ([finding](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7084750136)), recounted +for ASSET-256; read 4 bytes later, as before, each entry paired one entry's fields with the next one's +position, and the trailer became the last "counter": ``` -0 f32 value (3.658 .. 146.789 measured; spans up to 133 within one stream) -4 u16 p (a multiple of 32 on every measured entry) -6 u16 z (0 .. 16) -8 u16 index_lo -10 u16 index_hi (index pairs tile 0..129 / 1..130 measured) -12 u16 s -14 u16 t -16 u32 counter (every entry but the last: a sample position, see below) -16 f32 tail (the last entry only: 2/3 = 0x3f2aaaab on 1,182 streams, 0.666812 on 1, 0.725624 on 2) +0 u32 position (a sample position at the stream's rate, see below) +4 f32 value (3.658 .. 146.789 measured; spans up to 133 within one stream) +8 u16 p (a multiple of 512 on every measured entry) +10 u16 z (0 .. 16) +12 u16 index_lo +14 u16 index_hi (index pairs tile 0..129 / 1..130 measured) +16 u16 s +18 u16 t +trailer: f32 (2/3 = 0x3f2aaaab on 1,182 streams, 0.666812 on 1, 0.725624 on 2) ``` -The counter is a sample position in the stream (ASSET-256, measured over all 1,185 streams and 386,048 counters, -`tools/rsc8_audio.py`'s `grid20_counter_past_samples` = 0). On every entry but the last it ascends strictly and -stays below the `0x76` sample count: the largest counter is 0.9986 of the stream's samples, the last one ends -p10/p50/p90 0.8/1.85/5.4 mean entry steps before the stream's end, and the first entry-to-entry step averages -the stream's samples-per-entry (p50 ratio 0.996). The last entry holds an f32 at `+16` in place of a counter. -Read as a u32 it is about 1.06 × 10⁹, 2^9.9–2^15.2 times the sample count, which is what made the counter look -finer than a sample before. What the tail float means is not known. Every one of these streams is mono XMA2 -(`0x76` codec 5) at 32,000 Hz (one at 32,007 Hz). +The position is a sample position in the stream (ASSET-256, all 1,185 streams and 387,233 entries; +`tools/rsc8_audio.py`'s `grid20_position_past_samples` = 0). It ascends strictly and stays below the `0x76` +sample count: the largest is 0.9986 of the stream's samples, and the last one ends p10/p50/p90 0.8/1.85/5.4 +mean entry steps before the stream's end. One entry lasts one period of its `value` read as a frequency: +`(position[k+1] − position[k]) × value[k] / rate` is within 1% of 1 on 365,803 of the 386,048 entry pairs +(within 5%: 383,993), so `value` reads as a pitch in Hz. Read as a u32, the trailer is about 1.06 × 10⁹, +2^9.9–2^15.2 times the sample count, which made the old "counter" look finer than a sample. Every one of these +streams is mono XMA2 (`0x76` codec 5) at 32,000 Hz (one at 32,007 Hz). `0xd9` — `{u32 K; K × {u32 2; u32 len; u32 hash; len × u32}}`: the run values ascend strictly inside each group, exactly one distinct `hash` appears per stream, the group count always equals `K`, and **every run @@ -146,6 +149,8 @@ records, 0 invalid on `audio.rpf`). Over all of `audio.rpf`: +12 u32 extra 0 on 363,166 records, 1..6 on the rest ``` +The name word is 0 on 96 records (78 tags start with one); what a nameless record means is unknown. + - **The name is a joaat of a lowercase word.** Four of the stored values are the hashes of `beat` (`0xe89ae78c`, 17,770 records), `trackid` (`0xa6d93246`, 1,042), `intro` (`0xda8f5f53`, 835) and `outro` (`0x5d40b28d`, 825), as the [GTA6-Asset-Info](https://github.com/TrinitronClient/GTA6-Asset-Info) byte reference reports @@ -158,8 +163,9 @@ records, 0 invalid on `audio.rpf`). Over all of `audio.rpf`: - The same reference states that an AWC tag id is the low byte of the joaat of the chunk name. That holds for `markers` (`0xbd`), `data` (`0x55`), `peak` (`0x36`), `seektable` (`0xa3`) and `streamformat` (`0x48`), which `tests/test_rsc8_audio.py` checks, and by the same rule `0x5a` and `0xd9` are `granulargrains` and - `granularloops`. It does not hold for `0x5c`, `0x76` and `0xb2` under the names `animation`, `format` and - `metadata`, so those three names stay open. + `granularloops`. Those spellings are this document's: the reference prints the last two as `seek_table` and + `stream_format`, and with the underscore the rule fails (`0xb8` and `0xf9`). It does not hold for `0x5c`, + `0x76` and `0xb2` under the names `animation`, `format` and `metadata` either, so those three names stay open. ## Binary format of `RSC8` (version `8001`) @@ -262,16 +268,18 @@ block after it, or splits long dialogue animations across `2` or `3` blocks): +0x00 u32 signature +0x04 u32 payload_size always anim_size - 32 +0x08 u32 reserved 0 -+0x0C u32 chunk_data_offset <= payload_size ++0x0C u32 chunk_data_offset <= payload_size; where the channel definitions end and the frame data starts +0x10 u32 anim_size total packed block size in bytes (>= 32) +0x14 u16 format_version always 2 +0x16 u16 frame_count frames in this block -+0x18 u32 extra_flags -+0x1C u16 sub_count -+0x1E u16 track_format_tag always 11 -+0x20 ... compressed facial animation bitstream (`payload_size` bytes) ++0x18 u32 extra_flags low u16: bytes per frame; high u16 not decoded ++0x1C u16 sub_count sum of the type-4 channel bit widths ++0x1E u16 track_format_tag always 11: a u8 11 (the number of channel types) and a zero byte ++0x20 ... one keyframe sequence (`payload_size` bytes), see section 7 ``` +The field names are the ones `tools/rsc8_audio.py` reports; the notes on the right are what section 7 measured. + Multi-block animations share their boundary frame between consecutive blocks, so across `N` blocks: ``` @@ -286,10 +294,39 @@ and `restofworld` clips; `90`, `88`, or `87` on `audio.rpf`) × 12-byte records ``` +0x00 u32 track_id_hash sorted ascending (non-decreasing) across the directory -+0x04 u32 schema_hash constant 0x364D3BDB -+0x08 u32 track_type 3 (vector/quaternion-style) or 4 (scalar facial weight) ++0x04 u32 schema_hash constant 0x364D3BDB = joaat("facialtranslation"), a track type ++0x08 u32 track_type the value format: 4 = one value per frame, 3 = two values per frame ``` +This is the 12-byte track entry of the clip dictionaries in `anim.rpf` (`{id, track-type hash, value format}`, +[animation.md](animation.md#objects)); `facialtranslation` is one of the track types `tools/anim_clips.py` names. + +### 7. Keyframes + +A packed block is one **sequence** as [animation.md](animation.md#sequences) describes it for `anim.rpf`: the +0x20-byte header, the channel definitions grouped by type, `frames x bytes per frame` of frame data, `u16 +count[11]` and the per-type `(track << 2 | component)` lists. Nothing new had to be decoded: `rsc8_audio.py +--curves` hands every block to `anim_clips`' sequence decoder and counts the outcome. It writes counts only. + +| Archive | Clips | Decoded | Type-10 chunk boundaries closed | +|---|---:|---:|---:| +| `story000_restofworld.rpf` | 9 | 9 | 593 / 593 | +| `shared_minigame000.rpf` | 1,957 | 1,957 | 439,313 / 439,313 | +| `story000.rpf` | 225,281 | 225,281 | 29,144,718 / 29,144,718 | +| `audio.rpf` | 414,181 | 414,181 | 58,428,044 / 58,428,044 | +| **Total** | **641,428** | **641,428** | **88,012,668 / 88,012,668** | + +Over those 641,428 clips: + +- The decoded frame count equals the clip's on 641,428, and the header's bit sum equals the + type-4 widths on 641,428. +- Channels by type: type 2 (constant) 21,683,337, type 4 (quantised) 9,171,169, type 5 (table) 162,508 and + type 10 (second-order delta) 33,239,783. No other type occurs, so a facial clip has no quaternion channel. +- All 57,706,322 directory entries get values, and the component count follows the entry's format on every one: + format 4 decodes to one value per frame (51,159,853 tracks) and format 3 to two (6,546,469 tracks). + +`decode_facial_curves` returns the per-frame values to a caller; the tool itself never prints or stores them. + ## Full-corpus validation results `tools/rsc8_audio.py` validates every resource against 24 structural integrity checks (wrapper size, @@ -312,9 +349,10 @@ internal `RSC8` clip-name hash whose low 29 bits differ from the enclosing AWC ` ## What remains undecoded -- Individual facial keyframe curves inside the compressed `crAnimation` bitstream (`block+0x20 .. block+anim_size`, - `format_version = 2`, `track_format_tag = 11`). Decoding facial rigs/blendshape evaluation belongs to - the animation runtime, not audio extraction. +- What the curves drive. The keyframes decode (section 7), but which facial control each `track_id_hash` names, + the unit of a value and how the rig evaluates them are not established here; that belongs to the animation + runtime, not audio extraction. +- The high u16 of a block's `+0x18` word. - The semantic difference (if any) of version flag bit 24 (`0x01001F41`) on the 201 `audio.rpf` clips; structurally all 201 parse identically to `0x00001F41`. @@ -330,6 +368,10 @@ python -I tools/rsc8_audio.py \pack\shared_minigame000\shared_minigame0 python -I tools/rsc8_audio.py \pack\story000\story000.rpf --summary-only python -I tools/rsc8_audio.py \audio.rpf --summary-only +# Also decode every clip's keyframes and count the outcome (slower: about 40 clips per second per process; +# split a large archive with --start/--limit and add the summaries) +python -I tools/rsc8_audio.py \pack\shared_minigame000\shared_minigame000.rpf --summary-only --curves + # Optional per-clip structural JSON/CSV export to a local work directory python -I tools/rsc8_audio.py \pack\shared_minigame000\shared_minigame000.rpf \rsc8.csv ``` diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 6487151af..790fbc0de 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -114,7 +114,10 @@ and the `api-ms-win-core-file-*` sets a GDK title links against. `ERROR_ACCESS_DENIED` (as deleting one does), a move between `GAME:` and a host path with `ERROR_NOT_SAME_DEVICE`, and `MOVEFILE_DELAY_UNTIL_REBOOT` with `ERROR_INVALID_PARAMETER`. - `CopyFile`, `CopyFileEx` and `CopyFile2` read the source the way a read does and write a `GAME:` destination in the - overlay; fail-if-exists counts a name only the package has. Either side can be a host path. + overlay; fail-if-exists counts a name only the package has. Either side can be a host path. Where the host has no + `CopyFile2` (Wine 9, whose loader binds the import to a stub that aborts the process), the shim copies with + `CopyFileExW` instead: the flags both calls define and the cancel flag are passed on, CopyFile2-only hints are + dropped, and a `COPYFILE2` progress routine is not called. - `SetFileAttributes*` sets the attributes on the overlay copy, copying a package file up (or mirroring a package folder) first, so the package keeps its own. @@ -162,7 +165,8 @@ pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name with `ERROR_PROC_NOT_FOUND` and is logged once. Every other module goes to the host unchanged. `runtime/shims/xgameruntime.cpp` serves the five entry points. The initializers succeed offline and log the GDK -version and mode once. `QueryApiImpl` serves `XThreadingImpl` and `XErrorImpl` (below); for any other class it logs +version and mode once. `QueryApiImpl` serves `XThreadingImpl` and `XErrorImpl` (below), and `XUserImpl` from xgameruntime-docs' layout +(below); for any other class it logs the class and interface id and returns `0x80070032`, the documented error for a class the runtime doesn't provide, so the first boot with the executable lists the classes to implement next. `xgameruntime_test` drives this path through the api-set binding `XCurl.dll` uses, and calls the two classes slot by slot. @@ -194,7 +198,18 @@ count and width, the function at that position of xgameruntime-docs' "Layout" li | `XNetworkingImpl` (`IXNetworkingImpl2`, slots 3-20) | 11-17 (`XCurl.dll`), 3-20 (`libHttpClient.GDK.dll`, each in its documented argument shape, e.g. 18-20 (enum, u64 pointer / u64 / pointer)) | the Utf16 `XNetworkingQuerySecurityInformationForUrl*` trio, `XNetworkingVerifyServerCertificate`, `XNetworkingGetConnectivityHint`, `XNetworkingRegister/UnregisterConnectivityHintChanged` (pointer, bool). Served offline, asked for with `IXNetworkingImpl2`'s id | | `XSystemImpl` (`IXSystemImpl5`, slots 3-8 known) | 3-8 (`libHttpClient.GDK.dll`) | 3-5 `XSystemGetConsoleId` / `GetXboxLiveSandboxId` / `GetAppSpecificDeviceId` (size, pointer, pointer each), 6 `XSystemHandleTrack` (two pointers, IXSystemImpl3), 7 `XSystemIsHandleValid` (pointer), 8 `XSystemAllowFullDownloadBandwidth` (bool, IXSystemImpl4); IXSystemImpl2 and 5 add no known method. Served offline | | `XPersistentLocalStorageImpl` (`IXPersistentLocalStorageImpl3`, slots 3-8) | none called (the table of ids only) | slots 3-7 are `XPersistentLocalStorageGetPathSize` / `GetPath` / `GetSpaceInfo` / `PromptUserForSpaceAsync` / `PromptUserForSpaceResult`, slot 8 `XPersistentLocalStorageMountForPackage` (IXPersistentLocalStorageImpl3). Slots from the public xgameruntime-docs and Wine IDL, not measured in a caller. Served offline: the folder is `\persistent`, the quota is the 2048 MB of `MicrosoftGame.Config`, a prompt for space the quota holds succeeds, and `MountForPackage` is `E_NOTIMPL` | -| `XPackageImpl` (`IXPackageImpl3`) | 3-19, 22, 24-27, 30, 32-34, 37-40 (`libHttpClient.GDK.dll`) | slots 3-34 are IXPackageImpl's 32 entries, 35-38 IXPackageImpl2's 4, 39-40 IXPackageImpl3's 2. Not served yet | +| `XPackageImpl` (`IXPackageImpl3`) | 3-19, 22, 24-27, 30, 32-34, 37-40 (`libHttpClient.GDK.dll`) | slots 3-34 are IXPackageImpl's 32 entries, 35-38 IXPackageImpl2's 4, 39-40 IXPackageImpl3's 2. Served offline: 3 identifier, 4 packaged process, 11 user locale, 24-26 mount path size / path / close; the rest log once and return `E_NOTIMPL` | +| `XGameImpl` (`IXGameImpl3`, slots 3-5) | none in the package's DLLs (`libHttpClient.GDK.dll` holds its id only in the linked id table); the executable's requests are unmeasured | from the xgameruntime IDL: 3 `XGameGetXboxTitleId` (pointer), 4 `XLaunchNewGame` (two strings and a user handle, `void`), 5 `XLaunchRestartOnCrash` (string, u32). Served offline: the title id is `MicrosoftGame.Config`'s `` (`E_FAIL` without one), a new game launch is logged and ignored, a crash restart succeeds with nothing registered | + +**Two layout sources, and where they differ.** Besides xgameruntime-docs (GPL; facts only), the LGPL +`include/*.idl` of xodus-gaming/xgameruntime (from the Wine project) declares each interface with its methods in +order. Compared class by class, the two agree exactly wherever the docs list no `_unknown_` slot: `XGameSaveImpl`'s 30 +methods, `XGameImpl`'s 3, `XStoreImpl`'s 81 (to `IXStoreImpl6`). Where the docs list one, the IDL is not consistent: +for `XErrorImpl` it keeps the slot as `HRESULT __PADDING__()`, so the two still line up, but for `XUserImpl` (the +docs' slot 15) and `XDisplayImpl` (slot 3) it has no entry at all, and every later method sits one slot earlier than +the docs put it. Take a layout from the IDL only where it matches the docs' slot count, and read an IDL interface that +skips one of the docs' unknown slots as missing it, not as proof the slot doesn't exist. The measured slots in the +table above all follow the docs. `XThreadingImpl` forwards each slot to `third_party/xtaskqueue`, the same implementation the named exports use; `XThreadSetTimeSensitive`/`XThreadIsTimeSensitive` keep a per-thread flag and the two private slots log once and @@ -205,18 +220,94 @@ connectivity (level None), the port and URL security-information queries fail wi certificate check fails the same way, change registrations return tokens that never fire, and the three `IXNetworkingImpl2` additions are `E_NOTIMPL`. +`XUserImpl` (`runtime/shims/xgameruntime_user.cpp`) is served from xgameruntime-docs' layout alone. No package DLL +calls an `XUser*` slot (`libHttpClient.GDK.dll` only holds the GUID table), so its slots are **not measured** yet. +The executable's first boot confirms them, or names the slots that differ. +- **Interfaces:** the class id doubles as `IXUserImpl`'s; `IXUserImpl2`-`6` answer with the same 50-slot vtable; + `IXUserGamertagImpl` (`XUserGetGamertag`) is a second interface. +- **The user:** one offline local user, always signed in. `XUserAddAsync` adds it with or without + `AddDefaultUserSilently` (with `AllowGuests` as well, it's `E_INVALIDARG`, as documented). It has fixed non-zero user + and local ids, is not a guest, is an adult, and has every privilege. Its gamertag comes from `LEONIDA_GAMERTAG` (15 + printable ASCII characters at most), `Player` otherwise. +- **Handles:** each one is its own allocation, closed once by `XUserCloseHandle`. `XUserCompare` is 0 for any two + handles, since they all name the one user. +- **Not available offline:** token, gamer-picture, MSA-token and resolve-issue requests fail synchronously before + starting (`E_GAMEUSER_FAILED_TO_GET_TOKEN`, `E_FAIL`, `E_GAMEUSER_FAILED_TO_RESOLVE`), so no `XAsyncBlock` waits. + `XUserGetSignOutDeferral` is `E_GAMEUSER_DEFERRAL_NOT_AVAILABLE`, and change callbacks are only tracked as tokens, + because the user never changes. +- **Logged on first use:** the docs' unknown slot 15 (answers `E_NOTIMPL`, so nothing reads outputs it didn't + write), the PC-only `IXUserImpl5` slots and `IXUserImpl6`'s undocumented sign-out trio (`XUserIsSignOutPresent`, a + bool, answers false). +- **Validity:** handles are looked up in a live set, never read, so a closed or foreign pointer is refused without + touching its memory, and a double close does nothing. Unregistering a change callback is never pending, so it + returns true for any token. `XUserIsStoreUser` is true, as documented for console. + +`xgameruntime_user_test` calls every served slot with the documented arguments. + Which classes the package's GDK modules reference, from a byte search for the class and interface GUIDs that xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; counts only, nothing else read): | Module | Runtime classes referenced (highest interface id present) | |---|---| | `XCurl.dll` | `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl` (`IXNetworkingImpl2`) | -| `libHttpClient.GDK.dll` | 24 of the 24 documented classes, each GUID once. Five are called through thunks ("Class layouts, measured" below): `XThreadingImpl` (27 thunks), `XPackageImpl` (30), `XNetworkingImpl` (18), `XSystemImpl` (6), `XErrorImpl` (3); the others are referenced only by the id table. Highest interfaces: `IXSystemImpl5`, `IXUserImpl5` (not 6), `IXGameImpl3`, `IXStoreImpl6`, `IXPackageImpl3` (not 4), `IXGameUiImpl4`, `IXGameSaveImpl3`, `IXGameStreamingImpl3`, `IXPersistentLocalStorageImpl3`, `IXUserDeviceImpl2`, `IXNetworkingImpl2` | +| `libHttpClient.GDK.dll` | 23 of the 24 documented classes (not `XGameActivationImpl`), each GUID once: the ids of the `xgameruntime.lib` thunks the incremental link kept, 404 of them. `XThreadingImpl` (27 thunks), `XPackageImpl` (30), `XNetworkingImpl` (18) and `XSystemImpl` (6) are the ones read by hand above; `XErrorImpl` (3) and 18 more classes have thunks too. Only `XThreadingImpl`'s and `XErrorImpl`'s are called ([below](#measuring-which-runtime-classes-a-binary-calls)). Highest interfaces: `IXSystemImpl5`, `IXUserImpl5` (not 6), `IXGameImpl3`, `IXStoreImpl6`, `IXPackageImpl3` (not 4), `IXGameUiImpl4`, `IXGameSaveImpl3`, `IXGameStreamingImpl3`, `IXPersistentLocalStorageImpl3`, `IXUserDeviceImpl2`, `IXNetworkingImpl2` | | every other `.dll` | none | So `XCurl.dll` needs threading, error reporting and networking from the runtime, and the interface versions in `libHttpClient.GDK.dll` date the GDK the package was built with: newer than the first `IXUserImpl5`, older than -`IXUserImpl6`. The executable's own set is still unmeasured. `QueryApiImpl`'s log gives it on the first boot. +`IXUserImpl6`. The executable's own set is still unmeasured. `tools/gdk_runtime_calls.py` gives it from the file +(below), and `QueryApiImpl`'s log on the first boot. + +### Measuring which runtime classes a binary calls + +`tools/gdk_runtime_calls.py` lists, from the file alone, the runtime classes, interface ids and vtable slots an image +calls through `xgameruntime.lib`'s thunks, so the executable's list is known before it first runs. +`scripts/first_look.ps1` runs it on the executable. + +```powershell +python -I tools/gdk_runtime_calls.py "$game\XCurl.dll" "$game\libHttpClient.GDK.dll" # text; --json for JSON +python -I tools/gdk_runtime_calls.py --out # writes .gdk_calls.txt and .json, prints a summary +``` + +It finds the helper the thunks share (the call a known id's `lea` feeds, after which a vtable slot past IUnknown is +called), takes every call to it as a thunk, reads the class and interface ids loaded into `rcx` and `rdx` (an id the +table doesn't know is listed as unknown) and records each slot called up to `Release`, within the thunk's +`.pdata` function or a byte window without one. The slots are named from `tools/gdk_runtime_classes.json`: the ids, +inheritance and method order of xodus-gaming/xgameruntime-docs (GPL-3.0; facts only), made with +`python -I tools/gen_gdk_runtime_classes.py `. An interface's slot table is its chain's methods, base +first, from slot 3. For each class the report says whether `runtime/shims/xgameruntime.cpp` has its class id (a +`constexpr GUID k...Class`), and for each thunk whether anything in the image reaches it: a call, tail jump, address +load or pointer in data, directly or through an incremental-link `jmp` stub, a call from another thunk counting only +when that thunk is reached. The argument count it prints is an estimate from the registers and stack slots written +before the call. + +Measured on the package's DLLs (counts and slots only): + +| Image | Thunks (referenced) | Classes and slots | +|---|---:|---| +| `XCurl.dll` | 16 (16) | `XThreadingImpl` 3, 5, 12, 16-18, 22, 29; `XErrorImpl` 3; `XNetworkingImpl` as `IXNetworkingImpl2` 11-17, as in the table above. The estimated argument counts match the documented signatures for all 16 | +| `libHttpClient.GDK.dll` | 404 (15) | 23 classes through one helper. `XThreadingImpl` 3-7, 9-30, `XNetworkingImpl` as `IXNetworkingImpl2` 3-20, `XSystemImpl` as `IXSystemImpl5` 3-8 and `XPackageImpl` as `IXPackageImpl3` 3-19, 22, 24-27, 30, 32-34, 37-40 match the slots read by hand; the other 19 classes have thunks too. Referenced: `XThreadingImpl` 3, 5, 7, 9-15, 17, 19, 22, 29 and `XErrorImpl` 3 only | +| the other 14 DLLs | 0 | none | + +`libHttpClient.GDK.dll` is incrementally linked (its entry point is a `jmp rel32` stub), and an incremental link +doesn't remove unreferenced functions (`/INCREMENTAL` turns `/OPT:REF` off): it carries 404 thunks and calls 15. Two +interface ids its thunks ask for are not in xgameruntime-docs: one of `XGameSaveImpl` (slots 33-49, after the 30 of +`IXGameSaveImpl3`'s chain) and one of `XGameStreamingImpl` (slots 3-6). The report prints them. + +Limits: + +- x86-64 only, and the thunk shape measured here: the class id loaded with a RIP-relative `lea` into `rcx` and the + interface id into `rdx` (or the class id copied there), the vtable read with `mov r,[r]` and the slot with + `mov r,[r+disp]` and a call (the CFG dispatch, or `call r`) or `call [r+disp]`, register copies followed. A + `QueryApiImpl` call outside the library's thunks is found only when it has that shape; helper calls it can't + follow to a slot are listed. +- Static: a referenced thunk may never run, and a reference through a computed address or from another module is + not seen. +- "Served" means the shim has the class id. It doesn't say that each slot does more than log, nor that + `QueryApiImpl` accepts the interface id the thunk passes; the report marks each request whose interface id is not + the class id. +- Names are as complete as xgameruntime-docs: an *unknown* entry keeps its slot unnamed, and a slot past an interface + without a documented layout is unknown. A title that calls `LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress` or `FreeLibrary` on one of the package's bundled DLLs (`Bink2Scarlett.dll`, `XboxBvhBuilder.dll`, the FidelityFX DLLs) is routed through `rt::Loader` instead of @@ -240,8 +331,9 @@ end to end with a synthetic bundled DLL importing `xmem.dll!XMemAlloc` and `XMem no error callback. - Reading a response and `WinHttpWriteData` fail with `ERROR_WINHTTP_INCORRECT_HANDLE_STATE`. Options, timeouts and headers are accepted; `WINHTTP_OPTION_CONTEXT_VALUE` and `WINHTTP_OPTION_HANDLE_TYPE` can be queried. -- A status callback is inherited by child handles, which report `HANDLE_CREATED`; every handle reports - `HANDLE_CLOSING` once, last. `WinHttpCrackUrl` only parses, so it is the host's. +- A status callback is inherited by child handles, and so is the parent's `WINHTTP_OPTION_CONTEXT_VALUE` as it is + when the child is made (measured on the host's `winhttp.dll`). Child handles report `HANDLE_CREATED`; every + handle reports `HANDLE_CLOSING` once, last. `WinHttpCrackUrl` only parses, so it is the host's. - Because the shims own the module, a title's `LoadLibrary("winhttp.dll")` gets a pseudo-handle too, and a WinHTTP function outside these 16 resolves to `NULL` (logged), never to the host. diff --git a/docs/sandbox.md b/docs/sandbox.md new file mode 100644 index 000000000..701c4e515 --- /dev/null +++ b/docs/sandbox.md @@ -0,0 +1,86 @@ +# Real-shader sandbox: placed props through the game's own translated shaders + +Follows [first_light.md](first_light.md) §5: a real camera through a vertex shader's constants, a TTPF albedo +through the bindless set with the game's sampler, and many placed world props instead of one model. Measured on +2026-11-22 from one retail Xbox Series install (1.0.2.1), on an NVIDIA GeForce RTX 4070 Ti SUPER (driver 621.24). +Nothing below reproduces game data; every number is a count. + +## 1. What runs + +`tools/sandbox.py` packs the props around a point (`tools/sandbox_scene.py`), picks one translated VS/PS pair from +the work folder and runs `vk_sandbox` (`runtime/test/vk_sandbox.cpp`), which draws every prop with that pair: vertex buffers at +locations 0–2 (position, normal, UV), a D32 depth buffer, one indexed draw per mesh and one descriptor table per +draw. `--window` opens a window to fly, walk or drive through the scene; `--check` renders one frame headless and +prints only counts. + +The shaders are not stand-ins: the VS transforms each vertex with the world rows and view-projection it loads from +the heap and lights it with its own `max(0.25, n·l)`; the PS samples the albedo through the T# it loads and the +S# literal in its code, and multiplies by the VS colour. Lighting beyond that, shadows and the G-buffer passes are +not part of this pair. + +## 2. How the pair is chosen + +The material → program table is in the executable (#2519), so the pair is chosen by what the shaders read, from +`/shaders/spirv/index.json` and the listings in `/shaders/dxbc/disasm`: + +| | Vertex shader | Pixel shader | +|---|---|---| +| inputs | POSITION (xyz), NORMAL (xyz), TEXCOORD (xy) | SV_Position, TEXCOORD, COLOR | +| user data | user SGPR 8 only (`ptr32_lo`) | user SGPR 8 (`ptr32_lo`) | +| bindings | none | 0, 1, 2 (images, samplers, hash table) | +| listing | three `s_load_dwordx4` from `s[8:9]` at 0x0, 0x40, 0x60; a 4-dword buffer load at 0x30 and a 16-dword one at 0x160 | one `s_load_dwordx8` from `s[8:9]` + 0x20; one `image_sample`; `exp mrt0` | + +On the 1.0.2.1 corpus 3 VS and 231 PS match the signatures, and 2 VS and 4 PS also match the listing patterns; +they share one table layout. `tests/test_sandbox_pick.py` checks the picker on hand-written listings. + +## 3. The table the pair reads + +User SGPR 8 is a 32-bit pointer (the shaders force the high dword to 0) to one table in the heap: + +| Offset | Descriptor | Contents (byte offsets in the buffer) | +|---|---|---| +| 0x00 | V# | world rows 0–2 at 0x00, 0x10, 0x20 (xyz each), translation at 0x30; world = x·row0 + y·row1 + z·row2 + row3 | +| 0x20 | T# | the albedo image (8 dwords) | +| 0x40 | V# | light direction at 0xa0; view-projection at 0x160, clip = wx·r0 + wy·r1 + wz·r2 + r3 (D3D clip, y up, z 0..1) | +| 0x60 | V# | colour at 0x00 (rgb × the lighting term, alpha as is) | + +`vk_sandbox` writes raw V#s (stride 0, NUM_RECORDS = the buffer's bytes, OOB_SELECT 3), registers each texture's +T# words and the PS's S# literal in the descriptor hash table, builds the sampler from those S# words +(`gfx10::decode`), and draws through a negative-height viewport so the D3D-convention matrices stay unchanged. + +## 4. Reproduce it + +```sh +python -I tools/world_index.py ... --entities-out /entities.jsonl # placements (docs/world.md) +rpf9dump models "/levels.rpf" /assets +rpf9dump ttpf "/data/ttdb/maps/ttdb_maps__7.ttpf" /ttpf_maps # n = 0..7 +rpf9dump ttpf "/data/ttdb/terrain/ttdb_terrain__7.ttpf" /ttpf_terrain # n = 0..7 +cmake --build runtime/build --target vk_sandbox +python -I tools/sandbox.py --work --entities /entities.jsonl --models /assets \ + --textures /ttpf_maps --textures /ttpf_terrain [--center X Y] --window +``` + +Window keys: WASD move, right mouse button held to look, Q/E down/up (fly), Shift faster, 1 fly, 2 walk (eye 1.7 m +over the highest scene triangle under the camera), 3 drive (eye 1.2 m, accelerates and steers), P screenshot, +Esc quit. `--center` is in RAGE world metres; without it the densest 50 m cell of resolved props is used. + +## 5. Measured + +| | | +|---|---| +| map pools (8) | 133,697 textures exported, 0 failed, 7,030 skipped | +| terrain pools (8) | 46,115 exported, 0 failed, 26,903 skipped (`rpf9dump`'s limits in [textures.md](textures.md)) | +| test scene (one `levels.rpf` window) | 600 entities within 120 m, 150 placed (402 have no exported model in that window), 446 draws, 178 meshes, 345,782 triangles | +| albedo | the material's DiffuseTex reference (`Param` = `joaat("DiffuseTex")` = `C8E8C282`): 422 of 446 draws textured with 93 textures from the map and terrain pools (69 with the map pools alone). Two-layer blend materials have no DiffuseTex: 11 references each, two albedos, two normal maps, packed maps and a blend mask; the first layer's albedo (`Param` `346394EA`, name unknown) brings it to 442 of 446 draws and 107 textures | +| `--check` (640×360) | 114,503 pixels covered, 4,736 distinct colours (147 with the textures left out) | +| window | about 90 frames per second with a `vkQueueWaitIdle` per frame; a 60-frame windowed run ends on the same pixels as the headless render | +| walk / drive | eye at 1.70 m / 1.20 m over the roof the camera starts above | + +## 6. Limits and next + +* One pair, one forward pass. The world's own material shaders pull vertices (`SV_VertexID` only) and write the + G-buffer; drawing those needs their vertex fetch tables and the lighting passes that read the G-buffer. +* The scene stores mip 0 box-scaled to 256 px (`--tex-size`), so the sampler's LOD range is clamped to 0. +* Ground following uses the scene's own triangles; there is no collision against walls. +* Draws are not culled or sorted, and every frame waits for the GPU; a large `--max-props` gets slow (each prop is + one draw per mesh: 150 props gave 446 draws). diff --git a/docs/shader_inputs.md b/docs/shader_inputs.md index 17f715b38..aa9da8759 100644 --- a/docs/shader_inputs.md +++ b/docs/shader_inputs.md @@ -8,6 +8,38 @@ it. Measured on the local package's disassembly (`work/shaders/dxbc/disasm`) at `16282101`. Offsets, bit positions and counts only; no shader text. +## Bloom and exposure + +Reported by @Silliana in [#3235](https://github.com/ItsNotRexed/Leonida/issues/3235). The observations below were +checked against the local disassembly. Offsets are bytes into the constant buffer read by the named shader. + +### A black bloom chain (`PS_DownSampleBloomFilterKaris`) + +- Check the RGB tint at `+0x00`, `+0x04` and `+0x08` first. The shader multiplies the filtered colour by these + values before export. An all-zero tint makes bloom black even with a valid source. The fourth value at `+0x0C` + feeds the exported alpha. +- The sample loop has a limit of 13. Its luminance-dependent weight has the form `1 / (1 + k × luminance)`, + with scale `k` at `+0x1C`. Setting it to zero removes that dependence for finite inputs. The spatial filter + and output tint still apply. + +### Flat, wrong or slowly changing exposure (`PS_CalculateExposure`) + +- The mode dword at `+0x410` selects the exposure calculation. A nonzero value takes the path that computes + logarithmic exposure from the measured luminance. Check this before diagnosing the automatic exposure path. +- On the compensation path, a nonzero dword at `+0x40C` selects the fixed value at `+0x408`. Zero selects a + sample from a 1D compensation curve. Check that the curve is bound when using the texture path. +- Check the previous-exposure texture when the pass changes slowly. The adaptation code subtracts its sample + from the target exposure and can blend back toward the target. It tests `+0x3B0` against zero and compares + a value derived from the exposure delta against the threshold at `+0x3B4`. For a single-frame comparison, + the issue report suggests seeding the previous exposure with the target. + +### Luminance downsample and bloom upsample + +All five sampling sites in `PS_LuminanceSourceDownsample` contribute to the export. All nine in +`PS_UpSampleBloomFilterBlend` do too. Check the source resolution, sampling and reduction before comparing +the luminance pyramid with a whole-frame average. +When inspecting the upsample in isolation, check in the pipeline state how its output blends with the previous level. + ## Studio-shot lighting (`PS_STUDIOSHOT_PBR_MATERIAL_STANDARD_LIGHTING`) Reported by @Silliana in [#1892](https://github.com/ItsNotRexed/Leonida/issues/1892). The corpus has one program @@ -40,7 +72,8 @@ The fields below are the ones confirmed. The rest of the record is read but not |---|---|---| | +0x10 | 3 × f32 | Light position; the shader subtracts the world position of the pixel from it. | | +0x20 | u32 | Bits 0–8: profile index (9 bits) into the profile table. Bits 9–17 and 18–21 are two more fields, not decoded. | -| +0x28 | u32 | Flags. Bit 24 enables the light-shaping planes; bit 16 takes part in the shadow-map gate; bits 17, 20, 21, 26, 27 and 30 are tested, not decoded. | +| +0x28 | u32 | Flags. Bit 24 enables the light-shaping planes; bit 16 takes part in the shadow-map gate; bits 30–31 are the light type (0–3), which selects how +0x3C is used; bits 17, 20, 21, 26 and 27 are tested, not decoded. | +| +0x3C | 2 × f16 | Light shape size: the light's dimensions, used differently per light type. See [Light shape size](#light-shape-size). | | +0x40 | u32 | Low 24 bits non-zero turns on one per-light factor; at zero that factor is 1.0, so the light still shades. The top byte isn't read on the paths checked. | | +0x4C | u32 | Top byte: number of light-shaping planes (0–255). See below. | | +0x5F | u8 | Read as byte / 255; at 0 one block of the light's shading is skipped. | @@ -58,6 +91,25 @@ end of the buffer after the last light. A float in this dword has its exponent i gives 63 planes. The loop itself ends after at most 255 iterations. If a device-lost still shows up there, check this dword and the buffer's bounds first. +#### Light shape size + +Reported by @Silliana [on the pull request](https://github.com/ItsNotRexed/Leonida/pull/3157): +0x3C holds two f16, +the low half a sphere radius and the high half a range. Since intensity is radiance, the light's power grows with +radius², so a radius that's too big (for example the range written into both halves) gives scattered single-pixel +specular blowups that look like a translator bug. + +What the shader shows confirms the two f16 halves, but their use depends on the light type (bits 30–31 at +0x28): + +- In one path they are the two half-sizes of a rectangle. The light's position is moved by ± the low half along one + axis and ± the high half along the other, and points are clamped to those bounds. +- In another path the high half is a length along the light's axis (clamped to ± half of it), and it is also squared + and compared against a distance. +- The low half also sets one blend factor. +- No range-style falloff was found: neither half divides a distance. + +So a wrong value here makes the light the wrong size, and an oversized area light is a likely cause of the blowups. +Which light type reads the low half as a sphere radius isn't decoded yet. + #### Correction to #1892 #1892 puts two checks on one dword at +0x40: a top-byte loop count, and low 24 bits that must be non-zero or the light @@ -171,6 +223,13 @@ transmittance table #1897 names, so it runs second and not side by side with `CS (mip 0). Which texture is bound to which table comes from #1897, not from the program. If a sky pass runs before the tables are built, it reads whatever is in them, and the black or noisy sky looks like a translator bug. +### Transmittance addresses texel corners + +`CS_Transmittance` turns its integer texel index into table coordinates as x × 1/256 and y × 1/64, with no +0.5, +so each texel holds the value at its corner, not its centre (pointed out by @Silliana in +[#3217](https://github.com/ItsNotRexed/Leonida/pull/3217#issuecomment-7084678180)). A reference table built at texel +centres differs from it slightly, most visibly near the ground. That difference is expected and isn't a translator bug. + ### The dword at +0xD0: output format, not an enable #1897 reports a SkyView dword that skips the stores when it is zero. In `CS_SkyView` and `CS_MultipleScattering` diff --git a/docs/shader_validation.md b/docs/shader_validation.md index b7fad4106..ef4d44edc 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md @@ -443,6 +443,10 @@ that starts from a known pattern. It runs 4 to 12 random `ds_*` instructions, ea `s_waitcnt` and `s_barrier`, then stores all 16 result VGPRs of every thread and the whole LDS. `vk_compute_test` reads them back with `VKC_OUT_WORDS` / `VKC_DUMP`. +For the translator oracle, `lds_fuzz.py` and `valu_fuzz.py` create and retain a unique output folder per run. With +`--work DIR`, that folder is a new child of `DIR` (the printed work directory), rather than `DIR` itself; files from +older runs and other contents of `DIR` are left alone. Without `--work`, it is created in the system temporary folder. + - **Instructions.** Every read width (`b32` to `b128`, `u8`/`i8`/`u16`/`i16`, `u16_d16[_hi]`, `u8_d16[_hi]`, `i8_d16[_hi]`), the byte and short writes (also `d16_hi`), `read2`/`write2` with and without `st64`, the add, sub, min, max, and, or and xor atomics with and without return, `wrxchg`, `cmpst`, `ds_swizzle_b32` @@ -460,7 +464,9 @@ that starts from a known pattern. It runs 4 to 12 random `ds_*` instructions, ea `--no-exec KIND` drops one op kind's masks without changing the rest of the program, to separate a known finding from new ones. - **Subgroup size.** Wave32 programs, and wave64 ones built with `--emulate`, ask `vk_compute_test` for - 32-lane subgroups (`VKC_SUBGROUP_SIZE=32`). Where the device can't pin that size, `vk_compute_test` + 32-lane subgroups (`VKC_SUBGROUP_SIZE=32`). Where the device can't require it but 32 is its default + (MoltenVK), a probe shader checks the lanes first and the programs are compared (see `docs/testing.md`, + "GPUs with 32-wide subgroups"). Where the device can't pin that size at all, `vk_compute_test` prints `compute subgroup size: 32 not available` and runs at the driver's choice, and the wave32 program is a skip, not a mismatch: its words come from another wave size. Mesa llvmpipe (8 lanes) is such a device. Emulated wave64 uses no subgroup operations, so it is still compared there. @@ -671,6 +677,8 @@ c / 255. llvmpipe multiplies by an f32 1/255, which is one ulp above that for 12 0x3dd8d8da, not 0x3dd8d8d9), and a run stops at its first mismatch, so on llvmpipe no case after the first `R8G8B8A8_UNORM` one ran. The translator oracle therefore accepts one ulp on a UNORM8 texel component, never on another format or on a sentinel, and the summary says how many components needed it. `--oracle hw` stays bit exact. +Each run keeps its generated files in a unique output folder. With `--work DIR`, it is a new child of `DIR` and its +path is printed; existing contents and other runs are left alone. Without `--work`, it is in the system temporary folder. ```sh cmake --build runtime/build --target vk_image_fuzz @@ -927,6 +935,27 @@ every scalar. `vk_compute_test` reads them back with `VKC_OUT_WORDS` / `VKC_DUMP With `--dpp`: a DPP16 or DPP8 src0 on `v_mov`/`v_not`/`v_add_nc_u32`/`v_xor`, with every DPP16 control, `row_mask`, `bank_mask`, `bound_ctrl` and `fi`. Masks read as plain data (`v_mov_b32 v, s_mask`) belong to #293 and are left out with `--no-maskdata`. +- **`--ext` (wave64 programs only).** Adds the ops the list above leaves out: carries (`v_add_co`, `v_sub_co`, + `v_subrev_co_u32` and the `_ci` forms) through SGPR pairs and VCC; `ds_bpermute_b32`, `ds_permute_b32` (address + permutations and colliding addresses) and `ds_swizzle_b32` (`QUAD_PERM`, `BITMASK_PERM`, `SWAP`, `REVERSE`, + `BROADCAST`); `v_readlane`/`v_writelane` with an SGPR lane select of 64 and up; `s_bcnt0/1` and `s_ff0/1` of a + mask, `s_and/or/xor/andn2_b64`, the ten `s_*_saveexec_b64` forms and `s_andn1/andn2_wrexec_b64`, `s_wqm_b64`, + `s_cmp_eq/lg_u64` and `s_bitcmp0/1_b64`, each followed by an `s_cselect_b32` so that its SCC is stored; + `s_cselect_b64` between masks, `s_mov_b64 exec, mask`, `s_bfm_b64` into a mask or EXEC; and a loop in LLVM's + SI_LOOP shape (per-lane trip counts of 1 to 8, a break mask, `s_andn2_b64 exec`, `s_cbranch_execnz` back to the + head) around one to four of the other ops. Without the flag, and for wave32 programs with it, a seed gives the + same program as before. The model of every op was checked on an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 + 9950X3D, raw wave64 kernels): `--ext --dpp --wave 64 --oracle hw --programs 100 --seed 21` matches 100/100, + with groups of one to three waves and partial waves. What that run settled where the ISA guide is terse: the + three DS ops need `s_waitcnt lgkmcnt(0)` before their result is used (without it a later VALU write to the same + VGPR is overwritten when the result arrives; the generator emits the wait); `ds_bpermute_b32` and + `ds_permute_b32` stay inside the lane's 32-lane half; with several senders `ds_permute_b32` keeps the highest + lane's value; an EXEC-off source reads 0 in `ds_bpermute_b32` and in `ds_swizzle_b32`. The translator matches + the same 100 programs on that GPU both natively (64-wide subgroup, `--w64-native`) and with + `--wave64-emulate`, apart from 15 that reach a known open case and are filed `hyp_only`: an EXEC-off + `v_permlane` source (#580) or `ds_swizzle_b32` source (#2780, tagged like the permlane case until it lands). An + RTX 5080 (driver 616.92) gives 46 matches and 14 `hyp_only` of 60 emulated programs (`--seed 23`). Not + generated: 32-bit ops on one half of a mask or of EXEC (#663, #3225) and carries with a DPP source (#3553). - **Reference.** A 64-lane model in the same file, written from the ISA (rules in its docstring). Its unit test, `tests/test_crosslane_fuzz.py`, needs no GPU. - **Defined behaviour only.** Lane selects, permlane and DPP never read a lane missing from a partial wave. @@ -1658,11 +1687,9 @@ metadata to copy the conventions from. With the built-in `interp2` template on g the perspective I/J barycentrics are in v0/v1, M0 comes from s2 (`s_mov_b32 m0, s2`), and parameters 0 and 1 are the vertex shader's locations 0 = (u, v, 0, 1) and 1 = (u, v, 0, 0), u and v going 0..2 across the screen. -```powershell $env:LEONIDA_VK_DEVICE = "radeon" python -I tools/ps_oracle.py --build --template interp2 --show-template python -I tools/ps_oracle.py --build --template interp2 --asm body.s --size 4 1 [--json out.json] -``` Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary (there is no check over the code), the patched code runs as the pixel shader, and `v_interp_p1/p2_f32` of `attr0.x` at the four @@ -1687,6 +1714,7 @@ limits: `--set` is refused (RADV keeps the SPI setup in its own structs, so a te needs), and only GFX10 (RDNA1/RDNA2) devices are taken, from the chip name RADV puts in the device name; GFX11 and later interpolate with `lds_param_load` instead of `v_interp_*`, so e.g. an RX 9070 XT (`RADV GFX1201`) gets `unsupported architecture` and exit 77. +### Packed 16-bit integer operations on RDNA2 (SHADER-302) Mesa optimises varyings across stages, so a template's parameter layout can differ from the Windows driver's: RADV moves `interp2`'s `in0 + in1` into the vertex shader and the pixel shader reads one parameter, attr0 = @@ -1701,6 +1729,53 @@ the Windows check's `attr0.x` code (with `v40`, past the template's 8 VGPRs) giv P0 = 0 and P10 = 4.0 for the single parameter, and a second patch with another constant changes the result (nothing is cached). +- **Constant operands under `op_sel` / `op_sel_hi`:** Integer constants under VOP3P are uniformly treated as 32-bit dwords `C`. When `op_sel[i] == 0`, bits `[15:0]` are selected; when `op_sel[i] == 1`, bits `[31:16]` are selected. Positive inline constants zero-extend (`5` → `0x00000005`: lo=`0x0005`, hi=`0x0000`; `64` → `0x00000040`: lo=`0x0040`, hi=`0x0000`). Negative inline constants sign-extend (`-1` → `0xFFFFFFFF`: lo=`0xFFFF`, hi=`0xFFFF`; `-16` → `0xFFFFFFF0`: lo=`0xFFF0`, hi=`0xFFFF`). 32-bit literals preserve their full dword (`0x12345678`: lo=`0x5678`, hi=`0x1234`; `0x80017fff`: lo=`0x7fff`, hi=`0x8001`). Float inline tokens (`0.5`, `1.0`, `-2.0`, `4.0`) assemble as their 32-bit IEEE 754 bit patterns (`1.0` → `0x3f800000`: lo=`0x0000`, hi=`0x3f80`). +- **`clamp` saturation:** Unsigned add/mad saturate to `0xFFFF`; unsigned sub saturates underflow to `0x0000`; signed add/sub/mad saturate to `[-32768, 32767]`. +- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences). +#### Helper lanes at a triangle edge (`tools/ps_helper_probe.py`, SHADER-681) + +What a pixel wave does with the helper lanes of a partly covered 2x2 quad, which the translator's EXEC model and +`s_wqm` lowering depend on (`docs/design.md` row "Whole-quad mode"). The probe draws one triangle, (-1, -1), (1.3, -1), +(-1, 0.9), into a 16 x 16 target, so its edge cuts quads; the varying is the vertex position, so each lane's +interpolated value is its own pixel centre. The template pixel shader takes a derivative, so the driver builds it as +a shader that needs quads. Seven wave64 programs replace the pixel shader. A helper is never written to the target, +so a covered lane of the same quad reads the helper's registers through DPP `quad_perm` and exports them. + +```sh +LEONIDA_VK_DEVICE=raphael python -I tools/ps_helper_probe.py --build [--json out.json] +``` + +On the Ryzen 7 9800X3D iGPU (`RADV RAPHAEL_MENDOCINO`, gfx1036, Mesa 26.3.1): 137 covered pixels in three waves, +25 (covered lane, helper neighbour) pairs, and all 10 checks hold in three runs, with identical words except an +unwritten helper register: + +| check | gfx1036 | +|---|---| +| entry EXEC | exactly the covered pixels: helpers start off | +| `s_wqm_b64 exec, exec` | turns on exactly the quads with a covered pixel | +| wave layout | quads packed from lane 0; a quad with no covered pixel is not in the wave | +| lane order in a quad | lane % 4 = (x & 1) + 2 (y & 1): top-left, top-right, bottom-left, bottom-right | +| a helper's `v_interp_p1/p2_f32` after `s_wqm` | its own pixel centre, extrapolated (error 1.64e-4, as covered) | +| a helper's v0/v1 without `s_wqm` | already its own pixel's I/J (to 7e-5; I + J > 1, outside the triangle) | +| a helper's VGPR without `s_wqm` | not written (an unwritten register, different in every run) | +| EXEC without `s_wqm` | stays the entry mask | +| DPP without `fi` from an inactive lane | leaves the destination unchanged | +| `exp mrt0 ... done vm` with helpers on in EXEC | writes no pixel outside the triangle | + +The last row is what the driver's own code relies on: RADV compiles the template as `s_wqm_b64 exec, exec` at entry, +then the interpolation and an `exp mrt0 ... done vm` with the helpers still on. The programs are wave64; a wave32 +pixel stage (`RADV_PERFTEST=pswave32`) and GFX11+ exit 77. Not measured: wave32, RDNA1/gfx1013 and the Windows driver. + +### Packed 16-bit integer operations on RDNA2 (SHADER-302) + +*Measured on an RDNA2 iGPU (gfx1036), Windows 11, AMD Windows driver 32.0.21045.29003, HIP backend (`amdhip64_6.dll`), AMD clang 23.0.0git (`rocm-sdk-core 10.0.0`).* + +380 raw compute kernels covering all 11 packed 16-bit integer instructions (`v_pk_add_u16`, `v_pk_sub_u16`, `v_pk_add_i16`, `v_pk_sub_i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16`, `v_pk_mad_i16`, `v_pk_max_u16`, `v_pk_min_u16`, `v_pk_max_i16`, `v_pk_min_i16`), tested in both wave32 and wave64: + +- **Constant operands under `op_sel` / `op_sel_hi`:** Integer constants under VOP3P are uniformly treated as 32-bit dwords `C`. When `op_sel[i] == 0`, bits `[15:0]` are selected; when `op_sel[i] == 1`, bits `[31:16]` are selected. Positive inline constants zero-extend (`5` → `0x00000005`: lo=`0x0005`, hi=`0x0000`; `64` → `0x00000040`: lo=`0x0040`, hi=`0x0000`). Negative inline constants sign-extend (`-1` → `0xFFFFFFFF`: lo=`0xFFFF`, hi=`0xFFFF`; `-16` → `0xFFFFFFF0`: lo=`0xFFF0`, hi=`0xFFFF`). 32-bit literals preserve their full dword (`0x12345678`: lo=`0x5678`, hi=`0x1234`; `0x80017fff`: lo=`0x7fff`, hi=`0x8001`). Float inline tokens (`0.5`, `1.0`, `-2.0`, `4.0`) assemble as their 32-bit IEEE 754 bit patterns (`1.0` → `0x3f800000`: lo=`0x0000`, hi=`0x3f80`). +- **`clamp` saturation:** Unsigned add/mad saturate to `0xFFFF`; unsigned sub saturates underflow to `0x0000`; signed add/sub/mad saturate to `[-32768, 32767]`. +- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences). + ## Coverage plan and cost diff --git a/docs/story.md b/docs/story.md index 69a23cbeb..9d255f0f1 100644 --- a/docs/story.md +++ b/docs/story.md @@ -277,14 +277,14 @@ of the 347 groups with a type-1 normal have fewer than 5% opposed, and 2% are mo which fits mirrored parts. The rest may be groups that the span rule binds to the wrong block. **Meshlet record words +8/+12 hold the meshlet's centre.** Three 12-bit fields give x, y and z: w2 bits 0-11, -w2 bits 12-23 and w3 bits 0-11. Each is in 1/16 m steps around 2047, so the centre is `(field − 2047) / 16`, over -±128 m, and the default `0x007FF7FF / 0x7FF` is the origin. When w2 bit 28 is set, the step is 1/8 m instead, -`(field − 2047) / 8` over ±256 m (below). `tools/meshlet_page.py --centres` compares each stored +w2 bits 12-23 and w3 bits 0-11. Each counts steps around 2047: the centre is `(field − 2047) × step`, with a step of +2^e / 16 m, where e is w2 bits 28-31: 1/16 m (±128 m) for most meshlets, coarser for larger ones further out (below). The default `0x007FF7FF / 0x7FF` is the origin. +`tools/meshlet_page.py --centres` compares each stored centre with the centre of its meshlet's vertex box, using the `42 40` positions above. Over all 1,569 streams: -| Meshlets | Default words | Axes | Same 1/16 m step | Within one step | +| Meshlets | Default words | Axes | Same step | Within one step | |---:|---:|---:|---:|---:| -| 142,613 | 68 | 427,839 | 214,204 (50.1%) | 307,158 (71.8%) | +| 142,613 | 68 | 427,839 | 214,263 (50.1%) | 307,248 (71.8%) | The rest are further off. The stored centre may be a bounding-sphere centre rather than the box centre: the mean of the vertices fits worse (about 30% in the same step on the first 400 streams, against 51.8% for the box). @@ -309,7 +309,7 @@ and it is tight, at most 1.25 × that distance plus the rounding: | Archive | Meshlets | Covers | Covers within rounding | Tight | |---|---:|---:|---:|---:| -| `shared_minigame000.rpf` | 142,613 | 137,626 (96.5%) | 140,724 (98.7%) | 142,518 (99.9%) | +| `shared_minigame000.rpf` | 142,613 | 137,777 (96.6%) | 140,881 (98.8%) | 142,518 (99.9%) | | `core_restofworld.rpf` | 4,899 | 4,771 (97.4%) | 4,895 (99.9%) | 4,883 (99.7%) | So the record carries a culling sphere (centre plus radius) for each meshlet. @@ -329,14 +329,21 @@ clear. On the first 400 streams, the median smallest dot between a face normal a So the cone is rounded to the nearest step, not widened to be conservative. With the centre and radius it completes a meshlet's culling data. -**w2 bit 28 doubles the centre's step.** w2 bits 24-31 are 0 or 16, so bit 28 is the only one that varies. It is -set on 1,732 meshlets of the minigame archive, and none in `core_restofworld`. Those meshlets are large (median -radius 33 m), face upward, and sit 100 m or more from the origin. Read with 1/16 m steps, their radius covers the -farthest vertex from the stored centre in 0 of 1,732. Read with 1/8 m steps, it covers it in 1,697 (98.0%), and in -1,730 (99.9%) once the centre's rounding is allowed for. A least-squares fit of box centre against field on them -gives slopes of 1/8.07, 1/8.05 and 1/8.08 per axis. `--centres` counts them as `coarse_steps`; the centre and -radius tables above use the right step for each meshlet. Bit 28 may be the low bit of a scale exponent, but only -0 and 1 occur. +**w2 bits 28-31 are an exponent for the centre's step.** The step is 2^e / 16 m; bits 24-27 are always clear. +@zzEmmazz's count over the minigame archive and `story000` found e = 0 to 4 (review on #2991; the first version of +this section saw only e = 0 and 1 in the first 400 streams). In the minigame archive, e = 1 is set on 1,732 +meshlets and e = 2 on 157; `core_restofworld` has none. These meshlets are large (median radius 33 m), face upward, +and sit 100 m or more from the origin. Within the centre's rounding, the radius around the stored centre covers +the farthest vertex as follows: + +| e | Meshlets | Step 2^e/16 | 1/16 m | 1/8 m | +|---:|---:|---:|---:|---:| +| 1 | 1,732 | 1,730 | 0 | 1,730 | +| 2 | 157 | 157 | 0 | 0 | + +A least-squares fit of box centre against field on the e = 1 meshlets gives slopes of 1/8.07, 1/8.05 and 1/8.08 +per axis. `--centres` counts the meshlets with e > 0 as `coarse_steps`. The centre and radius tables above use each +meshlet's own step. **Slots 11 and 18 are tangents.** Their type-7 words are unit vectors in the same 10:10:10 unorm, perpendicular to the vertex's stored normal. Bits 30-31 are always 3 or 0, which fits the bitangent sign +1 or −1. Over the minigame @@ -366,6 +373,7 @@ chunks on a 256-byte boundary behind zero padding; the walk stops there (`stoppe | positions within 300 m | 29,572,450 (99.9%) | | shared edges with neighbouring faces within ~25° | 33,342,470 of 36,707,506 (90.8%); 1.4% opposed | | normals within 8° / 25° of their faces | 76.5% / 94.6% of 20,801,089; 2.1% opposed | +| normals within 8° / 25° of their faces | 76.5% / 94.5% of 20,801,089; 2.1% opposed | | tangents perpendicular to the normal | 30,473,135 of 30,569,246 (99.7%) | | radius covers the farthest vertex from the stored centre | 257,091 of 275,832 meshlets (93.2%); 94.8% within rounding | | cones: axis within 25° / every face inside within 0.05 | 89.5% / 94.2% of 228,244 | @@ -374,6 +382,12 @@ The stored centres match the box centre less often here: 25.7% of axes in the sa against 50.1% / 71.8% in the minigame archive. 625 meshlets use the 1/8 m step. Since the radius still covers the farthest vertex from the stored centre in 93.2%, the decoding holds; these assets seem to store a centre other than the box midpoint (a sphere centre would fit). +against 50.1% / 71.8% in the minigame archive. Since the radius still covers the farthest vertex from the stored +centre in 93.2%, the decoding holds. These assets seem to store a centre other than the box midpoint; a sphere +centre would fit. The centre and radius counts in this table were taken before the step exponent was read in +full: they read only w2 bit 28. `story000` also has e = 2 to 4 on about 456 meshlets (@zzEmmazz's count), so those +few rows will move slightly when recounted. Most of the remaining misses come from the group-to-block binding: +several blocks in a page share a vertex count (@Pipodi's count on #2991). Still open: the +0x5C word, the type-1 normal's bits 20-31, and what the `42 40` colour and UV slots hold beyond rpf9-explorer's reading. @@ -466,13 +480,18 @@ the same in every inflated page: `0x7A` (122). No format is inferred beyond thes ## Readable versus opaque Readable: zlib streams, Bink 2 streams, XML/text streams, `PSIN` section headers, `0DRP` page -headers and `RSC8` fixed headers. Opaque: encrypted RPF9 tables of contents, the body of each -`RSC8` resource, the nested high-entropy payloads in the script archive, and the raw region of -`story000` that has no zlib stream. +headers and `RSC8` resources. Opaque: encrypted RPF9 tables of contents and the nested +high-entropy payloads in the script archive. + +The raw region of `story000` that has no zlib stream holds unencrypted `ADAT` (AWC) audio banks: +63,861 of them, 9,423,830,212 bytes. Every `RSC8` resource in this family is an AWC tag `0x5c` +facial/lip-sync clip inside one of those banks, next to its Opus dialogue line +([rsc8_audio.md](rsc8_audio.md#resolution-of-the-docsstorymd-raw-gaps), decoded by +`tools/rsc8_audio.py`). "Unread" in the index tables means bytes the zlib walk could not inflate. It is not a claim that -those bytes are empty or unimportant; in minigame and restofworld they contain `RSC8` headers and -nested RPF9 archives. +those bytes are empty or unimportant; in minigame and restofworld they contain `ADAT` banks with +their `RSC8` clips, and nested RPF9 archives. ## Likely format family @@ -483,7 +502,8 @@ The bytes support a **new RAGE resource family in an RPF9 container**: - `0DRP` is a page header, not a GTA V `RSC7` header: magic at +16, version 122, page count at +0x20, and payload pages after it. - `RSC8` is the resource header in the raw story region: version 8001, a u32 at +8, flags and a - name string. No `RSC7` header was found in 20 GB. + name string. It is the payload of AWC tag `0x5c`, a facial/lip-sync clip dictionary, and the u32 + at +8 is its body size ([rsc8_audio.md](rsc8_audio.md)). No `RSC7` header was found in 20 GB. - `PSIN` is a sectioned metadata container, not a script opcode stream. Repository notes already describe it as PSO metadata; this pass confirms the section names and the big-endian length chain, not the section semantics. @@ -501,8 +521,8 @@ was found in the inflated sample. names, paths and exact entry boundaries remain unavailable. 2. A recursive RPF9 walker. The flat zlib carve does not group streams by the 441 additional RPF9 headers in `story000`; a decoder needs their spans and TOCs to group resources. -3. An `RSC8` header parser and a type map for version 8001. The fixed 0x30-byte header and the - following name are measured; the payload is not decoded. +3. An `RSC8` decoder for version 8001: done. `tools/rsc8_audio.py` decodes the header and the + facial/lip-sync clip payload ([rsc8_audio.md](rsc8_audio.md)). 4. A `PSIN` section walker. The tag/length chain is measured; `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC` and `CHKS` semantics are still open. 5. `0DRP` page grouping. The page count at +0x20 is the only measured grouping field; a decoder diff --git a/docs/testing.md b/docs/testing.md index fc695d014..279eab0b2 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -86,8 +86,11 @@ belongs to the commit that built it; check that commit out as well. If you cannot build the test programs locally, the Runtime workflow publishes them as the `runtime-windows` artifact of its own commit. It holds Windows executables, so use them on Windows or under Wine as in the -section below; GitHub expires the artifact after 7 days. Open the run for that commit under Actions -> -Runtime, download and unzip `runtime-windows`, and pass the unzipped folder to `--build`: +section below; GitHub expires the artifact after 7 days. Not every commit on `main` has one: the workflow runs +only when a commit touches what it builds or reads (the `paths` list in `.github/workflows/runtime.yml`), so a +commit that changes only docs, tests or other tools has no Runtime run. Take the most recent run under +Actions -> Runtime, and check out the commit it built, or start a run of the commit you want on your own fork with +"Run workflow" (`workflow_dispatch`). Download and unzip `runtime-windows`, and pass the unzipped folder to `--build`: ```sh python -I scripts/run_gpu_tests.py --build @@ -204,6 +207,18 @@ drivers report subgroups of 8..32 and may run it 8 or 16 wide; its second patter don't run. The test skips when the frame shows that (#1318), and the translation gives 0 for a source lane that isn't running instead of an undefined value (#618). At 16 wide the first pattern stays inside the running lanes, so it is still checked before the skip. +The wave32 tests whose words depend on 32 lanes (`cs_dpp*`, `cs_bpermute32`, `cs_exec_const`, `cs_wqm_w32`, +`cs_w32_*`, and in `check.py` every compute test the index records at 32) ask `vk_compute_test` for 32 lanes +(`VKC_SUBGROUP_SIZE=32`). MoltenVK can't require a subgroup size (`requiredSubgroupSizeStages` is 0, sizes 4..32), +but its default is 32 and the translator's SPIR-V 1.5 doesn't allow varying sizes, so Vulkan fixes the size at 32. +`vk_compute_test` checks that with a probe shader before the test (where the device has compute ballots): same +local size and flags as the test's `main`, every subgroup 32 lanes wide by its own lane numbers and ballot, and the +lanes in invocation order, which the translator assumes. It prints `compute subgroup size: 32 (observed: ...)` and +the test is judged. A wrong width fails the test with `observed wrong` and the first wrong invocation; 32-lane +subgroups in another order print `not available`, a skip. Measured +on an Apple M3 Max (MoltenVK 1.4.2 and 1.4.3): 17 workgroup shapes from 1 to 1024 invocations, partial last +subgroups, with and without full subgroups and register pressure, all 32 lanes in order. A device whose default +isn't the requested size still prints `not available`, and those tests skip. ## Wave64 pixel, vertex and geometry shaders (`w64_graphics.py`) @@ -286,7 +301,8 @@ compute and drawn by a generated vertex shader (`docs/design.md`, "Mesh shaders ## Without a GPU: Mesa llvmpipe Mesa's llvmpipe is a software Vulkan driver (`mesa-vulkan-drivers` on Debian and Ubuntu). CI runs the suite on it -for every pull request (`.github/workflows/runtime.yml`), and you can do the same on Linux without a GPU: +for every pull request that touches the runtime, the scripts or a tool the jobs read (`.github/workflows/runtime.yml` +lists them), and you can do the same on Linux without a GPU: ```sh sudo apt-get install -y libvulkan-dev mesa-vulkan-drivers vulkan-tools spirv-tools llvm-18 @@ -353,8 +369,28 @@ That needs `VK_KHR_shader_fma` with `shaderFmaFloat32`; the test programs enable fused, whereas **Mesa RADV (26.2.6-arch3.1, AMD Radeon RX 6800, Linux)** splits 5 of the 7 f32 ops under `--fma glsl` (reusing the live `a * a` product in `v3`) and returns 8/8 fused exact under `LEONIDA_FMA=khr`. Under default `--fma glsl`, `check.py` and `run_gpu_tests.py` therefore accept either the fused or the exact split word for each of +fused, whereas **Mesa RADV (Linux)** splits several of the 7 f32 ops under `--fma glsl` — the exact split count varies +by GPU, Mesa/ACO version, and execution modes (4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel +with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, 7 of 7 on Radeon Pro V540 RDNA1 / Mesa +25.2.8) — while returning 8/8 fused exact under `LEONIDA_FMA=khr` where supported. Under default `--fma glsl`, +`check.py` and `run_gpu_tests.py` therefore accept either the fused or the exact split word independently for each of the 7 f32 outputs while still requiring exact f16 round-to-odd (`0x00007351`); under `LEONIDA_FMA=khr`, all 8 words must be strictly fused. +operands taken from user SGPRs so the driver cannot fold them. It passes with the default translation (`--fma glsl`, +GLSL.std.450 `Fma`) on a driver that keeps `Fma` fused, and with `LEONIDA_FMA=khr` **for `build.py`** (or for +`run_gpu_tests.py`), which emits `OpFmaKHR`. That needs `VK_KHR_shader_fma` with `shaderFmaFloat32`; the test programs +enable it when the device has it and exit 77 (a SKIP) for a module that needs it on a device without it. The Vulkan +specification allows a driver to split GLSL `Fma` into two roundings, which is why `khr` exists. The AMD Windows +(26.11.2) and NVIDIA (617.42) drivers we tried don't. Two do, failing `cs_fma_fused` with `glsl` in words 0, 2, 3 and 5 +(`v_fma_f32`, `v_fmaak_f32`, `v_fmac_f32`), which get the split value: + +- RADV (Mesa 26.3.1, RX 6700 XT, measured in #3004's review). It has `VK_KHR_shader_fma` since Mesa 26.2 (#1364), so + `khr` fixes it, and so does `exact`. +- The Intel UHD Graphics driver (Xe-LP, Windows 101.7088). It has no `VK_KHR_shader_fma`, so only `exact` fixes it. + +`LEONIDA_FMA=exact` (`--fma exact`) builds the single rounding from plain f32 operations and needs no extension; with +it `cs_fma_fused` passes on both of those, on an RTX 3050 Laptop (617.42), an RTX 5060 Laptop (621.01), an RTX 5070 Ti +(621.24) and a Radeon 780M (26.11.2). ## Hardware oracle (optional, AMD) @@ -397,14 +433,22 @@ The GPU tools of `runtime/test/shaders` (`vk_compute_test`, `vk_harness`, ...) r | `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` | | `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old | | `ps_bary` and `ps_uniform_branch` fail by about 0.9 | The GPU runs pixel shaders wave64 without fragment barycentrics (GCN3 and RDNA1 on RADV), or an old AMD Windows driver (22.40) | Current `main` skips them on such devices; on Windows, update the driver | +| `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation | +| `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). | | `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") | | `ps_vcmpx_forms` fails on a Mac: word 1 reads `0xf05e8e16`, want `0xf05e8a12` | MoltenVK's fast-math makes a compare of a NaN with itself true (SHADER-234) | Current `main`'s test programs turn it off (`MVK_CONFIG_FAST_MATH_ENABLED=0`, unless you set the variable yourself); rebuild them | | On a Mac, a translated shader's GPU time is 1.5 to 16 times what it would be without the precise-arithmetic overhead | MoltenVK's SPIRV-Cross turns every `NoContraction` float add, subtract and multiply into a call to an `[[clang::optnone]]` helper that Metal does not inline. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-234, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions, and the output is still exact. Before you time shaders on a Mac, build MoltenVK with SPIRV-Cross `98cbb7c0` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision` (KhronosGroup/MoltenVK#2917 moves it to `57e4efcc`), and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | `d3d12_descriptor_test` reports that the set had room for fewer than 5001 2D views and 2100 samplers, and the device logs that the bindless set holds fewer samplers than a full shader-visible sampler heap | The device's descriptor limits, or its `vkGetDescriptorSetLayoutSupport`, allow no bigger bindless set ([d3d12_vulkan.md](d3d12_vulkan.md) section 5). MoltenVK's answer is ignored, since it rejects every layout of `maxPerSetDescriptors` (1212) or more although it runs the full set | Expected where the limits are low. The test still checks the last index of each array and that the next view and sampler are refused | +| `cs_dpp_ops` fails on a Mac with MoltenVK 1.4.2: `out[0..7] = 100 100 11 ...`, want `100 10 11 ...` | MoltenVK 1.4.2's SPIRV-Cross moves the DPP lowering's subgroup ballot and shuffle into a short-circuiting `&&` and `?:`, so only some lanes run them and lane 1 sees its source lane 0 as inactive. SPIRV-Cross `5c372ffb` (in MoltenVK `main`) keeps them out of `?:`; a ballot on the right of `&&` is still moved there in SPIRV-Cross `57e4efcc` | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` (point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib`) and on KosmicKrisp | +| `check.py`'s `cs_fma_fused` fails on a Mac with MoltenVK 1.4.2: word 7 reads `15360` (`0x3c00`), want `29521` (`0x7351`) | The f16 multiply-add (round to odd). The MSL of 1.4.2 and of MoltenVK `main` differ only in SPIRV-Cross's precise-arithmetic helpers (`[[clang::optnone]]` and `fma(l, r, 0)` against `math_mode(safe)` and `fma(l, r, -0.0)`, the SHADER-182 / SHADER-234 change) | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` | | `gs_tri` and `ms_tri` fail on a Mac | MoltenVK has no geometry stage and no `VK_EXT_mesh_shader` | Current `main` reports them as skipped | | On a Mac, `valu_fuzz.py --family f16` reads `+0` where the model wants `-0`, from a multiply whose exact product is -0 (`v_mul_f16`, `v_pk_mul_f16`) or from an FMA whose product and addend are both -0 (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) | MoltenVK computes a `NoContraction` multiply as `fma(l, r, +0)`, which drops the sign. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-182, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions. To run the rest of the fuzzer clean, add `--skip-op` for each of the five ops. To see them match, install Homebrew's `mesa` and use its KosmicKrisp driver: `LEONIDA_VULKAN_LOADER=/opt/homebrew/opt/vulkan-loader/lib/libvulkan.1.dylib VK_DRIVER_FILES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json python3 -I tools/valu_fuzz.py --family f16 --build runtime/build/linux`. Or build MoltenVK with SPIRV-Cross `300681bb` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision`, and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | CMake stops with "needs the Windows SDK 10.0.26100 or newer", or MSVC reports `'Desc_1_2': is not a member of 'D3D12_VERSIONED_ROOT_SIGNATURE_DESC'` | A Windows SDK older than 10.0.26100 (10.0.22621 is the common one), which has no version 1.2 root signatures | `winget install Microsoft.WindowsSDK.10.0.26100`, or add it in the Visual Studio Installer, then delete `runtime/build` and configure again | | `ctest` lists `fsr_dispatch` and `bvh_builder` as failed (`Not Run`) after clang-cl hits an internal compiler error in `fsr_dispatch_test.cpp` and `bvh_builder_test.cpp` | clang-cl 22.1.8 on Fedora (Linux cross-build) and Windows, plus 22.1.7 on Windows | Use clang-cl 23.1.6 (both files compile on Windows) | +| `d3d12_compute`, `d3d12_draw` or another test that writes a shader library under the temp directory fails now and then (a PSO creation `line N: SUCCEEDED(...)`, or exit 3 with no message) but passes when run alone | Two copies running at once (`ctest -j`, or two suites sharing one Wine prefix or `TMPDIR`) used the same `leonida_` folder under the temp directory, and one copy deleted the shader modules the other was loading: 6 of 40 runs failed with four copies of `d3d12_compute` at once on a Mac under Wine | Current `main` gives each process its own folder (`/leonida__`) | +| A Windows CI artifact run under Wine by hand: `d3d12_compute` and the other tests that read `LEONIDA_TEST_*_SPV` end with exit 3 and no message | The `.spv` paths are compiled in as `D:/a/Leonida/Leonida/runtime/build/generated/...`; the prefix has no `D:` drive and the test isn't run from the artifact folder | Run it from the artifact folder (the tests then find `generated/.spv` there) or through `scripts/run_wine_tests.py`, which maps that drive for the run; current `main` names the file it couldn't copy (`cannot copy ...: File not found`) | +| Linux cross-build: CMake can't find `clang-cl-19` (or another versioned `clang-cl-`) although `clang-19` and `lld-19` are installed | On Debian and Ubuntu, the versioned `clang-cl-` link is in the `clang-tools-` package, not in `clang-` (`/usr/lib/llvm-/bin/clang-cl` comes from it too); `lld-link-`, `llvm-lib`, `llvm-rc` and `llvm-mt` come from `lld-` and `llvm-` | `sudo apt-get install clang-tools-19 lld-19 llvm-19` (Ubuntu 24.04 has 19 and 20), then pass the versioned names as in [the cross-build](#the-windows-runtime-on-linux-under-wine-or-proton) | +| Under Ubuntu's Wine 9.0, `wineboot --init` (and every Wine program after it) stops at once with `free(): invalid pointer` or a segmentation fault, before printing anything else; the prefix holds only a `wineserver` file | That Wine opens `/run/user/` for its server directory, whether `XDG_RUNTIME_DIR` is set or not, and aborts when the folder doesn't exist. The login manager makes it for a desktop session; a container or a shell started without a login session (a root shell in Docker, a CI runner image) has none | Create it before starting Wine: `mkdir -p /run/user/$(id -u) && chmod 700 /run/user/$(id -u)` (setting `XDG_RUNTIME_DIR` alone doesn't help), delete the half-made prefix, and run `wineboot --init` again | | `run_gpu_tests.py` fails on a `dict \| None` annotation | Python older than 3.10 | Use Python 3.11+ | | `vulkaninfo` lists `Microsoft Direct3D12 ()` next to the real GPU and the tests run on it | The Windows "OpenCL™, OpenGL® and Vulkan® Compatibility Pack" installs Mesa's Dozen, a Vulkan-on-D3D12 layer that reports `DISCRETE_GPU` like the native card | Current `main` prefers a native ICD over Microsoft's vendor (`0x1414`) in the runtime and every harness; set `LEONIDA_VK_DEVICE=` to select explicitly. See #915. | | A GPU test that uses `image_load` (or lighting built from real shaders) reads zeros from its image; @Silliana saw every texel except pixel (0,0) come back zero in their own layer (#603, not reproduced here) | In this runtime the shader turns the T# words into an index through the descriptor hash table (`runtime/src/descriptor_table.h`: a miss gives index 0), and index 0 is a 1×1 image of zeros (`runtime/src/vulkan_bindless.h`), so a hand-built or zeroed T# that was never registered reads zeros even at (0,0). The translator does not compare coordinates with the T# size, and `cs_imgload.asm` only uses its T# words as a hash key | Register the descriptor through the runtime (for D3D12, create it with `CreateShaderResourceView`) so its T# hits the table, with the image's real width and height (stored as size − 1, see `runtime/src/gfx10_descriptors.h`) | diff --git a/docs/text.md b/docs/text.md index 8c92bcb17..9de8d2560 100644 --- a/docs/text.md +++ b/docs/text.md @@ -17,22 +17,45 @@ into the logical resource. ``` descriptor ptr index | u32 | u32 0x10 | ptr | 01 01 00 00 | u32 hash_bytes | ptr hash - | u32 0x10 | u32 blob_bytes | ptr blob + | u32 0x10 | u32 blob_bytes | ptr blob | ... more entries (u32 tag, u32 bytes, ptr) ptr u32 0x5xxxxxxx, u32 0 hash entry 16 bytes: u32 joaat(lowercase label), u32 0, u8 1, u8[2], u24 index (at +11), u8 -index entry 16 bytes: u64, u64 (blob offset << 20 | flags) -blob NUL-terminated UTF-8 strings +index entry 16 bytes: u64, u64 (offset in its blob chunk << 20 | flags); the chunk is flags & 3 +blob NUL-terminated UTF-8 strings, in one or more chunks ``` A hash entry whose first word is 0, whose second word is not 0, or whose byte at +8 is not 1 is an empty slot. Text keeps the game's inline markup (`~o~`, `~s~`, `~n~`, `~sl:0.05:0.9~`, `~COLOR_SUBTITLE_FOREIGN_DIALOGUE~`, ...). +### Blob chunks + +From the blob on, the descriptor is a run of 16-byte entries: u32 tag, u32 bytes, pointer. The run ends at the first +16 bytes whose pointer word is not a `0x5xxxxxxx` pointer. A table with more than 1 MiB of text has several tag +`0x10` entries instead of one. Each is a blob chunk of at most 1 MiB, and the chunks need not be contiguous. An +index entry's second word names its chunk: its low 20 bits are always `0b1cc`, where `cc` is the chunk, and the bits +above them are the offset inside that chunk. + +Measured on `data.rpf` (counts only): + +| | | +|---|---:| +| Tables with more than one chunk | 23 (3 of them contiguous) | +| Chunks per such table | 2-4 | +| Index entries in them | 649,246 | +| Low 20 bits `0b100` / `0b101` / `0b110` / `0b111`, all tables | 3,914,583 / 220,161 / 66,416 / 6,721 | +| Index entries pointing at the start of a string, chunk = `flags & 3` | 4,207,881 of 4,207,881 | + +Before this rule, `text_tables.py` read every offset from the first chunk, which is a full 1 MiB. The offset then +landed inside some other string, so 293,292 strings in those 23 tables came out with the wrong text and no error. +The other 14,459 `data.rpf` tables read the same as before. So do all 15,951 tables of `story000.rpf` and all 78 +of `shared_minigame000.rpf`. + | Archive | Tables | |---|---:| | `data.rpf` | 14,482 | -| `story000.rpf` | 15,831 | +| `story000.rpf` | 15,951 | | `shared_minigame000.rpf` | 78 | -| **Total** | **30,391** tables, 7,252,163 strings | +| **Total** | **30,511** tables, 7,530,381 strings | The same 14,482 `data.rpf` tables come out of a directory carved by `rpf9_carve.py`, the archive read directly, and an older carve that wrote each resource as one file. @@ -86,30 +109,33 @@ separately, so nothing is lost. ### Language from the nested archive -In `data.rpf` and `story000.rpf` every string table sits in one of 13 nested RPF9 archives: `9FPR` headers at 4 KiB- -aligned offsets, whose data offset at +4 stays inside the file. Each of those archives holds a single language. -`text_tables.py` therefore gives every table in a nested archive the guess that most of that archive's tables share -(`xx` left out), when that guess covers more than half of them. A table outside a nested archive, or in an archive with -no majority, keeps its own guess. The tool finds the archive in an `.rpf` source, or in the archive that an +In `data.rpf`, `story000.rpf` and `shared_minigame000.rpf` every string table sits in one of 13 nested RPF9 archives: +`9FPR` headers at 4 KiB-aligned offsets, whose data offset at +4 stays inside the file. Each of those archives holds a +single language. `text_tables.py` therefore gives every table in a nested archive the guess that most of that archive's +tables share (`xx` left out), when that guess covers more than half of them. A table outside a nested archive, or in an +archive with no majority, keeps its own guess. The tool finds the archive in an `.rpf` source, or in the archive that an `rpf9_carve.py` directory's `index.json` names. Without it, every table keeps its own guess. +`story000_restofworld.rpf` has 18 nested archives, but the descriptor search finds no string table in it: none of its +101 `0DRP` resources matches the table descriptor. Measured with the per-table guess (counts only): -| | `data.rpf` | `story000.rpf` | -|---|---:|---:| -| Nested archives (all) | 41 | 436 | -| Nested archives holding string tables | 13 | 13 | -| Tables in them / all tables | 14,440 / 14,440 | 15,831 / 15,831 | -| Tables per archive | 1,109-1,113 | 1,214-1,220 | -| Per-table guess equal to its archive's language | 57.7%-99.9% | 72.2%-100% | -| Tables whose language changes | 2,075 | 849 | -| `xx` before / after | 869 / 0 | 188 / 0 | -| Plain `es` before / after | 659 / 0 | 553 / 0 | -| Plain `zh` before / after | 203 / 0 | 47 / 0 | +| | `data.rpf` | `story000.rpf` | `shared_minigame000.rpf` | `story000_restofworld.rpf` | +|---|---:|---:|---:|---:| +| Nested archives (all) | 41 | 436 | 48 | 18 | +| Nested archives holding string tables | 13 | 13 | 13 | 0 | +| Tables in them / all tables | 14,440 / 14,440 | 15,831 / 15,831 | 78 / 78 | 0 / 0 | +| Tables per archive | 1,109-1,113 | 1,214-1,220 | 6 | - | +| Per-table guess equal to its archive's language | 57.7%-99.9% | 72.2%-100% | 66.7%-100% | - | +| Tables whose language changes | 2,075 | 849 | 5 | 0 | +| `xx` before / after | 869 / 0 | 188 / 0 | 2 / 0 | 0 / 0 | +| Plain `es` before / after | 659 / 0 | 553 / 0 | 2 / 0 | 0 / 0 | +| Plain `zh` before / after | 203 / 0 | 47 / 0 | 0 / 0 | 0 / 0 | -Both archives hold the 13 languages in the same order: `en`, `pt`, `zh-Hans`, `zh-Hant`, `fr`, `de`, `it`, `ja`, `ko`, -`es-419`, `pl`, `ru`, `es-ES`. The lowest agreement is in the two Spanish archives, where 208 to 314 tables per archive -had no variant marker. +The three archives that hold tables share the 13 languages in the same order: `en`, `pt`, `zh-Hans`, `zh-Hant`, `fr`, +`de`, `it`, `ja`, `ko`, `es-419`, `pl`, `ru`, `es-ES`. The lowest agreement is in the Spanish archives: in `data.rpf` and +`story000.rpf` 208 to 314 tables per archive had no variant marker, and in `shared_minigame000.rpf` the `es-ES` archive +agrees on 4 of its 6 tables. Reading `story000.rpf` this way needs the `rpf9_carve.py` that checks a gap in chunks (#2117): one unread gap there is 9.56 GB, and slicing it whole ran out of memory. @@ -169,9 +195,18 @@ Standard library only. The four archives above take about 2 minutes on one core ## Open questions -- **Language per table.** The nested archive now groups the tables of `data.rpf` and `story000.rpf` by language, - but the language code of each archive is still the majority guess of its tables. A field or a naming rule outside - the tables (the TOC or the executable) would name it directly. `shared_minigame000.rpf` and - `story000_restofworld.rpf` are not measured for nested archives here. +- **Language per table.** The nested archive now groups the tables of `data.rpf`, `story000.rpf` and + `shared_minigame000.rpf` by language, but the language code of each archive is still the majority guess of its + tables. A field or a naming rule outside the tables (the TOC or the executable) would name it directly. The + descriptor search finds no string table in `story000_restofworld.rpf`, so no nested archive there has a table + language to name. - **Which text the game picks.** When a label has two texts in one language, which table wins at run time (load order, mission scope, the foreign-dialogue subtitle option) is not established. +- **Hash entries whose byte at +8 is 5, 7 or 8.** `data.rpf` has 3,026 of them, in 62 tables, and none of those tables + is guessed as English. They are not strings: their u24 at +11 runs 0, 2, 4, ... in every table. That is, in units + of 16 bytes, an index into a 32-byte record array, the descriptor entry tagged `0x956a9df5`, whose size is exactly + 32 bytes times the number of such entries. Another entry, tagged `0x10075946`, holds 32-byte records whose first + word is a blob reference like an index entry's second word. All 7,345 of them point at the start of a string. + A group record holds a u32 count equal to the u32 after it (1-7). Read as (first record, count), its first word + and that count cover the `0x10075946` array exactly in only 34 of the 62 tables, so the layout is not decoded. + `text_tables.py` skips these entries. diff --git a/docs/textures.md b/docs/textures.md index 85d83b926..2a6fb2df9 100644 --- a/docs/textures.md +++ b/docs/textures.md @@ -985,8 +985,18 @@ their first 4 KiB, and the large ones are high-entropy (7.3 to 7.7 bits per byte one at 4.1). They are left as opaque raw data here; matching them to the `data/ttdb` texture pools is the obvious next check. -Not measured here (hypothesis): what the 1,313 texture pairs are keyed by, and whether the format codes are -DXGI values (the exact-size match supports it). +**Measured keying and format codes (ASSET-274):** +All 1,315 system streams are RAGE `pgDictionary` pages containing descriptor pointers and a 32-bit +`joaat32` hash table: +- **Format codes are 1:1 DXGI format enums:** + - `0x5f` (95) = `DXGI_FORMAT_BC6H_UF16` (1,313 pairs, 128 x 128). + - `0x62` (98) = `DXGI_FORMAT_BC7_UNORM` (1 pair, 172 x 172: UI switch portraits `switch_jason` and `switch_lucia`). + - `0x4d` (77) = `DXGI_FORMAT_BC3_UNORM` (1 pair, 512 x 512: UI indicators `qrcode_logo` and `busy_spinner`). +- **Keying:** Each dictionary indexes textures by the lower-case ASCII asset name hash (`joaat32`). + - The 1,313 pairs are each keyed by `waterfog2` (`0x9b9b31df`) and `waterfog` (`0xf1389e16`). + - The count of 1,313 matches the water-bearing cells of the 36 x 41 (1,476 total) world streaming grid + (`StreamingDesc/NumberOfTilesX, Y` in `docs/world.md:361`); whether the remaining 163 cells are inland/dry + cells with no waterfog dictionary is a hypothesis. ## Next step diff --git a/docs/world.md b/docs/world.md index 16a220a6f..f6562e925 100644 --- a/docs/world.md +++ b/docs/world.md @@ -401,10 +401,66 @@ The place names shown to the player come from one `GameShape__Data__LocationName sections. - **All 2,280 interior positions lie inside the world rectangle** shared by the `PAMH` heightmap and the region tint map (x -13,312..5,120, y -9,728..11,264); none is at the origin. Heights run from -78 to 821 (median 5). -- None of the keys is an archive entry name or the joaat of a model archetype name in the local catalog, the two - texture-dictionary names match archive entries but not `.ytd` ones, so the keys are their own namespace (probably shape - or zone ids resolved elsewhere at runtime; not measured). The 46 textures match no texture-dictionary item - in the catalog either. +- **Interior keys are interior archetype names.** 1,357 of the 1,358 `InteriorNames` keys, lower-cased, are the + joaat `name` of a `CMloArchetypeDef` in `levels.rpf`, and all 1,357 are confirmed by that archetype's 64-bit key + (MurmurHash3 x64 low 64 of the lower-cased key at +0x08, member `8bfb6095`). The remaining key names no interior + and its hash occurs in no hash member of `levels.rpf`. The earlier "own namespace" reading came from a 1 GiB + window holding 15 of the 1,706 interior archetypes and from the model catalog, which has no interiors. See + [Interior keys and interior placements](#interior-keys-and-interior-placements). +- None of the location, river or road keys is an archive entry name or the joaat of a model archetype name in the + local catalog; the two texture-dictionary names match archive entries but not `.ytd` ones. The 46 textures + match no texture-dictionary item in the catalog either. + +### Interior keys and interior placements + +`tools/world_interior_names.py` reads every interior definition and every interior placement in `levels.rpf` +and joins them with the `InteriorNames` section (full archive, `--jobs 15`, about 2 minutes): + +| Measured | Count | +|---|---:| +| `CMloArchetypeDef` definitions / distinct names | 1,706 / 1,706 | +| `CMloInstanceDef` placements / distinct interiors placed | 2,590 / 1,704 | +| keys naming an interior (confirmed by the 64-bit key) | 1,357 (1,357) | +| keys whose interior is placed | 1,356 | +| ... with as many positions as placements | 1,268 | +| ... with more positions than placements | 64 | +| ... with fewer positions than placements | 24 | + +So a key selects one interior archetype, and its inner items are, in most cases, one per placed copy of that +interior: the `Name` of each item labels that copy. + +Interiors are not placed by `CEntityDef`: no entity in the 1,670,435 rows of `world_index.py --entities-out` +uses an interior name. They are placed by `CMloInstanceDef` (`09cc28be`, 0x250 bytes), which carries the entity +members `rotation` (+0x10), `position` (+0x38), `archetypeName` (+0x44), `scaleXY` (+0x54) and `scaleZ` (+0x58) +plus interior-specific members. These 2,590 placements are separate from the 23,535 map / 1,670,442 entity +census, which counts `CEntityDef` only. + +The positions sit at the edge of their own interior, not at its origin or centre. Distance from each of the 2,278 +positions to the nearest placed copy of its own interior's box (0 = inside): + +| Rotation | Inside | ≤ 1 m | ≤ 2 m | ≤ 5 m | ≤ 25 m | ≤ 100 m | Median | In a non-`limbo` room box | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| stored quaternion | 315 | 1,015 | 1,189 | 1,443 | 1,867 | 2,199 | 1.72 m | 213 | +| conjugated | 571 | 950 | 1,121 | 1,416 | 1,863 | 2,199 | 2.10 m | 482 | + +The interior box's largest side has a median of 16.7 m. Most positions are therefore just outside or just inside +the interior shell, which fits an entry or label point; that they are doors is a hypothesis (portals were not +compared). The conjugated rotation puts more positions inside rooms, consistent with the entity rule in +[Map placement records](#map-placement-records); it is not a separate proof of it. 79 positions are more than +100 m from every copy of their interior. + +Interior rooms (`CMloRoomDef` `0b1811f1`, 0x70 bytes: `name` +0x00, `bbMin` +0x10, `bbMax` +0x20) are reached +through the interior's array members, which use the `InstanceList` reference of +[Instanced props and grass](#instanced-props-and-grass) (1-based block index, offset from bit 20, u16 count). Room +names are lower-cased joaat; in all 908 resources that hold one interior, its first room is `limbo`. A room's hash member `a261e0a9` (+0x34) +holds the hash of 267 interior keys. + +```powershell +python -I tools\gamedata_reader.py \common --root GameShape__Data__LocationNameLoopkup --out \gamedata +python -I tools\world_interior_names.py \levels.rpf --names \gamedata\GameShape__Data__LocationNameLoopkup_.json ` + --jobs 15 --out \world\interior_names.json +python -I tests\test_world_interior_names.py +``` ## What a runtime needs diff --git a/docs/xdxr.md b/docs/xdxr.md index a5b3ab87d..bf445d2e3 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -98,7 +98,8 @@ type is one of two checks, and neither reads past the `InfoType` field: - `0xe6a0`, which the batched export calls first (`0x216dc`), loops over every element's postbuild descs (count at `+0x30`, array at `+0x38`, stride 16) and compares `InfoType` (`+8`) with `0x10`. A match branches to the error - block at `0x106ba`, whose third message names the type, and the build ends with `E_INVALIDARG` before any work. + block at `0x106ba`, whose third message names the type, and the build throws `E_INVALIDARG` as a C++ exception + (`0x10702`) before any work; the export returns `void`. - The batched export's own postbuild loop (`0x2177b`..`0x217e9`) skips `0x10` explicitly, then sends 0 and 3 to `0x1d540` and 2 to `0x1d7c0`. Every other value falls through to the next desc. @@ -108,6 +109,5 @@ None of the 15 other DLLs in the package names the type or an offline builder. - The names of the stream record types and of their values. - The offline statistics layout (§4). It is not in the package: the one DLL that knows the type only rejects or - skips it (RT-155). It needs the offline BVH builder, which is not in the package. A runtime doesn't need it, - because the shipped builder refuses the request. + skips it (RT-155). A runtime doesn't need it, because the shipped builder refuses the request. - Whether the game passes a non-empty stream desc at all. That needs the executable's call sites (RT-5). diff --git a/make_game.py b/make_game.py index cb12b78c6..0d95ecf08 100644 --- a/make_game.py +++ b/make_game.py @@ -460,6 +460,25 @@ def icloud_default_notes() -> list: MIN_FREE_GB = {"shaders": 30, "assets": 300} +def tree_bytes(path: str) -> int: + """Bytes in the files under path (0 when it is missing); links are not followed.""" + total, stack = 0, [path] + while stack: + try: + with os.scandir(stack.pop()) as it: + for e in it: + try: + if e.is_dir(follow_symlinks=False): + stack.append(e.path) + elif e.is_file(follow_symlinks=False): + total += e.stat(follow_symlinks=False).st_size + except OSError: + pass + except OSError: + pass + return total + + def assets_exported(work: str) -> bool: """Whether an earlier run finished the assets stage's exports, so its space is already in use. xma.done is the last marker assets() writes, after every model, texture and audio export before it succeeded; ogg.done is read @@ -619,6 +638,12 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N if need.get("assets") and not wav and assets_exported(work): log(f"preflight: the assets are already exported in {work}; not counting their {need['assets']} GB") need["assets"] = 0 + elif need.get("assets") and not wav: + # A stopped export resumes: what it already wrote is on the disk, so it isn't needed free a second time. + done_gb = int(tree_bytes(os.path.join(work, "assets")) / 2**30) + if done_gb: + log(f"preflight: {done_gb} GB of assets are already exported in {work}; not counting them") + need["assets"] = max(0, need["assets"] - done_gb) os.makedirs(work, exist_ok=True) free_gb = shutil.disk_usage(work).free / 2**30 need_gb = sum(need.values()) @@ -643,8 +668,6 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N hint = " To prepare the loader without exporting assets, use --stages check,shaders,runtime." fail(f"{free_gb:.0f} GB free on the drive of {work}, about {need_gb} GB is needed. " "Free some space or choose another drive with --work." + hint) - if "assets" in stages: - ensure_submodule() if os.name != "nt" and not runtime_build and any(s in WINDOWS_ONLY for s in stages): cross_configure() if "pipelines" in stages and os.name != "nt" and not pipeline_check_exe(): @@ -653,6 +676,8 @@ def preflight(stages: list, work: str, wav: bool = False, runtime_build: str | N fail("vk_pipeline_check built, but not as runtime/build/linux/vk_pipeline_check (a multi-config " "generator puts it in a subfolder): unset CMAKE_GENERATOR if it names one, delete " "runtime/build/linux and run the build again.") + if "assets" in stages: + ensure_submodule() def visual_cpp_tools_ok() -> bool: @@ -762,15 +787,21 @@ def ensure_submodule() -> None: core = os.path.join(ROOT, "third_party", "rpf9-explorer", "Core") if os.path.isdir(core) and os.listdir(core): return + clone = "git clone --recursive https://github.com/ItsNotRexed/Leonida" git = shutil.which("git") - if git and subprocess.run([git, "-C", ROOT, "rev-parse", "--resolve-git-dir", ".git"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0: - log("fetching third_party/rpf9-explorer") - r = subprocess.run([git, "-C", ROOT, "submodule", "update", "--init", "--recursive"]) - if r.returncode == 0 and os.path.isdir(core): - return - fail("third_party/rpf9-explorer is missing. Download the project with: " - "git clone --recursive ") + if not git: + fail("third_party/rpf9-explorer is missing (a \"Download ZIP\" from GitHub leaves it out). Install Git " + f"(https://git-scm.com/downloads) and download the project with: {clone}") + if subprocess.run([git, "-C", ROOT, "rev-parse", "--resolve-git-dir", ".git"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode != 0: + fail("third_party/rpf9-explorer is missing (a \"Download ZIP\" from GitHub leaves it out). " + f"Download the project with: {clone}") + log("fetching third_party/rpf9-explorer") + r = subprocess.run([git, "-C", ROOT, "submodule", "update", "--init", "--recursive"]) + if r.returncode == 0 and os.path.isdir(core): + return + fail("fetching third_party/rpf9-explorer failed. Check your network connection, then run " + "\"git submodule update --init --recursive\" in this folder and build again.") def check(game: str, full: bool) -> dict: @@ -1135,6 +1166,25 @@ def fallback_flags(a) -> tuple[str, ...]: return tuple(flag for flag, attr in FALLBACK_FLAGS if getattr(a, attr, False)) +def recorded_fallback_flags(work: str) -> tuple[str, ...]: + """The fallback flags the translation in `work` was made with (spirv/translator_flags.txt), () when there is none.""" + return tuple(read_shader_setting(os.path.join(work, "shaders", "spirv", "translator_flags.txt")).split()) + + +def keep_recorded_fallback(flag: str, work: str) -> bool: + """Whether an automatic fallback flag stays on when the GPU probe can't tell if the GPU needs it. + + The probe answers differently from run to run (a GPU asleep or hidden, a missing Vulkan loader, its 60 s + timeout). Dropping the flag then would translate the whole corpus without it, and the next run that can ask + would translate it a third time. A flag the probe turned on was needed by the GPU it last reached, so a + translation made with it is kept, as wave64 emulation is; a probe that answers still decides.""" + if flag not in recorded_fallback_flags(work): + return False + log(f"shaders: couldn't ask the GPU the runtime would use whether it needs {flag}; the shaders were translated " + "with it and it stays on instead of translating them all again (a run that can ask the GPU decides again)") + return True + + def smallest_max_subgroup(vulkaninfo_text: str): """The smallest maxSubgroupSize vulkaninfo reports over all devices (text or --json output), or None.""" size = r'maxSubgroupSize"?\s*[=:]\s*(\d+)' @@ -1241,7 +1291,7 @@ def runtime_gpu_max_push_constants(): # Source and data files that produce the translated modules, metadata and partner stubs. TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py", "wave64_emulate_opt.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py", - "gfx10_formats.json") + "spirv_opt.py", "report_paths.py", "gfx10_formats.json") def sources_digest(folder: str, names, lead: str = "") -> str: @@ -1357,8 +1407,36 @@ def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False, raise bad = [f"shard {i} exited with {r}" for i, r in zip(todo, codes) if r != 0] if bad: + # An older index describes the corpus from the run before: keeping it would make the next run take the + # failed translation as finished. The next successful --merge writes it again. + index = os.path.join(spirv, "index.json") + try: + os.remove(index) + except FileNotFoundError: + pass + except OSError as e: + log(f" cannot remove the stale {index}: {e}") fail("rdna2spirv.py: " + ", ".join(bad)) py("rdna2spirv.py", disasm, "--out", spirv, "--merge") + index = os.path.join(spirv, "index.json") + if os.path.isfile(index): + # Present but empty or unreadable: the merge published nothing, and the next run would read that as finished. + try: + with open(index, encoding="utf-8") as f: + merged = json.load(f) + except (OSError, ValueError) as e: + os.remove(index) + fail(f"rdna2spirv.py --merge wrote an unreadable {index}: {e}") + if not merged: + # A marker left behind would look like a finished translation to the next run; drop it with the failure. + os.remove(index) + # The plan would make the retry reuse the same empty parts even after the disassembly was repaired. + try: + os.remove(plan_path) + except OSError: + pass + fail("rdna2spirv.py translated 0 shaders, so the empty index is not kept. Run the shaders stage again; " + "if it happens again, the disassembly logged above is why.") # ---------------------------------------------------------------- assets @@ -1378,6 +1456,11 @@ def decoder_digest() -> str: if git and os.path.exists(os.path.join(sub, ".git")): r = subprocess.run([git, "-C", sub, "rev-parse", "HEAD"], capture_output=True, text=True) pin = r.stdout.strip() if r.returncode == 0 else "" + # An edit to a tracked submodule file that is not committed changes the decoder but not HEAD. + # shortcut: new untracked files in the submodule are not seen; hash them too if that comes up. + r = subprocess.run([git, "-C", sub, "diff", "HEAD"], capture_output=True) + if r.returncode == 0 and r.stdout: + pin += "+" + hashlib.sha256(r.stdout).hexdigest() folder = os.path.join(TOOLS, "rpf9dump") names = sorted(n for n in os.listdir(folder) if n.endswith((".cs", ".csproj", ".json"))) return sources_digest(folder, names, pin) @@ -1443,7 +1526,9 @@ def assets(game: str, work: str, wav: bool, jobs: int) -> None: folder = os.path.join(out, name, mode) record = os.path.join(folder, DECODER_RECORD) if os.path.isdir(folder) and read_shader_setting(record) != decoder: - # rpf9dump keeps the files it finds, so another decoder's output is removed first. + # rpf9dump keeps the files it finds, so another decoder's output is removed first. The exporter is + # built before that: a build that fails leaves the old export in place. + get_exporter(work) log(f"assets: no matching decoder fingerprint for {mode} from {rel}: exporting again") shutil.rmtree(folder) elif os.path.isfile(os.path.join(folder, "manifest.json")): @@ -1690,8 +1775,17 @@ def pipeline_check_exe(runtime_build: str | None = None) -> str | None: def require_translated_shaders(work: str) -> str: spirv = os.path.join(work, "shaders", "spirv") - if not os.path.isfile(os.path.join(spirv, "index.json")): + index = os.path.join(spirv, "index.json") + if not os.path.isfile(index): fail("No translated shaders yet: run the shaders stage first.") + try: + with open(index, encoding="utf-8") as f: + translated = json.load(f) + except (OSError, ValueError) as e: + fail(f"The translated shader index {index} is unreadable ({e}): run the shaders stage again.") + if not translated: + # A build from before the shaders stage refused an empty merge can carry this marker. + fail(f"The translated shader index {index} is empty, so there is nothing to check. Run the shaders stage again.") return spirv @@ -1721,28 +1815,65 @@ def pipelines(work: str, out: str, jobs: "int | None" = None, *, runtime_build: log("pipelines: done") return base += ["--inflight-file", inflight] + # Bound each checker invocation to a range that recovery can split further when concurrent heavy compiles + # exceed available memory, without starting the entire corpus again (BUILD-1030). + names = pipeline_names(spirv) if checker_supports(exe, "--start", "--count") else [] crashed: "list[str]" = [] - code = 0 - for _ in range(PIPELINE_CRASH_RETRIES + 1): - code = run(base + (["--skip-file", skip] if crashed else []), check=False) - if code in (0, 1, 2) or interrupted(code): - break - # The driver took vk_pipeline_check down. Name the module it was compiling and check the rest without it: - # what was already compiled comes back from pipeline_cache.bin, saved every 10 minutes. - suspects = [n for n in read_names(inflight) if n not in crashed] - if len(suspects) > 1: # several were compiling: keep the ones that also kill it on their own - suspects = [n for n in suspects if crashes_alone(exe, spirv, cache, n)] - if not suspects: - fail(f"vk_pipeline_check exited with {exit_label(code)} while no module could be named as the cause; " - "run the pipelines stage again, and report it if it keeps happening") - for n in suspects: - log(f"pipelines: {n} took vk_pipeline_check down ({exit_label(code)}); checking the rest without it") - crashed += suspects - with open(skip, "w", encoding="utf-8", newline="\n") as f: - f.write("".join(n + "\n" for n in crashed)) - else: + + def check_range(start: int = 0, count: "int | None" = None) -> int: + selection = ["--start", str(start), "--count", str(count)] if count is not None else [] + allowed = set(names[start:start + count]) if count is not None else None + for _ in range(PIPELINE_CRASH_RETRIES + 1): + drop(inflight) # a crash during setup must not inherit another process's in-flight module names + code = run(base + selection + (["--skip-file", skip] if crashed else []), check=False) + # Native setup failures also return 1. A finished pass writes/clears this report even when shaders + # fail validation; setup failures return before writing it. Do not repeat setup for every batch. + if code == 1 and not os.path.isfile(inflight): + fail("vk_pipeline_check exited with 1 before writing its work report; check Vulkan initialization " + "and report-file access in the output above") + if code in (0, 1, 2) or interrupted(code): + return code + suspects = list(dict.fromkeys(n for n in read_names(inflight) + if n not in crashed and (allowed is None or n in allowed))) + # Even the last in-flight module can be innocent after other heavy compiles in the batch. + if count is not None or len(suspects) > 1: + suspects = [n for n in suspects if crashes_alone(exe, spirv, cache, n, inflight)] + if not suspects: + if count is not None and count > 1: + # All suspects survived in fresh processes: do not blacklist them. Re-check the entire failed + # range in smaller processes; completed earlier batches retain their cache checkpoints. + log(f"pipelines: shaders {start + 1}-{start + count} exited with {exit_label(code)} without " + "a reproducible module crash; retrying this range in smaller batches") + half = count // 2 + first = check_range(start, half) + if first == 2 or interrupted(first): + return first + second = check_range(start + half, count - half) + return second or first + fail(f"vk_pipeline_check exited with {exit_label(code)} while no module could be named as the cause; " + "the checker could not finish even this range in a fresh process; check available memory " + "and report it if it keeps happening") + for n in suspects: + log(f"pipelines: {n} took vk_pipeline_check down ({exit_label(code)}); checking the rest without it") + crashed.extend(suspects) + with open(skip, "w", encoding="utf-8", newline="\n") as f: + f.write("".join(n + "\n" for n in crashed)) fail(f"vk_pipeline_check still crashed after {PIPELINE_CRASH_RETRIES} retries; modules that took it down: " + ", ".join(crashed)) + + code = 0 + ranges = [(s, min(PIPELINE_BATCH_SIZE, len(names) - s)) + for s in range(0, len(names), PIPELINE_BATCH_SIZE)] if names else [(0, None)] + for start, count in ranges: + if count is not None: + log(f"pipelines: checking shaders {start + 1}-{start + count} of {len(names)} in a fresh process") + result = check_range(start, count) + if result: + code = result # a later successful batch must not erase an earlier validation failure + if result == 2 or interrupted(result): + break + if crashed and not code: + code = 1 drop(inflight) if code != 0: why = f"; {len(crashed)} module(s) took the driver down and were counted as failed: " + ", ".join(crashed) \ @@ -1754,6 +1885,7 @@ def pipelines(work: str, out: str, jobs: "int | None" = None, *, runtime_build: # How many times the pipelines stage restarts vk_pipeline_check after a module takes it down (each costs at most the # 10 minutes since the last cache checkpoint, plus loading the cache). PIPELINE_CRASH_RETRIES = 5 +PIPELINE_BATCH_SIZE = 500 # fresh compiler process and cache checkpoint after at most this many index entries def interrupted(code: int) -> bool: @@ -1789,17 +1921,44 @@ def read_names(path: str) -> "list[str]": return [] -def crashes_alone(exe: str, spirv: str, cache: str, name: str) -> bool: - """Whether one module takes vk_pipeline_check down on its own: --start/--count select it in the checker's - name-sorted index (byte order, as its std::map).""" - with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: - names = sorted(json.load(f), key=lambda n: n.encode("utf-8")) +def pipeline_names(spirv: str) -> "list[str]": + """The checker's name-sorted index (byte order, as its std::map); ranges and diagnostic probes share it.""" + path = os.path.join(spirv, "index.json") + try: + with open(path, encoding="utf-8") as f: + index = json.load(f) + except (OSError, ValueError) as e: + fail(f"pipelines: cannot read {path}: {e}") + if not isinstance(index, dict): + fail(f"pipelines: {path} must contain a JSON object") + return sorted(index, key=lambda n: n.encode("utf-8")) + + +def crashes_alone(exe: str, spirv: str, cache: str, name: str, inflight: str | None = None) -> bool: + """Whether one module takes vk_pipeline_check down on its own, using its global index position.""" + names = pipeline_names(spirv) if name not in names: return False - code = run([exe, spirv, cache, "--jobs", "1", "--start", str(names.index(name)), "--count", "1"], check=False) + args = [exe, spirv, cache, "--jobs", "1", "--start", str(names.index(name)), "--count", "1"] + if inflight: + drop(inflight) + args += ["--inflight-file", inflight] + code = run(args, check=False) + if code == 1 and inflight and not os.path.isfile(inflight): + fail(f"pipelines: checking {name} alone exited with 1 before writing its work report; " + "check Vulkan initialization and report-file access in the output above") + if interrupted(code) or code == 2: + fail(f"pipelines: checking {name} alone stopped with {exit_label(code)}") return code not in (0, 1, 2) and not interrupted(code) +def path_is_within(path: str, directory: str) -> bool: + try: + return os.path.commonpath([path, directory]) == directory + except ValueError: # Different Windows drives or UNC shares have no common path. + return False + + def main() -> int: ap = argparse.ArgumentParser(description="Build the PC port from your own copy of the game.") ap.add_argument("--game", help="your package folder (found automatically if left out)") @@ -1886,20 +2045,16 @@ def main() -> int: except OSError: game_entries = [] for p in (out, work): - try: - # normcase: Windows paths compare without case, so C:\Games\X and c:\games\x\out are inside. - real_destination = os.path.normcase(os.path.realpath(p)) - if is_game_drive_root: - # If the game is at drive root (e.g. D:\), reject the drive root itself and anything - # inside the dump's existing top-level entries, but allow separate top-level folders. - inside = (real_destination == real_game) or any( - os.path.commonpath([real_destination, entry]) == entry - for entry in game_entries - ) - else: - inside = os.path.commonpath([real_destination, real_game]) == real_game - except ValueError: # different drives - inside = False + # normcase: Windows paths compare without case, so C:\Games\X and c:\games\x\out are inside. + real_destination = os.path.normcase(os.path.realpath(p)) + if is_game_drive_root: + # If the game is at drive root (e.g. D:\), reject the drive root itself and anything + # inside the dump's existing top-level entries, but allow separate top-level folders. + inside = (real_destination == real_game) or any( + path_is_within(real_destination, entry) for entry in game_entries + ) + else: + inside = path_is_within(real_destination, real_game) if inside: fail("--out and --work must be outside the game folder.") runtime_build = os.path.abspath(a.runtime_build) if a.runtime_build else None @@ -1911,14 +2066,20 @@ def main() -> int: "(or pass --runtime-build)") emulate, keep_emulated = (wave64_settings(a.wave64_emulate, mesh_compute=a.mesh_compute) if "shaders" in stages else (False, a.wave64_emulate == "auto")) - if "shaders" in stages and not a.f16_interp_fallback and runtime_gpu_per_vertex() is False: - log("shaders: the GPU the runtime would use can't take PerVertexKHR inputs (MoltenVK, or no " - "fragmentShaderBarycentric): translating with --f16-interp-fallback") - a.f16_interp_fallback = True + if "shaders" in stages and not a.f16_interp_fallback: + per_vertex = runtime_gpu_per_vertex() + if per_vertex is False: + log("shaders: the GPU the runtime would use can't take PerVertexKHR inputs (MoltenVK, or no " + "fragmentShaderBarycentric): translating with --f16-interp-fallback") + a.f16_interp_fallback = True + elif per_vertex is None: + a.f16_interp_fallback = keep_recorded_fallback("--f16-interp-fallback", work) if "shaders" in stages and not a.pc_tail_ubo: need_pc = 152 if a.mesh_compute else 144 max_pc = runtime_gpu_max_push_constants() - if max_pc is not None and max_pc < need_pc: + if max_pc is None: + a.pc_tail_ubo = keep_recorded_fallback("--pc-tail-ubo", work) + elif max_pc < need_pc: log(f"shaders: the GPU the runtime would use reports maxPushConstantsSize = {max_pc} (< {need_pc}): " "translating with --pc-tail-ubo") a.pc_tail_ubo = True diff --git a/navmeshes.navmesh-decode.json b/navmeshes.navmesh-decode.json new file mode 100644 index 000000000..37e62d8c1 --- /dev/null +++ b/navmeshes.navmesh-decode.json @@ -0,0 +1,518 @@ +{ + "input": "navmeshes.rpf", + "mode": "rpf", + "start": 1920, + "end": 6707512496, + "span": 6707510576, + "carver_streams": { + "streams": 90295, + "stored": 6540238392, + "inflated": 20551068624, + "zero_padding": 161191191, + "unread": 6080993, + "tiny_continuations": 10, + "tiny_orphans": 0, + "past_window": 0, + "past_window_stored": 0 + }, + "resources": { + "0drp": { + "resources": 9603, + "streams": { + "1": 7122, + "2": 2481 + }, + "stored": 765075110, + "inflated": 2802161120, + "incomplete": 0 + }, + "grid": { + "resources": 27482, + "streams": { + "1": 27476, + "2": 6 + }, + "stored": 375890383, + "inflated": 2325782256, + "incomplete": 0 + }, + "navmesh": { + "resources": 27644, + "streams": { + "1": 4598, + "2": 23046 + }, + "stored": 5397713337, + "inflated": 15420757856, + "incomplete": 0 + }, + "psin": { + "resources": 22, + "streams": { + "1": 1, + "2": 21 + }, + "stored": 1559767, + "inflated": 2367712, + "incomplete": 1 + } + }, + "checks": { + "0drp": { + "block_map": { + "pass": 9603, + "fail": 0 + }, + "blocks_disjoint": { + "pass": 9603, + "fail": 0 + }, + "blocks_in_bounds": { + "pass": 9603, + "fail": 0 + }, + "cover_nodes_whole": { + "pass": 9585, + "fail": 0 + }, + "enum_values_dense": { + "pass": 9603, + "fail": 0 + }, + "enums_in_bounds": { + "pass": 9603, + "fail": 0 + }, + "pages_4k_rule": { + "pass": 9603, + "fail": 0 + }, + "payload_at_0x60": { + "pass": 9603, + "fail": 0 + }, + "prefix_zero": { + "pass": 9603, + "fail": 0 + }, + "q40_in_bounds": { + "pass": 9603, + "fail": 0 + }, + "region_array_count": { + "pass": 8412, + "fail": 0 + }, + "reserved_zero": { + "pass": 9603, + "fail": 0 + }, + "root_index_valid": { + "pass": 9603, + "fail": 0 + }, + "root_is_struct": { + "pass": 9603, + "fail": 0 + }, + "structs_in_bounds": { + "pass": 9603, + "fail": 0 + }, + "version_122": { + "pass": 9603, + "fail": 0 + } + }, + "grid": { + "block_map": { + "pass": 27482, + "fail": 0 + }, + "control_bytes": { + "pass": 27482, + "fail": 0 + }, + "cubic_extent": { + "pass": 27482, + "fail": 0 + }, + "inner_payload_ff00": { + "pass": 27482, + "fail": 0 + }, + "keys_octree": { + "pass": 27482, + "fail": 0 + }, + "occupied_equals_entries": { + "pass": 27482, + "fail": 0 + }, + "payload_in_bounds": { + "pass": 27482, + "fail": 0 + }, + "prefix_zero": { + "pass": 27482, + "fail": 0 + }, + "reserved_zero": { + "pass": 27482, + "fail": 0 + }, + "sector_origin": { + "pass": 27482, + "fail": 0 + }, + "table_in_bounds": { + "pass": 27482, + "fail": 0 + }, + "values_bijective": { + "pass": 27482, + "fail": 0 + } + }, + "navmesh": { + "block_map": { + "pass": 27644, + "fail": 0 + }, + "data_size_identity": { + "pass": 27644, + "fail": 0 + }, + "extents_match_root": { + "pass": 27644, + "fail": 0 + }, + "flag0_set": { + "pass": 27644, + "fail": 0 + }, + "flag1_links": { + "pass": 27644, + "fail": 0 + }, + "flag2_no_sector": { + "pass": 27644, + "fail": 0 + }, + "identity_matrix": { + "pass": 27644, + "fail": 0 + }, + "indices_below_vertices": { + "pass": 27644, + "fail": 0 + }, + "links_in_bounds": { + "pass": 27644, + "fail": 0 + }, + "polygons_chain": { + "pass": 27644, + "fail": 0 + }, + "prefix_zero": { + "pass": 27644, + "fail": 0 + }, + "quadtree_root": { + "pass": 27644, + "fail": 0 + }, + "quadtree_valid": { + "pass": 27644, + "fail": 0 + }, + "reserved_zero": { + "pass": 27644, + "fail": 0 + }, + "sector_origin": { + "pass": 27482, + "fail": 0 + }, + "split_70": { + "pass": 27644, + "fail": 0 + }, + "split_80": { + "pass": 27644, + "fail": 0 + }, + "split_88": { + "pass": 27644, + "fail": 0 + }, + "split_98": { + "pass": 27644, + "fail": 0 + }, + "tile_128m": { + "pass": 27482, + "fail": 0 + }, + "volumes_in_bounds": { + "pass": 27644, + "fail": 0 + } + }, + "psin": {} + }, + "0drp": { + "schemas": { + "CCoverPointRegion/12 structs": 7635, + "0x4712787b/7 structs": 932, + "CCoverPointRegion/11 structs": 777, + "0x4712787b/9 structs": 219, + "0x4712787b/8 structs": 22, + "0x4712787b/3 structs": 14, + "CCoverPointRegionManifest/4 structs": 1, + "0xb6dbe11b/2 structs": 1, + "0x339accda/2 structs": 1, + "0x2bf76252/2 structs": 1 + }, + "root": { + "CCoverPointRegion": 8412, + "0x4712787b": 1187, + "0x2bf76252": 1, + "0x339accda": 1, + "0xb6dbe11b": 1, + "CCoverPointRegionManifest": 1 + }, + "block_at_0x60": { + "CCoverPointNode": 9378, + "0xde5f1345": 207, + "0x00000100": 16, + "0x0904902e": 1, + "CCoverPointRegionDef": 1 + }, + "block_hash": { + "CCoverPointNode": 9585, + "0x00000100": 8825, + "0x00000013": 8412, + "0xde5f1345": 8412, + "CCoverPointRegion": 8412, + "CCoverSpatialTreeNode": 8412, + "0x4712787b": 1187, + "0x57ad0b12": 1187, + "0xdd53676a": 241, + "0xf2dd6348": 219, + "0x0904902e": 1, + "0x2bf76252": 1, + "0x339accda": 1, + "0xb6dbe11b": 1, + "CCoverPointRegionDef": 1, + "CCoverPointRegionManifest": 1 + }, + "enums": { + "eCoverFlags": 9585, + "eCoverHeight": 9585, + "eCoverUsage": 9585, + "0x32ff8fb9": 1187, + "eCoverRegionFlags": 1 + }, + "q40_shape": { + "[('0x101', 32)]": 6462, + "[]": 1324, + "[('0x101', 48)]": 1182, + "[('0x101', 64)]": 600, + "[('0x101', 80)]": 31, + "[('0x101', 141824)]": 1, + "[('0x101', 2800)]": 1, + "[('0x101', 95792), ('0x211', 8624)]": 1, + "[('0x207', 26560)]": 1 + }, + "root_index": { + "3": 7650, + "4": 932, + "2": 779, + "6": 219, + "5": 22, + "1": 1 + }, + "u16_0x48": { + "n_structs": { + "12": 7635, + "7": 932, + "11": 777, + "9": 219, + "8": 22, + "3": 14, + "2": 3, + "4": 1 + }, + "n_enums": { + "3": 8412, + "4": 1173, + "1": 15, + "0": 3 + }, + "n_blocks": { + "6": 7854, + "4": 932, + "5": 799, + "3": 15, + "2": 3 + } + }, + "pages_4k_zero": 2578, + "pages_4k_boundary": { + "nonzero": 93, + "zero": 214 + }, + "cover_nodes": 15629979, + "region_cover_nodes": 15474729, + "dynamic_cover_nodes": 155250, + "region_points": 15474744, + "region_inumpoints": { + "match": 8411, + "mismatch": 1 + }, + "first_node": { + "id0_index_zero": 9378, + "id1_index_ffffffff": 3966, + "pages": 9378 + }, + "region_bounds": { + "min": [ + -10368.0, + -8448.0, + -500.0 + ], + "max": [ + 10411.852, + 9472.0, + 1350.0 + ] + } + }, + "navmesh": { + "flags": { + "9": 18791, + "11": 5507, + "3": 3149, + "7": 161, + "1": 35, + "69": 1 + }, + "build_ids": 7, + "totals": { + "vertices": 138041746, + "polygons": 124768148, + "pool": 493024188, + "special_links": 26679246, + "link_indices": 26903247, + "volumes": 6246890 + }, + "max": { + "vertices": 52608, + "polygons": 71803, + "pool": 235411, + "special_links": 30324, + "link_indices": 30324, + "volumes": 7868 + }, + "static_sectors": 24480, + "sector_x": [ + 160, + 295 + ], + "sector_y": [ + 179, + 358 + ], + "split_blocks_max": { + "0x70": 20, + "0x80": 29, + "0x88": 173, + "0x98": 194 + }, + "tile_bounds": { + "min": [ + -12288.0, + -9856.0, + -78.55 + ], + "max": [ + 5120.0, + 13184.0, + 403.838 + ] + }, + "water_bit3": { + "b3_1_w_1": 24009, + "b3_0_w_0": 3346, + "b3_1_w_0": 289 + }, + "quadtree": { + "nodes": 2337904, + "leaves": 1760339, + "max_depth": 9 + } + }, + "grid": { + "groups": { + "8": 12778, + "256": 7131, + "512": 6263, + "32": 377, + "64": 356, + "1024": 338, + "16": 184, + "128": 54, + "2048": 1 + }, + "extent": { + "128": 16487, + "256": 7466, + "1024": 2662, + "512": 866, + "4096": 1 + }, + "origin_z": { + "0.0": 16826, + "-128.0": 7048, + "-512.0": 2670, + "-256.0": 844, + "128.0": 81, + "256.0": 12, + "-2048.0": 1 + }, + "sectors": 24480, + "sectors_not_in_navmesh": 0, + "navmesh_sectors_not_in_grid": 0, + "entries_total": 53835068, + "entries_max": 14903, + "key_depth": { + "6": 20640002, + "5": 17413561, + "7": 5569707, + "4": 4278022, + "8": 3601634, + "3": 1767427, + "2": 431181, + "1": 101453, + "0": 27482, + "10": 3649, + "9": 950 + }, + "inner_nodes": 8617353, + "leaf_payload": { + "low_byte_01": 26659574, + "low_byte_03": 16767045, + "ff00": 1791096 + } + }, + "psin": { + "version": { + "256": 21, + "79": 1 + }, + "complete": 21 + }, + "elapsed_s": 157.9 +} \ No newline at end of file diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 896c125a8..4d34b7f0d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4,12 +4,26 @@ project(gta6rt LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) +# The sources are UTF-8. Without /utf-8, MSVC reads them in the system's ANSI code page, so on code page 936 (or +# any other non-1252 locale) it prints C4819 for every non-ASCII comment. Many targets set /utf-8 themselves; this +# covers every target, including those that don't. clang-cl accepts it too. Only C and C++: ml64 (abi_probe.asm) has +# no /utf-8 and warns A4018 for it. +if(MSVC) + add_compile_options($<$:/utf-8>) +endif() + if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) message(FATAL_ERROR "gta6rt must be built for x64 (run from an x64 Native Tools prompt or vcvars64.bat)") endif() option(LEONIDA_BUILD_WINDOWS_RUNTIME "Build the Windows runtime, its shims and their tests" ${WIN32}) if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) + # Custom CMAKE_CXX_FLAGS can replace MSVC's default /EHsc. Require C++ stack unwinding so error + # paths in the runtime and its libraries still destroy automatic objects when an exception leaves a frame. + if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + add_compile_options($<$:/EHsc>) + endif() + # The d3d12_xs shim and its tests use version 1.2 root signatures (D3D12_ROOT_SIGNATURE_DESC2), which the Windows # SDK declares from 10.0.26100 on. Stop here with the fix instead of failing halfway through the build. include(CheckCXXSourceCompiles) @@ -97,6 +111,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp shims/xgameruntime.cpp + shims/xgameruntime_user.cpp shims/library_loader.cpp shims/process.cpp ) @@ -226,9 +241,10 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) add_executable(xgameruntime_test test/xgameruntime_test.cpp shims/xgameruntime.cpp - shims/file_system.cpp + shims/xgameruntime_user.cpp shims/library_loader.cpp shims/registry.cpp + shims/file_system.cpp ) target_include_directories(xgameruntime_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) target_compile_definitions(xgameruntime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -236,6 +252,21 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_link_options(xgameruntime_test PRIVATE /OPT:NOREF) target_link_libraries(xgameruntime_test PRIVATE gta6rt_xtaskqueue) + # XUserImpl (offline local user) through QueryApiImpl, slot by slot as xgameruntime.lib's thunks call it. + add_executable(xgameruntime_user_test + test/xgameruntime_user_test.cpp + shims/xgameruntime.cpp + shims/xgameruntime_user.cpp + shims/library_loader.cpp + shims/registry.cpp + shims/file_system.cpp + ) + target_include_directories(xgameruntime_user_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(xgameruntime_user_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xgameruntime_user_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(xgameruntime_user_test PRIVATE /OPT:NOREF) + target_link_libraries(xgameruntime_user_test PRIVATE gta6rt_xtaskqueue) + # GameInput shim on SDL3 (zlib licence): any controller SDL supports, DualSense trigger effects and lightbar. # Nothing is downloaded unless asked. The shim is built when SDL3 is available: # - an installed SDL3 3.2+ that find_package finds (SDL3_DIR / CMAKE_PREFIX_PATH), or @@ -308,6 +339,11 @@ if(BUILD_TESTING) add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) + # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. + add_executable(large_module_gate_test test/large_module_gate_test.cpp) + find_package(Threads REQUIRED) + target_link_libraries(large_module_gate_test PRIVATE Threads::Threads) + add_test(NAME large_module_gate COMMAND large_module_gate_test) # XDXR build descriptions (docs/xdxr.md); compared with d3d12.h where the Windows SDK provides it. add_executable(xdxr_descs_test test/xdxr_descs_test.cpp) add_test(NAME xdxr_descs COMMAND xdxr_descs_test) @@ -316,6 +352,11 @@ if(BUILD_TESTING) target_include_directories(vulkan_device_filter_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test) if(TARGET gta6rt) + if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + add_executable(cpp_unwind_test test/cpp_unwind_test.cpp) + add_test(NAME cpp_unwind COMMAND cpp_unwind_test) + endif() + # Compile-time ABI checks (D3D12/XMem structure sizes, alignments and member offsets against the Windows SDK). # The file existed but no target built it, so none of its static_asserts ever ran. add_executable(runtime_types_test test/test_runtime_types.cpp) @@ -445,6 +486,12 @@ if(BUILD_TESTING) RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" ) endforeach() + add_executable(tiny_atexit test/fixtures/tiny_atexit.cpp) + target_compile_definitions(tiny_atexit PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_atexit PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_atexit PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) add_executable(tiny_game test/fixtures/tiny_game.cpp) target_link_libraries(tiny_game PRIVATE xgameruntime_stub) target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use @@ -563,6 +610,34 @@ if(BUILD_TESTING) COMMAND dll_thread_calls_test "$" ) + # The host GameInput path (docs/gameinput.md): mapped code that imports GameInputCreate from GameInput.dll, with no + # GameInput shim linked. Needs the SDK's gameinput.lib and GameInput.h to build the fixture, and a GameInput.dll on + # the machine to run (the test skips with 77 only when Windows cannot load GameInput.dll). No game files. + find_library(GAMEINPUT_LIBRARY NAMES gameinput HINTS ${_sdk_lib_hints}) + if(GAMEINPUT_LIBRARY) + add_library(gameinput_host SHARED test/fixtures/gameinput_host.cpp) + target_compile_options(gameinput_host PRIVATE /W4 /permissive- /utf-8 /GS-) + target_link_options(gameinput_host PRIVATE /NODEFAULTLIB /ENTRY:gameinput_host_main) + target_link_libraries(gameinput_host PRIVATE kernel32 ${GAMEINPUT_LIBRARY}) + set_target_properties(gameinput_host PROPERTIES + OUTPUT_NAME gameinput_host + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + add_executable(gameinput_host_test + test/gameinput_host_test.cpp + src/pe_loader.cpp + shims/registry.cpp + ) + target_include_directories(gameinput_host_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(gameinput_host_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(gameinput_host_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + add_dependencies(gameinput_host_test gameinput_host) + add_test(NAME gameinput_host COMMAND gameinput_host_test "$") + set_tests_properties(gameinput_host PROPERTIES SKIP_RETURN_CODE 77) # Windows cannot load GameInput.dll + endif() + # LEONIDA_UNIMPLEMENTED=log|fail|stop: builds its own image with two imports that bind to nothing, calls them in # process (log, fail) and in child processes (default/env parsing, stop). No game files, no GPU. add_executable(unimplemented_policy_test @@ -737,7 +812,20 @@ if(BUILD_TESTING) endif() if(WIN32 AND TARGET xgameruntime_test) add_test(NAME xgameruntime COMMAND xgameruntime_test) + add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test) + add_test(NAME xgameruntime_user_gamertag COMMAND xgameruntime_user_test --expect-gamertag Tester42) + set_tests_properties(xgameruntime_user_gamertag PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=Tester42") + # Longer than getenv_s's old 64-byte buffer: still the "Player" fallback (and its message), not a silent one. + add_test(NAME xgameruntime_user_gamertag_long COMMAND xgameruntime_user_test --expect-gamertag Player) + set_tests_properties(xgameruntime_user_gamertag_long PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG") endif() + # The active-input tracker the GameInput shim feeds (src/active_input.h), on synthetic samples: no SDL, no + # controller, no GPU, so it builds and runs everywhere, with or without SDL3. + add_executable(active_input_test test/active_input_test.cpp) + if(MSVC) + target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME active_input COMMAND active_input_test) if(WIN32 AND TARGET gameinput_test) add_test(NAME gameinput COMMAND gameinput_test) elseif(TARGET gta6rt) @@ -758,6 +846,10 @@ if(BUILD_TESTING) add_test(NAME run_tiny_bundled_load COMMAND ${CMAKE_COMMAND} "-DLOADER=$" "-DGUEST=$" "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_bundled.cmake") + # atexit handlers, static destructors and the ways out, compared with the same program run natively. + add_test(NAME run_tiny_atexit COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_atexit.cmake") add_test(NAME run_tiny_game COMMAND gta6rt --run $ -- hello 42) add_test(NAME run_tiny_game_console_paths COMMAND ${CMAKE_COMMAND} "-DLOADER=$" "-DGUEST=$" @@ -848,7 +940,7 @@ endif() if(TARGET Vulkan::Headers) foreach(tool vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test - vk_xdxr_build_test vk_queue_test) + vk_xdxr_build_test vk_queue_test vk_sandbox) add_executable(${tool} test/${tool}.cpp) target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) if(WIN32) @@ -1138,6 +1230,22 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_buffer_tiles COMMAND d3d12_buffer_tiles_test) set_tests_properties(d3d12_buffer_tiles PROPERTIES SKIP_RETURN_CODE 77 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # D3D12 permits UpdateTileMappings on DIRECT/COPY/COMPUTE and a sparse buffer must remain + # accessible across their selected Vulkan families. The optional API-dump check catches an + # EXCLUSIVE VkBuffer even on drivers that happen to return correct bytes without ownership barriers. + add_executable(d3d12_sparse_queue_family_test test/d3d12_sparse_queue_family_test.cpp) + target_link_libraries(d3d12_sparse_queue_family_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_sparse_queue_family_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_sparse_queue_family_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_sparse_queue_family COMMAND d3d12_sparse_queue_family_test) + set_tests_properties(d3d12_sparse_queue_family PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + if(Python3_FOUND AND NOT CMAKE_CROSSCOMPILING) + add_test(NAME d3d12_sparse_queue_family_contract COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_sparse_queue_family.py" + "$") + set_tests_properties(d3d12_sparse_queue_family_contract PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 65) + endif() set_tests_properties(d3d12_vulkan_device PROPERTIES SKIP_RETURN_CODE 77) add_executable(d3d12_texture1d_test test/d3d12_texture1d_test.cpp) @@ -1147,6 +1255,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_texture1d COMMAND d3d12_texture1d_test) set_tests_properties(d3d12_texture1d PROPERTIES SKIP_RETURN_CODE 77) + # Placed 1D and 3D textures against the host runtime and WARP, and a copy round trip through them. + add_executable(d3d12_placed_dimensions_test test/d3d12_placed_dimensions_test.cpp) + target_link_libraries(d3d12_placed_dimensions_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_placed_dimensions_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_placed_dimensions_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_placed_dimensions COMMAND d3d12_placed_dimensions_test) + set_tests_properties(d3d12_placed_dimensions PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12. add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp) target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com) @@ -1230,6 +1347,14 @@ if(TARGET Vulkan::Headers) target_compile_options(allocator_proxy_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME allocator_proxy COMMAND allocator_proxy_test) set_tests_properties(allocator_proxy PROPERTIES SKIP_RETURN_CODE 77) + # IDXGIDevice1 on the device proxy (the GDKX boot step: QueryInterface, GetAdapter, EnumOutputs), on the host + # runtime and on the Vulkan device: COM identity with the device, the adapter's LUID. 77: no device at all. + add_executable(dxgi_device_test test/dxgi_device_test.cpp) + target_link_libraries(dxgi_device_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(dxgi_device_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dxgi_device_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME dxgi_device COMMAND dxgi_device_test) + set_tests_properties(dxgi_device PROPERTIES SKIP_RETURN_CODE 77) # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero. add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp) target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -1301,6 +1426,24 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_predicated_copy_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_predicated_copy COMMAND d3d12_predicated_copy_test) set_tests_properties(d3d12_predicated_copy PROPERTIES SKIP_RETURN_CODE 77) + # A DISPATCH-only ExecuteIndirect signature with a GPU count buffer: native Windows WARP versus Vulkan GPU, + # including a GPU-written count that changes between two calls in the same command list. + if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) + set(_indirect_count_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_indirect_dispatch_count.spv) + add_custom_command(OUTPUT ${_indirect_count_spv} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 + -o ${_indirect_count_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp + COMMENT "Compiling the counted indirect dispatch test shader" VERBATIM) + add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp + ${_indirect_count_spv}) + target_link_libraries(d3d12_indirect_dispatch_count_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_indirect_dispatch_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_INDIRECT_COUNT_SPV="${_indirect_count_spv}") + target_compile_options(d3d12_indirect_dispatch_count_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_indirect_dispatch_count COMMAND d3d12_indirect_dispatch_count_test) + set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) + endif() # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP). add_executable(d3d12_clear_test test/d3d12_clear_test.cpp) @@ -1379,6 +1522,22 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_subresource_copy COMMAND d3d12_subresource_copy_test) set_tests_properties(d3d12_subresource_copy PROPERTIES SKIP_RETURN_CODE 77) + # MakeResident, Evict, SetResidencyPriority and EnqueueMakeResident, compared with the host runtime. + add_executable(d3d12_residency_test test/d3d12_residency_test.cpp) + target_link_libraries(d3d12_residency_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_residency_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_residency_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_residency COMMAND d3d12_residency_test) + set_tests_properties(d3d12_residency PROPERTIES SKIP_RETURN_CODE 77) + + # ID3D12Resource::GetHeapProperties for committed, placed and reserved resources, compared with the host runtime. + add_executable(d3d12_heap_properties_test test/d3d12_heap_properties_test.cpp) + target_link_libraries(d3d12_heap_properties_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_heap_properties_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_heap_properties_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_heap_properties COMMAND d3d12_heap_properties_test) + set_tests_properties(d3d12_heap_properties PROPERTIES SKIP_RETURN_CODE 77) + # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. add_executable(d3d12_present_test test/d3d12_present_test.cpp) target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) @@ -1460,18 +1619,20 @@ if(TARGET Vulkan::Headers) # D3D12 API only. set(LEONIDA_M2_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2_shaders) set(LEONIDA_M2_FILES ${LEONIDA_M2_DIR}/spirv/index.json ${LEONIDA_M2_DIR}/fssm/vs_m2.fssm - ${LEONIDA_M2_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2_DIR}/fssm/ps_m2_uoff.fssm) + ${LEONIDA_M2_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2_DIR}/fssm/ps_m2_uoff.fssm + ${LEONIDA_M2_DIR}/fssm/ps_m2_literal.fssm) add_custom_command( OUTPUT ${LEONIDA_M2_FILES} COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2_DIR} COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff + ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff ps_m2_literal DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_uoff.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_literal.asm ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating vs_m2 and ps_m2 for the textured draw test" VERBATIM) @@ -1653,6 +1814,14 @@ if(TARGET Vulkan::Headers) add_test(NAME dxgi_swapchain COMMAND dxgi_swapchain_test) set_tests_properties(dxgi_swapchain PROPERTIES SKIP_RETURN_CODE 77) + # Synthetic (no GPU): VulkanSwapchain's DXGI BufferCount contract when Vulkan returns more images than the + # app asked for, or the surface minimum exceeds the request (D3D-389). + add_executable(dxgi_swapchain_count_test test/dxgi_swapchain_count_test.cpp) + target_link_libraries(dxgi_swapchain_count_test PRIVATE Vulkan::Headers) + target_compile_definitions(dxgi_swapchain_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dxgi_swapchain_count_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME dxgi_swapchain_count COMMAND dxgi_swapchain_count_test) + # ExecuteIndirect with CountBuffer (vkCmdDrawIndirectCount) + optional BLAS/TLAS/RayQueryKHR GPU test. add_executable(d3d12_indirect_rt_test test/d3d12_indirect_rt_test.cpp) target_link_libraries(d3d12_indirect_rt_test PRIVATE gta6rt_d3d12_com) @@ -1789,6 +1958,36 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_geometry_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_geometry COMMAND d3d12_geometry_test) set_tests_properties(d3d12_geometry PROPERTIES SKIP_RETURN_CODE 77) + # D3D-309: D24 depth bias and 24-bit depth in draws, with and without a pixel shader and with a geometry shader + # (src/depth24_fragment.h). + set(LEONIDA_TEST_VS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_depth.spv) + set(LEONIDA_TEST_PS_DEPTH_EMPTY ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_empty.spv) + set(LEONIDA_TEST_PS_DEPTH_WRITE ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_write.spv) + set(LEONIDA_TEST_GS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_depth.spv) + foreach(pair "vs_depth.vert;${LEONIDA_TEST_VS_DEPTH}" "ps_depth_empty.frag;${LEONIDA_TEST_PS_DEPTH_EMPTY}" + "ps_depth_write.frag;${LEONIDA_TEST_PS_DEPTH_WRITE}" "gs_depth.geom;${LEONIDA_TEST_GS_DEPTH}") + list(GET pair 0 source) + list(GET pair 1 output) + add_custom_command( + OUTPUT ${output} + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} + ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} + COMMENT "Compiling the D24 draw test shader ${source}" + VERBATIM) + endforeach() + add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_TEST_VS_DEPTH} ${LEONIDA_TEST_PS_DEPTH_EMPTY} ${LEONIDA_TEST_PS_DEPTH_WRITE} + ${LEONIDA_TEST_GS_DEPTH}) + target_link_libraries(d3d12_depth24_draw_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_depth24_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_VS_DEPTH_SPV="${LEONIDA_TEST_VS_DEPTH}" + LEONIDA_TEST_PS_DEPTH_EMPTY_SPV="${LEONIDA_TEST_PS_DEPTH_EMPTY}" + LEONIDA_TEST_PS_DEPTH_WRITE_SPV="${LEONIDA_TEST_PS_DEPTH_WRITE}" + LEONIDA_TEST_GS_DEPTH_SPV="${LEONIDA_TEST_GS_DEPTH}") + target_compile_options(d3d12_depth24_draw_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_depth24_draw COMMAND d3d12_depth24_draw_test) + set_tests_properties(d3d12_depth24_draw PROPERTIES SKIP_RETURN_CODE 77) # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the # device's bindless set, which nothing but the layer binds. set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv) @@ -1894,6 +2093,33 @@ if(TARGET Vulkan::Headers) if(TARGET gta6rt) target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com user32) # user32: the PresentX window target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE) + + # A stand-in title that imports d3d12_xs.dll!D3D12XboxCreateDevice and runs a clear and a readback on the + # device it gets, mapped and run by `gta6rt --run` with LEONIDA_D3D12=vulkan: the loader, the game thread, the + # proxies and the Vulkan device in one process. check_tiny_frame.py reads the verdict, the binding and the + # call order from outside; d3d12_com_test is its probe for "no usable Vulkan device" (exit code 77). + add_library(d3d12_xs_stub SHARED test/fixtures/d3d12_xs_stub.cpp test/fixtures/d3d12_xs_stub.def) + target_compile_definitions(d3d12_xs_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_xs_stub PRIVATE /W4 /permissive- /utf-8) + set_target_properties(d3d12_xs_stub PROPERTIES + OUTPUT_NAME d3d12_xs + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" + ) + add_executable(tiny_frame test/fixtures/tiny_frame.cpp) + target_link_libraries(tiny_frame PRIVATE d3d12_xs_stub) + target_compile_definitions(tiny_frame PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_frame PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_frame PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + if(Python3_FOUND) + add_test(NAME run_tiny_frame COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$" + "$" "--probe=$" ${_trace_runner}) + set_tests_properties(run_tiny_frame PROPERTIES SKIP_RETURN_CODE 77) + endif() endif() # bvh_builder_test can put the package's XboxBvhBuilder on this device too (LEONIDA_BVH_DEVICE=vulkan). if(TARGET bvh_builder_test) diff --git a/runtime/README.md b/runtime/README.md index 23eb2fb97..aace038d9 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -161,8 +161,9 @@ Current limits, by design: the measured-slot Xbox-ABI proxy: the host PC `ID3D12Device` by default, or the Vulkan-backed device (`shims/d3d12_vulkan_device.cpp`) when `LEONIDA_D3D12=vulkan` is set and the runtime was built with the Vulkan SDK and Python 3. The Vulkan device covers command submission, descriptor heaps, render-target and - depth views, committed resources and copies (uploads, readbacks, BC textures); see `docs/d3d12_vulkan.md` - section 3.2 for what is missing. + depth views, committed resources and copies (uploads, readbacks, BC textures), root signatures, graphics and + compute pipeline states, draws, dispatches and `ExecuteIndirect`; see `docs/d3d12_vulkan.md` for what is + missing. - `gameinput.dll` / `xgameruntime.dll` — `GameInputCreate`: the v0 GameInput API for gamepads on SDL3 (`shims/gameinput.cpp`), so any controller SDL supports works, with rumble, Xbox trigger rumble, force feedback @@ -172,6 +173,22 @@ Current limits, by design: `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is unverified. +### What `xgameruntime.dll` reports: environment overrides + +The `xgameruntime` shim (`shims/xgameruntime.cpp`) answers the title's questions about the console and its package +with fixed values. Five environment variables change an answer, for trying another of the title's code paths. Each +is read on every call, and a value that is empty or too long for its buffer is ignored. +`tests/test_docs_env_vars.py` fails when the runtime or `make_game.py` reads a `LEONIDA_*` variable that no +document names. + +| variable | default | what it changes | +|---|---|---| +| `LEONIDA_DEVICE_TYPE` | `7` | The `XSystemDeviceType` that `XSystemGetDeviceType` returns: `0` Unknown, `1` Pc, `2` XboxOne, `3` XboxOneS, `4` XboxOneX, `5` XboxOneXDevkit, `6` XboxScarlettLockhart (Series S), `7` XboxScarlettAnaconda (Series X), `8` XboxScarlettDevkit. A number outside 0..8 is ignored; text that is not a number counts as `0`. `6` also makes `XSystemGetAnalyticsInfo` report the form `Xbox Series S` instead of `Xbox Series X`. | +| `LEONIDA_ANALYTICS_FORM` | unset | The `form` string of `XSystemGetAnalyticsInfo`, in place of the one the device type gives (up to 63 characters). | +| `LEONIDA_PACKAGE_ID` | `LeonidaPackageIdentifier00000000` | The identifier `XPackageGetCurrentProcessPackageIdentifier` returns (up to 32 characters). It is also the one identifier `XPackageMount` refuses with `E_ACCESSDENIED`, as the game's own package. | +| `LEONIDA_CONTENT_PACKAGES` | unset | The content packages `XPackageMount` can mount: `id1=path1;id2=path2` (up to 1,023 characters). The mount path of a listed identifier is its path, as written; any other identifier is `ERROR_NOT_FOUND`, and a path longer than 259 characters is `ERROR_INSUFFICIENT_BUFFER`. | +| `LEONIDA_PACKAGED` | `1` | `0`, or text that is not a number, makes `XPackageIsPackagedProcess` return false. Any other number keeps it true. | + The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own imports are unknown until it is available. @@ -254,10 +271,36 @@ It prints counts only; on the 1.0.2.1 corpus all 26,503 containers resolve. `gta6rt --run [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game. +The game's `atexit` handlers and static destructors go to a table of the run's own (the CRT's process-wide one is +shared with gta6rt): `exit` and a return from `main` run them newest first before the run ends, `_cexit` runs them and +returns, and `_exit`, `quick_exit`, `ExitProcess` and `abort` skip them, as natively. `run_tiny_atexit` runs a stand-in +program natively and through `--run` for each of those paths (and for `_exit` from a second thread during `exit`) and +holds both to the Windows sequence (under Wine, whose CRT differs, a native difference is only reported). Not covered +yet: `at_quick_exit` handlers (`quick_exit` runs none) and the thread-local destructor callback +(`_register_thread_local_exe_atexit_callback`); both still reach the host CRT. +`run_tiny_frame` does it with a stand-in that imports `d3d12_xs.dll!D3D12XboxCreateDevice` and, with +`LEONIDA_D3D12=vulkan`, clears a render target and reads it back on the Vulkan device: the loader, the game thread, +the Xbox-ABI proxies and the device in one process (`test/fixtures/tiny_frame.cpp`; `test/check_tiny_frame.py` checks +the verdict, the `shim` binding and the call order in the `--trace-d3d12` output, and skips without a Vulkan GPU). The game does not boot yet. The missing executable blocks the import-driven work: the real device entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`; see `xgameruntime_test`). The D3D12-to-Vulkan design and the measured console ABI are in +The game does not boot yet, and none of this has been measured against the real executable. The missing executable +blocks the import-driven work: + +- The device entry point: `D3D12XboxCreateDevice` exists and wraps the PC or the Vulkan-backed device in the + measured-slot proxy, but its parameter and flag layout is unmeasured and so is the Xbox device vtable beyond + slots 62, 67 and 76. +- The command-queue and fence extensions: the proxies forward the public slots, and the console's own methods past + them (`PresentX`, `SuspendX`, `ResumeX`) have unknown slots, so they are refused with a log. + `PresentX` and the frame events themselves are implemented (`shims/xbox_present.*`, `xbox_present_test`) but + nothing reaches them yet: their queue and device slots are unmeasured. +- Most of the `xgameruntime` surface: an offline shim covers `XGameRuntimeInitialize`, device/console queries, + `XTaskQueue` and `XAsync`, and `QueryApiImpl` serves `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl` and + `XSystemImpl` (see `xgameruntime_test`); any other class is refused with a log. + +The D3D12-to-Vulkan design and the measured console ABI are in [docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md); the shader translator and its GPU checks are described in [docs/design.md](../docs/design.md), and the differential-validation design is in the shader-validation work. @@ -294,6 +337,7 @@ from the ANSI code page. | `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` | | `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | | `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) | +| `xmem_attributes` | the first `XMemAlloc` and the first `XMemFree` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (`XMemAlloc` only), `caller` (module+RVA) | | `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` | | `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) | | `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` | @@ -379,6 +423,17 @@ $env:LEONIDA_VK_VALIDATION = '1' .\runtime\build\RelWithDebInfo\d3d12_resource_desc_test.exe ``` +`d3d12_placed_dimensions_test` places 1D and 3D textures (arrays, mips, BC1, UAV and render targets, plus a 2D +control) in heaps big enough for both sides' `GetResourceAllocationInfo`, at offset 0 and at 64 KiB, on the +Vulkan-backed device and on Windows D3D12 (the default adapter and WARP), and compares the answers and `GetDesc`. A +dimension outside the enum must be refused alike. It also copies a pattern through a buffer into every subresource of a placed +3D texture and a placed 1D array and back, and checks the bytes. It needs a Vulkan GPU. + +```powershell +$env:LEONIDA_VK_VALIDATION = '1' +.\runtime\build\RelWithDebInfo\d3d12_placed_dimensions_test.exe +``` + ### Depth and stencil resolves `d3d12_depth_resolve_test` resolves one plane of a 4x D32 or D24S8 target into a 1x one with diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index d9b1a009c..6858f073c 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -368,6 +368,7 @@ public: if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false); render_targets_.fill({}); render_target_count_ = count; + draw_views_stale_ = true; for (UINT i = 0; i < count && targets; ++i) { const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr; if (handle) render_targets_[i] = *reinterpret_cast(handle); @@ -989,6 +990,10 @@ private: leonida::Rect scissor_{}; std::array render_targets_{}; UINT render_target_count_ = 0; + // One block shared by every draw that keeps the same targets and buffers, rebuilt when either changes, so a + // run of draws does not allocate per draw. + std::shared_ptr draw_views_; + bool draw_views_stale_ = true; leonida::TargetView depth_{}; std::array blend_factor_{1, 1, 1, 1}; @@ -1053,12 +1058,14 @@ private: scissor_ = {}; render_targets_.fill({}); render_target_count_ = 0; + draw_views_stale_ = true; depth_ = {}; blend_factor_ = {1, 1, 1, 1}; set_pipeline(state); } void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { + if (count) draw_views_stale_ = true; for (UINT i = 0; i < count; ++i) vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, views[i].StrideInBytes} @@ -1075,16 +1082,28 @@ private: check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); } + // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. + const std::shared_ptr& draw_views() { + if (draw_views_stale_ || !draw_views_) { + auto views = std::make_shared(); + views->render_targets = render_targets_; + views->vertex_buffers = vertex_buffers_; + views->render_target_count = render_target_count_; + draw_views_ = std::move(views); + draw_views_stale_ = false; + } + return draw_views_; + } + // A draw needs a graphics pipeline, a graphics root signature and a topology. void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; - leonida::Draw draw{graphics_pipeline_, graphics_.data, render_targets_, depth_, - vertex_buffers_, index_, topology_, viewport_, scissor_, - blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, - base_vertex, first_instance, render_target_count_}; + leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_, + scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, + first, base_vertex, first_instance}; check(list_.draw(std::move(draw))); } }; @@ -1542,8 +1561,11 @@ HRESULT create_command_queue(leonida::VulkanContext& context, VkQueue queue, std } HRESULT create_command_allocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** out, IUnknown* device) { - if (!out) return E_POINTER; - *out = nullptr; + // The host runtime's order (d3d12_vulkan_device_test, compare_invalid_arguments "command allocator:"): a type + // past VIDEO_ENCODE is E_INVALIDARG, then a null output is E_UNEXPECTED. + if (out) *out = nullptr; + if (UINT(type) > UINT(D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE)) return E_INVALIDARG; + if (!out) return E_UNEXPECTED; auto* object = new CommandAllocator(type); object->attach_device(device); return hand_out(object, riid, out); @@ -1551,12 +1573,13 @@ HRESULT create_command_allocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void HRESULT create_command_list(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, REFIID riid, void** out, IUnknown* device, ID3D12PipelineState* initial_state) { - if (!out) return E_POINTER; - *out = nullptr; + if (out) *out = nullptr; CommandAllocator* command_allocator = CommandAllocator::from(allocator); if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG; // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51). if (command_allocator->recording()) return E_INVALIDARG; + // A null output only after the arguments, as the host runtime answers ("command list:" cases). + if (!out) return E_UNEXPECTED; if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE && type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY) stub("create_command_list(non-direct type)"); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index d8e084478..6cab20a8e 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -185,7 +185,9 @@ HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** o HRESULT create_vulkan_device_standalone(REFIID riid, void** out); // Tells a device from create_vulkan_device* that `outer` (the Xbox-ABI proxy that owns it) is what its children's -// GetDevice must return. No reference is taken: the outer object owns the device. +// GetDevice must return. No reference is taken: the outer object owns the device. `outer` may be the proxy's +// IDXGIDevice1 pointer (what create_device_proxy returns for that IID); the proxy itself becomes the outer. For a +// proxy it also makes the proxy's IDXGIDevice1::GetAdapter return this layer's adapter (d3d12_xs_device.h). void set_device_outer(ID3D12Device* device, IUnknown* outer); // The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. @@ -299,6 +301,7 @@ public: bool enable_capture(); // See VulkanPresenter::set_abort: polled while a present waits for a swapchain image. void set_abort(std::function abort); + // See VulkanPresenter::read_back: false after a present skipped while the window is minimised, too. bool read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format); VkExtent2D extent() const; std::uint64_t presented() const; diff --git a/runtime/shims/d3d12_feature_compat.h b/runtime/shims/d3d12_feature_compat.h index ad14f19cd..efba257a7 100644 --- a/runtime/shims/d3d12_feature_compat.h +++ b/runtime/shims/d3d12_feature_compat.h @@ -2,10 +2,15 @@ #include -// D3D12_FEATURE values introduced after Windows SDK 10.0.26100.0. Keep their ABI values and payload available to -// the runtime and its tests without requiring a newer d3d12.h. +#include + +// D3D12 values newer than some Windows SDK 10.0.26100 releases. The README asks for "Windows SDK 10.0.26100 or newer", +// but the SDK's d3d12.h moved within 10.0.26100 (D3D12_SDK_VERSION 612 in 10.0.26100.6584, 616 later), so anything the +// runtime uses from a newer header is declared here with its ABI value and payload, and checked against the header +// where the header has it. That keeps the runtime and its tests building on every 10.0.26100 SDK. namespace rt::d3d12::compat { +// Feature values introduced after Windows SDK 10.0.26100.0. inline constexpr D3D12_FEATURE kFeatureApplicationSpecificDriverState = static_cast(56); inline constexpr D3D12_FEATURE kFeatureBytecodeBypassHashSupported = static_cast(57); @@ -15,4 +20,64 @@ struct FeatureSupportFlag { static_assert(sizeof(FeatureSupportFlag) == sizeof(BOOL)); +// D3D12_FEATURE_D3D12_OPTIONS20 and D3D12_FEATURE_PREDICATION: D3D12_SDK_VERSION 611 (DirectX-Headers v1.611.0); not +// in 610. PREDICATION's payload is one BOOL, FeatureSupportFlag above. +inline constexpr D3D12_FEATURE kFeatureOptions20 = static_cast(49); +inline constexpr D3D12_FEATURE kFeaturePredication = static_cast(50); +inline constexpr UINT kRecreateAtTierNotSupported = 0; // D3D12_RECREATE_AT_TIER_NOT_SUPPORTED + +struct FeatureDataOptions20 { + BOOL ComputeOnlyWriteWatchSupported; + UINT RecreateAtTier; // D3D12_RECREATE_AT_TIER +}; + +static_assert(sizeof(FeatureDataOptions20) == 8); + +#if defined(D3D12_SDK_VERSION) && D3D12_SDK_VERSION >= 611 +static_assert(kFeatureOptions20 == D3D12_FEATURE_D3D12_OPTIONS20); +static_assert(kFeaturePredication == D3D12_FEATURE_PREDICATION); +static_assert(kRecreateAtTierNotSupported == UINT(D3D12_RECREATE_AT_TIER_NOT_SUPPORTED)); +static_assert(sizeof(FeatureDataOptions20) == sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS20)); +static_assert(sizeof(D3D12_RECREATE_AT_TIER) == sizeof(UINT)); +static_assert(offsetof(FeatureDataOptions20, RecreateAtTier) == + offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS20, RecreateAtTier)); +static_assert(sizeof(FeatureSupportFlag) == sizeof(D3D12_FEATURE_DATA_PREDICATION)); +#endif + +// D3D12_FEATURE_D3D12_OPTIONS21 (work graphs and the ExecuteIndirect tier): D3D12_SDK_VERSION 613 (DirectX-Headers +// v1.613.0); not in 611. The enums are UINT-sized in d3d12.h, as here. +inline constexpr D3D12_FEATURE kFeatureOptions21 = static_cast(53); +inline constexpr UINT kWorkGraphsTierNotSupported = 0; // D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED +inline constexpr UINT kExecuteIndirectTier1_0 = 10; // D3D12_EXECUTE_INDIRECT_TIER_1_0 + +struct FeatureDataOptions21 { + UINT WorkGraphsTier; // D3D12_WORK_GRAPHS_TIER + UINT ExecuteIndirectTier; // D3D12_EXECUTE_INDIRECT_TIER + BOOL SampleCmpGradientAndBiasSupported; + BOOL ExtendedCommandInfoSupported; +}; + +static_assert(sizeof(FeatureDataOptions21) == 16); + +// D3D12_INDIRECT_ARGUMENT_TYPE_INCREMENTING_CONSTANT (ExecuteIndirect tier 1.1): the value after DISPATCH_MESH, from +// the same header version as OPTIONS21. +inline constexpr D3D12_INDIRECT_ARGUMENT_TYPE kIndirectArgumentIncrementingConstant = + static_cast(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH + 1); + +#if defined(D3D12_SDK_VERSION) && D3D12_SDK_VERSION >= 613 +// A header that declares these must agree with the values above. +static_assert(kFeatureOptions21 == D3D12_FEATURE_D3D12_OPTIONS21); +static_assert(kWorkGraphsTierNotSupported == UINT(D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED)); +static_assert(kExecuteIndirectTier1_0 == UINT(D3D12_EXECUTE_INDIRECT_TIER_1_0)); +static_assert(kIndirectArgumentIncrementingConstant == D3D12_INDIRECT_ARGUMENT_TYPE_INCREMENTING_CONSTANT); +static_assert(sizeof(FeatureDataOptions21) == sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS21)); +static_assert(sizeof(D3D12_WORK_GRAPHS_TIER) == sizeof(UINT) && sizeof(D3D12_EXECUTE_INDIRECT_TIER) == sizeof(UINT)); +static_assert(offsetof(FeatureDataOptions21, ExecuteIndirectTier) == + offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, ExecuteIndirectTier)); +static_assert(offsetof(FeatureDataOptions21, SampleCmpGradientAndBiasSupported) == + offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, SampleCmpGradientAndBiasSupported)); +static_assert(offsetof(FeatureDataOptions21, ExtendedCommandInfoSupported) == + offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, ExtendedCommandInfoSupported)); +#endif + } // namespace rt::d3d12::compat diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 2b6d1c806..ded17e79d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -16,6 +16,7 @@ #include "d3d12_xs_device.h" #include "dxgi_com.h" #include "../src/gfx10_descriptors.h" +#include "../src/depth24_fragment.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" @@ -79,6 +80,81 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } +// The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory. +std::filesystem::path pipeline_cache_path() { + std::wstring path(32768, L'\0'); + const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); + if (!length || length >= path.size()) return {}; + path.resize(length); + return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; +} + +// A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache +// and deny writers while the view is in use. +class PipelineCacheSeed { +public: + explicit PipelineCacheSeed(const std::filesystem::path& path) { + if (path.empty()) return; + file_ = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file_ == INVALID_HANDLE_VALUE) return; + LARGE_INTEGER length{}; + constexpr auto header_size = static_cast(sizeof(VkPipelineCacheHeaderVersionOne)); + if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size) + return; + const HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (!mapping) return; + data_ = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); + CloseHandle(mapping); + if (data_) size_ = static_cast(length.QuadPart); + } + + ~PipelineCacheSeed() { + if (data_) UnmapViewOfFile(data_); + if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_); + } + + PipelineCacheSeed(const PipelineCacheSeed&) = delete; + PipelineCacheSeed& operator=(const PipelineCacheSeed&) = delete; + + const void* data() const { return data_; } + std::size_t size() const { return size_; } + + bool compatible(const leonida::cached_pso::Identity& identity) const { + static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == 32); + VkPipelineCacheHeaderVersionOne header{}; + // The header is little-endian, like the host. The driver interprets the opaque payload. + std::memcpy(&header, data_, sizeof(header)); + return header.headerSize == sizeof(header) && header.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE && + header.vendorID == identity.vendor && header.deviceID == identity.device && + std::memcmp(header.pipelineCacheUUID, identity.cache_uuid, VK_UUID_SIZE) == 0; + } + +private: + HANDLE file_ = INVALID_HANDLE_VALUE; + const void* data_ = nullptr; + std::size_t size_ = 0; +}; + +VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_cache, VkDevice device, + const leonida::cached_pso::Identity& identity) { + const PipelineCacheSeed seed(pipeline_cache_path()); + if (!seed.data()) return VK_NULL_HANDLE; + if (!seed.compatible(identity)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.bin does not match this Vulkan device\n"); + return VK_NULL_HANDLE; + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, + nullptr, 0, seed.size(), seed.data()}; + VkPipelineCache cache = VK_NULL_HANDLE; + if (create_cache(device, &create, nullptr, &cache) != VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: Vulkan declined the pipeline cache seed\n"); + return VK_NULL_HANDLE; + } + std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.bin\n", seed.size()); + return cache; +} + // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first // shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable. @@ -407,6 +483,8 @@ struct DeviceState { // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only // with Resizable BAR (leonida::resizable_bar); LEONIDA_UPLOAD_SYSMEM=1 keeps them in system memory to compare. bool upload_in_vram = false; + // D3D-299: the first texture or default-heap buffer that lands outside device-local memory is logged, once. + mutable std::once_flag spill_logged; // What D3D12_OPTIONS1 answers with: the physical device's own subgroup facts, read on first use. struct SubgroupFacts { @@ -422,6 +500,23 @@ struct DeviceState { PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4 LUID luid{}; // VkPhysicalDeviceIDProperties::deviceLUID; zero when the driver reports none leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against + std::once_flag pipeline_cache_once; + VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; + + VkPipelineCache pipeline_cache() { + std::call_once(pipeline_cache_once, [this] { + const auto& vk = context->vk; + if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; + pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); + if (pipeline_cache_handle) return; + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) + pipeline_cache_handle = VK_NULL_HANDLE; + }); + // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. + return pipeline_cache_handle; + } + QueueClock clock; // what every queue's GetClockCalibration uses PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2 = nullptr; // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9} @@ -483,6 +578,10 @@ struct DeviceState { VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (info.conditional_rendering) result.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + // D3D12 reserved buffers are visible to DIRECT, COPY and COMPUTE queues without exposing Vulkan + // queue-family ownership. Their tile bindings and accesses may use distinct families, so match the + // CONCURRENT sharing policy used for ordinary buffers and the GPU address arena. + share(result); return result; } @@ -1111,12 +1210,15 @@ struct DeviceState { if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) { if (chosen) *chosen = memory.memoryTypes[i].propertyFlags; if (chosen_type) *chosen_type = i; - if ((preferred & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && - !(memory.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { - const std::string msg = "resource allocation spilled from DEVICE_LOCAL to host memory (heap " + - std::to_string(memory.memoryTypes[i].heapIndex) + "); size in KiB:"; - log_once(msg.c_str(), static_cast(requirements.size / 1024)); - } + if (leonida::spilled_to_host(required, preferred, memory.memoryTypes[i].propertyFlags)) + std::call_once(spill_logged, [&] { + const std::uint32_t heap = memory.memoryTypes[i].heapIndex; + std::fprintf(stderr, + "[rt] d3d12: a %llu-byte allocation did not fit in device-local memory and went " + "to memory type %u (heap %u, %llu MiB); later ones are not logged\n", + static_cast(requirements.size), i, heap, + static_cast(memory.memoryHeaps[heap].size >> 20)); + }); return out; } } @@ -1377,6 +1479,30 @@ const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_ return nullptr; } +// Why the host refuses this enhanced-barrier initial layout for `desc`, or null when valid (measured on Windows D3D12). +const char* barrier_layout_refusal(const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout) { + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) + return layout == D3D12_BARRIER_LAYOUT_UNDEFINED ? nullptr : "buffer barrier layout"; + const UINT flags = UINT(desc.Flags); + switch (layout) { + case D3D12_BARRIER_LAYOUT_RENDER_TARGET: + return (flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? nullptr : "RENDER_TARGET barrier layout"; + case D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS: + case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS: + case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS: + return (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) ? nullptr : "UNORDERED_ACCESS barrier layout"; + case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE: + case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ: + return (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? nullptr : "DEPTH_STENCIL barrier layout"; + case D3D12_BARRIER_LAYOUT_SHADER_RESOURCE: + case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE: + case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE: + return (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) ? "SHADER_RESOURCE barrier layout" : nullptr; + default: + return nullptr; + } +} + class DescriptorHeap final : public Child { @@ -1451,7 +1577,7 @@ public: // here and nothing goes back to the arena when this object dies. Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags, VkDeviceSize placed_va) - : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), va_(placed_va) {} + : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} ~Resource() override { if (accel_) { @@ -1576,8 +1702,6 @@ public: if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) return E_OUTOFMEMORY; std::memset(mapped_, 0, std::size_t(desc_.Width)); // committed resources start zeroed - } else { - log_once("default-heap buffers are not zero-filled yet; dimension", int(desc_.Dimension)); } if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; @@ -1610,6 +1734,10 @@ public: heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); binding.va = va_; device_.context->add_resource(id(), binding); + // Committed resources start zeroed unless the heap says otherwise; the host cannot reach device-local memory, + // so the next submission fills it (D3D-71). + if (!host && !(heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED)) + device_.context->zero_on_next_submit(id(), buffer_); return S_OK; } @@ -1775,6 +1903,8 @@ public: desc_.Layout = layout; } bool reserved() const { return reserved_; } + // A committed resource: neither placed in a heap nor reserved. It owns its memory, like a heap does. + bool committed() const { return !placed_ && !reserved_; } // D3D12 answers only for committed and placed resources (E_INVALIDARG for reserved ones, measured on the PC // runtime). @@ -1808,6 +1938,9 @@ public: else if (desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) deny = deny_buffers | deny_non_rt_ds; const UINT creation_only = D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED; + // A placed resource reports its heap's flags as they are (an ALLOW_ALL heap reads back 0): the DENY bits + // are the runtime's choice only for the implicit heap of a committed resource (d3d12_heap_properties_test). + if (placed_) return D3D12_HEAP_FLAGS(UINT(heap_flags_) & ~creation_only); return D3D12_HEAP_FLAGS((UINT(heap_flags_) & ~creation_only) | deny); } @@ -2075,6 +2208,7 @@ private: std::uint64_t buffer_va_ = 0; std::uint64_t gpu_va_ = 0; bool reserved_ = false; + bool placed_ = false; leonida::ResourceBinding binding_{}; // a texture's, as registered with the context bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; @@ -2306,6 +2440,17 @@ private: // Among index entries for one program (containers with the same FSSM program; 789 groups in the 26,503-shader // corpus), the one to build: the first that `fits` and declares no set-0 bindings (the cheaper pipeline); else the // first that fits; else the first without bindings; else the first. Null when there is none. +// The S#s a shader builds from immediates (literal_samplers in its index entry) are named by no heap slot, so +// nothing else gives them a sampler and a hash-table key: without this their lookup finds the fallback sampler +// (index 0) and the shader samples with the wrong filter and address modes (docs/design.md, Literal samplers). +// Registering is idempotent and also runs when the pipeline is created again. +void register_literal_samplers(DeviceState& device, const leonida::ShaderEntry& entry) { + for (const leonida::gfx10::SamplerWords& words : entry.literal_samplers) + if (!device.bind_sampler(words)) + log_once("a shader's literal S# has no sampler (no bindless set, or its sampler array is full); words", + int(entry.literal_samplers.size())); +} + template const leonida::ShaderEntry* pick_entry(const std::vector& candidates, Fits&& fits) { const leonida::ShaderEntry* fitting = nullptr; @@ -2535,11 +2680,13 @@ public: bool graphics() const { return registered_ && is_graphics_; } const std::vector& subgroup_requests() const { return subgroup_requests_; } - // A VS (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the VS's - // input signature by semantic name and index: location = the element's register, the translator's rule - // (docs/design.md, "Vertex fetch"). Hull, domain and geometry stages, more than one sample, and two stages - // that both read their code base are refused with a log. Viewport, scissor, topology, vertex strides, stencil - // reference and blend factor are dynamic, set from the list's state at each draw. + // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the + // VS's input signature by semantic name and index: location = the element's register, the translator's rule + // (docs/design.md, "Vertex fetch"). Refused with a log: hull and domain stages, stream output, the centre + // multisample pattern, two stages that both read their code base, and state that needs a Vulkan feature the + // device lacks (including the geometryShader feature a GS needs). A GS takes triangles; the sample count may + // be above one. Viewport, scissor, topology, vertex strides, stencil reference and blend factor are dynamic, + // set from the list's state at each draw. HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; @@ -2611,6 +2758,21 @@ public: // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe. auto& required_sizes = recipe_.required_sizes; const Stage* code_stage = nullptr; + // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU): the pixel stage writes the depth D24 + // would hold, biased in D24 units and quantised (src/depth24_fragment.h, D3D-309), and the rasterizer's own + // bias is turned off. Multisampled targets keep the old path: a FragDepth write is per pixel. + const bool d24_as_float = desc.DSVFormat != DXGI_FORMAT_UNKNOWN && + vulkan_format(desc.DSVFormat, true).format == VK_FORMAT_D24_UNORM_S8_UINT && + !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); + bool depth24_fragment = d24_as_float && desc.DepthStencilState.DepthEnable; + if (depth24_fragment && samples > 1) { + log_once("D24 depth stored as D32 keeps float depth bias and precision on multisampled targets; samples", + int(samples)); + depth24_fragment = false; + } + const leonida::Depth24Bias depth24_bias{desc.RasterizerState.DepthBias, + desc.RasterizerState.SlopeScaledDepthBias, + desc.RasterizerState.DepthBiasClamp}; for (Stage& stage : stages) { if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only stage.fssm = leonida::fssm_program( @@ -2637,6 +2799,7 @@ public: return E_NOTIMPL; } uses_bindless = true; + register_literal_samplers(device_, *stage.entry); } if (stage.entry->uses_code_base) { if (code_stage) { @@ -2668,6 +2831,18 @@ public: } for (Stage& stage : stages) { if (!stage.entry) continue; + // After the f16 link above, which can also edit the pixel shader's words. + if (depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) { + std::string why; + std::vector patched = leonida::depth24_patch_fragment(stage.words, depth24_bias, why); + if (patched.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s keeps float depth on a D24 target stored as D32: %s\n", + stage.entry->name.c_str(), why.c_str()); + depth24_fragment = false; + } else { + stage.words = std::move(patched); + } + } VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = stage.words.size() * 4; module_info.pCode = stage.words.data(); @@ -2681,6 +2856,21 @@ public: subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } + if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth + const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (words.empty() || vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) + return E_FAIL; + modules_.push_back(module); + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } // Input layout -> vertex input, by semantic. std::vector attributes; @@ -2776,10 +2966,14 @@ public: : VK_CULL_MODE_NONE; // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; - raster.depthBiasEnable = r.DepthBias || r.SlopeScaledDepthBias != 0.0f; - raster.depthBiasConstantFactor = float(r.DepthBias); - raster.depthBiasClamp = r.DepthBiasClamp; - raster.depthBiasSlopeFactor = r.SlopeScaledDepthBias; + // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the + // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either. + raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f); + if (raster.depthBiasEnable) { + raster.depthBiasConstantFactor = float(r.DepthBias); + raster.depthBiasClamp = r.DepthBiasClamp; + raster.depthBiasSlopeFactor = r.SlopeScaledDepthBias; + } raster.lineWidth = 1.0f; // No depth clipping: fragments outside the viewport's depth range are kept and their depth clamped to it, as // D3D12 clamps output depth to MinDepth..MaxDepth anyway (needs depthClamp, checked below). @@ -3029,6 +3223,7 @@ public: entry->name.c_str()); return E_NOTIMPL; } + if (entry->binding_count) register_literal_samplers(device_, *entry); // SHADER-309: a module over the device's maxComputeSharedMemorySize is invalid usage that spirv-val accepts // and RADV dies on (#1721); some drivers report 32768. Refuse it here instead of creating the pipeline. if (entry->lds_bytes) { @@ -3078,7 +3273,7 @@ public: VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != + if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) return E_FAIL; @@ -3184,8 +3379,8 @@ private: info.pDynamicState = &dynamic; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; - if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, VK_NULL_HANDLE, 1, &info, nullptr, - &pipeline) != VK_SUCCESS) + if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 1, + &info, nullptr, &pipeline) != VK_SUCCESS) return VK_NULL_HANDLE; return pipeline; } @@ -3907,7 +4102,8 @@ leonida::gfx10::Sampler sampler_descriptor(const D3D12_SAMPLER_DESC& desc, Devic // A query heap: one VkQueryPool, registered with the context so that lists can resolve it by ID // (docs/d3d12_vulkan.md section 4.6). Occlusion heaps hold both OCCLUSION and BINARY_OCCLUSION queries; timestamp // and copy-queue timestamp heaps are timestamp pools; pipeline-statistics heaps count all eleven Vulkan -// statistics, whose result order is the field order of D3D12_QUERY_DATA_PIPELINE_STATISTICS. +// statistics, whose result order is the field order of D3D12_QUERY_DATA_PIPELINE_STATISTICS. Stream-output +// statistics heaps have no pool: without stream output every such query is zero. class QueryHeap final : public Child { @@ -3918,9 +4114,9 @@ public: explicit QueryHeap(DeviceState& device) : device_(device) {} ~QueryHeap() override { - if (!pool_) return; + if (!registered_) return; device_.context->remove_query_pool(id()); - device_.context->vk.vkDestroyQueryPool(device_.info.device, pool_, nullptr); + if (pool_) device_.context->vk.vkDestroyQueryPool(device_.info.device, pool_, nullptr); } leonida::QueryHeapId id() const { return query_heap_id(this); } @@ -3941,6 +4137,12 @@ public: } info.queryType = VK_QUERY_TYPE_TIMESTAMP; break; + case h::so_statistics: + // The layer has no stream output: a graphics PSO with StreamOutput entries is refused (E_NOTIMPL) and + // SOSetTargets is not implemented, so no primitive ever reaches a stream and every query of this heap + // counts 0 written and 0 needed. That needs no Vulkan pool: Begin/EndQuery run nothing and a resolve fills zeros. When stream + // output lands, this becomes a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool (D3D-302). + return register_pool(desc); case h::pipeline_statistics: if (!device_.info.pipeline_statistics_query) { log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); @@ -3950,7 +4152,7 @@ public: info.pipelineStatistics = kPipelineStatistics; break; default: - // Stream output, video decode and mesh-shader statistics (PIPELINE_STATISTICS1) have no path yet. + // Video decode and mesh-shader statistics (PIPELINE_STATISTICS1) have no path yet. log_once("query heap type not supported:", desc.Type); return E_NOTIMPL; } @@ -3958,6 +4160,11 @@ public: pool_ = VK_NULL_HANDLE; return E_OUTOFMEMORY; } + return register_pool(desc); + } + +private: + HRESULT register_pool(const D3D12_QUERY_HEAP_DESC& desc) { leonida::QueryPool pool{}; pool.pool = pool_; pool.heap_type = desc.Type; @@ -3965,10 +4172,10 @@ public: pool.precise = device_.info.occlusion_query_precise; pool.ended.assign(desc.Count, false); device_.context->add_query_pool(id(), pool); + registered_ = true; return S_OK; } -private: // VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT through COMPUTE_SHADER_INVOCATIONS_BIT (0x1-0x400): // IAVertices, IAPrimitives, VSInvocations, GSInvocations, GSPrimitives, CInvocations, CPrimitives, // PSInvocations, HSInvocations (patches), DSInvocations, CSInvocations. @@ -3976,7 +4183,8 @@ private: static_assert(sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS) == 11 * sizeof(UINT64)); DeviceState& device_; - VkQueryPool pool_ = VK_NULL_HANDLE; + VkQueryPool pool_ = VK_NULL_HANDLE; // null for a stream-output heap (no Vulkan query behind it) + bool registered_ = false; // added to the context, so removed from it on destruction }; // The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. @@ -4122,6 +4330,14 @@ public: state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); }); + if (info.buffer_device_address && info.physical && info.get_instance_proc) { + if (const auto get_props = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { + VkPhysicalDeviceProperties props{}; + get_props(info.physical, &props); + state_.context->configure_counted_dispatch(get_device, state_.memory, props.limits); + } + } // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of // a 96-bit texture, which every GPU stores as RGBA32 (D3D-62): the converter is there whether or not the // GPU has a native D24_UNORM_S8_UINT. It costs nothing until a copy needs it (its pipeline is made on the @@ -4380,6 +4596,8 @@ public: vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } + if (state_.pipeline_cache_handle) + state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); state_.context.reset(); if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); @@ -4468,20 +4686,31 @@ public: // Device1: priorities only order what the OS evicts first under memory pressure. VK_EXT_pageable_device_local_memory // could pass them on, but it is optional and changes no result, so they are accepted and dropped. Any UINT is a - // valid priority (the D3D12_RESIDENCY_PRIORITY values are named points, the low 24 bits a refinement). + // valid priority (the D3D12_RESIDENCY_PRIORITY values are named points, the low 24 bits a refinement). As on the + // host runtime (d3d12_residency_test, RTX 3060 / 610.88), only objects that own their memory take one: committed + // resources and heaps. A placed resource (a reserved one too, by the same rule; not measured), a descriptor heap, a query heap or a fence is E_INVALIDARG. + // The host also removes its device then (DXGI_ERROR_INVALID_CALL); the layer doesn't, since a console title that + // sets priorities on its placed resources would lose its device over a hint. HRESULT STDMETHODCALLTYPE SetResidencyPriority(UINT count, ID3D12Pageable* const* objects, const D3D12_RESIDENCY_PRIORITY* priorities) override { - return count && (!objects || !priorities) ? E_INVALIDARG : S_OK; + if (count && (!objects || !priorities)) return E_INVALIDARG; + for (UINT i = 0; i < count; ++i) { + if (from(objects[i])) continue; + const Resource* resource = from(objects[i]); + if (!resource || !resource->committed()) return E_INVALIDARG; + } + return S_OK; } // Device3: the asynchronous MakeResident. The objects are already resident, so the work is complete at once // and the fence is signalled from the CPU now. The caller's queue Wait on it must not hang, which is why the - // signal is kept although the residency part is a no-op. DENY_OVERBUDGET cannot fail: nothing is paged in. + // signal is kept although the residency part is a no-op. DENY_OVERBUDGET cannot fail: nothing is paged in. A + // null fence is accepted, as the host runtime does: there is nothing to signal. HRESULT STDMETHODCALLTYPE EnqueueMakeResident(D3D12_RESIDENCY_FLAGS flags, UINT count, ID3D12Pageable* const* objects, ID3D12Fence* fence, UINT64 value) override { - if (!fence || (count && !objects) || (flags & ~D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET)) return E_INVALIDARG; - return fence->Signal(value); + if ((count && !objects) || (flags & ~D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET)) return E_INVALIDARG; + return fence ? fence->Signal(value) : S_OK; } // Stable power state pins GPU clocks for profiling, a developer-mode feature on Windows. Vulkan has no clock @@ -4622,20 +4851,27 @@ public: return d3d12_trace::result(method, create_command_allocator(type, riid, out, identity())); } - HRESULT STDMETHODCALLTYPE CreateCommandList(UINT, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, - ID3D12PipelineState* state, REFIID riid, void** out) override { + HRESULT STDMETHODCALLTYPE CreateCommandList(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, + ID3D12CommandAllocator* allocator, ID3D12PipelineState* state, + REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateCommandList"; + if (out) *out = nullptr; + if (node_mask & ~1u) return d3d12_trace::result(method, E_INVALIDARG); // one node, as the host answers // The initial pipeline state is set as SetPipelineState would set it (a bundle's is its first deferred call). HRESULT hr = create_command_list(type, allocator, riid, out, identity(), state); return d3d12_trace::result(method, hr); } // Device4: a list created closed, without an allocator. - HRESULT STDMETHODCALLTYPE CreateCommandList1(UINT, D3D12_COMMAND_LIST_TYPE type, D3D12_COMMAND_LIST_FLAGS, - REFIID riid, void** out) override { + HRESULT STDMETHODCALLTYPE CreateCommandList1(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, + D3D12_COMMAND_LIST_FLAGS, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device4::CreateCommandList1"; - if (!out) return d3d12_trace::result(method, E_POINTER); - *out = nullptr; + // The host runtime's order ("command list1:" cases): one node and a type up to VIDEO_ENCODE, then a null + // output is E_UNEXPECTED. + if (out) *out = nullptr; + if ((node_mask & ~1u) || UINT(type) > UINT(D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE)) + return d3d12_trace::result(method, E_INVALIDARG); + if (!out) return d3d12_trace::result(method, E_UNEXPECTED); ID3D12CommandAllocator* allocator = nullptr; HRESULT hr = create_command_allocator(type, IID_PPV_ARGS(&allocator), identity()); if (FAILED(hr)) return d3d12_trace::result(method, hr); @@ -4686,7 +4922,7 @@ public: case D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW: size += sizeof(D3D12_VERTEX_BUFFER_VIEW); break; case D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW: size += sizeof(D3D12_INDEX_BUFFER_VIEW); break; case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT: size += UINT64{4} * arg.Constant.Num32BitValuesToSet; break; - case D3D12_INDIRECT_ARGUMENT_TYPE_INCREMENTING_CONSTANT: size += 4; break; + case compat::kIndirectArgumentIncrementingConstant: size += 4; break; case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW: case D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW: case D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW: size += sizeof(D3D12_GPU_VIRTUAL_ADDRESS); break; @@ -4888,6 +5124,7 @@ public: } layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values}); } + register_static_samplers(parsed.sig); auto* signature = new RootSignature( std::move(layout), leonida::sha256_hex({static_cast(blob), size})); signature->attach_device(identity()); @@ -5545,17 +5782,25 @@ public: log_once(refusal, desc->Flags); return; } - const bool uint_border = desc->Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; - D3D12_SAMPLER_DESC base{desc->Filter, desc->AddressU, desc->AddressV, desc->AddressW, - desc->MipLODBias, desc->MaxAnisotropy, desc->ComparisonFunc, {}, - desc->MinLOD, desc->MaxLOD}; - if (!uint_border) std::memcpy(base.BorderColor, desc->FloatBorderColor, sizeof(base.BorderColor)); + const leonida::gfx10::SamplerWords words = sampler2_words(*desc); + std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); + std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + state_.bind_sampler(words); + } + + // The S# of a D3D12_SAMPLER_DESC2 that sampler2_refusal accepts. + leonida::gfx10::SamplerWords sampler2_words(const D3D12_SAMPLER_DESC2& desc) { + const bool uint_border = desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; + D3D12_SAMPLER_DESC base{desc.Filter, desc.AddressU, desc.AddressV, desc.AddressW, + desc.MipLODBias, desc.MaxAnisotropy, desc.ComparisonFunc, {}, + desc.MinLOD, desc.MaxLOD}; + if (!uint_border) std::memcpy(base.BorderColor, desc.FloatBorderColor, sizeof(base.BorderColor)); leonida::gfx10::Sampler sampler = sampler_descriptor(base, uint_border ? nullptr : &state_); if (uint_border) { // The S#'s border types are the float ones', plus the layer's integer mark (kIntegerBorderPtr), which // gives the integer border its own key and VK_BORDER_COLOR_INT_* in Vulkan. namespace g = leonida::gfx10; - const UINT* c = desc->UintBorderColor; + const UINT* c = desc.UintBorderColor; const bool black = c[0] == 0 && c[1] == 0 && c[2] == 0; if (black && c[3] == 0) { sampler.border_color = g::BorderColor::transparent_black; @@ -5569,11 +5814,54 @@ public: } sampler.integer_border = true; } - sampler.unnormalized = desc->Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES; - const leonida::gfx10::SamplerWords words = leonida::gfx10::encode(sampler); - std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); - std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - state_.bind_sampler(words); + sampler.unnormalized = desc.Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES; + return leonida::gfx10::encode(sampler); + } + + // A root signature's static samplers take no root argument: a shader that uses one holds its S# by value + // (docs/d3d12_vulkan.md section 3.5). So each gets a sampler in set 0 and a key in the hash table here, as + // CreateSampler gives a heap slot's S#; without them the shader's lookup misses and it samples through the + // fallback sampler. A static sampler is a D3D12_SAMPLER_DESC2 whose border colour is one of five named ones + // (D3D12_STATIC_BORDER_COLOR; the two UINT ones can be in a blob of any version, the flags only in 1.2). + void register_static_samplers(const rt::rootsig::RootSignature& signature) { + for (const rt::rootsig::StaticSampler& s : signature.static_samplers) { + D3D12_SAMPLER_DESC2 desc{}; + desc.Filter = D3D12_FILTER(s.filter); + desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE(s.address_u); + desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE(s.address_v); + desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE(s.address_w); + desc.MipLODBias = s.mip_lod_bias; + desc.MaxAnisotropy = s.max_anisotropy; + desc.ComparisonFunc = D3D12_COMPARISON_FUNC(s.comparison_func); + desc.MinLOD = s.min_lod; + desc.MaxLOD = s.max_lod; + desc.Flags = D3D12_SAMPLER_FLAGS(s.flags); + const bool white = s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE || + s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT; + if (s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT || + s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT) { + desc.Flags |= D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; + desc.UintBorderColor[0] = desc.UintBorderColor[1] = desc.UintBorderColor[2] = white ? 1u : 0u; + desc.UintBorderColor[3] = 1; + } else if (s.border_color > D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT || + (desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR)) { + // A value past the enum, or the UINT flag with a float border: not a sampler D3D12 defines. + log_once("static sampler not registered: border colour and flags do not go together; border colour", + int(s.border_color)); + continue; + } else { + desc.FloatBorderColor[0] = desc.FloatBorderColor[1] = desc.FloatBorderColor[2] = white ? 1.0f : 0.0f; + desc.FloatBorderColor[3] = + s.border_color == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : 1.0f; + } + if (sampler2_refusal(desc)) { + log_once("static sampler not registered: a sampler CreateSampler2 refuses; flags", int(desc.Flags)); + continue; + } + if (!state_.bind_sampler(sampler2_words(desc))) + log_once("static sampler not registered: no room in the bindless set; register", + int(s.shader_register)); + } } // Why the PC runtime refuses a D3D12_SAMPLER_DESC2, or null. The non-normalized rules are its debug layer's @@ -5601,32 +5889,8 @@ public: const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device::CreateCommittedResource"; - if (out) *out = nullptr; - if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); - // The host runtime's argument checks (D3D-49). A refusal is logged once per reason and dimension, since a - // game that trips one (for example with an Xbox-only flag through slot 76) gets no resource. - if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear, - acceleration_structures())) { - log_once((std::string("CreateCommittedResource refused (") + why + "), dimension").c_str(), - desc->Dimension); - return d3d12_trace::result(method, E_INVALIDARG); - } - // The sample quality is checked above as the host does it here: CreateCommittedResource accepts a quality on a - // single-sampled texture and the two standard MSAA patterns, which GetResourceAllocationInfo's rules refuse. - // The size, mip and alignment checks below run on a copy with quality 0. - D3D12_RESOURCE_DESC checked = *desc; - if (checked.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) checked.SampleDesc.Quality = 0; - if ((desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || - desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) && - allocation(checked).SizeInBytes == UINT64_MAX) { - // Extents, mips, samples and alignment, as GetResourceAllocationInfo answers. - log_once("CreateCommittedResource refused (texture size, mips, samples or alignment), dimension", - desc->Dimension); - return d3d12_trace::result(method, E_INVALIDARG); - } - return d3d12_trace::result(method, create_committed(heap, heap_flags, desc, state, 0, nullptr, riid, - out)); + return create_committed_validated("ID3D12Device::CreateCommittedResource", heap, heap_flags, desc, state, clear, + 0, nullptr, riid, out); } // Reserved buffers use sparse binding where available. Textures and fallback buffers are fully backed. @@ -5637,8 +5901,7 @@ public: HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device::CreateReservedResource"; - return d3d12_trace::result(method, create_reserved(desc, state, clear, riid, out)); + return create_reserved("ID3D12Device::CreateReservedResource", desc, state, clear, 0, nullptr, riid, out); } // Device4. Protected sessions are not supported. @@ -5646,23 +5909,29 @@ public: const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, REFIID riid, void** out) override { - if (session) { - if (out) *out = nullptr; - log_once("CreateReservedResource1 with a protected session not supported:", 1); - return E_NOTIMPL; - } - return create_reserved(desc, state, clear, riid, out); + constexpr auto method = "ID3D12Device4::CreateReservedResource1"; + if (out) *out = nullptr; + if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource1")); + return create_reserved(method, desc, state, clear, 0, nullptr, riid, out); } - // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway). - // Castable formats are not used: typeless resources are already mutable-format images. - HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT, + // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway), and a + // castable-format list forwarded to the backing texture. + HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, - UINT32 castable_formats, const DXGI_FORMAT*, REFIID riid, + UINT32 castable_formats, const DXGI_FORMAT* castable, REFIID riid, void** out) override { - if (castable_formats) log_once("CreateReservedResource2: castable formats ignored, count", int(castable_formats)); - return CreateReservedResource1(desc, D3D12_RESOURCE_STATE_COMMON, clear, session, riid, out); + constexpr auto method = "ID3D12Device10::CreateReservedResource2"; + if (out) *out = nullptr; + if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource2")); + if (const char* why = barrier_layout_refusal(*desc, layout)) { + log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); + return d3d12_trace::result(method, E_INVALIDARG); + } + return create_reserved(method, desc, D3D12_RESOURCE_STATE_COMMON, clear, castable_formats, castable, riid, out); } // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything @@ -5701,7 +5970,7 @@ public: ID3D12ProtectedResourceSession* session, REFIID riid, void** out) override { if (out) *out = nullptr; - if (session) return refuse_protected_session(1); + if (session) return refuse_protected_session("CreateCommittedResource1"); return CreateCommittedResource(heap, heap_flags, desc, state, clear, riid, out); } @@ -5712,7 +5981,7 @@ public: void** out) override { if (out) *out = nullptr; if (!desc) return E_INVALIDARG; - if (session) return refuse_protected_session(2); + if (session) return refuse_protected_session("CreateCommittedResource2"); if (texture_mip_region(*desc)) return E_INVALIDARG; const D3D12_RESOURCE_DESC base = resource_desc(*desc); return CreateCommittedResource(heap, heap_flags, &base, state, clear, riid, out); @@ -5720,23 +5989,25 @@ public: HRESULT STDMETHODCALLTYPE CreateCommittedResource3(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, - const D3D12_CLEAR_VALUE*, + const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) override { + constexpr auto method = "ID3D12Device10::CreateCommittedResource3"; if (out) *out = nullptr; - if (!desc) return E_INVALIDARG; - if (session) return refuse_protected_session(3); - if (texture_mip_region(*desc)) return E_INVALIDARG; - // Enhanced barriers: a buffer has no layout, so its initial layout must be UNDEFINED. - if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && layout != D3D12_BARRIER_LAYOUT_UNDEFINED) - return E_INVALIDARG; + if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + if (session) return d3d12_trace::result(method, refuse_protected_session("CreateCommittedResource3")); + if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so // a real list is passed through; only buffers are refused. const D3D12_RESOURCE_DESC base = resource_desc(*desc); + if (const char* why = barrier_layout_refusal(base, layout)) { + log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); + return d3d12_trace::result(method, E_INVALIDARG); + } // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the // legacy CreateCommittedResource path. Buffers here start COMMON, as before. - return create_committed(heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, castable_count, castable, - riid, out); + return create_committed_validated(method, heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, clear, + castable_count, castable, riid, out); } // Device9. The creator ID only groups queues for tools; one creator is as good as another here. @@ -5786,7 +6057,8 @@ public: HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { - return create_placed(heap_interface, heap_offset, desc, state, clear, 0, nullptr, riid, out); + return create_placed("ID3D12Device::CreatePlacedResource", heap_interface, heap_offset, desc, state, clear, 0, + nullptr, riid, out); } // Device8: the DESC1 placed variant without a castable list. A texture with a mip region gets the failure @@ -5794,11 +6066,12 @@ public: HRESULT STDMETHODCALLTYPE CreatePlacedResource1(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { + constexpr auto method = "ID3D12Device8::CreatePlacedResource1"; if (out) *out = nullptr; - if (!desc) return E_INVALIDARG; - if (texture_mip_region(*desc)) return E_INVALIDARG; + if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); const D3D12_RESOURCE_DESC base = resource_desc(*desc); - return create_placed(heap_interface, heap_offset, &base, state, clear, 0, nullptr, riid, out); + return create_placed(method, heap_interface, heap_offset, &base, state, clear, 0, nullptr, riid, out); } // Device10: an initial layout instead of a state, and the castable-format list, which the placed texture's @@ -5808,16 +6081,18 @@ public: const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) override { + constexpr auto method = "ID3D12Device10::CreatePlacedResource2"; if (out) *out = nullptr; - if (!desc) return E_INVALIDARG; - if (texture_mip_region(*desc)) return E_INVALIDARG; - // Enhanced barriers: a buffer has no layout, so its initial layout must be UNDEFINED. - if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && layout != D3D12_BARRIER_LAYOUT_UNDEFINED) - return E_INVALIDARG; + if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); const D3D12_RESOURCE_DESC base = resource_desc(*desc); + if (const char* why = barrier_layout_refusal(base, layout)) { + log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); + return d3d12_trace::result(method, E_INVALIDARG); + } // An initial layout replaces the state, so the state rules are not this call's. - return create_placed(heap_interface, heap_offset, &base, D3D12_RESOURCE_STATE_COMMON, clear, castable_count, - castable, riid, out); + return create_placed(method, heap_interface, heap_offset, &base, D3D12_RESOURCE_STATE_COMMON, clear, + castable_count, castable, riid, out); } // The placed path every CreatePlacedResource variant shares. A castable-format list reaches the placed @@ -5828,15 +6103,15 @@ public: // CreateCommittedResource has, then the placement: a buffer at a 64 KiB-aligned offset, a texture at a // multiple of its GetResourceAllocationInfo alignment (4 KiB for a small texture), in a heap aligned at least // as much, and the whole resource inside the heap. Only then is a null output E_UNEXPECTED, with nothing made. - HRESULT create_placed(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, - D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, - const DXGI_FORMAT* castable, REFIID riid, void** out) { + HRESULT create_placed(const char* method, ID3D12Heap* heap_interface, UINT64 heap_offset, + const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { if (out) *out = nullptr; auto* heap = Heap::from(heap_interface); - if (!heap || !desc) return E_INVALIDARG; + if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a placed buffer are invalid; count", int(castable_count)); - return E_INVALIDARG; + return d3d12_trace::result(method, E_INVALIDARG); } // The description, state and clear value rules of a committed resource, but on a default heap: the heap's // DENY flags are checked against the resource below, and the host takes any initial state for a buffer in @@ -5850,62 +6125,73 @@ public: (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) why = "UAV access in an upload or readback heap"; if (why) { - log_once((std::string("CreatePlacedResource refused (") + why + "), dimension").c_str(), - desc->Dimension); - return E_INVALIDARG; + log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension)); + return d3d12_trace::result(method, E_INVALIDARG); } const bool tiled = is_tiled_layout(desc->Layout); + const bool msaa = desc->SampleDesc.Count > 1; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return E_INVALIDARG; + if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return d3d12_trace::result(method, E_INVALIDARG); if (heap_offset % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) { log_once("placed buffer offset not 64 KiB aligned:", int(heap_offset)); - return E_INVALIDARG; + return d3d12_trace::result(method, E_INVALIDARG); } - if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return E_INVALIDARG; + if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) + return d3d12_trace::result(method, E_INVALIDARG); } else { if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD || heap->properties().Type == D3D12_HEAP_TYPE_READBACK) - return E_INVALIDARG; + return d3d12_trace::result(method, E_INVALIDARG); const bool rt_ds = (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0; - if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return E_INVALIDARG; - if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) return E_INVALIDARG; + if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) + return d3d12_trace::result(method, E_INVALIDARG); + if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) + return d3d12_trace::result(method, E_INVALIDARG); if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) - return E_INVALIDARG; - if (desc->SampleDesc.Count > 1 && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) - return E_INVALIDARG; + return d3d12_trace::result(method, E_INVALIDARG); + if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) + return d3d12_trace::result(method, E_INVALIDARG); // Extents, mips, samples, layout and alignment, as GetResourceAllocationInfo answers them (the sample // quality is the description rules' above, as in CreateCommittedResource). D3D12_RESOURCE_DESC checked = *desc; checked.SampleDesc.Quality = 0; const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(checked); if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment || - heap_offset % alloc.Alignment || alloc.SizeInBytes > heap->bytes() || - heap_offset > heap->bytes() - alloc.SizeInBytes) { + heap_offset % alloc.Alignment) { log_once("placed texture refused (size, alignment or room in the heap), dimension", int(desc->Dimension)); - return E_INVALIDARG; + return d3d12_trace::result(method, E_INVALIDARG); + } + const UINT64 fit_bytes = + (tiled || msaa) + ? alloc.SizeInBytes + : min_placed_texture_bytes(checked, state_.texture_format(checked), alloc.Alignment, + alloc.SizeInBytes); + if (fit_bytes > heap->bytes() || heap_offset > heap->bytes() - fit_bytes) { + log_once("placed texture refused (size, alignment or room in the heap), dimension", + int(desc->Dimension)); + return d3d12_trace::result(method, E_INVALIDARG); } if (tiled && static_cast(desc->Layout) == kXboxTiledLayout) { log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", int(desc->Dimension)); } } - if (!out) return E_UNEXPECTED; + if (!out) return d3d12_trace::result(method, E_UNEXPECTED); if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && !heap->use_as_placed_buffer(true)) { log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1); - return E_NOTIMPL; + return d3d12_trace::result(method, E_NOTIMPL); } - // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image. + // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image, which + // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture. const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); resource->attach_device(identity()); HRESULT hr = E_NOTIMPL; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { hr = resource->create_placed_buffer(); - } else if (!tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { - log_once("placed resource dimension not supported:", int(desc->Dimension)); } else { hr = S_OK; const Format format = state_.texture_format(*desc); @@ -5920,9 +6206,9 @@ public: } if (FAILED(hr)) { resource->Release(); - return hr; + return d3d12_trace::result(method, hr); } - return hand_out(resource, riid, out); + return d3d12_trace::result(method, hand_out(resource, riid, out)); } // Footprints for copies through a buffer: rows padded to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (512 for planar @@ -6020,16 +6306,23 @@ public: // to D3D12's alignment for it; the alignment itself is D3D12's, since placed textures bind their own memory // (section 4.2). Several resources are laid out one after another, each at its own alignment. An invalid // description gives SizeInBytes = UINT64_MAX, as on D3D12. d3d12_vulkan_device_test compares with the PC runtime. + // A visible mask above 1 names a node the single-node adapter lacks: the same invalid answer, also for no + // resources at all, and the per-resource array is left untouched (host runtime and WARP, measured). D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo( - UINT, UINT count, const D3D12_RESOURCE_DESC* descs) override { + UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs) override { + if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { return descs[i]; }, nullptr); } D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo1( - UINT, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { + UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs, + D3D12_RESOURCE_ALLOCATION_INFO1* each) override { + if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { return descs[i]; }, each); } D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo2( - UINT, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { + UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC1* descs, + D3D12_RESOURCE_ALLOCATION_INFO1* each) override { + if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { const D3D12_RESOURCE_DESC1& d = descs[i]; if (d.SamplerFeedbackMipRegion.Width || d.SamplerFeedbackMipRegion.Height || @@ -6276,20 +6569,20 @@ public: opts->ComputeOnlyCustomHeapSupported = FALSE; return d3d12_trace::result(method, S_OK); } - case D3D12_FEATURE_D3D12_OPTIONS20: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS20)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); + case compat::kFeatureOptions20: { + if (size != sizeof(compat::FeatureDataOptions20)) return d3d12_trace::result(method, E_INVALIDARG); + auto* opts = static_cast(data); *opts = {}; opts->ComputeOnlyWriteWatchSupported = FALSE; - opts->RecreateAtTier = D3D12_RECREATE_AT_TIER_NOT_SUPPORTED; + opts->RecreateAtTier = compat::kRecreateAtTierNotSupported; return d3d12_trace::result(method, S_OK); } - case D3D12_FEATURE_D3D12_OPTIONS21: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS21)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); + case compat::kFeatureOptions21: { + if (size != sizeof(compat::FeatureDataOptions21)) return d3d12_trace::result(method, E_INVALIDARG); + auto* opts = static_cast(data); *opts = {}; - opts->WorkGraphsTier = D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED; - opts->ExecuteIndirectTier = D3D12_EXECUTE_INDIRECT_TIER_1_0; + opts->WorkGraphsTier = compat::kWorkGraphsTierNotSupported; + opts->ExecuteIndirectTier = compat::kExecuteIndirectTier1_0; opts->SampleCmpGradientAndBiasSupported = FALSE; opts->ExtendedCommandInfoSupported = FALSE; return d3d12_trace::result(method, S_OK); @@ -6718,8 +7011,8 @@ public: case D3D12_FEATURE_QUERY_META_COMMAND: // EnumerateMetaCommands reports 0 meta-commands, so any query is rejected (as on host D3D12). return d3d12_trace::result(method, E_INVALIDARG); - case D3D12_FEATURE_PREDICATION: - return write_supported_feature( + case compat::kFeaturePredication: + return write_supported_feature( method, data, size, state_.info.conditional_rendering ? TRUE : FALSE); case compat::kFeatureApplicationSpecificDriverState: return write_supported_feature(method, data, size, FALSE); @@ -6870,6 +7163,42 @@ private: tiles(volume ? desc.DepthOrArraySize : 1, 1, shape.depth) <= 16; } + // Strict lower bound on the heap bytes a non-tiled single-sample texture needs: sums uncompressed texel/block + // payload across subresources and rounds to `alignment`, capped at `fallback` (Vulkan allocation size). Avoids + // rejecting host-valid placed textures when Vulkan driver padding exceeds D3D12's GetResourceAllocationInfo. + static UINT64 min_placed_texture_bytes(const D3D12_RESOURCE_DESC& desc, const Format& format, UINT64 alignment, + UINT64 fallback) { + const VkImageAspectFlags aspect = + (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT : format.aspects; + const leonida::BlockFormat block = footprint_block(format, aspect); + if (!block.bytes || !alignment) return fallback; + const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; + const UINT depth = volume ? desc.DepthOrArraySize : 1; + const UINT slices = volume ? 1 : desc.DepthOrArraySize; + const UINT mips = desc.MipLevels ? desc.MipLevels : full_mips(desc.Width, desc.Height, depth); + UINT64 per_slice = 0; + for (UINT m = 0; m < mips; ++m) { + const UINT64 w = std::max(1, desc.Width >> m); + const UINT64 h = one_d ? 1 : std::max(1, desc.Height >> m); + const UINT64 d = volume ? std::max(1, depth >> m) : 1; + const UINT64 bw = (w + block.block - 1) / block.block; + const UINT64 bh = (h + block.block - 1) / block.block; + if (bw > UINT64_MAX / bh) return fallback; + const UINT64 blocks = bw * bh; + if (blocks > UINT64_MAX / d) return fallback; + const UINT64 count = blocks * d; + if (count > UINT64_MAX / block.bytes) return fallback; + const UINT64 mip_bytes = count * block.bytes; + if (per_slice > UINT64_MAX - mip_bytes) return fallback; + per_slice += mip_bytes; + } + if (slices && per_slice > UINT64_MAX / slices) return fallback; + const UINT64 total = per_slice * slices; + if (total > UINT64_MAX - (alignment - 1)) return fallback; + return std::min(fallback, align_up(total, alignment)); + } + // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be // shown leaves the slot a null descriptor. void write_image_descriptor(const Resource& resource, const TextureView& view, @@ -6884,9 +7213,40 @@ private: std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } - // Shared by CreateCommittedResource and CreateCommittedResource3. A castable-format list is only meaningful on - // textures; the layer reports RelaxedFormatCastingSupported, so each format is mapped and handed to Vulkan as a - // VkImageFormatListCreateInfo. A nonzero count with a null list is no list, as on the PC runtime. + // Validation shared by CreateCommittedResource and CreateCommittedResource3; internal callers pass null `method` + // to skip trace recording. + HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap, + D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, + D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; }; + if (out) *out = nullptr; + if (!heap || !desc) return finish(E_INVALIDARG); + if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear, + acceleration_structures())) { + log_once((std::string(method ? method : "CreateCommittedResource") + " refused (" + why + "), dimension") + .c_str(), + int(desc->Dimension)); + return finish(E_INVALIDARG); + } + // The sample quality is checked above as the host does it here: CreateCommittedResource accepts a quality on a + // 1x texture while GetResourceAllocationInfo requires 0; the other texture checks stay shared with allocation. + D3D12_RESOURCE_DESC checked = *desc; + if (checked.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) checked.SampleDesc.Quality = 0; + if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && allocation(checked).SizeInBytes == UINT64_MAX) { + log_once((std::string(method ? method : "CreateCommittedResource") + + " refused (texture size, mips, samples or alignment), dimension") + .c_str(), + int(desc->Dimension)); + return finish(E_INVALIDARG); + } + return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out)); + } + + // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list + // is only meaningful on textures; the layer reports RelaxedFormatCastingSupported, so each format is mapped and + // handed to Vulkan as a VkImageFormatListCreateInfo. A nonzero count with a null list is no list, as on the PC + // runtime. HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { @@ -7012,43 +7372,47 @@ private: // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules of a // committed resource on a default heap, the reserved layouts below, and only then E_UNEXPECTED for a null // output, with nothing made. - HRESULT create_reserved(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) { + HRESULT create_reserved(const char* method, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, + const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, + REFIID riid, void** out) { if (out) *out = nullptr; - if (!desc) return E_INVALIDARG; + if (!desc) return d3d12_trace::result(method, E_INVALIDARG); + if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + log_once("castable formats on a reserved buffer are invalid; count", int(castable_count)); + return d3d12_trace::result(method, E_INVALIDARG); + } D3D12_RESOURCE_DESC backing = *desc; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG; + if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return d3d12_trace::result(method, E_INVALIDARG); } else { if (static_cast(desc->Layout) == kXboxTiledLayout) { log_once("reserved resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", desc->Dimension); } else if (desc->Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) { - return E_INVALIDARG; // 64KB_STANDARD_SWIZZLE too: CheckFeatureSupport reports it unsupported + return d3d12_trace::result(method, E_INVALIDARG); // 64KB_STANDARD_SWIZZLE too: CheckFeatureSupport reports it unsupported } backing.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; leonida::ResourceTiling tiling; backing.MipLevels = std::max(desc->MipLevels, 1); // any count: only the format is checked here if (!resource_tiling(backing, tiling)) { log_once("reserved texture format has no tile shape:", desc->Format); - return E_INVALIDARG; + return d3d12_trace::result(method, E_INVALIDARG); } backing.MipLevels = desc->MipLevels; } if (const char* why = committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, backing, state, clear, acceleration_structures())) { - log_once((std::string("CreateReservedResource refused (") + why + "), dimension").c_str(), - desc->Dimension); - return E_INVALIDARG; + log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension)); + return d3d12_trace::result(method, E_INVALIDARG); } if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // Extents, mips and samples, as the committed backing below checks them (GetResourceAllocationInfo). D3D12_RESOURCE_DESC checked = backing; checked.SampleDesc.Quality = 0; - if (allocation(checked).SizeInBytes == UINT64_MAX) return E_INVALIDARG; + if (allocation(checked).SizeInBytes == UINT64_MAX) return d3d12_trace::result(method, E_INVALIDARG); } - if (!out) return E_UNEXPECTED; + if (!out) return d3d12_trace::result(method, E_UNEXPECTED); ID3D12Resource* resource = nullptr; HRESULT hr; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && state_.sparse_buffer_memory_types) { @@ -7057,18 +7421,18 @@ private: hr = sparse->create_sparse_buffer(); if (FAILED(hr)) { sparse->Release(); - return hr; + return d3d12_trace::result(method, hr); } resource = sparse; } else { - hr = CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &backing, D3D12_RESOURCE_STATE_COMMON, - nullptr, IID_PPV_ARGS(&resource)); + hr = create_committed_validated(nullptr, &heap, D3D12_HEAP_FLAG_NONE, &backing, D3D12_RESOURCE_STATE_COMMON, + clear, castable_count, castable, IID_PPV_ARGS(&resource)); } - if (FAILED(hr)) return hr; + if (FAILED(hr)) return d3d12_trace::result(method, hr); Resource::from(resource)->make_reserved(desc->Layout); hr = resource->QueryInterface(riid, out); resource->Release(); - return hr; + return d3d12_trace::result(method, hr); } // The tiling of a reserved resource's description; false for formats without a tile shape (three- and @@ -7133,9 +7497,9 @@ private: } // The layer reports no protected-session support, so a session is refused, as D3D12 refuses one on a device - // without D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT. `variant` is the method's number. - static HRESULT refuse_protected_session(int variant) { - log_once("protected resource session refused (not supported) by CreateCommittedResource", variant); + // without D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT. + static HRESULT refuse_protected_session(const char* method) { + log_once((std::string("protected resource session refused (not supported) by ") + method + ':').c_str(), 1); return E_INVALIDARG; } @@ -7181,7 +7545,28 @@ std::shared_ptr tile_heap(ID3D12Heap* heap, c } void set_device_outer(ID3D12Device* device, IUnknown* outer) { - if (Device* d = Device::from(device)) d->set_outer(outer); + Device* d = Device::from(device); + if (!d) return; + // A caller passes what create_device_proxy returned, which is the proxy's DXGI pointer when the title asked + // for IDXGIDevice1: the device's outer identity is the proxy itself either way. + if (void* proxy = rt::d3d12_xs::device_proxy_primary(outer)) outer = static_cast(proxy); + d->set_outer(outer); + // Second job, for an outer that is the Xbox-ABI proxy: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands + // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets + // a host DXGI object from it. + if (!rt::d3d12_xs::is_device_proxy(outer)) return; + rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) { + IDXGIFactory1* factory = nullptr; + HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); + if (FAILED(hr)) return hr; + IDXGIAdapter* adapter = nullptr; + hr = factory->EnumAdapters(0, &adapter); + factory->Release(); + if (FAILED(hr)) return hr; + hr = adapter->QueryInterface(riid, out); + adapter->Release(); + return hr; + }); } const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) { @@ -7835,7 +8220,15 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { q.pQueuePriorities = priorities.data(); queue_infos.push_back(q); } - const auto picked = leonida::pick_queue_families(families, info.queue_family); + const auto preferred = leonida::pick_queue_families(families, info.queue_family); + // D3D12 permits UpdateTileMappings on DIRECT, COMPUTE and COPY queues. Vulkan requires + // VK_QUEUE_SPARSE_BINDING_BIT on the VkQueue passed to vkQueueBindSparse. A dedicated + // async family without that capability cannot implement all D3D12 queue operations; + // fall back to the graphics family when sparse buffers are supported. QueueKind still + // enforces the D3D12 COPY/COMPUTE stage restrictions on the more capable family. + const bool sparse_buffers = chosen_features.sparseBinding && chosen_features.sparseResidencyBuffer && + chosen_features.sparseResidencyAliased; + const auto picked = leonida::sparse_capable_queue_families(families, preferred, sparse_buffers); std::uint32_t compute_count = 0, copy_count = 0; if (picked.compute != info.queue_family) { info.compute_family = picked.compute; diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 3c3cf6724..31c91745f 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -26,8 +26,10 @@ #endif #include +#include #include +#include #include #include #include @@ -66,6 +68,11 @@ struct DeviceProxy { // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers // compiled against the PC headers. bool console_lists = true; + // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here. + void** dxgi_vtable; + DxgiAdapterProvider adapter_provider; + std::atomic gpu_thread_priority; + std::atomic max_frame_latency; }; // Freed in proxy_release; defined where the states are complete. @@ -227,6 +234,12 @@ HRESULT proxy_query_interface(DeviceProxy* self, const IID* riid, void** out) { proxy_add_ref(self); return S_OK; } + if (IsEqualIID(*riid, __uuidof(IDXGIObject)) || IsEqualIID(*riid, __uuidof(IDXGIDevice)) || + IsEqualIID(*riid, __uuidof(IDXGIDevice1))) { + *out = &self->dxgi_vtable; + proxy_add_ref(self); + return S_OK; + } if (!is_device_iid(*riid)) return E_NOINTERFACE; // Only claim an interface the PC device really implements; the proxy vtable covers its slots. @@ -240,6 +253,142 @@ HRESULT proxy_query_interface(DeviceProxy* self, const IID* riid, void** out) { return S_OK; } +// ---- IDXGIDevice1 on the device --------------------------------------------------------------------------------- +// +// A GDKX title finds its output through the device: QueryInterface for IDXGIDevice1, GetAdapter, EnumOutputs(0), +// and hands that output to SetFrameIntervalX (docs/d3d12_vulkan.md section 4.5, from the public samples). A PC +// ID3D12Device has no IDXGIDevice, so the proxy answers it itself: a second vtable pointer inside the proxy object, +// with the proxy's reference count and QueryInterface, so the two pointers are one COM object. Only IDXGIDevice and +// IDXGIDevice1 are answered (what the samples ask for). The 14 slots are the public dxgi.h order; that the console +// keeps it is the same assumption as for the queue and the fence. +// +// GetAdapter and GetParent hand out the adapter of the device behind the proxy. The provider says how: the default +// asks the host's DXGI for the adapter with the device's LUID (the host backend); set_device_adapter_provider puts +// the Vulkan layer's own adapter there, so that backend never loads the host's dxgi.dll for it. +constexpr unsigned kDxgiDeviceSlots = 14; // IUnknown 3, IDXGIObject 4, IDXGIDevice 5, IDXGIDevice1 2 + +DeviceProxy* dxgi_owner(void* self) { + return reinterpret_cast(static_cast(self) - offsetof(DeviceProxy, dxgi_vtable)); +} + +HRESULT host_adapter(ID3D12Device* real, REFIID riid, void** out) { + using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**); + static const CreateFactoryFn create_factory = [] { + const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + return dxgi ? reinterpret_cast( + reinterpret_cast(GetProcAddress(dxgi, "CreateDXGIFactory1"))) + : nullptr; + }(); + if (!create_factory) return DXGI_ERROR_NOT_FOUND; + IDXGIFactory4* factory = nullptr; + HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast(&factory)); + if (FAILED(hr) || !factory) return FAILED(hr) ? hr : DXGI_ERROR_NOT_FOUND; + hr = factory->EnumAdapterByLuid(real->GetAdapterLuid(), riid, out); + factory->Release(); + return hr; +} + +HRESULT dxgi_adapter(DeviceProxy* self, REFIID riid, void** out) { + if (!out) return E_POINTER; + *out = nullptr; + const DxgiAdapterProvider provider = self->adapter_provider ? self->adapter_provider : &host_adapter; + const HRESULT hr = provider(self->real, riid, out); + if (FAILED(hr)) *out = nullptr; + return hr; +} + +void note_dxgi(const char* method) { + d3d12_trace::record(method); +} + +HRESULT WINAPI dxgi_query_interface(void* self, const IID* riid, void** out) { + return proxy_query_interface(dxgi_owner(self), riid, out); +} +ULONG WINAPI dxgi_add_ref(void* self) { return proxy_add_ref(dxgi_owner(self)); } +ULONG WINAPI dxgi_release(void* self) { return proxy_release(dxgi_owner(self)); } + +// IDXGIObject's private data is the device's: ID3D12Object has the same three methods with the same arguments. +HRESULT WINAPI dxgi_set_private_data(void* self, const GUID* name, UINT size, const void* data) { + if (!name) return E_INVALIDARG; + return dxgi_owner(self)->real->SetPrivateData(*name, size, data); +} +HRESULT WINAPI dxgi_set_private_data_interface(void* self, const GUID* name, const IUnknown* object) { + if (!name) return E_INVALIDARG; + return dxgi_owner(self)->real->SetPrivateDataInterface(*name, object); +} +HRESULT WINAPI dxgi_get_private_data(void* self, const GUID* name, UINT* size, void* data) { + if (!name) return E_INVALIDARG; + return dxgi_owner(self)->real->GetPrivateData(*name, size, data); +} +HRESULT WINAPI dxgi_get_parent(void* self, const IID* riid, void** out) { + note_dxgi("XboxIDXGIDevice::GetParent"); + if (!riid) return E_POINTER; + return dxgi_adapter(dxgi_owner(self), *riid, out); +} +HRESULT WINAPI dxgi_get_adapter(void* self, IDXGIAdapter** out) { + note_dxgi("XboxIDXGIDevice::GetAdapter"); + return dxgi_adapter(dxgi_owner(self), __uuidof(IDXGIAdapter), reinterpret_cast(out)); +} +// CreateSurface and QueryResourceResidency are D3D10/11-era methods no D3D12 title has a use for; what the console +// answers is not measured, so they are refused and say so once. +HRESULT WINAPI dxgi_create_surface(void*, const DXGI_SURFACE_DESC*, UINT, DXGI_USAGE, const DXGI_SHARED_RESOURCE*, + IDXGISurface** out) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: IDXGIDevice::CreateSurface is not implemented; returning E_NOTIMPL\n"); + if (out) *out = nullptr; + return E_NOTIMPL; +} +HRESULT WINAPI dxgi_query_resource_residency(void*, IUnknown* const*, DXGI_RESIDENCY*, UINT) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: IDXGIDevice::QueryResourceResidency is not implemented; returning E_NOTIMPL\n"); + return E_NOTIMPL; +} +// The priority and the frame latency are kept and read back; nothing acts on them (the Xbox presenter's latency is +// SetFrameIntervalX's). The ranges are the documented ones: -7..7, and 1..16 with 0 for the default of 3. +HRESULT WINAPI dxgi_set_gpu_thread_priority(void* self, INT priority) { + if (priority < -7 || priority > 7) return E_INVALIDARG; + dxgi_owner(self)->gpu_thread_priority.store(priority, std::memory_order_relaxed); + return S_OK; +} +HRESULT WINAPI dxgi_get_gpu_thread_priority(void* self, INT* priority) { + if (!priority) return E_POINTER; + *priority = dxgi_owner(self)->gpu_thread_priority.load(std::memory_order_relaxed); + return S_OK; +} +HRESULT WINAPI dxgi_set_maximum_frame_latency(void* self, UINT latency) { + if (latency > 16) return DXGI_ERROR_INVALID_CALL; + dxgi_owner(self)->max_frame_latency.store(latency ? latency : 3, std::memory_order_relaxed); + return S_OK; +} +HRESULT WINAPI dxgi_get_maximum_frame_latency(void* self, UINT* latency) { + if (!latency) return E_POINTER; + *latency = dxgi_owner(self)->max_frame_latency.load(std::memory_order_relaxed); + return S_OK; +} + +void** get_dxgi_vtable() { + static void* table[kDxgiDeviceSlots] = { + reinterpret_cast(&dxgi_query_interface), // 0 + reinterpret_cast(&dxgi_add_ref), // 1 + reinterpret_cast(&dxgi_release), // 2 + reinterpret_cast(&dxgi_set_private_data), // 3 IDXGIObject + reinterpret_cast(&dxgi_set_private_data_interface), + reinterpret_cast(&dxgi_get_private_data), + reinterpret_cast(&dxgi_get_parent), + reinterpret_cast(&dxgi_get_adapter), // 7 IDXGIDevice + reinterpret_cast(&dxgi_create_surface), + reinterpret_cast(&dxgi_query_resource_residency), + reinterpret_cast(&dxgi_set_gpu_thread_priority), + reinterpret_cast(&dxgi_get_gpu_thread_priority), + reinterpret_cast(&dxgi_set_maximum_frame_latency), // 12 IDXGIDevice1 + reinterpret_cast(&dxgi_get_maximum_frame_latency), + }; + return table; +} + unsigned long heap_add_ref(HeapProxy* self) { note_heap_slot(1); return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; @@ -1984,6 +2133,10 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool co proxy->slot_count = detect_slot_count(real); proxy->console_lists = console_lists; proxy->refs.store(1, std::memory_order_relaxed); + proxy->dxgi_vtable = get_dxgi_vtable(); + proxy->adapter_provider = nullptr; + proxy->gpu_thread_priority.store(0, std::memory_order_relaxed); + proxy->max_frame_latency.store(3, std::memory_order_relaxed); const unsigned slot_count = proxy->slot_count; HRESULT hr = proxy_query_interface(proxy, &riid, out); @@ -2003,6 +2156,28 @@ bool is_device_proxy(const void* device) { return device && *reinterpret_cast(device) == reinterpret_cast(get_vtable()); } +void* device_proxy_from_dxgi_device(void* dxgi_device) { + if (!dxgi_device || *static_cast(dxgi_device) != get_dxgi_vtable()) return nullptr; + return dxgi_owner(dxgi_device); +} + +void* device_proxy_primary(void* device) { + if (is_device_proxy(device)) return device; + return device_proxy_from_dxgi_device(device); +} + +bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { + auto* proxy = static_cast(device_proxy_primary(device)); + if (!proxy) { + // Not installing one silently would leave the host's adapter in its place. + std::fprintf(stderr, "[rt] d3d12_xs: set_device_adapter_provider: %p is not a device proxy; no provider set\n", + device); + return false; + } + proxy->adapter_provider = provider; + return true; +} + bool is_heap_proxy(const void* heap) { return heap && *reinterpret_cast(heap) == reinterpret_cast(get_heap_vtable()); } diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 76bbf5377..ed5d33ada 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -61,6 +61,24 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool co // True when `device` points at a proxy created by create_device_proxy. Used by the tests. bool is_device_proxy(const void* device); +// IDXGIDevice1 on the device. A GDKX title asks its device for IDXGIDevice1, then GetAdapter and EnumOutputs(0), +// to find the output it gives SetFrameIntervalX (docs/d3d12_vulkan.md section 4.5). The proxy answers IDXGIObject, +// IDXGIDevice and IDXGIDevice1 itself, as one COM object with the device (same reference count, QueryInterface +// both ways). GetAdapter and GetParent return the adapter of the device behind the proxy: by default the host DXGI +// adapter with that device's LUID. A provider replaces that: `real` is the device behind the proxy, and it returns +// the adapter as `riid`. rt::d3d12::set_device_outer sets one for the Vulkan-backed device (the layer's own adapter). +// +// A title may ask D3D12XboxCreateDevice (so create_device_proxy) for IDXGIDevice1 directly. What comes back then is +// the proxy's DXGI pointer, not the proxy: is_device_proxy is false for it. Code that takes "the proxy" from a +// creation call goes through device_proxy_primary first. +using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** out); +// `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither: nothing is set then. +bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider); +// The device proxy an IDXGIDevice pointer handed out by one belongs to, or null. +void* device_proxy_from_dxgi_device(void* dxgi_device); +// The device proxy itself, given the proxy or its DXGI pointer; null for anything else. +void* device_proxy_primary(void* device); + // True when `heap` is a descriptor-heap proxy created by device slot 14. bool is_heap_proxy(const void* heap); ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap); diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp index 734824e07..54aa57991 100644 --- a/runtime/shims/dxgi_com.cpp +++ b/runtime/shims/dxgi_com.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -26,6 +27,90 @@ void stub(const char* method) { if (seen.insert(method).second) std::fprintf(stderr, "[rt] dxgi: unimplemented %s\n", method); } +// IDXGIObject private data, shared by the factory, adapter and swapchain. SetPrivateData keeps a copy of the bytes; +// SetPrivateDataInterface holds one reference until the entry is replaced, removed or the owner dies (Microsoft: +// IDXGIObject::SetPrivateDataInterface). Zero bytes remove the entry. GetPrivateData gives an interface back with a +// reference added, and a buffer too small for the entry gets DXGI_ERROR_MORE_DATA and the size to retry with. +class PrivateDataStore { +public: + PrivateDataStore() = default; + PrivateDataStore(const PrivateDataStore&) = delete; + PrivateDataStore& operator=(const PrivateDataStore&) = delete; + ~PrivateDataStore() { + for (auto& entry : data_) + if (entry.object) entry.object->Release(); + } + + HRESULT get(REFGUID guid, UINT* size, void* data) { + if (!size) return E_INVALIDARG; + std::lock_guard lock(mutex_); + for (const auto& entry : data_) { + if (entry.key != guid) continue; + const UINT bytes = entry.object ? UINT(sizeof(IUnknown*)) : UINT(entry.bytes.size()); + if (data && *size < bytes) { + *size = bytes; + return DXGI_ERROR_MORE_DATA; + } + if (data) { + if (entry.object) { + entry.object->AddRef(); + std::memcpy(data, &entry.object, sizeof(IUnknown*)); + } else { + std::memcpy(data, entry.bytes.data(), bytes); + } + } + *size = bytes; + return S_OK; + } + *size = 0; + return DXGI_ERROR_NOT_FOUND; + } + + HRESULT set(REFGUID guid, UINT size, const void* data) { + if (size && !data) return E_INVALIDARG; + Entry entry{guid, {}, nullptr}; + if (size) { + const auto* bytes = static_cast(data); + entry.bytes.assign(bytes, bytes + size); + } + store(std::move(entry), size != 0); + return S_OK; + } + + HRESULT set_interface(REFGUID guid, const IUnknown* object) { + IUnknown* held = const_cast(object); + if (held) held->AddRef(); + store(Entry{guid, {}, held}, held != nullptr); + return S_OK; + } + +private: + struct Entry { + GUID key; + std::vector bytes; + IUnknown* object; + }; + + // The replaced interface is released after the lock is dropped, since its Release may run arbitrary code. + void store(Entry entry, bool keep) { + IUnknown* released = nullptr; + { + std::lock_guard lock(mutex_); + for (auto it = data_.begin(); it != data_.end(); ++it) { + if (it->key != entry.key) continue; + released = it->object; + data_.erase(it); + break; + } + if (keep) data_.push_back(std::move(entry)); + } + if (released) released->Release(); + } + + std::mutex mutex_; + std::vector data_; +}; + bool valid_flip_buffer_count(UINT count) { return count >= 2 && count <= DXGI_MAX_SWAP_CHAIN_BUFFERS; } @@ -177,9 +262,15 @@ public: } // IDXGIObject - HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override { + return private_data_.set(guid, size, data); + } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override { + return private_data_.set_interface(guid, object); + } + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override { + return private_data_.get(guid, size, data); + } HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { if (!out) return E_POINTER; *out = nullptr; @@ -481,6 +572,7 @@ private: } std::atomic refs_{1}; + PrivateDataStore private_data_; IDXGIFactory4* parent_ = nullptr; IUnknown* device_ = nullptr; leonida::VulkanContext& context_; @@ -573,9 +665,15 @@ public: } // IDXGIObject - HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override { + return private_data_.set(guid, size, data); + } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override { + return private_data_.set_interface(guid, object); + } + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override { + return private_data_.get(guid, size, data); + } HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { if (!out) return E_POINTER; *out = nullptr; @@ -767,6 +865,7 @@ private: std::atomic next_budget_cookie_{1}; std::atomic refs_{1}; + PrivateDataStore private_data_; IDXGIFactory4* parent_ = nullptr; PFN_vkGetInstanceProcAddr gipa_ = nullptr; VkInstance instance_ = VK_NULL_HANDLE; @@ -805,9 +904,15 @@ public: } // IDXGIObject - HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override { + return private_data_.set(guid, size, data); + } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override { + return private_data_.set_interface(guid, object); + } + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override { + return private_data_.get(guid, size, data); + } HRESULT STDMETHODCALLTYPE GetParent(REFIID, void** out) override { if (!out) return E_POINTER; *out = nullptr; @@ -883,6 +988,49 @@ public: HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, const DXGI_SWAP_CHAIN_FULLSCREEN_DESC*, IDXGIOutput* restrict_to_output, IDXGISwapChain1** out) override { + if (out) *out = nullptr; + if (const HRESULT hr = check_hwnd_swap_chain(device, hwnd, desc, out); FAILED(hr)) return hr; + return create_swap_chain(device, hwnd, desc, restrict_to_output, out); + } + + // What the host runtime's DXGI refuses for a D3D12 swap chain on a window (dxgi_swapchain_test compares these, + // RTX 5070 / 621.14): a null queue, window, description or output, an ID3D12Device in place of the queue, the + // bitblt effects, a scaling or alpha mode a window can't present, a flag outside the ones a D3D12 window swap chain + // takes (MODE_SWITCH, DISPLAY_ONLY, FRAME_LATENCY_WAITABLE_OBJECT, ALLOW_TEARING, the holographic restriction and + // 0x2000), a shared, read-only, discard-on-present or unordered-access buffer usage, MSAA, a buffer count outside + // 2..16 and a format the swap chain can't take are DXGI_ERROR_INVALID_CALL; a side above 16384 is E_INVALIDARG, + // only when nothing else is wrong. + static HRESULT check_hwnd_swap_chain(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, + IDXGISwapChain1** out) { + if (!device || !hwnd || !desc || !out) return DXGI_ERROR_INVALID_CALL; + ID3D12CommandQueue* queue = nullptr; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&queue))) || !queue) return DXGI_ERROR_INVALID_CALL; + queue->Release(); + if (desc->SwapEffect != DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL && desc->SwapEffect != DXGI_SWAP_EFFECT_FLIP_DISCARD) + return DXGI_ERROR_INVALID_CALL; + if (desc->Scaling != DXGI_SCALING_STRETCH && desc->Scaling != DXGI_SCALING_NONE) return DXGI_ERROR_INVALID_CALL; + if (desc->AlphaMode != DXGI_ALPHA_MODE_UNSPECIFIED && desc->AlphaMode != DXGI_ALPHA_MODE_IGNORE) + return DXGI_ERROR_INVALID_CALL; + constexpr UINT kWindowFlags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH | DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY | + DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT | + DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | 0x1000u | 0x2000u; + if (desc->Flags & ~kWindowFlags) return DXGI_ERROR_INVALID_CALL; + constexpr DXGI_USAGE kRefusedUsage = + DXGI_USAGE_SHARED | DXGI_USAGE_READ_ONLY | DXGI_USAGE_DISCARD_ON_PRESENT | DXGI_USAGE_UNORDERED_ACCESS; + if (desc->BufferUsage & kRefusedUsage) return DXGI_ERROR_INVALID_CALL; + // The host checks these before the size: MSAA 4 or one buffer at width 16385 is still INVALID_CALL. + if (desc->SampleDesc.Count != 1 || desc->SampleDesc.Quality != 0) return DXGI_ERROR_INVALID_CALL; + if (!valid_flip_buffer_count(desc->BufferCount)) return DXGI_ERROR_INVALID_CALL; + if (dxgi_to_vk_format(desc->Format) == VK_FORMAT_UNDEFINED) return DXGI_ERROR_INVALID_CALL; + if (desc->Width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION || desc->Height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) + return E_INVALIDARG; + return S_OK; + } + + // The swap chain itself, for a window or (through its HWND) a CoreWindow. The CoreWindow path keeps only these + // checks: the host's rules for it (ASPECT_RATIO_STRETCH, for one) can't be compared without a real CoreWindow. + HRESULT create_swap_chain(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, + IDXGIOutput* restrict_to_output, IDXGISwapChain1** out) { if (!out) return E_POINTER; *out = nullptr; if (!hwnd || !desc) return E_INVALIDARG; @@ -922,7 +1070,7 @@ public: const HRESULT hr = interop->get_WindowHandle(&hwnd); interop->Release(); if (FAILED(hr) || !hwnd) return DXGI_ERROR_INVALID_CALL; - return CreateSwapChainForHwnd(device, hwnd, desc, nullptr, restrict_to_output, out); + return create_swap_chain(device, hwnd, desc, restrict_to_output, out); } HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(HANDLE, LUID*) override { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(HWND, UINT, DWORD*) override { return E_NOTIMPL; } @@ -1047,6 +1195,7 @@ private: } std::atomic refs_{1}; + PrivateDataStore private_data_; leonida::VulkanContext& context_; PFN_vkGetInstanceProcAddr gipa_; VkInstance instance_; diff --git a/runtime/shims/dxgi_swapchain.h b/runtime/shims/dxgi_swapchain.h index 6c6684a66..531a49f28 100644 --- a/runtime/shims/dxgi_swapchain.h +++ b/runtime/shims/dxgi_swapchain.h @@ -166,7 +166,7 @@ public: } allow_tearing_ = allow_tearing; const VkFormat fmt = (preferred_format != VK_FORMAT_UNDEFINED) ? preferred_format : format_; - const std::uint32_t count = buffer_count ? buffer_count : static_cast(images_.size()); + const std::uint32_t count = buffer_count ? buffer_count : exposed_count_; return rebuild(width, height, fmt, count ? count : 2u); } @@ -177,11 +177,21 @@ public: &out_index); if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) return false; if (fn_.wait_for_fences(device_, 1, &acquire_fence_, VK_TRUE, timeout_ns) != VK_SUCCESS) return false; - current_index_ = out_index; + acquired_index_ = out_index; + if (is_offscreen()) { + // The native image count may differ from the DXGI BufferCount (Vulkan is free to return more + // images than minImageCount, and caps.minImageCount can exceed the app's request). The app's + // backbuffers are the stable offscreen ring; each present blits the current slot into whichever + // native image was acquired, so the exposed index never follows the native one. + current_index_ = next_back_buffer_; + next_back_buffer_ = (next_back_buffer_ + 1) % exposed_count_; + } else { + current_index_ = out_index; + } // D3D12 swapchain backbuffers begin in D3D12_RESOURCE_STATE_PRESENT; transition each newly acquired // native swapchain image once from UNDEFINED -> PRESENT_SRC_KHR so presenting an untouched backbuffer // or transitioning from PRESENT matches the tracked layout. - if (offscreen_images_.empty() && out_index < image_initialized_.size() && !image_initialized_[out_index]) { + if (!is_offscreen() && out_index < image_initialized_.size() && !image_initialized_[out_index]) { if (!transition_image_layout(images_[out_index], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR)) return false; @@ -190,10 +200,12 @@ public: return true; } - bool present(std::uint32_t image_index) { - if (!swapchain_ || image_index >= images_.size()) return false; - if (!offscreen_images_.empty()) { - if (!blit_to_swapchain(image_index)) return false; + bool present(std::uint32_t back_buffer_index) { + if (!swapchain_ || back_buffer_index >= exposed_count_ || acquired_index_ >= images_.size()) return false; + std::uint32_t image_index = back_buffer_index; + if (is_offscreen()) { + if (!blit_to_swapchain(back_buffer_index)) return false; + image_index = acquired_index_; } VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; pi.swapchainCount = 1; @@ -204,21 +216,24 @@ public: return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR; } - std::uint32_t image_count() const { return static_cast(images_.size()); } + // DXGI exposes exactly the BufferCount the app asked for (GetDesc/GetDesc1 and GetCurrentBackBufferIndex + // stay inside it). When Vulkan supplies a different number of native images the extra ones are hidden + // behind a stable offscreen ring (is_offscreen()). + std::uint32_t image_count() const { return exposed_count_; } std::uint32_t current_back_buffer_index() const { return current_index_; } VkFormat format() const { return format_; } VkExtent2D extent() const { return extent_; } bool is_offscreen() const { return !offscreen_images_.empty(); } VkPresentModeKHR present_mode() const { return present_mode_; } VkImage image(std::uint32_t i) const { - if (i >= images_.size()) return VK_NULL_HANDLE; - return !offscreen_images_.empty() ? offscreen_images_[i] : images_[i]; + if (i >= exposed_count_) return VK_NULL_HANDLE; + return is_offscreen() ? offscreen_images_[i] : images_[i]; } ResourceBinding resource_binding(std::uint32_t i) const { ResourceBinding b{}; - if (i >= images_.size()) return b; - const bool offscreen = !offscreen_images_.empty(); + if (i >= exposed_count_) return b; + const bool offscreen = is_offscreen(); b.image = offscreen ? offscreen_images_[i] : images_[i]; b.format = format_; b.aspects = VK_IMAGE_ASPECT_COLOR_BIT; @@ -280,6 +295,7 @@ private: } } images_.clear(); + exposed_count_ = 0; } bool create_offscreen_backbuffers(std::uint32_t count) { @@ -383,7 +399,10 @@ private: } bool blit_to_swapchain(std::uint32_t image_index) { - if (!blit_cmd_ || !blit_fence_ || image_index >= offscreen_images_.size()) return false; + if (!blit_cmd_ || !blit_fence_ || image_index >= offscreen_images_.size() || + acquired_index_ >= images_.size()) + return false; + const VkImage dst_image = images_[acquired_index_]; std::lock_guard lock(submit_mutex_); if (fn_.reset_fences(device_, 1, &blit_fence_) != VK_SUCCESS) return false; if (fn_.reset_cmd_buf(blit_cmd_, 0) != VK_SUCCESS) return false; @@ -409,7 +428,7 @@ private: pre[1].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; pre[1].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; pre[1].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - pre[1].image = images_[image_index]; + pre[1].image = dst_image; pre[1].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, @@ -422,7 +441,7 @@ private: region.dstOffsets[1] = {static_cast(surface_extent_.width), static_cast(surface_extent_.height), 1}; fn_.cmd_blit(blit_cmd_, offscreen_images_[image_index], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - images_[image_index], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion, VK_FILTER_LINEAR); + dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion, VK_FILTER_LINEAR); VkImageMemoryBarrier post[2]{}; post[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; @@ -442,7 +461,7 @@ private: post[1].newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; post[1].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; post[1].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - post[1].image = images_[image_index]; + post[1].image = dst_image; post[1].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, @@ -532,15 +551,27 @@ private: std::uint32_t img_count = 0; fn_.get_images(device_, swapchain_, &img_count, nullptr); + if (img_count == 0) return false; images_.resize(img_count); fn_.get_images(device_, swapchain_, &img_count, images_.data()); image_initialized_.assign(img_count, false); - if (extent_.width != surface_extent_.width || extent_.height != surface_extent_.height || - format_ != chosen.format) { - if (!create_offscreen_backbuffers(img_count)) return false; + const std::uint32_t requested = buffer_count ? buffer_count : 2u; + const bool blit_needed = extent_.width != surface_extent_.width || extent_.height != surface_extent_.height || + format_ != chosen.format; + if (blit_needed || img_count != requested) { + // A varying native count (Vulkan may return more images than minImageCount, and minImageCount may + // exceed the app's request) cannot be mapped one-to-one onto DXGI backbuffers: the app owns one + // persistent resource per BufferCount index. Expose the requested count as offscreen images and + // blit the presented slot into the acquired native image instead. + if (!create_offscreen_backbuffers(requested)) return false; + exposed_count_ = requested; + } else { + exposed_count_ = img_count; } current_index_ = 0; - return !images_.empty(); + next_back_buffer_ = 0; + acquired_index_ = 0; + return true; } SwapchainFunctions fn_{}; @@ -566,7 +597,10 @@ private: std::vector image_initialized_; std::vector offscreen_images_; std::vector offscreen_memory_; + std::uint32_t exposed_count_ = 0; std::uint32_t current_index_ = 0; + std::uint32_t acquired_index_ = 0; + std::uint32_t next_back_buffer_ = 0; }; } // namespace leonida diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp index 5b9f92199..014514597 100644 --- a/runtime/shims/file_system.cpp +++ b/runtime/shims/file_system.cpp @@ -393,9 +393,11 @@ Target write_target(const std::wstring& path, bool copy_up) { return t; } +// MAXIMUM_ALLOWED names no right and grants every one the file allows, write included, so it is a write-open: opened +// as a read it handed out a handle to the package file itself, and a WriteFile through it changed the package. bool writes(DWORD access, DWORD disposition) { - constexpr DWORD kWriteAccess = GENERIC_WRITE | GENERIC_ALL | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | - FILE_WRITE_ATTRIBUTES | DELETE | WRITE_DAC | WRITE_OWNER; + constexpr DWORD kWriteAccess = GENERIC_WRITE | GENERIC_ALL | MAXIMUM_ALLOWED | FILE_WRITE_DATA | FILE_APPEND_DATA | + FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | DELETE | WRITE_DAC | WRITE_OWNER; if ((access & kWriteAccess) != 0) return true; return disposition == CREATE_NEW || disposition == CREATE_ALWAYS || disposition == OPEN_ALWAYS || disposition == TRUNCATE_EXISTING; @@ -1043,12 +1045,50 @@ BOOL WINAPI copy_file_ex_a(LPCSTR from, LPCSTR to, LPPROGRESS_ROUTINE progress, return copy_file_ex_w(wide_from.c_str(), wide_to.c_str(), progress, data, cancel, flags); } +namespace { + +// The host's CopyFile2, or null where the host has none. Wine 9's kernel32 and kernelbase don't export it: Wine's +// loader binds a static import of it to a stub that aborts the process when called ("unimplemented function +// KERNEL32.dll.CopyFile2, aborting"), so a direct ::CopyFile2 call (or MSVC's std::filesystem::copy_file, which uses +// it) kills a title under Wine 9 or a Proton built on it; pe_loader.cpp and loader_tls_test.cpp avoid it for the same +// reason. GetProcAddress returns null there instead, and the fallback below runs. +using CopyFile2Fn = HRESULT(WINAPI*)(PCWSTR, PCWSTR, COPYFILE2_EXTENDED_PARAMETERS*); +CopyFile2Fn host_copy_file2() { + static const CopyFile2Fn fn = [] { + for (const wchar_t* dll : {L"kernelbase.dll", L"kernel32.dll"}) { + if (const HMODULE module = GetModuleHandleW(dll)) + if (const FARPROC p = GetProcAddress(module, "CopyFile2")) return reinterpret_cast(p); + } + return CopyFile2Fn{}; + }(); + return fn; +} + +// CopyFile2 through CopyFileExW, for hosts without it. The flags both calls define are passed on; the rest are +// CopyFile2-only hints and privilege requests (no offload, compressed traffic, low-free-space mode, ...) that don't +// change what a plain file copy produces, and CopyFileExW refuses flags it doesn't know. The cancel flag has the same +// type in both. A COPYFILE2 progress routine has another signature and message set, so it isn't called here. +HRESULT copy_file2_fallback(const wchar_t* source, const wchar_t* destination, + const COPYFILE2_EXTENDED_PARAMETERS* parameters) { + constexpr DWORD kCopyFileExFlags = COPY_FILE_FAIL_IF_EXISTS | COPY_FILE_RESTARTABLE | + COPY_FILE_OPEN_SOURCE_FOR_WRITE | COPY_FILE_ALLOW_DECRYPTED_DESTINATION | + COPY_FILE_COPY_SYMLINK | COPY_FILE_NO_BUFFERING; + const DWORD flags = parameters ? parameters->dwCopyFlags & kCopyFileExFlags : 0; + BOOL* const cancel = parameters ? parameters->pfCancel : nullptr; + if (::CopyFileExW(source, destination, nullptr, nullptr, cancel, flags)) return S_OK; + const DWORD error = GetLastError(); + return HRESULT_FROM_WIN32(error ? error : ERROR_GEN_FAILURE); +} + +} // namespace + HRESULT WINAPI copy_file2(PCWSTR from, PCWSTR to, COPYFILE2_EXTENDED_PARAMETERS* parameters) { const bool fail_if_exists = parameters && (parameters->dwCopyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0; std::filesystem::path source, destination; DWORD error = 0; if (!copy_paths(from, to, fail_if_exists, source, destination, error)) return HRESULT_FROM_WIN32(error); - return ::CopyFile2(source.c_str(), destination.c_str(), parameters); + if (const CopyFile2Fn host = host_copy_file2()) return host(source.c_str(), destination.c_str(), parameters); + return copy_file2_fallback(source.c_str(), destination.c_str(), parameters); } BOOL WINAPI set_file_attributes_w(LPCWSTR name, DWORD attributes) { diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index 69707f75a..2bc486042 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -16,6 +16,8 @@ // SDL_CreateHapticEffect/RunHapticEffect (IGameInputForceFeedbackEffect); haptic trigger motors, reported from the // trigger motors the pad already has, played as an intensity through the same trigger output as SetRumbleState // - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse +// - which kind of device the player used last (rt::gameinput::active_input, LEONIDA_PROMPTS), for the runtime's +// own use: the title is told every pad is an Xbox One pad // // One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when // LEONIDA_GAMEINPUT_THREAD=0. Title calls never touch SDL: they read the latest snapshot and leave rumble requests @@ -170,6 +172,19 @@ rt::gameinput::Config read_config() { else if (!k.empty() && k != "0" && k != "off") std::fprintf(stderr, "[rt] gameinput: LEONIDA_KEYBOARD_PAD=%s unknown (1, always or off), keyboard pad off\n", k.c_str()); + using leonida::InputFamily; + const std::string p = env("LEONIDA_PROMPTS"); + if (p == "xbox") c.prompts = InputFamily::Xbox; + else if (p == "playstation" || p == "ps5") c.prompts = InputFamily::PlayStation5; + else if (p == "ps4") c.prompts = InputFamily::PlayStation4; + else if (p == "ps3") c.prompts = InputFamily::PlayStation3; + else if (p == "nintendo" || p == "switch") c.prompts = InputFamily::Nintendo; + else if (p == "keyboard") c.prompts = InputFamily::Keyboard; + else if (!p.empty() && p != "auto") + std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS=%s unknown (auto, xbox, playstation, ps5, ps4, ps3, " + "nintendo or keyboard), following the devices\n", p.c_str()); + if (const std::string m = env("LEONIDA_PROMPTS_SWITCH_MS"); !m.empty()) + c.prompts_switch_ms = static_cast(std::clamp(std::atoi(m.c_str()), 0, 2000)); return c; } @@ -508,6 +523,7 @@ public: int sent_gain = -1; // device gain 0..100 last sent, so a steady gain costs one call uint32_t haptic_motors = 0; // trigger haptic motors the pad reports (0 or 2) rt::gameinput::OutputState sent{}; + leonida::InputFamily family = leonida::InputFamily::Xbox; // what kind of device it really is (active_input) Snapshot last_snap{}; // what the latest reading holds uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0; @@ -923,6 +939,79 @@ float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGa float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); } +bool is_keyboard_pad(SDL_JoystickID jid); // with the keyboard pad below + +// What kind of device a pad really is, for active_input(): SDL's gamepad type, which it takes from the vendor and +// product id. Anything SDL does not place (a generic or unknown pad, a GameCube adapter) counts as Xbox, the layout +// GameInput itself describes. +leonida::InputFamily family_of(SDL_JoystickID jid, SDL_Gamepad* p) { + using leonida::InputFamily; + if (is_keyboard_pad(jid)) return InputFamily::Keyboard; + switch (SDL_GetGamepadType(p)) { + case SDL_GAMEPAD_TYPE_PS5: return InputFamily::PlayStation5; + case SDL_GAMEPAD_TYPE_PS4: return InputFamily::PlayStation4; + case SDL_GAMEPAD_TYPE_PS3: return InputFamily::PlayStation3; + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT: + case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: return InputFamily::Nintendo; + default: return InputFamily::Xbox; + } +} + +// ---- active input (src/active_input.h) ---- +// +// The tracker is poll-thread state, under poll_mu like the rest of the poll. What it answers is published in one word, +// so active_input() needs no lock and never sees a family from one change with the generation of another: the family +// in bits 0-7, forced in bit 8, the generation from bit 16. +leonida::ActiveInputTracker g_tracker; +std::atomic g_active{0}; + +void publish_active() { + g_active.store(static_cast(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) | + (g_tracker.generation() << 16), + std::memory_order_release); +} + +leonida::InputSample sample_of(const Snapshot& s) { + static_assert(kButtonCount <= 32, "every SDL gamepad button needs a bit"); + leonida::InputSample out; + for (uint32_t i = 0; i < kButtonCount; ++i) // all of SDL's buttons: guide, touchpad and paddles included + if (s.buttons[i]) out.buttons |= 1u << i; + out.left_trigger = s.gamepad.leftTrigger; + out.right_trigger = s.gamepad.rightTrigger; + out.left_x = s.gamepad.leftThumbstickX; + out.left_y = s.gamepad.leftThumbstickY; + out.right_x = s.gamepad.rightThumbstickX; + out.right_y = s.gamepad.rightThumbstickY; + return out; +} + +// LEONIDA_PROMPTS and LEONIDA_PROMPTS_SWITCH_MS, applied at each poll: reload_config can change them at any time. +void apply_prompt_config() { + std::optional want; + uint32_t switch_ms; + { + std::lock_guard lock(g().mu); + want = g().config.prompts; + switch_ms = g().config.prompts_switch_ms; + } + leonida::ActiveInputTracker::Thresholds t = g_tracker.thresholds(); + t.min_switch_us = uint64_t{switch_ms} * 1000; + g_tracker.set_thresholds(t); + const std::optional now = + g_tracker.forced() ? std::optional(g_tracker.active()) : std::nullopt; + if (want == now) return; + g_tracker.force(want); + publish_active(); + if (want) + std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS: input family set to %s\n", + leonida::input_family_name(*want)); + else + std::fprintf(stderr, "[rt] gameinput: LEONIDA_PROMPTS cleared: input family follows the devices (%s now)\n", + leonida::input_family_name(g_tracker.active())); +} + Snapshot read_pad(Device* d) { SDL_Gamepad* p = d->pad; Snapshot s; @@ -1243,6 +1332,7 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) { } d->pad = p; d->id = jid; + d->family = family_of(jid, p); d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5; d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false); d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false); @@ -1343,6 +1433,7 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) { void close_pad(Device* d, uint64_t ts) { State& s = g(); + g_tracker.forget(d->id); // poll-thread state: a pad that comes back starts from a fresh baseline std::lock_guard lock(s.mu); const uint32_t old = d->status.exchange(GameInputDeviceNoStatus); SDL_CloseGamepad(d->pad); @@ -1636,6 +1727,8 @@ struct KeyboardPad { }; KeyboardPad g_keyboard; +bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; } + void detach_keyboard_pad() { if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js); if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id); @@ -1782,6 +1875,7 @@ void poll_once() { State& s = g(); std::lock_guard pl(s.poll_mu); if (!init_sdl()) return; + apply_prompt_config(); update_keyboard_pad(); SDL_UpdateGamepads(); const uint64_t now = now_us(); @@ -1818,6 +1912,15 @@ void poll_once() { const bool guide_changed = d->last_snap.guide != snap.guide; const bool changed = !(d->last_snap == snap); d->last_snap = snap; + // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button + // held changes nothing. + if (const leonida::InputEdge edge = g_tracker.observe(d->id, d->family, sample_of(snap), now); + edge != leonida::InputEdge::None) { + publish_active(); + if (!g_tracker.forced()) + std::fprintf(stderr, "[rt] gameinput: input in use: %s (%s, %s)\n", + leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge)); + } // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads // between its frames is never stuck at the last button event; pads without sensors only read on change, as // before. push_reading stamps last_reading_us, so the cadence follows the actual history. @@ -2447,6 +2550,11 @@ int connected_count() { return static_cast(g().connected.size()); } +ActiveInput active_input() { + const uint64_t v = g_active.load(std::memory_order_acquire); + return {static_cast(v & 0xFF), v >> 16, ((v >> 8) & 1) != 0}; +} + bool output_state(int i, OutputState* out) { std::lock_guard lock(g().mu); if (i < 0 || i >= static_cast(g().connected.size()) || !out) return false; diff --git a/runtime/shims/gameinput.h b/runtime/shims/gameinput.h index acee24e85..57dbfc503 100644 --- a/runtime/shims/gameinput.h +++ b/runtime/shims/gameinput.h @@ -5,6 +5,8 @@ #include #include +#include "../src/active_input.h" // leonida::InputFamily (and std::optional) for Config::prompts and active_input() + namespace rt::gameinput { // How the impulse-trigger motors (GameInputRumbleParams::leftTrigger/rightTrigger) reach a DualSense. @@ -15,6 +17,10 @@ enum class DsTriggerMode { Off, Rumble, Resistance }; enum class KeyboardPadMode { Off, Focused, Always }; struct Config { + // LEONIDA_PROMPTS=auto|xbox|playstation|ps5|ps4|ps3|nintendo|keyboard: a family that active_input() reports + // whatever is in use; unset or auto follows the devices. + std::optional prompts; + uint32_t prompts_switch_ms = 300; // LEONIDA_PROMPTS_SWITCH_MS, 0..2000: shortest time between two changes DsTriggerMode ds_triggers = DsTriggerMode::Rumble; // LEONIDA_DS_TRIGGERS=off|rumble|resistance float ds_trigger_gain = 1.0f; // LEONIDA_DS_TRIGGER_GAIN, 0..4, scales the effect strength float mouse_sensitivity = 1.0f; // LEONIDA_MOUSE_SENSITIVITY, 0.1..10, scales mouse movement @@ -40,6 +46,17 @@ void poll(); // Number of gamepads currently open by the backend (tests, gameinput_probe). int connected_count(); +// The kind of device the player used last (src/active_input.h has the rules), or the one LEONIDA_PROMPTS forces. +// The title is told every pad is an Xbox One pad; this is for the runtime's own use, such as button prompt glyphs. +// Safe from any thread. `generation` goes up by one with each change of `family`, so a reader can check it every +// frame and act only when it moved. Xbox, generation 0, until the first deliberate input. +struct ActiveInput { + leonida::InputFamily family = leonida::InputFamily::Xbox; + uint64_t generation = 0; + bool forced = false; // LEONIDA_PROMPTS set the family +}; +ActiveInput active_input(); + // The SDL haptic calls the shim makes, one entry per call, so a test can stand in for them: SDL's virtual joysticks // report no haptics, and a pad that does is the only other way to reach this path. `joystick` is the SDL_Joystick the // gamepad was opened from, `haptic` what open_joystick returned, `effect` is an SDL_HapticEffect. Returning null from diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp index 1fc4fee7f..0bca28443 100644 --- a/runtime/shims/process.cpp +++ b/runtime/shims/process.cpp @@ -5,8 +5,14 @@ // - argv/argc and the command line are the game's (set by run_entry), not gta6rt's; // - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host: // the exit code is recorded, the run is signalled as finished and the calling thread waits for the host to -// exit. atexit handlers and static destructors of the game are not run (its CRT shares the host's, whose -// process-wide atexit table also holds gta6rt's own). +// exit; +// - the game's atexit registrations (_crt_atexit, which MSVC's atexit and static destructors reach; msvcrt's +// atexit and _onexit) go to a table of the run's own instead of the CRT's process-wide one, which the game +// shares with gta6rt. exit() runs it newest first, as the CRT does, before the run ends; _exit(), _Exit(), +// quick_exit(), ExitProcess() and abort() do not. _cexit() runs it and returns, _c_exit() returns. A second +// thread that calls exit(), _exit(), _Exit() or quick_exit() while the first is leaving waits, as with the +// CRT's exit lock. Not covered yet: at_quick_exit() handlers (quick_exit() runs none) and the thread-local +// destructor callback (_register_thread_local_exe_atexit_callback); both still reach the host CRT. // Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and // msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. // The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a @@ -19,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -84,8 +92,77 @@ std::string narrow(const std::wstring& w) { ExitProcess(static_cast(g_exit_code.load())); } +// ---- the game's atexit table +using AtexitFn = void(__cdecl*)(); +using OnexitFn = int(__cdecl*)(); +std::mutex g_atexit_lock; +std::vector g_atexit; +std::atomic g_exiting_thread{0}; + +bool register_atexit(AtexitFn fn) { + std::lock_guard lock(g_atexit_lock); + try { + g_atexit.push_back(fn); + } catch (const std::bad_alloc&) { + return false; // the CRT reports a full table as a failed registration + } + return true; +} + +// Newest first. A handler registered while the handlers run goes on the end and so runs next, as in the UCRT. +void run_atexit_handlers() { + for (;;) { + AtexitFn fn; + { + std::lock_guard lock(g_atexit_lock); + if (g_atexit.empty()) return; + fn = g_atexit.back(); + g_atexit.pop_back(); + } + fn(); + } +} + +// UCRT: int _crt_atexit(_PVFV), 0 on success. MSVC's atexit() and the static destructors of an EXE reach it. +int __cdecl game_crt_atexit(AtexitFn fn) { + return fn && register_atexit(fn) ? 0 : -1; +} +// msvcrt.dll (MinGW): int atexit(void (*)(void)) and _onexit_t _onexit(_onexit_t). +int __cdecl game_msvcrt_atexit(AtexitFn fn) { return game_crt_atexit(fn); } +OnexitFn __cdecl game_onexit(OnexitFn fn) { + // its int result is ignored, as the CRT ignores it + return fn && register_atexit(reinterpret_cast(fn)) ? fn : nullptr; +} + // ---- the way out -void __cdecl game_exit(int code) { end_run(code); } +// The CRT's exit lock, which exit(), _exit(), _Exit() and quick_exit() all take: the first thread to leave owns it +// and ends the run; any other thread that tries to leave waits forever. The owner may leave again from a handler +// (undefined in C): that ends the run with the new code and skips the remaining handlers. +bool take_exit_lock() { + const DWORD self = GetCurrentThreadId(); + DWORD owner = 0; + if (g_exiting_thread.compare_exchange_strong(owner, self)) return true; + if (owner != self) { + for (;;) Sleep(INFINITE); + } + return false; +} +// exit(): the game's handlers and static destructors, then the end of the run. +void __cdecl game_exit(int code) { + if (take_exit_lock()) run_atexit_handlers(); + end_run(code); +} +// _exit(), _Exit(), quick_exit(): the end of the run without the atexit handlers. +void __cdecl game_quick_exit(int code) { + take_exit_lock(); + end_run(code); +} +// _cexit() runs the handlers and flushes the streams, then returns; _c_exit() only returns. +void __cdecl game_cexit() { + run_atexit_handlers(); + std::fflush(nullptr); +} +void __cdecl game_c_exit() {} void __stdcall game_exit_process(UINT code) { end_run(static_cast(code)); } void __cdecl game_abort() { std::fprintf(stderr, "[rt] process: the game called abort()\n"); @@ -203,6 +280,11 @@ void set_command_line(const std::wstring& program, const std::vector lock(g_atexit_lock); + g_atexit.clear(); // a run never sees the handlers of an earlier one + } + g_exiting_thread = 0; g_exited = false; g_exit_code = 0; g_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); @@ -242,8 +324,11 @@ int run_entry(void* entry, size_t stack_bytes) { namespace { using namespace rt::process; #define UCRT(dll) \ - {dll, "exit", reinterpret_cast(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_exit)}, \ - {dll, "_Exit", reinterpret_cast(&game_exit)}, {dll, "quick_exit", reinterpret_cast(&game_exit)}, \ + {dll, "exit", reinterpret_cast(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_quick_exit)}, \ + {dll, "_Exit", reinterpret_cast(&game_quick_exit)}, \ + {dll, "quick_exit", reinterpret_cast(&game_quick_exit)}, \ + {dll, "_crt_atexit", reinterpret_cast(&game_crt_atexit)}, \ + {dll, "_cexit", reinterpret_cast(&game_cexit)}, {dll, "_c_exit", reinterpret_cast(&game_c_exit)}, \ {dll, "abort", reinterpret_cast(&game_abort)}, {dll, "__p___argc", reinterpret_cast(&game_p_argc)}, \ {dll, "__p___argv", reinterpret_cast(&game_p_argv)}, \ {dll, "__p___wargv", reinterpret_cast(&game_p_wargv)}, \ @@ -264,7 +349,11 @@ SHIM_TABLE(process, UCRT("ucrtbase.dll"), UCRT("ucrtbased.dll"), // the Debug UCRT: a Debug build of the stand-in game (run_tiny_game) links it {"msvcrt.dll", "exit", reinterpret_cast(&game_exit)}, - {"msvcrt.dll", "_exit", reinterpret_cast(&game_exit)}, + {"msvcrt.dll", "_exit", reinterpret_cast(&game_quick_exit)}, + {"msvcrt.dll", "atexit", reinterpret_cast(&game_msvcrt_atexit)}, + {"msvcrt.dll", "_onexit", reinterpret_cast(&game_onexit)}, + {"msvcrt.dll", "_cexit", reinterpret_cast(&game_cexit)}, + {"msvcrt.dll", "_c_exit", reinterpret_cast(&game_c_exit)}, {"msvcrt.dll", "abort", reinterpret_cast(&game_abort)}, {"msvcrt.dll", "__getmainargs", reinterpret_cast(&game_getmainargs)}, {"msvcrt.dll", "__wgetmainargs", reinterpret_cast(&game_wgetmainargs)}, diff --git a/runtime/shims/winhttp_offline.cpp b/runtime/shims/winhttp_offline.cpp index 284f19eb1..10854d5f2 100644 --- a/runtime/shims/winhttp_offline.cpp +++ b/runtime/shims/winhttp_offline.cpp @@ -15,7 +15,8 @@ // WinHttpWriteData fail with ERROR_WINHTTP_INCORRECT_HANDLE_STATE: no request ever got that far. // - Options, timeouts and request headers are accepted. WINHTTP_OPTION_CONTEXT_VALUE is kept per handle and // WINHTTP_OPTION_HANDLE_TYPE answered; WinHttpQueryOption reports ERROR_WINHTTP_INVALID_OPTION for the rest. -// - A status callback set on a handle is inherited by the handles created under it, as in WinHTTP. +// - A status callback set on a handle is inherited by the handles created under it, as in WinHTTP, and so is +// the handle's WINHTTP_OPTION_CONTEXT_VALUE as it is when the child is made. // WINHTTP_CALLBACK_STATUS_HANDLE_CREATED is reported when a child handle is made, and // WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING once per handle, last, after WinHttpCloseHandle and any callback still // running for it. @@ -122,10 +123,12 @@ HINTERNET make_handle(Kind kind, Handle* parent, bool async) { h->parent = parent; h->async = async; if (parent) { - // A callback set on a handle is inherited by the handles created under it. + // A callback set on a handle is inherited by the handles created under it, and so is the context value + // (WINHTTP_OPTION_CONTEXT_VALUE), as the host's winhttp.dll does: what the parent has at this moment. std::lock_guard lock(parent->mutex); h->callback = parent->callback; h->notifications = parent->notifications; + h->context = parent->context; } { std::lock_guard lock(live_mutex()); diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp index 482c0ec5a..f6a8ec175 100644 --- a/runtime/shims/xgameruntime.cpp +++ b/runtime/shims/xgameruntime.cpp @@ -17,12 +17,15 @@ #include #include #include +#include #include +#include #include #include #include #include #include +#include #include #include @@ -31,6 +34,10 @@ #include "file_system.h" #include "shims.h" +namespace rt::shims { +bool xgameruntime_user_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr); +} + namespace { // ---- XGameRuntime ---- @@ -483,13 +490,18 @@ RuntimeObject g_networking{kNetworkingVtable, &kNetworkingClass, kNetworkingIids const GUID* const kPersistentStorageIids[] = {&kPersistentStorage2, &kPersistentStorage3, nullptr}; RuntimeObject g_persistent_storage{kPersistentStorageVtable, &kPersistentStorageClass, kPersistentStorageIids}; -RuntimeObject& system_object(); // XSystemImpl, defined after the XSystem functions it serves +RuntimeObject& system_object(); // XSystemImpl, defined after the XSystem functions it serves +RuntimeObject& package_object(); // XPackageImpl, after the XPackage functions +RuntimeObject& game_object(); // XGameImpl, after XPackageImpl HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** out) { if (out) *out = nullptr; if (class_id && out) { - for (RuntimeObject* o : {&g_threading, &g_error, &g_networking, &g_persistent_storage, &system_object()}) + for (RuntimeObject* o : {&g_threading, &g_error, &g_networking, &g_persistent_storage, &system_object(), + &package_object(), &game_object()}) if (*class_id == *o->class_id) return object_query_interface(o, interface_id, out); + HRESULT hr = S_OK; + if (rt::shims::xgameruntime_user_query(*class_id, interface_id, out, &hr)) return hr; // xgameruntime_user.cpp } char cls[40], iid[40]; print_guid(cls, class_id); @@ -840,6 +852,238 @@ bool __stdcall XPackageIsPackagedProcess() { return true; } +// ---- XPackageImpl (asked for as IXPackageImpl3), offline ---- +// +// libHttpClient.GDK.dll asks QueryApiImpl for XPackageImpl with IXPackageImpl3's id through 30 thunks (slots 3-19, +// 22, 24-27, 30, 32-34, 37-40), each in the argument shape of the method at that position of xgameruntime-docs' +// IXPackageImpl (slots 3-34), IXPackageImpl2 (35-38) and IXPackageImpl3 (39-40) lists (docs/runtime_imports.md). +// The slots with an offline answer forward to the XPackage functions above (the package identifier, whether the +// process is packaged, the mount path and its size, the user's locale); every other slot logs its number once and +// returns E_NOTIMPL, so the first boot shows which ones the title needs. + +constexpr GUID kPackageClass = {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}}; +// IXPackageImpl3 : IXPackageImpl2 : IXPackageImpl (xgameruntime include/xpackage.idl); the class id is its own. +constexpr GUID kPackage1 = {0x3720de07, 0xe8e4, 0x44a3, {0xad, 0x32, 0xb3, 0x59, 0xe8, 0xad, 0xbe, 0x55}}; +constexpr GUID kPackage2 = {0xf92d8712, 0x2b27, 0x4d8a, {0xbf, 0x01, 0x11, 0xa6, 0xf8, 0xe3, 0xeb, 0x42}}; +constexpr GUID kPackage3 = {0xe2a4734b, 0x2f4a, 0x456d, {0xaa, 0x8f, 0xd0, 0x65, 0xe0, 0x4f, 0xb2, 0x09}}; +const GUID* const kPackageIids[] = {&kPackage1, &kPackage2, &kPackage3, nullptr}; + +template HRESULT STDMETHODCALLTYPE package_not_implemented(void*) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XPackageImpl slot %d not implemented offline (E_NOTIMPL)\n", Slot); + return E_NOTIMPL; +} +HRESULT STDMETHODCALLTYPE pkg_identifier(void*, size_t size, char* buffer) { + return XPackageGetCurrentProcessPackageIdentifier(size, buffer); +} +bool STDMETHODCALLTYPE pkg_is_packaged(void*) { return XPackageIsPackagedProcess(); } +// The locales the package declares: in MicrosoftGame.Config, read from +// the game folder (LEONIDA_GAME_DIR, else --game-dir). Empty when there is no config or it declares none. +// The package's MicrosoftGame.Config as text, from the game folder (LEONIDA_GAME_DIR, else --game-dir); empty when +// there is no folder or no config. Wide on purpose: a game folder named outside the ANSI code page must reach the file +// intact. +std::string package_config() { + wchar_t env[MAX_PATH] = {}; + const DWORD n = GetEnvironmentVariableW(L"LEONIDA_GAME_DIR", env, MAX_PATH); + const std::filesystem::path dir = (n > 0 && n < MAX_PATH) ? std::filesystem::path(env) : rt::fs::game_dir(); + if (dir.empty()) return {}; + std::ifstream f(dir / L"MicrosoftGame.Config", std::ios::binary); + if (!f) return {}; + return std::string{std::istreambuf_iterator(f), {}}; +} + +std::vector package_locales() { + std::vector out; + const std::string xml = package_config(); + if (xml.empty()) return out; + for (size_t at = 0; (at = xml.find("', at); + const size_t key = xml.find("Language=", at); + if (end == std::string::npos || key == std::string::npos || key + 10 > end) continue; + const char quote = xml[key + 9]; + const size_t close = xml.find(quote, key + 10); + if ((quote == '"' || quote == '\'') && close != std::string::npos && close < end) + out.push_back(xml.substr(key + 10, close - key - 10)); + } + return out; +} + +// XPackageGetUserLocale(size_t localeSize, char* locale): of the locales the package declares, the one closest to +// the user's (the same name, else the same language, else the first declared). Microsoft's contract: "If no locale +// information is declared for the package, this function succeeds but does not return a user locale". The host's +// locale is never handed out as the package's. +HRESULT STDMETHODCALLTYPE pkg_user_locale(void*, size_t size, char* locale) { + if (!locale || !size) return E_INVALIDARG; + const std::vector declared = package_locales(); + if (declared.empty()) return S_OK; + wchar_t wide[LOCALE_NAME_MAX_LENGTH] = {}; + char user[LOCALE_NAME_MAX_LENGTH * 4] = ""; + if (GetUserDefaultLocaleName(wide, LOCALE_NAME_MAX_LENGTH) > 0) + WideCharToMultiByte(CP_UTF8, 0, wide, -1, user, static_cast(sizeof(user)), nullptr, nullptr); + const auto language = [](const std::string& name) { return name.substr(0, name.find('-')); }; + const auto same = [](const std::string& a, const std::string& b) { return _stricmp(a.c_str(), b.c_str()) == 0; }; + const std::string* pick = &declared.front(); + bool exact = false; + for (const std::string& d : declared) + if (same(d, user)) { pick = &d; exact = true; break; } + if (!exact) + for (const std::string& d : declared) + if (same(language(d), language(user))) { pick = &d; break; } + if (size < pick->size() + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); + std::memcpy(locale, pick->c_str(), pick->size() + 1); + return S_OK; +} +// Slots 23-26 forward to the named exports' content-package mounts (XPackageMount and its handle registry), so the two +// ways in behave the same. XPackageMountHandle is one u64, passed in a register like the named exports take it. +HRESULT STDMETHODCALLTYPE pkg_mount(void*, const char* package_identifier, XPackageMountHandle* mount) { + return XPackageMount(package_identifier, mount); +} +HRESULT STDMETHODCALLTYPE pkg_mount_path_size(void*, XPackageMountHandle mount, size_t* size) { + return XPackageGetMountPathSize(mount, size); +} +HRESULT STDMETHODCALLTYPE pkg_mount_path(void*, XPackageMountHandle mount, size_t size, char* path) { + return XPackageGetMountPath(mount, size, path); +} +void STDMETHODCALLTYPE pkg_close_mount(void*, XPackageMountHandle mount) { XPackageCloseMountHandle(mount); } + +// XPackageInstallationProgress: totalBytes, installedBytes, launchBytes (u64), launchable, completed (bool). +struct InstallationProgress { + uint64_t total_bytes, installed_bytes, launch_bytes; + bool launchable, completed; +}; +static_assert(sizeof(InstallationProgress) == 32, "XPackageInstallationProgress layout"); +// void XPackageGetInstallationProgress(monitor, XPackageInstallationProgress*): an offline package is installed, +// launchable and completed, every byte present. +void STDMETHODCALLTYPE pkg_installation_progress(void*, void*, InstallationProgress* progress) { + if (progress) *progress = {0, 0, 0, true, true}; +} +// The bool methods with no offline work, as Microsoft documents them: XPackageUpdateInstallationMonitor is false +// (nothing changed), the two Unregister* calls are true (nothing pending), XPackageUninstallPackage is false (not +// uninstalled). A generic E_NOTIMPL stub would read as true in al. +bool STDMETHODCALLTYPE pkg_update_monitor(void*, void*) { return false; } +bool STDMETHODCALLTYPE pkg_unregister_progress(void*, void*, XTaskQueueRegistrationToken, bool) { return true; } +bool STDMETHODCALLTYPE pkg_unregister_installed(void*, XTaskQueueRegistrationToken, bool) { return true; } +bool STDMETHODCALLTYPE pkg_uninstall_package(void*, const char*) { return false; } + +#define PN(n) reinterpret_cast(&package_not_implemented) +const void* const kPackageVtable[] = { + reinterpret_cast(&object_query_interface), reinterpret_cast(&object_add_ref), + reinterpret_cast(&object_release), + reinterpret_cast(&pkg_identifier), // 3 XPackageGetCurrentProcessPackageIdentifier + reinterpret_cast(&pkg_is_packaged), // 4 XPackageIsPackagedProcess + PN(5), PN(6), // 5-6 installation monitor: create, close + reinterpret_cast(&pkg_installation_progress), // 7 XPackageGetInstallationProgress (void, writes) + reinterpret_cast(&pkg_update_monitor), // 8 XPackageUpdateInstallationMonitor (bool) + PN(9), // 9 XPackageRegisterInstallationProgressChanged + reinterpret_cast(&pkg_unregister_progress), // 10 ...UnregisterInstallationProgressChanged (bool) + reinterpret_cast(&pkg_user_locale), // 11 XPackageGetUserLocale + PN(12), PN(13), PN(14), PN(15), PN(16), PN(17), // 12-19 chunks: find / enumerate availability, change order, + PN(18), PN(19), // install (+ async, result), estimate size, uninstall + PN(20), PN(21), // 20-21 _unknown_ (older enumerate / register installed) + reinterpret_cast(&pkg_unregister_installed), // 22 XPackageUnregisterPackageInstalled (bool) + reinterpret_cast(&pkg_mount), // 23 XPackageMount + reinterpret_cast(&pkg_mount_path_size), // 24 XPackageGetMountPathSize + reinterpret_cast(&pkg_mount_path), // 25 XPackageGetMountPath + reinterpret_cast(&pkg_close_mount), // 26 XPackageCloseMountHandle + PN(27), PN(28), PN(29), PN(30), PN(31), // 27 _unknown_, 28 EnumeratePackages, 29 RegisterPackageInstalled, + // 30 GetWriteStats, 31 _unknown_ + PN(32), PN(33), // 32 UninstallUWPInstance, 33 EnumerateFeatures + reinterpret_cast(&pkg_uninstall_package), // 34 XPackageUninstallPackage (bool) + PN(35), PN(36), PN(37), PN(38), // IXPackageImpl2: EnumeratePackages, RegisterPackageInstalled, + // MountWithUiAsync, MountWithUiResult + PN(39), PN(40), // IXPackageImpl3: EnumeratePackages, RegisterPackageInstalled +}; +#undef PN +static_assert(std::size(kPackageVtable) == 41, "IUnknown + IXPackageImpl's 32 + IXPackageImpl2's 4 + IXPackageImpl3's 2"); + +RuntimeObject& package_object() { + static RuntimeObject object{kPackageVtable, &kPackageClass, kPackageIids}; + return object; +} + +// ---- XGameImpl (asked for as IXGameImpl3), offline ---- +// +// IXGameImpl3 : IXGameImpl2 : IXGameImpl (xgameruntime include/xgame.idl); the class id is IXGameImpl's. Three +// methods after IUnknown: 3 XGameGetXboxTitleId (IXGameImpl), 4 XLaunchNewGame (IXGameImpl2), 5 XLaunchRestartOnCrash +// (IXGameImpl3). A retail Gen9 title asks QueryApiImpl for this class (Freminet/ScarlettX's README, observed on +// Concept Destruction); the executable here is not available yet, so its own requests are unmeasured. + +constexpr GUID kGameClass = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; +constexpr GUID kGame2 = {0x50849859, 0x0ad8, 0x4f81, {0x80, 0xe4, 0x5b, 0xc7, 0x86, 0x26, 0xf8, 0x52}}; +constexpr GUID kGame3 = {0x2549f142, 0x6419, 0x4a06, {0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34}}; +const GUID* const kGameIids[] = {&kGame2, &kGame3, nullptr}; + +// The title id MicrosoftGame.Config declares (, eight hex digits), or false when there is none or it is not +// hex. The first element counts; surrounding whitespace is allowed. +bool package_title_id(uint32_t& out) { + const std::string xml = package_config(); + const size_t open = xml.find(""); + if (open == std::string::npos) return false; + const size_t begin = xml.find_first_not_of(" \t\r\n", open + 9); + const size_t close = xml.find("", open); + if (begin == std::string::npos || close == std::string::npos || begin >= close) return false; + size_t end = close; + while (end > begin && std::isspace(static_cast(xml[end - 1]))) --end; + if (end - begin == 0 || end - begin > 8) return false; + uint32_t value = 0; + for (size_t i = begin; i < end; ++i) { + const char c = xml[i]; + const int digit = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 + : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; + if (digit < 0) return false; + value = value << 4 | static_cast(digit); + } + out = value; + return true; +} + +// HRESULT XGameGetXboxTitleId(uint32_t* titleId): the package's title id. Without a config that declares one there +// is no title id to give (E_FAIL), rather than a made-up one. +HRESULT STDMETHODCALLTYPE game_get_title_id(void*, uint32_t* title_id) { + if (!title_id) return E_INVALIDARG; + uint32_t id = 0; + if (!package_title_id(id)) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XGameGetXboxTitleId: no in MicrosoftGame.Config\n"); + return E_FAIL; + } + *title_id = id; + return S_OK; +} + +// void XLaunchNewGame(const char* exePath, const char* args, XUserHandle defaultUser): on the console this ends the +// title and starts another. Offline there is no other title to start; the call is logged and returns. +void STDMETHODCALLTYPE game_launch_new(void*, const char* exe_path, const char* args, void*) { + std::fprintf(stderr, "[rt] xgameruntime: XLaunchNewGame(\"%s\", \"%s\") ignored offline\n", + exe_path ? exe_path : "", args ? args : ""); +} + +// HRESULT XLaunchRestartOnCrash(const char* args, uint32_t reserved): asks the console to restart the title after a +// crash. Nothing restarts the process here; it succeeds with nothing registered. +HRESULT STDMETHODCALLTYPE game_restart_on_crash(void*, const char*, uint32_t) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XLaunchRestartOnCrash: no restart is registered offline\n"); + return S_OK; +} + +const void* const kGameVtable[] = { + reinterpret_cast(&object_query_interface), reinterpret_cast(&object_add_ref), + reinterpret_cast(&object_release), + reinterpret_cast(&game_get_title_id), // 3 XGameGetXboxTitleId (IXGameImpl) + reinterpret_cast(&game_launch_new), // 4 XLaunchNewGame (IXGameImpl2, void) + reinterpret_cast(&game_restart_on_crash), // 5 XLaunchRestartOnCrash (IXGameImpl3) +}; +static_assert(std::size(kGameVtable) == 6, "IUnknown + IXGameImpl3's 3 methods"); + +RuntimeObject& game_object() { + static RuntimeObject object{kGameVtable, &kGameClass, kGameIids}; + return object; +} + #define XGR(name) {"xgameruntime.dll", #name, reinterpret_cast(&name)} } // namespace diff --git a/runtime/shims/xgameruntime_user.cpp b/runtime/shims/xgameruntime_user.cpp new file mode 100644 index 000000000..0cc343393 --- /dev/null +++ b/runtime/shims/xgameruntime_user.cpp @@ -0,0 +1,539 @@ +// xgameruntime: XUserImpl, the class xgameruntime.lib's XUser* functions reach through QueryApiImpl, offline. +// +// A GDK title links XUserAddAsync, XUserGetId, XUserGetGamertag and the rest statically (xgameruntime.lib); each of +// those thunks asks QueryApiImpl for XUserImpl and calls one slot with the function's own arguments after `this` +// (docs/runtime_imports.md, "Run-time loaded modules"; xgameruntime.cpp serves the other classes the same way). +// The class and interface ids and the slot order are xodus-gaming/xgameruntime-docs' "Layout" lists (GPL-3.0; facts +// only, nothing copied). Signatures, enum values and error codes follow Microsoft's public GDK reference +// (learn.microsoft.com/gaming/gdk, XUser and Error Codes pages). No GDK header or library code is used. +// +// Offline there is one local user, always signed in: the default user XUserAddAsync returns (with or without +// AddDefaultUserSilently), with a fixed Xbox user id and local id, and a gamertag from LEONIDA_GAMERTAG (15 ASCII +// characters at most, "Player" otherwise). Nothing goes online: token and gamer-picture requests fail as they would +// without a network, and the user never changes, so registered change callbacks are never called. +// +// ASSUMPTION: the console executable is not available, so which of these slots it calls is unknown until its first +// boot. Private and PC-only slots log once when called, so that boot lists them. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +// ---- Public GDK types (XUser.h, as the GDK reference documents them) ---- + +using XUserHandle = struct XUserLocal*; // opaque to the title +using XUserSignOutDeferralHandle = struct XUserSignOutDeferral*; +struct XUserLocalId { + uint64_t value; +}; +enum class XUserAddOptions : uint32_t { None = 0x00, AddDefaultUserSilently = 0x01, AllowGuests = 0x02, AddDefaultUserAllowingUI = 0x04 }; +enum class XUserState : uint32_t { SignedIn = 0, SigningOut = 1, SignedOut = 2 }; +enum class XUserAgeGroup : uint32_t { Unknown = 0, Child = 1, Teen = 2, Adult = 3 }; +enum class XUserGamertagComponent : uint32_t { Classic = 0, Modern = 1, ModernSuffix = 2, UniqueModern = 3 }; +enum class XUserPrivilegeDenyReason : uint32_t { None = 0 }; +enum class XUserChangeEvent : uint32_t { SignedInAgain = 0 }; +using XUserChangeEventCallback = void(CALLBACK*)(void* context, XUserLocalId user, XUserChangeEvent event); + +// XGameErr.h values, from the GDK "Error codes" page. +constexpr HRESULT E_GAMEUSER_USER_NOT_FOUND = static_cast(0x89245104); +constexpr HRESULT E_GAMEUSER_DEFERRAL_NOT_AVAILABLE = static_cast(0x89245103); +constexpr HRESULT E_GAMEUSER_FAILED_TO_RESOLVE = static_cast(0x89245107); +constexpr HRESULT E_GAMEUSER_FAILED_TO_GET_TOKEN = static_cast(0x89245111); +constexpr HRESULT kInsufficientBuffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); + +// ---- The offline user ---- + +// Fixed, non-zero ids. The Xbox user id has the shape of a real XUID (a 64-bit number); nothing checks it offline. +constexpr uint64_t kOfflineXuid = 0x0009000000000001ull; +constexpr uint64_t kOfflineLocalId = 1; + +const char* gamertag() { + static char tag[16] = "Player"; + static std::once_flag once; + std::call_once(once, [] { + size_t length = 0; // with the terminator; 0 when unset + if (getenv_s(&length, nullptr, 0, "LEONIDA_GAMERTAG") != 0 || length <= 1) return; + if (length - 1 > 15) { + std::fprintf(stderr, "[rt] xgameruntime: LEONIDA_GAMERTAG is longer than 15 characters; using \"Player\"\n"); + return; + } + char value[16] = {}; + if (getenv_s(&length, value, "LEONIDA_GAMERTAG") != 0) return; + for (size_t i = 0; i + 1 < length; ++i) + if (static_cast(value[i]) < 0x20 || static_cast(value[i]) > 0x7e) { + std::fprintf(stderr, "[rt] xgameruntime: LEONIDA_GAMERTAG is not printable ASCII; using \"Player\"\n"); + return; + } + std::memcpy(tag, value, length); + }); + return tag; +} + +// A title must close every XUserHandle it gets exactly once, so each one is its own allocation; they all name the +// one local user. A handle is valid while it is in the live set: it's looked up, never read, so a closed or foreign +// pointer is refused without touching its memory. The block is freed on close, so the heap may hand its address out +// again; a stale handle then names a newer live one, which is harmless here since every handle names the same user. +struct XUserLocal { + uint32_t unused; +}; +std::mutex g_handles_mutex; +std::unordered_set g_handles; + +XUserHandle new_handle() { + auto* h = new XUserLocal{}; + std::lock_guard lock(g_handles_mutex); + g_handles.insert(h); + return h; +} +bool valid(XUserHandle h) { + if (!h) return false; + std::lock_guard lock(g_handles_mutex); + return g_handles.count(h) != 0; +} + +// ---- IXUserImpl (slots 3-36) ---- + +// 3: HRESULT XUserDuplicateHandle(XUserHandle handle, XUserHandle* duplicatedHandle) +HRESULT STDMETHODCALLTYPE user_duplicate(void*, XUserHandle handle, XUserHandle* dup) { + if (!dup) return E_POINTER; + *dup = nullptr; + if (!valid(handle)) return E_INVALIDARG; + *dup = new_handle(); + return S_OK; +} + +// 4: void XUserCloseHandle(XUserHandle user) +void STDMETHODCALLTYPE user_close(void*, XUserHandle user) { + { + std::lock_guard lock(g_handles_mutex); + if (!user || g_handles.erase(user) == 0) return; // closed already, or not ours + } + delete user; +} + +// 5: int32_t XUserCompare(XUserHandle user1, XUserHandle user2): 0 when both name the same user. Every valid handle +// names the one local user. +int32_t STDMETHODCALLTYPE user_compare(void*, XUserHandle a, XUserHandle b) { + const bool va = valid(a), vb = valid(b); + if (va && vb) return 0; + if (va != vb) return va ? 1 : -1; + return a == b ? 0 : (a < b ? -1 : 1); +} + +// 6: HRESULT XUserGetMaxUsers(uint32_t* maxUsers). One local user offline. +HRESULT STDMETHODCALLTYPE user_get_max_users(void*, uint32_t* max_users) { + if (!max_users) return E_POINTER; + *max_users = 1; + return S_OK; +} + +// XAsync providers. The result of an add is a new handle, created when the title collects it, so a result the +// title never collects leaks nothing. +const char kAddIdentity = 0; +const char kAddByIdIdentity = 0; +const char kResolveIdentity = 0; + +HRESULT CALLBACK add_provider(XAsyncOp op, const XAsyncProviderData* data) { + switch (op) { + case XAsyncOp::Begin: + return XAsyncSchedule(data->async, 0); + case XAsyncOp::DoWork: + XAsyncComplete(data->async, S_OK, sizeof(XUserHandle)); + return S_OK; + case XAsyncOp::GetResult: + if (data->bufferSize < sizeof(XUserHandle) || !data->buffer) return E_INVALIDARG; + *static_cast(data->buffer) = new_handle(); + return S_OK; + default: + return S_OK; + } +} + +// The add-by-id flavour: the context is the requested id; an id other than the local user's completes with +// E_GAMEUSER_USER_NOT_FOUND (no other user can sign in offline). +HRESULT CALLBACK add_by_id_provider(XAsyncOp op, const XAsyncProviderData* data) { + switch (op) { + case XAsyncOp::Begin: + return XAsyncSchedule(data->async, 0); + case XAsyncOp::DoWork: { + const bool known = reinterpret_cast(data->context) == static_cast(kOfflineXuid); + XAsyncComplete(data->async, known ? S_OK : E_GAMEUSER_USER_NOT_FOUND, known ? sizeof(XUserHandle) : 0); + return S_OK; + } + case XAsyncOp::GetResult: + if (data->bufferSize < sizeof(XUserHandle) || !data->buffer) return E_INVALIDARG; + *static_cast(data->buffer) = new_handle(); + return S_OK; + default: + return S_OK; + } +} + +// Resolving a privilege: every privilege is granted offline, so there is nothing to show; completes with S_OK. +HRESULT CALLBACK resolve_provider(XAsyncOp op, const XAsyncProviderData* data) { + if (op == XAsyncOp::Begin) return XAsyncSchedule(data->async, 0); + if (op == XAsyncOp::DoWork) XAsyncComplete(data->async, S_OK, 0); + return S_OK; +} + +// 7: HRESULT XUserAddAsync(XUserAddOptions options, XAsyncBlock* async). AllowGuests with AddDefaultUserSilently is +// refused, as documented ("A guest cannot be the default user"). Without a silent option the console would show the +// account picker; offline the one user is the answer either way. +HRESULT STDMETHODCALLTYPE user_add_async(void*, XUserAddOptions options, XAsyncBlock* async) { + if (!async) return E_POINTER; + const auto bits = static_cast(options); + if ((bits & static_cast(XUserAddOptions::AddDefaultUserSilently)) && + (bits & static_cast(XUserAddOptions::AllowGuests))) + return E_INVALIDARG; + return XAsyncBegin(async, nullptr, &kAddIdentity, "XUserAddAsync", add_provider); +} + +// 8: HRESULT XUserAddResult(XAsyncBlock* async, XUserHandle* newUser) +HRESULT STDMETHODCALLTYPE user_add_result(void*, XAsyncBlock* async, XUserHandle* user) { + if (!user) return E_POINTER; + *user = nullptr; + return XAsyncGetResult(async, &kAddIdentity, sizeof(*user), user, nullptr); +} + +// 9: HRESULT XUserGetLocalId(XUserHandle user, XUserLocalId* userLocalId) +HRESULT STDMETHODCALLTYPE user_get_local_id(void*, XUserHandle user, XUserLocalId* id) { + if (!id) return E_POINTER; + if (!valid(user)) return E_INVALIDARG; + id->value = kOfflineLocalId; + return S_OK; +} + +// 10: HRESULT XUserFindUserByLocalId(XUserLocalId userLocalId, XUserHandle* handle) +HRESULT STDMETHODCALLTYPE user_find_by_local_id(void*, XUserLocalId id, XUserHandle* handle) { + if (!handle) return E_POINTER; + *handle = nullptr; + if (id.value != kOfflineLocalId) return E_GAMEUSER_USER_NOT_FOUND; + *handle = new_handle(); + return S_OK; +} + +// 11: HRESULT XUserGetId(XUserHandle user, uint64_t* userId) +HRESULT STDMETHODCALLTYPE user_get_id(void*, XUserHandle user, uint64_t* id) { + if (!id) return E_POINTER; + if (!valid(user)) return E_INVALIDARG; + *id = kOfflineXuid; + return S_OK; +} + +// 12: HRESULT XUserFindUserById(uint64_t userId, XUserHandle* handle) +HRESULT STDMETHODCALLTYPE user_find_by_id(void*, uint64_t id, XUserHandle* handle) { + if (!handle) return E_POINTER; + *handle = nullptr; + if (id != kOfflineXuid) return E_GAMEUSER_USER_NOT_FOUND; + *handle = new_handle(); + return S_OK; +} + +// 13: HRESULT XUserGetIsGuest(XUserHandle user, bool* isGuest) +HRESULT STDMETHODCALLTYPE user_get_is_guest(void*, XUserHandle user, bool* guest) { + if (!guest) return E_POINTER; + if (!valid(user)) return E_INVALIDARG; + *guest = false; + return S_OK; +} + +// 14: HRESULT XUserGetState(XUserHandle user, XUserState* state) +HRESULT STDMETHODCALLTYPE user_get_state(void*, XUserHandle user, XUserState* state) { + if (!state) return E_POINTER; + if (!valid(user)) return E_INVALIDARG; + *state = XUserState::SignedIn; + return S_OK; +} + +// A slot with no public signature, logged once. Slot 15 (the docs' "unknown") answers E_NOTIMPL, so a caller fails +// instead of reading outputs nothing wrote. Slot 47, IXUserImpl6's undocumented XUserIsSignOutPresent, is read as a +// bool, where E_NOTIMPL's low byte (1) would mean true, so it answers 0 (false: nothing signs out offline). +template HRESULT STDMETHODCALLTYPE unknown_slot(void*) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XUserImpl slot %d has no public signature; answering E_NOTIMPL\n", Slot); + return E_NOTIMPL; +} +template uint64_t STDMETHODCALLTYPE private_slot(void*) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XUserImpl private slot %d called; answering 0\n", Slot); + return 0; +} + +// An operation that needs the network or a system UI the offline runtime doesn't have. The *Async function fails +// before starting, so the XAsyncBlock is never used and no callback runs; its Result/ResultSize partners return the +// same error. Their arguments don't matter, so the functions take none (x64: the caller owns the argument area). +template HRESULT STDMETHODCALLTYPE offline_failure(void*) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XUserImpl slot %d is not available offline (HRESULT 0x%08lx)\n", Slot, + static_cast(Error)); + return Error; +} + +// 19: HRESULT XUserGetAgeGroup(XUserHandle user, XUserAgeGroup* ageGroup) +HRESULT STDMETHODCALLTYPE user_get_age_group(void*, XUserHandle user, XUserAgeGroup* group) { + if (!group) return E_POINTER; + if (!valid(user)) return E_INVALIDARG; + *group = XUserAgeGroup::Adult; + return S_OK; +} + +// 20: HRESULT XUserCheckPrivilege(XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege, +// bool* hasPrivilege, XUserPrivilegeDenyReason* reason). Everything is allowed offline +// (multiplayer and the like then fail at the network, as on a console without one). +HRESULT STDMETHODCALLTYPE user_check_privilege(void*, XUserHandle user, uint32_t, uint32_t, bool* has, + XUserPrivilegeDenyReason* reason) { + if (!has) return E_POINTER; + if (!valid(user)) return E_INVALIDARG; + *has = true; + if (reason) *reason = XUserPrivilegeDenyReason::None; + return S_OK; +} + +// 21: HRESULT XUserResolvePrivilegeWithUiAsync(XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege, +// XAsyncBlock* async) +HRESULT STDMETHODCALLTYPE user_resolve_privilege_async(void*, XUserHandle user, uint32_t, uint32_t, XAsyncBlock* async) { + if (!async) return E_POINTER; + if (!valid(user)) return E_INVALIDARG; + return XAsyncBegin(async, nullptr, &kResolveIdentity, "XUserResolvePrivilegeWithUiAsync", resolve_provider); +} + +// 22: HRESULT XUserResolvePrivilegeWithUiResult(XAsyncBlock* async) +HRESULT STDMETHODCALLTYPE user_resolve_privilege_result(void*, XAsyncBlock* async) { + return XAsyncGetResult(async, &kResolveIdentity, 0, nullptr, nullptr); +} + +// 33: HRESULT XUserRegisterForChangeEvent(XTaskQueueHandle queue, void* context, XUserChangeEventCallback* callback, +// XTaskQueueRegistrationToken* token) +// 34: bool XUserUnregisterForChangeEvent(XTaskQueueRegistrationToken token, bool wait) +// The user never changes offline, so the callbacks are kept only as tokens. +std::mutex g_tokens_mutex; +std::set g_tokens; +uint64_t g_next_token = 1; + +HRESULT STDMETHODCALLTYPE user_register_change(void*, XTaskQueueHandle, void*, XUserChangeEventCallback callback, + XTaskQueueRegistrationToken* token) { + if (!callback || !token) return E_POINTER; + std::lock_guard lock(g_tokens_mutex); + token->token = g_next_token++; + g_tokens.insert(token->token); + return S_OK; +} + +// false means "wait was false and the unregistration is still pending"; nothing is ever pending offline, so it is +// true for every token, including one already unregistered or never handed out (a title polling with wait = false +// would otherwise spin). +bool STDMETHODCALLTYPE user_unregister_change(void*, XTaskQueueRegistrationToken token, bool) { + std::lock_guard lock(g_tokens_mutex); + g_tokens.erase(token.token); + return true; +} + +// 35: HRESULT XUserGetSignOutDeferral(XUserSignOutDeferralHandle* deferral): nothing signs out offline, so there is +// no sign-out to defer (the documented E_GAMEUSER_DEFERRAL_NOT_AVAILABLE). +HRESULT STDMETHODCALLTYPE user_get_signout_deferral(void*, XUserSignOutDeferralHandle* deferral) { + if (deferral) *deferral = nullptr; + return E_GAMEUSER_DEFERRAL_NOT_AVAILABLE; +} + +// 36: void XUserCloseSignOutDeferralHandle(XUserSignOutDeferralHandle deferral) +void STDMETHODCALLTYPE user_close_signout_deferral(void*, XUserSignOutDeferralHandle) {} + +// ---- IXUserImpl2 (37-38) ---- + +// 37: HRESULT XUserAddByIdWithUiAsync(uint64_t userId, XAsyncBlock* async) +HRESULT STDMETHODCALLTYPE user_add_by_id_async(void*, uint64_t id, XAsyncBlock* async) { + if (!async) return E_POINTER; + return XAsyncBegin(async, reinterpret_cast(static_cast(id)), &kAddByIdIdentity, + "XUserAddByIdWithUiAsync", add_by_id_provider); +} + +// 38: HRESULT XUserAddByIdWithUiResult(XAsyncBlock* async, XUserHandle* newUser) +HRESULT STDMETHODCALLTYPE user_add_by_id_result(void*, XAsyncBlock* async, XUserHandle* user) { + if (!user) return E_POINTER; + *user = nullptr; + return XAsyncGetResult(async, &kAddByIdIdentity, sizeof(*user), user, nullptr); +} + +// ---- IXUserImpl4 (42) ---- + +// 42: bool XUserIsStoreUser(XUserHandle user): the handle is _In_opt_, and the GDK reference says the function +// always returns true on console. +bool STDMETHODCALLTYPE user_is_store_user(void*, XUserHandle) { return true; } + +// ---- IXUserGamertagImpl (its slot 3) ---- + +// HRESULT XUserGetGamertag(XUserHandle user, XUserGamertagComponent component, size_t gamertagSize, char* gamertag, +// size_t* gamertagUsed). The offline user has a classic gamertag: Modern and UniqueModern are +// the same text (a classic tag has no '#' and no suffix) and ModernSuffix is empty. gamertagUsed counts the +// terminator. +HRESULT STDMETHODCALLTYPE user_get_gamertag(void*, XUserHandle user, XUserGamertagComponent component, size_t size, + char* out, size_t* used) { + if (used) *used = 0; + if (!valid(user)) return E_INVALIDARG; + const char* text = nullptr; + switch (component) { + case XUserGamertagComponent::Classic: + case XUserGamertagComponent::Modern: + case XUserGamertagComponent::UniqueModern: + text = gamertag(); + break; + case XUserGamertagComponent::ModernSuffix: + text = ""; + break; + default: + return E_INVALIDARG; + } + const size_t need = std::strlen(text) + 1; + if (!out || size < need) return kInsufficientBuffer; + std::memcpy(out, text, need); + if (used) *used = need; + return S_OK; +} + +// ---- The object: one vtable for the IXUserImpl..IXUserImpl6 chain, one for IXUserGamertagImpl ---- + +constexpr GUID kUserClass = {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}}; +// IXUserImpl's id is the class id; IXUserImpl2..6 extend it, so each of them answers with the same vtable. +constexpr GUID kUserInterfaces[] = { + kUserClass, + {0xeb9bf948, 0x18dc, 0x4d82, {0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0}}, // IXUserImpl2 + {0x1bf2f8c5, 0xd507, 0x4e52, {0xbb, 0x05, 0xf7, 0x26, 0xd0, 0xe7, 0x11, 0x61}}, // IXUserImpl3 + {0x079415e3, 0x6727, 0x437f, {0x8e, 0x9d, 0x8f, 0x8f, 0x9b, 0x24, 0x39, 0xf7}}, // IXUserImpl4 + {0x26f3c674, 0xa2fe, 0x44fa, {0xb6, 0xc4, 0xa3, 0x23, 0xbc, 0x94, 0xff, 0x53}}, // IXUserImpl5 + {0x5131d685, 0x4394, 0x4ee6, {0x8c, 0x18, 0xbf, 0xb5, 0xd4, 0xae, 0xf1, 0xff}}, // IXUserImpl6 +}; +constexpr GUID kGamertagInterface = {0xcef4fac0, 0x7676, 0x4a94, {0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74}}; +constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; + +struct UserObject { + const void* const* vtable; // IXUserImpl6 + const void* const* gamertag_vtable; // IXUserGamertagImpl +}; +UserObject* user_object(); + +HRESULT query(REFIID iid, void** out) { + if (!out) return E_POINTER; + *out = nullptr; + UserObject* o = user_object(); + if (iid == kIUnknown) { + *out = &o->vtable; + return S_OK; + } + for (const GUID& id : kUserInterfaces) + if (iid == id) { + *out = &o->vtable; + return S_OK; + } + if (iid == kGamertagInterface) { + *out = &o->gamertag_vtable; + return S_OK; + } + return E_NOINTERFACE; +} + +// A process-wide singleton, as the other runtime classes: AddRef and Release don't free. +HRESULT STDMETHODCALLTYPE object_query_interface(void*, REFIID iid, void** out) { return query(iid, out); } +ULONG STDMETHODCALLTYPE object_add_ref(void*) { return 2; } +ULONG STDMETHODCALLTYPE object_release(void*) { return 1; } + +#define FN(f) reinterpret_cast(&f) + +const void* const kUserVtable[] = { + FN(object_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown + FN(user_duplicate), // 3 XUserDuplicateHandle + FN(user_close), // 4 XUserCloseHandle + FN(user_compare), // 5 XUserCompare + FN(user_get_max_users), // 6 XUserGetMaxUsers + FN(user_add_async), // 7 XUserAddAsync + FN(user_add_result), // 8 XUserAddResult + FN(user_get_local_id), // 9 XUserGetLocalId + FN(user_find_by_local_id), // 10 XUserFindUserByLocalId + FN(user_get_id), // 11 XUserGetId + FN(user_find_by_id), // 12 XUserFindUserById + FN(user_get_is_guest), // 13 XUserGetIsGuest + FN(user_get_state), // 14 XUserGetState + FN(unknown_slot<15>), // 15 (unknown in the docs) + FN((offline_failure<16, E_FAIL>)), // 16 XUserGetGamerPictureAsync + FN((offline_failure<17, E_FAIL>)), // 17 XUserGetGamerPictureResultSize + FN((offline_failure<18, E_FAIL>)), // 18 XUserGetGamerPictureResult + FN(user_get_age_group), // 19 XUserGetAgeGroup + FN(user_check_privilege), // 20 XUserCheckPrivilege + FN(user_resolve_privilege_async), // 21 XUserResolvePrivilegeWithUiAsync + FN(user_resolve_privilege_result), // 22 XUserResolvePrivilegeWithUiResult + FN((offline_failure<23, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 23 XUserGetTokenAndSignatureAsync + FN((offline_failure<24, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 24 ...ResultSize + FN((offline_failure<25, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 25 ...Result + FN((offline_failure<26, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 26 XUserGetTokenAndSignatureUtf16Async + FN((offline_failure<27, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 27 ...Utf16ResultSize + FN((offline_failure<28, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 28 ...Utf16Result + FN((offline_failure<29, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 29 XUserResolveIssueWithUiAsync + FN((offline_failure<30, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 30 XUserResolveIssueWithUiResult + FN((offline_failure<31, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 31 XUserResolveIssueWithUiUtf16Async + FN((offline_failure<32, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 32 XUserResolveIssueWithUiUtf16Result + FN(user_register_change), // 33 XUserRegisterForChangeEvent + FN(user_unregister_change), // 34 XUserUnregisterForChangeEvent + FN(user_get_signout_deferral), // 35 XUserGetSignOutDeferral + FN(user_close_signout_deferral), // 36 XUserCloseSignOutDeferralHandle + FN(user_add_by_id_async), // 37 XUserAddByIdWithUiAsync (2) + FN(user_add_by_id_result), // 38 XUserAddByIdWithUiResult (2) + FN((offline_failure<39, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 39 XUserGetMsaTokenSilentlyAsync (3) + FN((offline_failure<40, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 40 ...Result (3) + FN((offline_failure<41, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 41 ...ResultSize (3) + FN(user_is_store_user), // 42 XUserIsStoreUser (4) + FN((offline_failure<43, E_NOTIMPL>)), // 43 XUserPlatformRemoteConnectSetEventHandlers (5, PC) + FN((offline_failure<44, E_NOTIMPL>)), // 44 XUserPlatformRemoteConnectCancelPrompt (5, PC) + FN((offline_failure<45, E_NOTIMPL>)), // 45 XUserPlatformSpopPromptSetEventHandlers (5, PC) + FN((offline_failure<46, E_NOTIMPL>)), // 46 XUserPlatformSpopPromptComplete (5, PC) + FN(private_slot<47>), // 47 XUserIsSignOutPresent (6): false + FN((offline_failure<48, E_NOTIMPL>)), // 48 XUserSignOutAsync (6) + FN((offline_failure<49, E_NOTIMPL>)), // 49 XUserSignOutResult (6) +}; +static_assert(std::size(kUserVtable) == 50, "IUnknown + IXUserImpl's 34 methods + 2 + 3 + 1 + 4 + 3"); + +// The gamertag face's IUnknown slots get `this` = &gamertag_vtable; the object is a singleton, so they ignore it. +const void* const kGamertagVtable[] = { + FN(object_query_interface), FN(object_add_ref), FN(object_release), + FN(user_get_gamertag), // 3 XUserGetGamertag +}; + +#undef FN + +UserObject* user_object() { + static UserObject o{kUserVtable, kGamertagVtable}; + return &o; +} + +} // namespace + +namespace rt::shims { + +// Called by xgameruntime.cpp's QueryApiImpl for every class: true when the class is XUserImpl, with *hr set. +bool xgameruntime_user_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr) { + if (class_id != kUserClass) return false; + *hr = query(interface_id, out); + return true; +} + +// For tests: the XUserHandles a title holds open. +long xgameruntime_user_open_handles() { + std::lock_guard lock(g_handles_mutex); + return static_cast(g_handles.size()); +} + +} // namespace rt::shims diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index e925d3ee4..c7cfb76c0 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -10,6 +10,7 @@ // site shows the alignment/type fields, every block is 64-byte aligned (covers cache lines and SIMD) and a size of // zero is rounded up to one byte so the result is a stable, non-null pointer that XMemFree can release. #include +#include #include #include @@ -18,16 +19,46 @@ #include #include #include +#include +#include +#include #include "shims.h" +#include "startup_trace.h" namespace { constexpr size_t kAlign = 64; -void* __stdcall XMemAlloc(size_t size, uint64_t /*attributes*/) { return _aligned_malloc(size ? size : 1, kAlign); } +// gta6rt --trace FILE: the first XMemAlloc and the first XMemFree for each distinct raw attribute word go to the +// startup trace as an "xmem_attributes" event (api, the word, the size for an allocation, the caller as module+RVA). The +// bits of the attribute word are not known yet; this records them from a real run without logging every allocation, +// which would fill the file. Off: one relaxed load per call. +void note_attributes(bool is_alloc, uint64_t attributes, size_t size, const void* caller) { + if (!rt::startup_trace::enabled()) return; + static std::mutex mutex; + static std::set> seen; + { + const std::lock_guard lock(mutex); + if (!seen.insert({is_alloc, attributes}).second) return; + } + std::string fields = std::string("\"api\":\"") + (is_alloc ? "XMemAlloc" : "XMemFree") + + "\",\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes)); + if (is_alloc) fields += ",\"size\":" + std::to_string(size); + fields += ",\"caller\":" + + rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller))); + rt::startup_trace::event("xmem_attributes", fields); +} -void __stdcall XMemFree(void* p, uint64_t /*attributes*/) { _aligned_free(p); } +void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { + note_attributes(true, attributes, size, _ReturnAddress()); + return _aligned_malloc(size ? size : 1, kAlign); +} + +void __stdcall XMemFree(void* p, uint64_t attributes) { + note_attributes(false, attributes, 0, _ReturnAddress()); + _aligned_free(p); +} // Measured call sites pass a zeroed 64-byte structure. Only the MEMORY_BASIC_INFORMATION-compatible prefix is // known: callers read at least the base and size fields. Fill that prefix from VirtualQueryEx and zero the rest. @@ -64,8 +95,10 @@ SIZE_T __stdcall XMemVirtualQuery(HANDLE process, const void* address, void* out // 0x75b1): ECX is the constant 0x20000001 (its meaning is not known) and RDX points at a stack buffer (0x80 bytes // where the frame shows it). The caller reads a 64-bit size at +8 and treats a zero return as "no data". Taking the // pointer from the first argument wrote to address 0x20000001. -// Only the first 16 bytes are touched: zero at +0 (unknown) and the process working set at +8. Do not claim more of -// the struct than is measured. +// The measured FSR sites establish argument shape, kind and the 64-bit working-set read at +8; +0's title-total memory +// limit interpretation is inferred from other Series implementations (xcl, xbox-emulator) and title engine telemetry +// sizing memory pools (RT-220). Note that if GlobalMemoryStatusEx reports 0 physical memory, XMem falls back to the +// 12 GiB title limit, whereas XSystemGetAppMemoryUsageLimit remains 0. BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) { if (!stats) { static std::atomic warned{false}; @@ -78,8 +111,15 @@ BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) { PROCESS_MEMORY_COUNTERS pmc{}; if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return FALSE; + MEMORYSTATUSEX ms{sizeof(ms)}; + uint64_t total_memory = 12ULL * 1024 * 1024 * 1024; + if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { + total_memory = ms.ullTotalPhys; + } + uint8_t* bytes = static_cast(stats); std::memset(bytes, 0, 16); + std::memcpy(bytes + 0, &total_memory, sizeof(total_memory)); uint64_t working_set = pmc.WorkingSetSize; std::memcpy(bytes + 8, &working_set, sizeof(working_set)); return TRUE; diff --git a/runtime/src/active_input.h b/runtime/src/active_input.h new file mode 100644 index 000000000..c0f7451b1 --- /dev/null +++ b/runtime/src/active_input.h @@ -0,0 +1,146 @@ +#pragma once + +// Which kind of input device the player used last: an Xbox-style pad, a PlayStation pad, a Nintendo pad or the +// keyboard pad (docs/gameinput.md). The GameInput shim reports every pad to the title as an Xbox One pad, so the title +// itself cannot tell; this is the port's own record, for whatever wants to follow the device in use (button prompt +// glyphs first). No SDL, no Windows headers: the shim feeds it one sample per device per poll, and tests feed it +// synthetic samples with their own times. +// +// The rules, chosen so that only deliberate input changes the answer: +// * Only an edge counts: a button going down, a trigger rising past `trigger`, a stick leaving the `stick` radius. +// A button held down, a trigger held, a stick held over, stick drift that stays inside the radius and analog +// noise never count, so a pad lying on the desk cannot take over. The keyboard pad's right stick follows the +// mouse, so a real mouse movement counts as keyboard input through the same stick rule. +// * A device's first sample is its baseline and counts for nothing: a pad that connects with a button held or a +// worn stick resting past the radius does not switch anything until it produces a new edge. +// * After a change, another change waits until `min_switch_us` has passed. An edge from another family inside that +// window is ignored (not queued), so two devices used at once cannot make the answer flicker. +// * Edges from a device of the family already active change nothing. +// * Before any edge the answer is `initial` (Xbox unless the caller says otherwise). +// * A forced family (LEONIDA_PROMPTS) wins over all of this; the tracking still runs underneath, so clearing the +// force goes straight back to the device in use. +// `generation` counts changes of the answer (tracked or forced), so a reader can tell that something changed without +// comparing families. + +#include +#include +#include +#include + +namespace leonida { + +enum class InputFamily : std::uint8_t { + Xbox, // Xbox One/Series, Xbox 360, and any pad SDL does not know better (generic, unknown) + PlayStation5, // DualSense, DualSense Edge + PlayStation4, // DualShock 4 + PlayStation3, // DualShock 3 + Nintendo, // Switch Pro controller and Joy-Cons + Keyboard, // the keyboard pad: keyboard and mouse +}; + +inline const char* input_family_name(InputFamily f) { + switch (f) { + case InputFamily::Xbox: return "Xbox"; + case InputFamily::PlayStation5: return "PlayStation 5"; + case InputFamily::PlayStation4: return "PlayStation 4"; + case InputFamily::PlayStation3: return "PlayStation 3"; + case InputFamily::Nintendo: return "Nintendo"; + case InputFamily::Keyboard: return "keyboard and mouse"; + } + return "unknown"; +} + +// One device's state at one poll, in GameInput's units: sticks -1..1, triggers 0..1. `buttons` is any bit set per +// pressed button (the shim passes the GameInput gamepad bits plus one bit for the guide button); only its changes +// matter. +struct InputSample { + std::uint32_t buttons = 0; + float left_trigger = 0, right_trigger = 0; + float left_x = 0, left_y = 0, right_x = 0, right_y = 0; +}; + +// What made the answer change, for the log line. +enum class InputEdge : std::uint8_t { None, Button, Trigger, Stick }; + +inline const char* input_edge_name(InputEdge e) { + switch (e) { + case InputEdge::None: return "none"; + case InputEdge::Button: return "button press"; + case InputEdge::Trigger: return "trigger pull"; + case InputEdge::Stick: return "stick movement"; + } + return "unknown"; +} + +class ActiveInputTracker { +public: + struct Thresholds { + float stick = 0.35f; // radius a stick has to leave + float trigger = 0.3f; // a trigger has to rise past this + std::uint64_t min_switch_us = 300'000; // shortest time between two changes + }; + + explicit ActiveInputTracker(InputFamily initial = InputFamily::Xbox) : tracked_(initial) {} + ActiveInputTracker(InputFamily initial, Thresholds t) : thresholds_(t), tracked_(initial) {} + + // One sample of one device (`device` is any key that stays the same while the device is connected). Returns the + // edge that changed the tracked family, or None when it did not change. With a family forced, the tracked family + // still follows the devices, but active() does not move. + InputEdge observe(std::uint64_t device, InputFamily family, const InputSample& now, std::uint64_t time_us) { + auto it = devices_.find(device); + if (it == devices_.end()) { + devices_.emplace(device, now); // the baseline: counts for nothing + return InputEdge::None; + } + const InputEdge edge = edge_between(it->second, now); + it->second = now; + if (edge == InputEdge::None || family == tracked_) return InputEdge::None; + if (changed_once_ && time_us - changed_at_ < thresholds_.min_switch_us) return InputEdge::None; + const InputFamily before = active(); + tracked_ = family; + changed_at_ = time_us; + changed_once_ = true; + if (active() != before) ++generation_; + return edge; + } + + // The device disconnected: its next sample, if it comes back, is a baseline again. + void forget(std::uint64_t device) { devices_.erase(device); } + + // Forces the answer (a family) or returns to tracking (nullopt). Changing what active() returns bumps generation. + void force(std::optional family) { + const InputFamily before = active(); + forced_ = family; + if (active() != before) ++generation_; + } + + InputFamily active() const { return forced_ ? *forced_ : tracked_; } + InputFamily tracked() const { return tracked_; } + bool forced() const { return forced_.has_value(); } + std::uint64_t generation() const { return generation_; } + const Thresholds& thresholds() const { return thresholds_; } + void set_thresholds(const Thresholds& t) { thresholds_ = t; } + +private: + InputEdge edge_between(const InputSample& was, const InputSample& now) const { + if (now.buttons & ~was.buttons) return InputEdge::Button; + const float t = thresholds_.trigger; + if ((was.left_trigger <= t && now.left_trigger > t) || (was.right_trigger <= t && now.right_trigger > t)) + return InputEdge::Trigger; + const auto out = [this](float x, float y) { return std::hypot(x, y) > thresholds_.stick; }; + if ((!out(was.left_x, was.left_y) && out(now.left_x, now.left_y)) || + (!out(was.right_x, was.right_y) && out(now.right_x, now.right_y))) + return InputEdge::Stick; + return InputEdge::None; + } + + Thresholds thresholds_{}; + InputFamily tracked_; + std::optional forced_; + std::uint64_t generation_ = 0; + std::uint64_t changed_at_ = 0; + bool changed_once_ = false; + std::unordered_map devices_; +}; + +} // namespace leonida diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h index 5abab65df..5096771c7 100644 --- a/runtime/src/buffer_va_index.h +++ b/runtime/src/buffer_va_index.h @@ -5,9 +5,13 @@ // every registered resource. No Vulkan or Windows dependency; not thread-safe (VulkanContext guards it with // resource_mutex_, like the bindings themselves). // -// D3D12 lets placed buffers alias, so ranges may overlap. A lookup then returns the containing range that starts -// closest below the VA (the larger ID on a tie): the walk goes down from the nearest start and stops once no range can -// still reach the VA, which `longest_` bounds. Without overlaps the first range it looks at is the answer, or none is. +// D3D12 lets placed buffers alias, so ranges may overlap. A lookup names the bytes it needs, [va, va + bytes), and +// returns, among the ranges that hold va, the one that starts closest below it (the larger ID on a tie) that also +// holds all of those bytes; when none does, the closest one that holds va. So a view that starts in a small placed +// buffer and runs past its end resolves to a larger buffer that aliases the same memory and holds all of it, instead +// of being cut at the small one's end (found in review of #2823). The walk goes down from the nearest start and stops +// once no range can still reach the VA, or, with a fallback found, once no range can still hold all the bytes; both +// are bounded by `longest_`. Without overlaps the first range it looks at is the answer, or none is. // `longest_` is the longest range indexed now, not the longest ever: a large buffer that is freed stops lengthening // later misses. A miss still walks every start within the longest live range below the VA. @@ -49,20 +53,29 @@ public: std::uint64_t size; }; - // The range that holds `va`; false when none does. - bool find(std::uint64_t va, Hit& out) const { + // The range that holds `va`, preferring one that holds [va, va + bytes) (bytes 0 counts as 1); false when none + // holds va. + bool find(std::uint64_t va, Hit& out, std::uint64_t bytes = 1) const { + if (!bytes) bytes = 1; + bool found = false; // `out` holds the closest range that holds va, though not all the bytes auto it = ranges_.upper_bound({va, max_id()}); while (it != ranges_.begin()) { --it; const std::uint64_t start = it->first.first; - const std::uint64_t offset = va - start; // start <= va here - if (offset >= longest_) return false; // no range that starts this low reaches va - if (offset < it->second) { + const std::uint64_t offset = va - start; // start <= va here; it only grows as the walk goes down + if (offset >= longest_) break; // no range that starts this low reaches va + if (found && bytes > longest_ - offset) break; // nor holds all the bytes + if (offset >= it->second) continue; + if (bytes <= it->second - offset) { out = {it->first.second, start, it->second}; return true; } + if (!found) { + out = {it->first.second, start, it->second}; + found = true; + } } - return false; + return found; } std::size_t size() const { return ranges_.size(); } diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index fcdc1ca33..7e612e1eb 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -179,6 +180,11 @@ inline constexpr std::uint32_t video_decode_statistics = 8; inline constexpr std::uint32_t pipeline_statistics1 = 10; } // namespace d3d12_query +// A stream-output statistics query (SO_STATISTICS_STREAM0..3). +constexpr bool is_so_statistics(std::uint32_t query_type) { + return query_type >= d3d12_query::so_statistics_stream0 && query_type <= d3d12_query::so_statistics_stream3; +} + // Whether a heap of `heap_type` holds queries of `query_type` (the D3D12 pairing rules). constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type) { namespace h = d3d12_query_heap; @@ -196,7 +202,8 @@ constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type } // Bytes one resolved query takes: a UINT64 for occlusion and timestamps, D3D12_QUERY_DATA_PIPELINE_STATISTICS -// (11 UINT64s) for pipeline statistics. 0 for the types this layer does not resolve. +// (11 UINT64s) for pipeline statistics, D3D12_QUERY_DATA_SO_STATISTICS (2 UINT64s) for stream output. 0 for the +// types this layer does not resolve. constexpr std::uint32_t query_result_size(std::uint32_t query_type) { namespace q = d3d12_query; switch (query_type) { @@ -204,6 +211,11 @@ constexpr std::uint32_t query_result_size(std::uint32_t query_type) { case q::binary_occlusion: case q::timestamp: return 8; case q::pipeline_statistics: return 11 * 8; + // D3D12_QUERY_DATA_SO_STATISTICS: NumPrimitivesWritten, PrimitivesStorageNeeded. + case q::so_statistics_stream0: + case q::so_statistics_stream0 + 1: + case q::so_statistics_stream0 + 2: + case q::so_statistics_stream3: return 2 * 8; default: return 0; } } @@ -392,6 +404,15 @@ struct IndexBufferView { std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42) }; +// The views a draw captured, at the D3D12 maxima. Kept by value because the CPU descriptor slots and the bound +// views can change after the draw is recorded, and out of line because the command variant is sized by its largest +// member: inline they made every recorded command, barriers included, 976 bytes. +struct DrawViews { + std::array render_targets{}; + std::array vertex_buffers{}; // by input slot + std::uint32_t render_target_count = 8; +}; + // DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads // render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at // the draw. resource 0 marks an unbound render-target slot or no depth buffer. @@ -400,9 +421,8 @@ struct IndexBufferView { struct Draw { std::uintptr_t pipeline = 0; std::array user_data{}; - std::array render_targets{}; + std::shared_ptr views; // null: no render targets or vertex buffers captured TargetView depth{}; - std::array vertex_buffers{}; // by input slot IndexBufferView index{}; std::uint32_t topology = 0; // D3D_PRIMITIVE_TOPOLOGY Viewport viewport{}; // the first; more viewports are not modelled yet @@ -416,7 +436,6 @@ struct Draw { std::uint32_t first = 0; // first vertex or first index std::int32_t base_vertex = 0; std::uint32_t first_instance = 0; - std::uint32_t render_target_count = 8; }; // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. diff --git a/runtime/src/depth24_fragment.h b/runtime/src/depth24_fragment.h new file mode 100644 index 000000000..10f0dada8 --- /dev/null +++ b/runtime/src/depth24_fragment.h @@ -0,0 +1,445 @@ +#pragma once + +// D24_UNORM_S8_UINT on a GPU without D24 (the layer stores D32_SFLOAT_S8_UINT, depth24.h) in draws (D3D-309). +// +// Two D3D rules break when the depth attachment is float (found by @marquezinii, measured by @Vonsek on #291): +// * the integer RasterizerState.DepthBias is in fixed D24 units, r = 1 / (2^24 - 1) ("the minimum representable +// value > 0 in the depth-buffer format"), while Vulkan scales a float attachment's constant bias by the +// primitive's exponent; +// * clears are quantised to the D24 code (depth24_clear_value), fragment depth is not, so an EQUAL test at a +// cleared value fails where D24 hardware passes. +// The fix moves both into the pixel stage: the fragment writes FragDepth = quantise(z + bias), with z the rasterised +// depth, bias = DepthBias * r + SlopeScaledDepthBias * max(|dz/dx|, |dz/dy|) clamped by DepthBiasClamp (D3D's +// formula), and quantise = depth24_to_float(depth24_quantize(.)) from depth24_convert.comp, so a fragment holds +// exactly the float a D24 code reads back as. The rasterizer's own bias is then turned off for the pipeline. +// A shader that writes its own depth (SV_Depth) keeps its value, quantised; D3D applies no bias to it. +// +// depth24_patch_fragment edits a translated pixel shader's SPIR-V; depth24_depth_only_fragment builds the stage +// for a pipeline without a pixel shader (depth-only passes such as shadow maps). Both are plain word editing with +// no dependency beyond the standard library; d3d12_depth24_draw_test runs them (with LEONIDA_VK_VALIDATION=1 the +// validation layer checks the modules). +// +// Not covered (logged by the caller): a pixel shader with EarlyFragmentTests (its FragDepth write would be ignored), +// multisampled targets (FragDepth is per pixel, which would flatten per-sample depth), and a viewport depth range +// narrower than the biased depth (D3D clamps to MinDepth..MaxDepth before quantising; the quantisation here clamps +// to 0..1 and Vulkan's clamp to the viewport range follows it). + +#include +#include +#include +#include +#include +#include + +namespace leonida { + +struct Depth24Bias { + int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias + float slope = 0.0f; // SlopeScaledDepthBias + float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it + bool any() const { return constant != 0 || slope != 0.0f; } +}; + +// D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1). +inline float depth24_bias_constant(int bias) { + return float(bias) * float(1.0 / 16777215.0); +} + +namespace spirv24 { + +enum : std::uint32_t { + op_name = 5, op_line = 8, op_ext_inst_import = 11, op_ext_inst = 12, op_memory_model = 14, op_entry_point = 15, + op_execution_mode = 16, op_capability = 17, op_type_void = 19, op_type_bool = 20, op_type_int = 21, + op_type_float = 22, op_type_vector = 23, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_decorate = 71, + op_composite_extract = 81, op_convert_f_to_u = 109, op_convert_u_to_f = 112, op_bitcast = 124, op_i_add = 128, + op_f_add = 129, op_i_sub = 130, op_f_mul = 133, op_select = 169, op_i_equal = 170, op_u_greater_than = 172, + op_u_greater_than_equal = 174, op_shift_left_logical = 196, op_dpdx = 207, op_dpdy = 208, op_label = 248, + op_return = 253, op_no_line = 317, op_execution_mode_id = 331, +}; +enum : std::uint32_t { storage_input = 1, storage_output = 3 }; +enum : std::uint32_t { decoration_builtin = 11, builtin_frag_coord = 15, builtin_frag_depth = 22 }; +enum : std::uint32_t { model_fragment = 4 }; +enum : std::uint32_t { + mode_origin_upper_left = 7, mode_early_fragment_tests = 9, mode_depth_replacing = 12, mode_depth_greater = 14, + mode_depth_less = 15, mode_depth_unchanged = 16, +}; +enum : std::uint32_t { glsl_round_even = 2, glsl_fabs = 4, glsl_fmin = 37, glsl_fmax = 40, glsl_find_umsb = 75 }; + +using Inst = std::vector; // a whole instruction, word 0 included + +inline std::uint32_t opcode(const Inst& i) { return i[0] & 0xffffu; } +inline Inst make(std::uint32_t op, std::initializer_list operands) { + Inst i; + i.reserve(operands.size() + 1); + i.push_back(std::uint32_t(operands.size() + 1) << 16 | op); + i.insert(i.end(), operands.begin(), operands.end()); + return i; +} +inline void append_string(Inst& i, const char* s) { + const std::size_t n = std::strlen(s) + 1, words = (n + 3) / 4; + const std::size_t at = i.size(); + i.resize(at + words, 0); + std::memcpy(&i[at], s, n); +} +inline void fix_length(Inst& i) { i[0] = std::uint32_t(i.size()) << 16 | opcode(i); } +inline std::uint32_t bits(float f) { + std::uint32_t u; + std::memcpy(&u, &f, 4); + return u; +} +// Words a literal string takes in an instruction, starting at `at`. +inline std::size_t string_words(const Inst& i, std::size_t at) { + std::size_t w = at; + while (w < i.size()) { + const std::uint32_t word = i[w++]; + if ((word & 0xff000000u) == 0 || (word & 0x00ff0000u) == 0 || (word & 0x0000ff00u) == 0 || + (word & 0x000000ffu) == 0) + break; + } + return w - at; +} + +inline bool is_global_decl(std::uint32_t op) { + return op == 1 /* OpUndef */ || (op >= op_type_void && op <= 39) || (op >= 41 && op <= 52) || op == op_variable; +} + +class Module { +public: + bool parse(const std::vector& words, std::string& why) { + if (words.size() < 5 || words[0] != 0x07230203u) { + why = "not a SPIR-V module"; + return false; + } + header_.assign(words.begin(), words.begin() + 5); + for (std::size_t w = 5; w < words.size();) { + const std::uint32_t count = words[w] >> 16; + if (count == 0 || w + count > words.size()) { + why = "truncated instruction"; + return false; + } + insts_.emplace_back(words.begin() + std::ptrdiff_t(w), words.begin() + std::ptrdiff_t(w + count)); + w += count; + } + return true; + } + std::vector words() const { + std::vector out = header_; + for (const Inst& i : insts_) out.insert(out.end(), i.begin(), i.end()); + return out; + } + std::uint32_t fresh() { return header_[3]++; } + std::uint32_t version() const { return header_[1]; } + std::vector& insts() { return insts_; } + std::vector& header() { return header_; } + +private: + std::vector header_; + std::vector insts_; +}; + +// The edit, on a parsed module. Globals are collected first and spliced in at their section's end. +class Patch { +public: + Patch(Module& m, std::uint32_t entry) : m_(m), entry_(entry) { + // Copies: apply() moves the module's instructions while the code at returns still looks types up. + for (const Inst& i : m.insts()) { + if (opcode(i) == op_function) break; + existing_.push_back(i); + } + } + + // A type, reused when the module already declares it (SPIR-V forbids duplicate non-aggregate types). + std::uint32_t type(std::uint32_t op, std::initializer_list operands) { + auto same = [&](const Inst& i) { + if (opcode(i) != op || i.size() != operands.size() + 2) return false; + std::size_t k = 2; + for (std::uint32_t o : operands) + if (i[k++] != o) return false; + return true; + }; + for (const Inst& ex : existing_) + if (same(ex)) return ex[1]; + for (const Inst& i : globals_) + if (same(i)) return i[1]; + const std::uint32_t id = m_.fresh(); + Inst i = make(op, {id}); + i.insert(i.end(), operands.begin(), operands.end()); + fix_length(i); + globals_.push_back(std::move(i)); + return id; + } + std::uint32_t t_float() { return type(op_type_float, {32}); } + std::uint32_t t_uint() { return type(op_type_int, {32, 0}); } + std::uint32_t t_bool() { return type(op_type_bool, {}); } + // Constants are cached by type and value: all of them are declared before apply() writes the globals out. + std::uint32_t constant(std::uint32_t t, std::uint32_t value) { + for (const auto& c : constants_) + if (c[0] == t && c[1] == value) return c[2]; + const std::uint32_t id = m_.fresh(); + globals_.push_back(make(op_constant, {t, id, value})); + constants_.push_back({t, value, id}); + return id; + } + // Declares what quantise() uses, so it can run inside apply() (at returns) without adding globals. + void prime_quantise() { + t_bool(); + glsl(); + for (float f : {16777215.0f, 0.0f}) f32(f); + for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u); + } + std::uint32_t f32(float f) { return constant(t_float(), bits(f)); } + std::uint32_t u32(std::uint32_t u) { return constant(t_uint(), u); } + + std::uint32_t glsl() { + if (glsl_) return glsl_; + for (const Inst& ex : existing_) { + if (opcode(ex) != op_ext_inst_import || ex.size() < 3) continue; + std::string name((ex.size() - 2) * 4, '\0'); + std::memcpy(name.data(), &ex[2], name.size()); + if (std::strcmp(name.c_str(), "GLSL.std.450") == 0) return glsl_ = ex[1]; + } + glsl_ = m_.fresh(); + Inst i = make(op_ext_inst_import, {glsl_}); + append_string(i, "GLSL.std.450"); + fix_length(i); + import_ = std::move(i); + return glsl_; + } + + // A built-in variable already decorated in the module, or 0. + std::uint32_t builtin_variable(std::uint32_t builtin) const { + for (const Inst& ex : existing_) + if (opcode(ex) == op_decorate && ex.size() == 4 && ex[2] == decoration_builtin && ex[3] == builtin) + return ex[1]; + return 0; + } + std::uint32_t variable(std::uint32_t pointer_type, std::uint32_t storage, std::uint32_t builtin) { + const std::uint32_t id = m_.fresh(); + globals_.push_back(make(op_variable, {pointer_type, id, storage})); + decorations_.push_back(make(op_decorate, {id, decoration_builtin, builtin})); + interface_.push_back(id); + return id; + } + void ensure_interface(std::uint32_t id) { interface_.push_back(id); } + void mode(std::uint32_t m) { modes_.push_back(make(op_execution_mode, {entry_, m})); } + + // Instructions in a function body: emit returns the result id. + std::uint32_t emit(std::vector& code, std::uint32_t op, std::uint32_t type, + std::initializer_list operands) { + const std::uint32_t id = m_.fresh(); + Inst i = make(op, {type, id}); + i.insert(i.end(), operands.begin(), operands.end()); + fix_length(i); + code.push_back(std::move(i)); + return id; + } + std::uint32_t ext(std::vector& code, std::uint32_t type, std::uint32_t inst, + std::initializer_list operands) { + const std::uint32_t id = m_.fresh(); + Inst i = make(op_ext_inst, {type, id, glsl(), inst}); + i.insert(i.end(), operands.begin(), operands.end()); + fix_length(i); + code.push_back(std::move(i)); + return id; + } + + // depth24_to_float(depth24_from_bits(z)) of depth24_convert.comp, branch-free. + std::uint32_t quantise(std::vector& code, std::uint32_t z) { + const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool(); + const std::uint32_t b = emit(code, op_bitcast, tu, {z}); + const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(16777215.0f)}); + const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product}); + // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there). + const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}), + f32(16777215.0f)}); + const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe}); + const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)}); + const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid}); + const std::uint32_t negative_or_nan = emit(code, op_u_greater_than, tb, {b, u32(0x7f800000u)}); + const std::uint32_t d = emit(code, op_select, tu, {negative_or_nan, u32(0), code_hi}); + // float(m + 1) * 2^(e - 47) with e = findMSB(d) and m = d << (23 - e); d == 0 gives 0. + const std::uint32_t e = ext(code, tu, glsl_find_umsb, {d}); + const std::uint32_t m = emit(code, op_shift_left_logical, tu, {d, emit(code, op_i_sub, tu, {u32(23), e})}); + const std::uint32_t mf = emit(code, op_convert_u_to_f, tf, {emit(code, op_i_add, tu, {m, u32(1)})}); + const std::uint32_t exponent = emit(code, op_shift_left_logical, tu, {emit(code, op_i_add, tu, {e, u32(80)}), + u32(23)}); + const std::uint32_t scale = emit(code, op_bitcast, tf, {exponent}); + const std::uint32_t value = emit(code, op_f_mul, tf, {mf, scale}); + const std::uint32_t zero = emit(code, op_i_equal, tb, {d, u32(0)}); + return emit(code, op_select, tf, {zero, f32(0.0f), value}); + } + + // Splices everything into the module. + void apply(std::vector entry_code, std::vector (*at_return)(Patch&, void*), void* ctx, + bool drop_conservative_modes) { + auto& in = m_.insts(); + std::size_t last_entry_point = 0; + for (std::size_t k = 0; k < in.size(); ++k) + if (opcode(in[k]) == op_entry_point) last_entry_point = k; + std::vector out; + out.reserve(in.size() + globals_.size() + entry_code.size() + 16); + bool imported = import_.empty(), decorated = false, declared = false; + bool in_main = false, entry_done = false; + for (std::size_t k = 0; k < in.size(); ++k) { + Inst& i = in[k]; + const std::uint32_t op = opcode(i); + if (!imported && op == op_memory_model) { + out.push_back(std::move(import_)); + imported = true; + } + if (op == op_execution_mode && i.size() >= 3 && i[1] == entry_ && drop_conservative_modes && + (i[2] == mode_depth_greater || i[2] == mode_depth_less || i[2] == mode_depth_unchanged || + i[2] == mode_depth_replacing)) + continue; // replaced by the DepthReplacing in modes_ + if (op == op_entry_point && i.size() > 2 && i[2] == entry_) { + const std::size_t names = 3 + string_words(i, 3); + for (std::uint32_t id : interface_) { + bool listed = false; + for (std::size_t w = names; w < i.size(); ++w) listed |= i[w] == id; + if (!listed) i.push_back(id); + } + fix_length(i); + } + if (!decorated && (is_global_decl(op) || op == op_function)) { + for (Inst& d : decorations_) out.push_back(std::move(d)); + decorated = true; + } + if (!declared && op == op_function) { + for (const Inst& g : globals_) out.push_back(g); // copies: type() may still read them + declared = true; + } + if (op == op_function && i.size() > 2 && i[2] == entry_) in_main = true; + if (in_main && !entry_done && op != op_function && op != op_label && op != op_variable && + op != op_line && op != op_no_line && op != 55 /* OpFunctionParameter */) { + for (Inst& c : entry_code) out.push_back(std::move(c)); + entry_done = true; + } + if (in_main && op == op_return && at_return) { + for (Inst& c : at_return(*this, ctx)) out.push_back(std::move(c)); + } + if (op == op_function_end) in_main = false; + out.push_back(std::move(i)); + if (k == last_entry_point) // execution modes follow the entry points + for (Inst& mo : modes_) out.push_back(std::move(mo)); + } + in = std::move(out); + } + +private: + Module& m_; + std::uint32_t entry_; + std::vector existing_; + std::vector globals_, decorations_, modes_; + Inst import_; + std::vector interface_; + std::vector> constants_; // type, value, id + std::uint32_t glsl_ = 0; +}; + +} // namespace spirv24 + +// Edits a pixel shader so it writes the D24-quantised (and, unless it writes depth itself, D3D-biased) depth. +// Returns the new words, or an empty vector with `why` set when the shader can't take the edit. +inline std::vector depth24_patch_fragment(const std::vector& words, + const Depth24Bias& bias, std::string& why) { + using namespace spirv24; + Module m; + if (!m.parse(words, why)) return {}; + std::uint32_t entry = 0; + for (const Inst& i : m.insts()) { + if (opcode(i) == op_entry_point && i.size() > 2 && i[1] == model_fragment) { + if (entry) { + why = "more than one fragment entry point"; + return {}; + } + entry = i[2]; + } + if (opcode(i) == op_function) break; + } + if (!entry) { + why = "no fragment entry point"; + return {}; + } + for (const Inst& i : m.insts()) { + if (opcode(i) == op_execution_mode && i.size() >= 3 && i[1] == entry && i[2] == mode_early_fragment_tests) { + why = "the shader forces early fragment tests, which ignore a FragDepth write"; + return {}; + } + if (opcode(i) == op_function) break; + } + + Patch p(m, entry); + const std::uint32_t tf = p.t_float(); + p.prime_quantise(); + std::uint32_t frag_depth = p.builtin_variable(builtin_frag_depth); + const bool shader_writes_depth = frag_depth != 0; + if (!shader_writes_depth) + frag_depth = p.variable(p.type(op_type_pointer, {storage_output, tf}), storage_output, builtin_frag_depth); + else + p.ensure_interface(frag_depth); + p.mode(mode_depth_replacing); + + std::vector entry_code; + if (!shader_writes_depth) { + std::uint32_t frag_coord = p.builtin_variable(builtin_frag_coord); + const std::uint32_t tv4 = p.type(op_type_vector, {tf, 4}); + if (!frag_coord) + frag_coord = p.variable(p.type(op_type_pointer, {storage_input, tv4}), storage_input, builtin_frag_coord); + else + p.ensure_interface(frag_coord); + const std::uint32_t coord = p.emit(entry_code, op_load, tv4, {frag_coord}); + std::uint32_t z = p.emit(entry_code, op_composite_extract, tf, {coord, 2}); + if (bias.any()) { + // In the entry block: uniform control flow, so the derivatives are defined. + const std::uint32_t dx = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdx, tf, {z})}); + const std::uint32_t dy = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdy, tf, {z})}); + const std::uint32_t max_slope = p.ext(entry_code, tf, glsl_fmax, {dx, dy}); + std::uint32_t amount = p.emit(entry_code, op_f_mul, tf, {p.f32(bias.slope), max_slope}); + amount = p.emit(entry_code, op_f_add, tf, {amount, p.f32(depth24_bias_constant(bias.constant))}); + if (bias.clamp > 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)}); + if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)}); + z = p.emit(entry_code, op_f_add, tf, {z, amount}); + } + const std::uint32_t q = p.quantise(entry_code, z); + entry_code.push_back(make(op_store, {frag_depth, q})); + p.apply(std::move(entry_code), nullptr, nullptr, true); + } else { + struct Ctx { std::uint32_t var, tf; } ctx{frag_depth, tf}; + p.apply({}, [](Patch& patch, void* c) { + const auto& x = *static_cast(c); + std::vector code; + const std::uint32_t written = patch.emit(code, op_load, x.tf, {x.var}); + code.push_back(make(op_store, {x.var, patch.quantise(code, written)})); + return code; + }, &ctx, true); + } + return m.words(); +} + +// A pixel stage for a pipeline without one: no colour output, only the biased, quantised depth. +inline std::vector depth24_depth_only_fragment(const Depth24Bias& bias) { + using namespace spirv24; + // OpCapability Shader; OpMemoryModel Logical GLSL450; OpEntryPoint Fragment %main "main"; + // OpExecutionMode %main OriginUpperLeft; %void; %fn = void(); %main = function { label; return } + enum : std::uint32_t { id_main = 1, id_void = 2, id_fn = 3, id_label = 4, bound = 5 }; + std::vector w = {0x07230203u, 0x00010000u, 0, bound, 0}; + auto put = [&](Inst i) { w.insert(w.end(), i.begin(), i.end()); }; + put(make(op_capability, {1})); + put(make(op_memory_model, {0, 1})); + Inst ep = make(op_entry_point, {model_fragment, id_main}); + append_string(ep, "main"); + fix_length(ep); + put(ep); + put(make(op_execution_mode, {id_main, mode_origin_upper_left})); + put(make(op_type_void, {id_void})); + put(make(op_type_function, {id_fn, id_void})); + put(make(op_function, {id_void, id_main, 0, id_fn})); + put(make(op_label, {id_label})); + put(make(op_return, {})); + put(make(op_function_end, {})); + std::string why; + return depth24_patch_fragment(w, bias, why); +} + +} // namespace leonida diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index 537f81623..b225cddef 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -630,6 +630,15 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ } if (sampler.unnormalized) { info.unnormalizedCoordinates = VK_TRUE; + // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a + // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag. + // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0). + const auto clamp_or_border = [](VkSamplerAddressMode m) { + return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + }; + info.addressModeU = clamp_or_border(info.addressModeU); + info.addressModeV = clamp_or_border(info.addressModeV); + info.minFilter = info.magFilter; info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; info.minLod = info.maxLod = 0.0f; info.anisotropyEnable = VK_FALSE; diff --git a/runtime/src/indirect_dispatch_count.comp b/runtime/src/indirect_dispatch_count.comp new file mode 100644 index 000000000..9cbc371d9 --- /dev/null +++ b/runtime/src/indirect_dispatch_count.comp @@ -0,0 +1,34 @@ +// Clamp a GPU-written D3D12 ExecuteIndirect DISPATCH count without reading it on the CPU. +// Each record is a VkDispatchIndirectCommand (three uints); disabled records are zero. +#version 460 +#extension GL_EXT_buffer_reference : require +layout(local_size_x = 64) in; +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn { + uint data[]; +}; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer WordsOut { + uint data[]; +}; +layout(push_constant) uniform Params { + WordsIn arguments; + WordsIn count; + WordsOut output_words; + uint stride_words; + uint first_record; + uint records; +} p; +void main() { + const uint local_record = gl_GlobalInvocationID.x; + if (local_record >= p.records) return; + const uint target = local_record * 3u; + if (p.first_record + local_record < p.count.data[0]) { + const uint source = local_record * p.stride_words; + p.output_words.data[target] = p.arguments.data[source]; + p.output_words.data[target + 1u] = p.arguments.data[source + 1u]; + p.output_words.data[target + 2u] = p.arguments.data[source + 2u]; + } else { + p.output_words.data[target] = 0u; + p.output_words.data[target + 1u] = 0u; + p.output_words.data[target + 2u] = 0u; + } +} diff --git a/runtime/src/indirect_dispatch_count_spv.h b/runtime/src/indirect_dispatch_count_spv.h new file mode 100644 index 000000000..9cf7bbae5 --- /dev/null +++ b/runtime/src/indirect_dispatch_count_spv.h @@ -0,0 +1,84 @@ +// Generated with glslangValidator -V --target-env vulkan1.2 -Os --spirv-val indirect_dispatch_count.comp +#pragma once +#include +namespace leonida { +inline constexpr std::uint32_t indirect_dispatch_count_spirv[] = { + 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000074u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, + 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, + 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu, + 0x00000019u, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, + 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, + 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00080005u, 0x0000000bu, 0x475f6c67u, + 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, 0x00040005u, 0x00000013u, 0x61726150u, + 0x0000736du, 0x00060006u, 0x00000013u, 0x00000000u, 0x75677261u, 0x746e656du, 0x00000073u, 0x00050006u, + 0x00000013u, 0x00000001u, 0x6e756f63u, 0x00000074u, 0x00070006u, 0x00000013u, 0x00000002u, 0x7074756fu, + 0x775f7475u, 0x7364726fu, 0x00000000u, 0x00070006u, 0x00000013u, 0x00000003u, 0x69727473u, 0x775f6564u, + 0x7364726fu, 0x00000000u, 0x00070006u, 0x00000013u, 0x00000004u, 0x73726966u, 0x65725f74u, 0x64726f63u, + 0x00000000u, 0x00050006u, 0x00000013u, 0x00000005u, 0x6f636572u, 0x00736472u, 0x00040005u, 0x00000015u, + 0x64726f57u, 0x006e4973u, 0x00050006u, 0x00000015u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u, + 0x00000017u, 0x64726f57u, 0x74754f73u, 0x00000000u, 0x00050006u, 0x00000017u, 0x00000000u, 0x61746164u, + 0x00000000u, 0x00030005u, 0x00000019u, 0x00000070u, 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu, + 0x00030047u, 0x00000013u, 0x00000002u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00050048u, 0x00000013u, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x00000013u, 0x00000002u, + 0x00000023u, 0x00000010u, 0x00050048u, 0x00000013u, 0x00000003u, 0x00000023u, 0x00000018u, 0x00050048u, + 0x00000013u, 0x00000004u, 0x00000023u, 0x0000001cu, 0x00050048u, 0x00000013u, 0x00000005u, 0x00000023u, + 0x00000020u, 0x00040047u, 0x00000014u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000015u, 0x00000002u, + 0x00040048u, 0x00000015u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000015u, 0x00000000u, 0x00000023u, + 0x00000000u, 0x00040047u, 0x00000016u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000017u, 0x00000002u, + 0x00050048u, 0x00000017u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000071u, 0x0000000bu, + 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, + 0x00000020u, 0x00000000u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au, + 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u, + 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, 0x00030027u, 0x00000011u, + 0x000014e5u, 0x00030027u, 0x00000012u, 0x000014e5u, 0x0008001eu, 0x00000013u, 0x00000011u, 0x00000011u, + 0x00000012u, 0x00000006u, 0x00000006u, 0x00000006u, 0x0003001du, 0x00000014u, 0x00000006u, 0x0003001eu, + 0x00000015u, 0x00000014u, 0x00040020u, 0x00000011u, 0x000014e5u, 0x00000015u, 0x0003001du, 0x00000016u, + 0x00000006u, 0x0003001eu, 0x00000017u, 0x00000016u, 0x00040020u, 0x00000012u, 0x000014e5u, 0x00000017u, + 0x00040020u, 0x00000018u, 0x00000009u, 0x00000013u, 0x0004003bu, 0x00000018u, 0x00000019u, 0x00000009u, + 0x00040015u, 0x0000001au, 0x00000020u, 0x00000001u, 0x0004002bu, 0x0000001au, 0x0000001bu, 0x00000005u, + 0x00040020u, 0x0000001cu, 0x00000009u, 0x00000006u, 0x00020014u, 0x0000001fu, 0x0004002bu, 0x00000006u, + 0x00000026u, 0x00000003u, 0x0004002bu, 0x0000001au, 0x00000028u, 0x00000004u, 0x0004002bu, 0x0000001au, + 0x0000002du, 0x00000001u, 0x00040020u, 0x0000002eu, 0x00000009u, 0x00000011u, 0x0004002bu, 0x0000001au, + 0x00000031u, 0x00000000u, 0x00040020u, 0x00000032u, 0x000014e5u, 0x00000006u, 0x0004002bu, 0x0000001au, + 0x0000003au, 0x00000003u, 0x0004002bu, 0x0000001au, 0x0000003eu, 0x00000002u, 0x00040020u, 0x0000003fu, + 0x00000009u, 0x00000012u, 0x0004002bu, 0x00000006u, 0x0000004cu, 0x00000001u, 0x0004002bu, 0x00000006u, + 0x00000058u, 0x00000002u, 0x0004002bu, 0x00000006u, 0x00000070u, 0x00000040u, 0x0006002cu, 0x00000009u, + 0x00000071u, 0x00000070u, 0x0000004cu, 0x0000004cu, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, + 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x00000072u, 0x00000000u, 0x000300fbu, 0x0000000cu, + 0x00000073u, 0x000200f8u, 0x00000073u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu, + 0x0004003du, 0x00000006u, 0x0000000fu, 0x0000000eu, 0x00050041u, 0x0000001cu, 0x0000001du, 0x00000019u, + 0x0000001bu, 0x0004003du, 0x00000006u, 0x0000001eu, 0x0000001du, 0x000500aeu, 0x0000001fu, 0x00000020u, + 0x0000000fu, 0x0000001eu, 0x000300f7u, 0x00000022u, 0x00000000u, 0x000400fau, 0x00000020u, 0x00000021u, + 0x00000022u, 0x000200f8u, 0x00000021u, 0x000200f9u, 0x00000072u, 0x000200f8u, 0x00000022u, 0x00050084u, + 0x00000006u, 0x00000027u, 0x0000000fu, 0x00000026u, 0x00050041u, 0x0000001cu, 0x00000029u, 0x00000019u, + 0x00000028u, 0x0004003du, 0x00000006u, 0x0000002au, 0x00000029u, 0x00050080u, 0x00000006u, 0x0000002cu, + 0x0000002au, 0x0000000fu, 0x00050041u, 0x0000002eu, 0x0000002fu, 0x00000019u, 0x0000002du, 0x0004003du, + 0x00000011u, 0x00000030u, 0x0000002fu, 0x00060041u, 0x00000032u, 0x00000033u, 0x00000030u, 0x00000031u, + 0x00000031u, 0x0006003du, 0x00000006u, 0x00000034u, 0x00000033u, 0x00000002u, 0x00000004u, 0x000500b0u, + 0x0000001fu, 0x00000035u, 0x0000002cu, 0x00000034u, 0x000300f7u, 0x00000037u, 0x00000000u, 0x000400fau, + 0x00000035u, 0x00000036u, 0x00000061u, 0x000200f8u, 0x00000036u, 0x00050041u, 0x0000001cu, 0x0000003bu, + 0x00000019u, 0x0000003au, 0x0004003du, 0x00000006u, 0x0000003cu, 0x0000003bu, 0x00050084u, 0x00000006u, + 0x0000003du, 0x0000000fu, 0x0000003cu, 0x00050041u, 0x0000003fu, 0x00000040u, 0x00000019u, 0x0000003eu, + 0x0004003du, 0x00000012u, 0x00000041u, 0x00000040u, 0x00050041u, 0x0000002eu, 0x00000043u, 0x00000019u, + 0x00000031u, 0x0004003du, 0x00000011u, 0x00000044u, 0x00000043u, 0x00060041u, 0x00000032u, 0x00000046u, + 0x00000044u, 0x00000031u, 0x0000003du, 0x0006003du, 0x00000006u, 0x00000047u, 0x00000046u, 0x00000002u, + 0x00000004u, 0x00060041u, 0x00000032u, 0x00000048u, 0x00000041u, 0x00000031u, 0x00000027u, 0x0005003eu, + 0x00000048u, 0x00000047u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x0000004du, 0x00000027u, + 0x0000004cu, 0x00050080u, 0x00000006u, 0x00000051u, 0x0000003du, 0x0000004cu, 0x00060041u, 0x00000032u, + 0x00000052u, 0x00000044u, 0x00000031u, 0x00000051u, 0x0006003du, 0x00000006u, 0x00000053u, 0x00000052u, + 0x00000002u, 0x00000004u, 0x00060041u, 0x00000032u, 0x00000054u, 0x00000041u, 0x00000031u, 0x0000004du, + 0x0005003eu, 0x00000054u, 0x00000053u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000059u, + 0x00000027u, 0x00000058u, 0x00050080u, 0x00000006u, 0x0000005du, 0x0000003du, 0x00000058u, 0x00060041u, + 0x00000032u, 0x0000005eu, 0x00000044u, 0x00000031u, 0x0000005du, 0x0006003du, 0x00000006u, 0x0000005fu, + 0x0000005eu, 0x00000002u, 0x00000004u, 0x00060041u, 0x00000032u, 0x00000060u, 0x00000041u, 0x00000031u, + 0x00000059u, 0x0005003eu, 0x00000060u, 0x0000005fu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000037u, + 0x000200f8u, 0x00000061u, 0x00050041u, 0x0000003fu, 0x00000062u, 0x00000019u, 0x0000003eu, 0x0004003du, + 0x00000012u, 0x00000063u, 0x00000062u, 0x00060041u, 0x00000032u, 0x00000065u, 0x00000063u, 0x00000031u, + 0x00000027u, 0x0005003eu, 0x00000065u, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, + 0x00000069u, 0x00000027u, 0x0000004cu, 0x00060041u, 0x00000032u, 0x0000006au, 0x00000063u, 0x00000031u, + 0x00000069u, 0x0005003eu, 0x0000006au, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, + 0x0000006eu, 0x00000027u, 0x00000058u, 0x00060041u, 0x00000032u, 0x0000006fu, 0x00000063u, 0x00000031u, + 0x0000006eu, 0x0005003eu, 0x0000006fu, 0x0000000cu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000037u, + 0x000200f8u, 0x00000037u, 0x000200f9u, 0x00000072u, 0x000200f8u, 0x00000072u, 0x000100fdu, 0x00010038u, +}; +} // namespace leonida diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 278444c6f..3c7f9da08 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -529,15 +529,7 @@ void cleanup_tls_clones() { cleanup_tls_clones_internal(); } namespace { bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { - for (const Module* m : static_cast(ctx)->modules()) { - const auto base = reinterpret_cast(m->base); - if (m->base && address >= base && address - base < m->size) { - module = m->name; - rva = static_cast(address - base); - return true; - } - } - return false; + return static_cast(ctx)->find_address(address, module, rva); } void* bundled_find_loaded(void* ctx, const std::string& dll_lower) { @@ -732,6 +724,18 @@ void* Loader::resolve_module_export(void* module_handle, const std::string& sym, return nullptr; } +bool Loader::find_address(uint64_t address, std::string& module, uint32_t& rva) const { + std::shared_lock lock(ranges_mutex_); + for (const MappedRange& r : ranges_) { + if (address >= r.base && address - r.base < r.size) { + module = r.name; + rva = static_cast(address - r.base); + return true; + } + } + return false; +} + bool Loader::owns_module_handle(void* module_handle) const { if (!module_handle) return false; std::lock_guard lock(mutex_); @@ -873,6 +877,12 @@ Module& Loader::map_image(const std::filesystem::path& path) { m->base = static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); } + { + // From here an address inside the image names it. The memory stays until ~Loader, which unregisters the + // lookup first. + std::unique_lock lock(ranges_mutex_); + ranges_.push_back({reinterpret_cast(m->base), m->size, m->name}); + } std::memcpy(m->base, file.data(), oh.SizeOfHeaders); auto* sec = IMAGE_FIRST_SECTION(nt); diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index e73c36339..d7e5be91c 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -79,6 +80,11 @@ public: const std::vector& modules() const { return order_; } + // The mapped module `address` lies in, with its RVA there. Safe from any thread at any time, also while another + // thread is in load(): it is what the shim registry asks for a caller's module (rt::shims::mapped_image_base on + // every C++ throw from a mapped image, and the trace and stop lines), and it reads its own table, not modules(). + bool find_address(uint64_t address, std::string& module, uint32_t& rva) const; + // The order initialise() runs modules in: each module after every module it imports (a cycle is broken at the // module that closed it). modules() is mapping order, which puts an importer before its imports. const std::vector& initialisation_order() const { return init_order_; } @@ -133,6 +139,17 @@ private: std::map by_name_; // lower-case file name std::vector order_; // mapping order; owns the modules std::vector init_order_; // dependencies first, see initialisation_order() + + // What find_address reads: one entry per mapped image, added once its memory exists. Under ranges_mutex_, a leaf + // lock: mutex_ is held while image code runs and the registry holds its own lock around the lookup, so the + // lookup must not wait for either. + struct MappedRange { + uint64_t base = 0; + uint32_t size = 0; + std::string name; + }; + mutable std::shared_mutex ranges_mutex_; // shared in find_address: lookups on different threads do not queue + std::vector ranges_; }; // Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load() diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h index 32ef1eb1d..e7dd50fe6 100644 --- a/runtime/src/queue_families.h +++ b/runtime/src/queue_families.h @@ -45,4 +45,24 @@ inline QueueFamilies pick_queue_families(std::span families, + QueueFamilies chosen, bool sparse_buffers) { + if (!sparse_buffers || chosen.direct >= families.size() || + !(families[chosen.direct].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)) + return chosen; + if (chosen.compute >= families.size() || + !(families[chosen.compute].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)) + chosen.compute = chosen.direct; + if (chosen.copy >= families.size() || + !(families[chosen.copy].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)) + chosen.copy = chosen.direct; + return chosen; +} + } // namespace leonida diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 528fd013d..69572ccd0 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -642,6 +642,9 @@ struct ShaderEntry { std::vector outputs; // pixel/vertex shaders: output locations written // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378). std::map> f16_halves; + // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a + // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers). + std::vector> literal_samplers; }; class ShaderLibrary { @@ -813,6 +816,14 @@ private: e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; } } + if (const Json* l = meta.find("literal_samplers"); l && l->kind == Json::Kind::array) { + for (const Json& item : l->array) { + if (item.kind != Json::Kind::array || item.array.size() != 4) continue; + std::array words{}; + for (std::size_t i = 0; i < 4; ++i) words[i] = u32(&item.array[i]); + e.literal_samplers.push_back(words); + } + } if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); if (by_fspx && prefix == "fspx/") ++fspx_count_; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 03ab7ba26..d247b8cb0 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -17,6 +17,7 @@ #include "statistics_sum_spirv.h" #include "vulkan13_features.h" #include "vulkan_depth24.h" +#include "vulkan_indirect_dispatch_count.h" #include "vulkan_scratch.h" #include "vulkan_replay.h" #include "queue_families.h" @@ -85,6 +86,7 @@ struct VulkanDeviceFunctions { X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) @@ -866,7 +868,7 @@ public: // buffer as out of bounds, which is no reason to drop the submission. replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { BufferVaIndex::Hit hit{}; - if (!buffer_vas_.find(va, hit)) return false; + if (!buffer_vas_.find(va, hit, size)) return false; // prefers an aliasing buffer that holds all of it const ResourceBinding* b = resolve(hit.id); if (!b) return false; buffer = b->buffer; @@ -953,6 +955,13 @@ public: std::unique_lock lock(resource_mutex_); predicated_copier_ = std::make_unique(get, device_, limits); } + // Counts for DISPATCH-only ExecuteIndirect are read by a helper compute shader from GPU memory. + // Requires Vulkan bufferDeviceAddress, already enabled for the D3D12 address arena. + void configure_counted_dispatch(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, + const VkPhysicalDeviceLimits& limits) { + std::unique_lock lock(resource_mutex_); + counted_dispatch_ = std::make_unique(get, device_, memory, limits); + } VkDevice device() const { return device_; } // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets @@ -990,6 +999,14 @@ public: storage_pending_.insert(id); } + // A device-local buffer D3D12 says starts zeroed (D3D-71): the host cannot write it, so the next submission on + // any queue fills it with zeros ahead of its lists. That submission publishes the same initialisation semaphore as + // the storage images above, so a list on another queue that uses the buffer first waits for the fill. + void zero_on_next_submit(ResourceId id, VkBuffer buffer) { + std::lock_guard lock(storage_mutex_); + zero_pending_.push_back({id, buffer}); + } + void add_sparse_buffer(ResourceId id, const ResourceBinding& binding, std::shared_ptr buffer) { std::unique_lock lock(resource_mutex_); set_resource_locked(id, binding); @@ -1007,6 +1024,10 @@ public: resources_.erase(it); sparse_buffers_.erase(id); } + { + std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled + std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; }); + } if (img) { std::lock_guard vlock(views_mutex_); for (auto v = views_.begin(); v != views_.end();) { @@ -1346,8 +1367,13 @@ private: std::unordered_map graphics_pipelines_; std::unordered_map acceleration_structures_; LayoutTracker tracker_; - std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ only + std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only std::unordered_set storage_pending_; + struct PendingZero { + ResourceId id; + VkBuffer buffer; + }; + std::vector zero_pending_; // zero_on_next_submit // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter // that says which one: every other queue's next submission waits for it, so no queue uses such an image before // the zero-fill that put it in GENERAL has run. @@ -1366,6 +1392,7 @@ private: ReplayFunctions replay_; std::unique_ptr predicate_reducer_; std::unique_ptr predicated_copier_; + std::unique_ptr counted_dispatch_; std::uint32_t predicate_family_ = UINT32_MAX; std::uint32_t transfer_only_family_ = UINT32_MAX; DebugLabelFunctions labels_; @@ -1489,6 +1516,12 @@ public: if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now if (context_.scratch_) context_.scratch_->forget(progress_); } + if (progress_) { + // This queue is idle, so whatever initialisation it published (storage images, zero-filled buffers) has + // finished: the next submission on another queue must not wait on a semaphore that is about to go. + std::lock_guard lock(context_.storage_mutex_); + if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE; + } if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); @@ -1690,6 +1723,7 @@ private: if (const auto* p = std::get_if(&command); p && p->buffer) ++captures; std::unique_ptr batch; std::unique_ptr copy_batch; + std::unique_ptr counted_batch; if (captures) { if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) return ReplayResult::unsupported; @@ -1727,6 +1761,19 @@ private: return context_.scratch_->get(bytes, buffer, offset); }; } + if (kind_ != QueueKind::copy && context_.counted_dispatch_) { + replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( + VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, + std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { + // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); + return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out); + }; + replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { + context_.counted_dispatch_->emit(cb, job); + }; + } if (context_.depth24_ && !transfer_only) { replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, std::vector& parts) { @@ -1871,6 +1918,7 @@ private: runs_shaders |= std::holds_alternative(command) || std::holds_alternative(command) || std::holds_alternative(command); std::vector storage_images; + std::vector zero_buffers; { std::lock_guard lock(context_.storage_mutex_); if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && @@ -1882,6 +1930,16 @@ private: if (kind_ != QueueKind::copy && runs_shaders) storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); if (!storage_images.empty()) context_.storage_pending_.clear(); + zero_buffers.swap(context_.zero_pending_); // any queue can fill a buffer + } + for (const auto& zero : zero_buffers) + context_.vk.vkCmdFillBuffer(command_buffer, zero.buffer, 0, VK_WHOLE_SIZE, 0); + if (!zero_buffers.empty()) { + VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + filled.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &filled, 0, nullptr, 0, nullptr); } for (const ResourceId id : storage_images) { const ResourceBinding* image = context_.resolve(id); @@ -1937,11 +1995,13 @@ private: wait_values_.push_back(submitted_); } const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); - if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission + if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) { + // not initialized after all: try again with the next submission std::lock_guard lock(context_.storage_mutex_); context_.storage_pending_.insert(storage_images.begin(), storage_images.end()); + context_.zero_pending_.insert(context_.zero_pending_.end(), zero_buffers.begin(), zero_buffers.end()); } - if (submitted && !storage_images.empty()) { + if (submitted && (!storage_images.empty() || !zero_buffers.empty())) { std::lock_guard lock(context_.storage_mutex_); context_.storage_init_semaphore_ = progress_; context_.storage_init_value_ = submitted_; @@ -1956,6 +2016,7 @@ private: context_.tracker_ = std::move(next_tracker); slot->predicate = std::move(batch); slot->predicated_copy = std::move(copy_batch); + slot->counted_dispatch = std::move(counted_batch); queries.commit(); slot->segments = std::move(queries.retained); } else { @@ -2110,6 +2171,7 @@ private: std::vector> segments; std::vector events; // order_timestamp_copy's, reset and reused once the slot completes std::unique_ptr predicated_copy; + std::unique_ptr counted_dispatch; std::unique_ptr predicate; // retained until this slot completes }; @@ -2228,6 +2290,7 @@ private: if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; reuse->predicate.reset(); reuse->predicated_copy.reset(); + reuse->counted_dispatch.reset(); reuse->ticket = UINT64_MAX; // in use until submitted return reuse; } diff --git a/runtime/src/vulkan_indirect_dispatch_count.h b/runtime/src/vulkan_indirect_dispatch_count.h new file mode 100644 index 000000000..225f7c1fc --- /dev/null +++ b/runtime/src/vulkan_indirect_dispatch_count.h @@ -0,0 +1,199 @@ +// GPU-only count gating for simple D3D12 ExecuteIndirect(DISPATCH) signatures. +// Vulkan has vkCmdDispatchIndirect but no vkCmdDispatchIndirectCount. We prepare a private indirect +// buffer with zero-group records past the GPU count, then execute all MaxCommandCount records. +#pragma once +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include +#include +#include +#include "indirect_dispatch_count_spv.h" + +namespace leonida { + +struct CountedDispatch { + VkBuffer indirect = VK_NULL_HANDLE; + VkDeviceSize offset = 0; + VkDeviceAddress arguments = 0; + VkDeviceAddress count = 0; + VkDeviceAddress output = 0; + std::uint32_t stride = 0; + std::uint32_t max_count = 0; +}; + +class IndirectDispatchCounter { +public: + IndirectDispatchCounter(PFN_vkGetDeviceProcAddr get, VkDevice device, + const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceLimits& limits) + : get_(get), device_(device), memory_(memory), limits_(limits) {} + ~IndirectDispatchCounter() { + if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); + if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); + } + IndirectDispatchCounter(const IndirectDispatchCounter&) = delete; + IndirectDispatchCounter& operator=(const IndirectDispatchCounter&) = delete; + + // Retained by the command-buffer slot until its submission's timeline ticket completes. + struct Batch { + IndirectDispatchCounter& owner; + struct Allocation { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + }; + std::vector allocations; + explicit Batch(IndirectDispatchCounter& value) : owner(value) {} + ~Batch() { + for (auto& a : allocations) { + if (a.buffer) owner.fn("vkDestroyBuffer")(owner.device_, a.buffer, nullptr); + if (a.memory) owner.fn("vkFreeMemory")(owner.device_, a.memory, nullptr); + } + } + Batch(const Batch&) = delete; + Batch& operator=(const Batch&) = delete; + + bool prepare(VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, + VkDeviceSize count_offset, std::uint32_t stride, std::uint32_t max_count, + CountedDispatch& out) { + out = {}; + if (!arguments || !count || !stride || stride % 4 || !max_count || + !owner.limits_.maxComputeWorkGroupCount[0] || !owner.make_pipeline()) return false; + constexpr VkDeviceSize record_bytes = 3 * sizeof(std::uint32_t); + if (VkDeviceSize(max_count) > std::numeric_limits::max() / record_bytes) + return false; + const VkDeviceSize bytes = VkDeviceSize(max_count) * record_bytes; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = bytes; + info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + Allocation scratch{}; + if (owner.fn("vkCreateBuffer")(owner.device_, &info, nullptr, &scratch.buffer) != VK_SUCCESS) + return false; + allocations.push_back(scratch); // all failure paths free it with the batch + auto& a = allocations.back(); + VkMemoryRequirements requirements{}; + owner.fn("vkGetBufferMemoryRequirements")( + owner.device_, a.buffer, &requirements); + std::uint32_t memory_type = UINT32_MAX; + for (std::uint32_t i = 0; i < owner.memory_.memoryTypeCount; ++i) { + if (!(requirements.memoryTypeBits & (1u << i))) continue; + if (memory_type == UINT32_MAX) memory_type = i; + if (owner.memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + memory_type = i; + break; + } + } + if (memory_type == UINT32_MAX) return false; + VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = memory_type; + if (owner.fn("vkAllocateMemory")(owner.device_, &allocation, nullptr, &a.memory) != VK_SUCCESS || + owner.fn("vkBindBufferMemory")(owner.device_, a.buffer, a.memory, 0) != VK_SUCCESS) + return false; + const auto address = owner.fn("vkGetBufferDeviceAddress"); + VkBufferDeviceAddressInfo addr{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + addr.buffer = arguments; + const VkDeviceAddress args_va = address(owner.device_, &addr); + addr.buffer = count; + const VkDeviceAddress count_va = address(owner.device_, &addr); + addr.buffer = a.buffer; + const VkDeviceAddress output_va = address(owner.device_, &addr); + if (!args_va || !count_va || !output_va || + argument_offset > UINT64_MAX - args_va || count_offset > UINT64_MAX - count_va) + return false; + out = {a.buffer, 0, args_va + argument_offset, count_va + count_offset, + output_va, stride, max_count}; + return true; + } + }; + + std::unique_ptr batch() { return std::make_unique(*this); } + + void emit(VkCommandBuffer cb, const CountedDispatch& job) const { + const auto barrier = fn("vkCmdPipelineBarrier"); + VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 1, &before, 0, nullptr, 0, nullptr); + fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + struct Push { + VkDeviceAddress arguments, count, output; + std::uint32_t stride_words, first_record, records; + }; + static_assert(sizeof(Push) == 40); + const VkDeviceSize dispatch_limit = VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * 64; + // Bound per-dispatch indexing to 32 bits, even when the D3D12 stride is very large. + // The shader loads three consecutive dwords, so leave room for the final +2. + const VkDeviceSize index_limit = (UINT32_MAX - 2u) / (job.stride / 4); + const VkDeviceSize chunk_limit = std::min(dispatch_limit, index_limit + 1); + for (VkDeviceSize first = 0; first < job.max_count;) { + const std::uint32_t count = std::uint32_t(std::min(chunk_limit, job.max_count - first)); + const Push push{job.arguments + first * job.stride, job.count, job.output + first * 12, + job.stride / 4, std::uint32_t(first), count}; + fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, + 0, sizeof(push), &push); + fn("vkCmdDispatch")(cb, (count + 63u) / 64u, 1, 1); + first += count; + } + VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT; + after.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_MEMORY_READ_BIT | + VK_ACCESS_MEMORY_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + 0, 1, &after, 0, nullptr, 0, nullptr); + } + +private: + template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } + bool make_pipeline() { + if (pipeline_) return true; + for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", + "vkAllocateMemory", "vkFreeMemory", "vkBindBufferMemory", "vkGetBufferDeviceAddress", + "vkCreateShaderModule", "vkDestroyShaderModule", "vkCreatePipelineLayout", + "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", + "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"}) + if (!get_(device_, name)) return false; + VkShaderModule module = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + shader.codeSize = sizeof(indirect_dispatch_count_spirv); + shader.pCode = indirect_dispatch_count_spirv; + bool ok = fn("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; + const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, 40}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = ⦥ + ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + info.stage.module = module; + info.stage.pName = "main"; + info.layout = layout; + ok = ok && fn("vkCreateComputePipelines")( + device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; + if (module) fn("vkDestroyShaderModule")(device_, module, nullptr); + if (!ok) { + if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); + if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + return false; + } + layout_ = layout; + pipeline_ = pipeline; + return true; + } + PFN_vkGetDeviceProcAddr get_; + VkDevice device_; + VkPhysicalDeviceMemoryProperties memory_; + VkPhysicalDeviceLimits limits_; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; +}; +} // namespace leonida diff --git a/runtime/src/vulkan_memory.h b/runtime/src/vulkan_memory.h index c89a68575..08c764d33 100644 --- a/runtime/src/vulkan_memory.h +++ b/runtime/src/vulkan_memory.h @@ -56,4 +56,13 @@ inline std::vector memory_type_order(const VkPhysicalDeviceMemory return order; } +// D3D-299: true when an allocation that preferred DEVICE_LOCAL without needing host access (a texture, a default-heap +// buffer outside the arena) got a type without it, so the GPU now reads it from system memory. A host-visible +// allocation (the arena, an upload heap) in system memory is the memory type policy without Resizable BAR, not this. +inline bool spilled_to_host(VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred, + VkMemoryPropertyFlags chosen) { + return (preferred & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && !(required & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) && + !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); +} + } // namespace leonida diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index fc6d1699e..a29cce3fa 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -166,8 +166,10 @@ public: { std::lock_guard lock(context_.submit_mutex()); vk.vkQueueWaitIdle(queue_); + // A WSI layer may perform a device-wide idle while destroying the swapchain. + // Keep that implicit idle serialized with submits from every context queue. + release(swapchain_); } - release(swapchain_); swapchain_ = VK_NULL_HANDLE; release_capture(); composer_.reset(); @@ -299,7 +301,9 @@ public: } // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). - // Waits for the frame to finish. False if no captured frame is available or the wait fails. + // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present + // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next + // frame that is shown (the frame before it is not what the window was last asked to show), or when the wait fails. bool read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format) { if (!capture_ || !capture_ptr_ || !captured_) return false; const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; @@ -331,6 +335,7 @@ public: } if (!swapchain_) { // minimised: try again next frame stale_ = true; + captured_ = false; // nothing was shown: read_back() must not hand out the frame before return VK_SUCCESS; } if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it @@ -347,7 +352,10 @@ public: VkResult acquired = acquire(frame.acquired, &image); if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; - if (!swapchain_) return VK_SUCCESS; + if (!swapchain_) { // minimised since the last present: skipped, as above + captured_ = false; + return VK_SUCCESS; + } acquired = acquire(frame.acquired, &image); } if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired @@ -873,7 +881,10 @@ private: } } if (extent.width == 0 || extent.height == 0) { - release(swapchain_); + { + std::lock_guard lock(context_.submit_mutex()); + release(swapchain_); + } swapchain_ = VK_NULL_HANDLE; vsync_ = vsync; swapchain_srgb_ = srgb; @@ -985,13 +996,18 @@ private: info.oldSwapchain = old; VkSwapchainKHR fresh = VK_NULL_HANDLE; const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh); - release(old); // retired by the creation attempt, whether or not it succeeded + { + std::lock_guard lock(context_.submit_mutex()); + release(old); // retired by the creation attempt, whether or not it succeeded + } if (created != VK_SUCCESS) return false; std::vector images; std::vector ready; const auto discard = [&] { for (VkSemaphore semaphore : ready) vk.vkDestroySemaphore(device, semaphore, nullptr); + // The WSI implementation may block on the device here too. + std::lock_guard lock(context_.submit_mutex()); vkDestroySwapchainKHR_(device, fresh, nullptr); return false; }; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 4185d6ff8..d5effb830 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -37,6 +37,7 @@ #include #include "vulkan_predicate.h" #include "vulkan_predicated_copy.h" +#include "vulkan_indirect_dispatch_count.h" #include #include @@ -721,6 +722,8 @@ struct OcclusionResult { // A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that // was never ended writes zeros instead of waiting on it. struct QueryPool { + // Null for a stream-output statistics heap: the layer has no stream output (PSOs with StreamOutput entries are + // refused), so every SO_STATISTICS_STREAMn query counts 0 written and 0 needed, and a resolve fills zeros. VkQueryPool pool = VK_NULL_HANDLE; std::uint32_t heap_type = 0; // d3d12_query_heap std::uint32_t count = 0; @@ -799,6 +802,10 @@ struct ReplayFunctions { std::function order_timestamp_copy; std::function sum_occlusion; + // Creates a query pool of `count` queries of that type for the single-list replay()'s occlusion and + // pipeline-statistics segments (D3D-399); the batched path creates its own. Unset, or with any sum helper unset, + // replay() refuses a list whose queries overlap, as before. + std::function(VkQueryType, std::uint32_t count)> create_segment_pool; PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches PFN_vkCmdPushConstants push_constants = nullptr; PFN_vkCmdBindDescriptorSets bind_descriptor_sets = nullptr; // set 0 of pipelines that declare bindings @@ -845,6 +852,11 @@ struct ReplayFunctions { PFN_vkCmdDrawIndirectCount draw_indirect_count = nullptr; PFN_vkCmdDrawIndexedIndirectCount draw_indexed_indirect_count = nullptr; PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr; + // A DISPATCH-only ExecuteIndirect signature with a GPU count buffer needs a compute prepass to clamp + // the number of commands. The resulting scratch buffer is owned by the queue's timeline-retained batch. + std::function prepare_counted_dispatch; + std::function emit_counted_dispatch; // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder @@ -926,6 +938,7 @@ struct Prepared { std::uint32_t statistics_begin = PreparedQuery::no_segment; PredicateCapture predicate; std::vector predicated_copy; + CountedDispatch counted_dispatch; ResourceBinding binding; VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) VkImageView view = VK_NULL_HANDLE; @@ -937,6 +950,7 @@ struct Prepared { std::vector buffer_copies; std::vector buffer_image_copies; // one direction, given by which side is an image std::vector image_copies; + bool same_copy_subresource = false; VkImageResolve resolve{}; // resolves // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE; @@ -1544,6 +1558,8 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { p.binding.volume != p.source.volume || p.binding.samples != p.source.samples || p.binding.rgb96 != p.source.rgb96) return ReplayResult::invalid_copy; + p.same_copy_subresource = p.source.image == p.binding.image && src.aspectMask == dst.aspectMask && + src.baseMipLevel == dst.baseMipLevel && src.baseArrayLayer == dst.baseArrayLayer; const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel); const auto to_depth = std::max(1u, p.binding.depth >> dst.baseMipLevel); @@ -1568,21 +1584,37 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { return ReplayResult::invalid_copy; const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left); const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top); - // shortcut: into a BC mip whose edge block is partial, Vulkan's extent cannot reach the padded edge; such - // a copy is refused until it is staged through a buffer. - if (dst_block > 1 && (copy.x + w * dst_block > to.width || copy.y + h * dst_block > to.height)) - return ReplayResult::invalid_copy; - p.image_copies.push_back({{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, - {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, - {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, - {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, - {w, h, box.back - box.front}}); + const VkImageCopy region{{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, + {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, + {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, + {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, + {w, h, box.back - box.front}}; + const std::uint32_t dst_w = w * dst_block, dst_h = h * dst_block; + if (dst_block > 1 && (copy.x + dst_w > to.width || copy.y + dst_h > to.height)) { + // Each uncompressed texel supplies a whole BC block. Keep the same scratch row and slice strides + // in bytes on both sides, with a destination extent clipped to the actual mip. + const VkBufferImageCopy read{0, w, h, region.srcSubresource, region.srcOffset, region.extent}; + const VkBufferImageCopy write{0, dst_w, dst_h, region.dstSubresource, region.dstOffset, + {std::min(dst_w, to.width - copy.x), std::min(dst_h, to.height - copy.y), region.extent.depth}}; + p.staged_reads.push_back(read); + p.staged_writes.push_back(write); + } else { + p.image_copies.push_back(region); + } p.range = dst; p.source_range = src; return ReplayResult::success; } std::uint32_t w = box.right - box.left, h = box.bottom - box.top; const std::uint32_t d = box.back - box.front; + if (p.same_copy_subresource) { + const auto intersects = [](std::uint32_t a, std::uint32_t b, std::uint32_t size) { + return (a < b ? b - a : a - b) < size; + }; + if (intersects(box.left, copy.x, padded(w)) && intersects(box.top, copy.y, padded(h)) && + intersects(box.front, copy.z, d)) + return ReplayResult::invalid_copy; + } if (block > 1) { // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip. // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the @@ -1934,8 +1966,9 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct }; p.colors.assign(pipeline->color_formats.size(), {}); - for (std::size_t slot = 0; slot < draw.render_target_count && slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) { - const TargetView& target = draw.render_targets[slot]; + const std::uint32_t render_target_count = draw.views ? draw.views->render_target_count : 0; + for (std::size_t slot = 0; slot < render_target_count && slot < p.colors.size(); ++slot) { + const TargetView& target = draw.views->render_targets[slot]; if (!target.resource) continue; const ResourceBinding* binding = resolve(target.resource); if (!binding) return ReplayResult::unresolved_resource; @@ -1993,7 +2026,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.vertex_offsets.resize(slot + 1, 0); p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE); p.vertex_strides.resize(slot + 1, 0); - const bool bound = slot < draw.vertex_buffers.size() && draw.vertex_buffers[slot].va; + const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && + draw.views->vertex_buffers[slot].va; if (!bound) { if (!vk.zero_buffer) return ReplayResult::unresolved_resource; p.vertex_buffers[slot] = vk.zero_buffer; @@ -2002,7 +2036,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.vertex_strides[slot] = 0; continue; } - const VertexBufferView& view = draw.vertex_buffers[slot]; + const VertexBufferView& view = draw.views->vertex_buffers[slot]; std::uint64_t size = view.size; if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) return ReplayResult::unresolved_resource; @@ -2163,14 +2197,16 @@ inline void plan_statistics_segments(PreparedList& out) { std::size_t next_query = 0; for (std::size_t i = 0; i < out.commands.size(); ++i) { auto& p = out.commands[i]; - if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) + if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || + p.counted_dispatch.indirect)) inner.push_back({&p.statistics_end, &p.statistics_begin}); if (next_query == out.queries.size() || out.queries[next_query].command != i) continue; auto& query = out.queries[next_query++]; const Command& command = out.list->commands()[i]; const auto range = query_range(command); if (std::holds_alternative(command)) { - if (begin && range.type != d3d12_query::timestamp) + // A stream-output resolve only fills zeros (no dispatch), so it needs no split. + if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type)) inner.push_back({&query.statistics_end, &query.statistics_begin}); } else if (range.type == d3d12_query::pipeline_statistics) { if (std::holds_alternative(command)) { @@ -2212,7 +2248,8 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) { if (!query) { // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical // segment before it and open a new one after, the way resolves do. - if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) { + if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || + p.counted_dispatch.indirect)) { p.statistics_end = current; current = out.statistics_segment_count++; p.statistics_begin = current; @@ -2703,6 +2740,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (range.type == d3d12_query::binary_occlusion) { overlaps |= begin && (ordinary_active || binary_active); if (begin) ++binary_active; else --binary_active; + } else if (is_so_statistics(range.type)) { + // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing. } else { statistics_overlaps |= begin && statistics_active_count; if (begin) ++statistics_active_count; else --statistics_active_count; @@ -2742,10 +2781,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) return ReplayResult::invalid_indirect_arguments; p.source = *cnt; - if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || - (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count) || - ind->kind == IndirectKind::dispatch) + if (ind->kind == IndirectKind::dispatch) { + // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch + // and replace commands past min(count, max_count) with zero-group dispatches. + if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch || + !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) || + !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, + p.source.buffer, p.source.buffer_offset + ind->count_offset, + ind->stride, ind->max_count, p.counted_dispatch)) + return ReplayResult::unsupported; + } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || + (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) { return ReplayResult::unsupported; + } } else { if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || @@ -2980,6 +3028,9 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu begin_statistics(); return; } + // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for + // BeginQuery and EndQuery; its resolves were planned as zero fills. + if (!heap.pool && !std::holds_alternative(command)) return; if (const auto* begin = std::get_if(&command)) { vk.reset_query_pool(cb, heap.pool, begin->index, 1); const bool precise = begin->type == d3d12_query::occlusion && heap.precise; @@ -3346,10 +3397,14 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); } else if (!p.image_copies.empty()) { + // A subresource can be both the source and destination only in a shared layout. + const bool self = p.same_copy_subresource; const VkImageLayout src_layout = detail::copy_layout( vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); - const VkImageLayout dst_layout = detail::copy_layout( + self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT, + tracker); + const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); const auto count = std::uint32_t(p.image_copies.size()); @@ -3562,7 +3617,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); } else if (const auto* ind = std::get_if(&command)) { const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; - if (ind->count_buffer) { + if (ind->count_buffer && ind->kind != IndirectKind::dispatch) { const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; if (ind->kind == IndirectKind::draw) { vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, @@ -3577,6 +3632,12 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } else if (ind->kind == IndirectKind::draw_indexed) { vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); } else if (ind->kind == IndirectKind::dispatch) { + if (ind->count_buffer) { + // No D3D12 query must count this internal compute pass as an application dispatch. + end_statistics(); + vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); + begin_statistics(); + } if (ind->pipeline) { ShaderUserData data{}; std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); @@ -3590,8 +3651,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c &data); } for (std::uint32_t k = 0; k < ind->max_count; ++k) { - vk.dispatch_indirect(command_buffer, p.binding.buffer, - arguments + VkDeviceSize(k) * ind->stride); + vk.dispatch_indirect(command_buffer, + ind->count_buffer ? p.counted_dispatch.indirect : p.binding.buffer, + (ind->count_buffer ? p.counted_dispatch.offset + VkDeviceSize(k) * 12 + : arguments + VkDeviceSize(k) * ind->stride)); } } } @@ -3758,18 +3821,33 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } // prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. +// With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get +// segment pools as in the batched path; the caller holds `keep` until the command buffer has completed. template ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Resolve&& resolve, - const ReplayFunctions& vk, LayoutTracker* tracker = nullptr) { + const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, + std::vector>* keep = nullptr) { if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) return ReplayResult::unsupported; + const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion && + vk.sum_statistics && vk.sum_binary_occlusion; PreparedList prepared; - if (const auto result = prepare(list, resolve, vk, prepared); result != ReplayResult::success) return result; + if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success) + return result; if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; + std::shared_ptr physical, statistics; + if (pools && prepared.segment_count && + !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count))) + return ReplayResult::unsupported; + if (pools && prepared.statistics_segment_count && + !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count))) + return ReplayResult::unsupported; QueryReplay queries; - if (const auto result = queries.plan(prepared); result != ReplayResult::success) return result; + if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success) + return result; emit(prepared, command_buffer, vk, tracker); queries.commit(); // the caller owns submission of the legacy command buffer + if (keep) keep->insert(keep->end(), queries.retained.begin(), queries.retained.end()); return ReplayResult::success; } diff --git a/runtime/test/active_input_test.cpp b/runtime/test/active_input_test.cpp new file mode 100644 index 000000000..11c628320 --- /dev/null +++ b/runtime/test/active_input_test.cpp @@ -0,0 +1,236 @@ +// ActiveInputTracker (src/active_input.h) on synthetic samples with its own clock: what counts as deliberate input +// (edges only, thresholds, baselines), the minimum time between changes, several devices of one family, a device that +// goes and comes back, and a forced family. No SDL, no controller, no GPU. +#include "../src/active_input.h" + +#include +#include +#include + +using namespace leonida; + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +constexpr std::uint64_t ms = 1000; // the tracker's clock is in microseconds + +InputSample rest() { return {}; } + +InputSample button(std::uint32_t bits) { + InputSample s; + s.buttons = bits; + return s; +} + +InputSample left_stick(float x, float y) { + InputSample s; + s.left_x = x; + s.left_y = y; + return s; +} + +InputSample right_stick(float x, float y) { + InputSample s; + s.right_x = x; + s.right_y = y; + return s; +} + +InputSample triggers(float left, float right) { + InputSample s; + s.left_trigger = left; + s.right_trigger = right; + return s; +} + +// Device keys and families used below. +constexpr std::uint64_t xbox = 1, dualsense = 2, ds4 = 3, keyboard = 4, xbox2 = 5, switch_pro = 6; + +int test_start_and_baseline() { + ActiveInputTracker t; + EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0 && !t.forced()); + + // A first sample is a baseline, whatever it holds: a pad connecting with a button down changes nothing. + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 0) == InputEdge::None); + EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0); + // Still held: no edge. + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 10 * ms) == InputEdge::None); + // Released, then pressed again: that press is the first deliberate input, and the first change needs no wait. + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, rest(), 20 * ms) == InputEdge::None); + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 30 * ms) == InputEdge::Button); + EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1); + return 0; +} + +int test_drift_and_thresholds() { + ActiveInputTracker t; + EXPECT(t.observe(xbox, InputFamily::Xbox, rest(), 0) == InputEdge::None); + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, rest(), 0) == InputEdge::None); + + // A worn stick drifting around inside the radius never counts, however long it wanders. + for (int i = 0; i < 200; ++i) { + const float d = 0.05f + 0.25f * static_cast(i % 7) / 6.0f; // 0.05 .. 0.30 + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(d, -d * 0.5f), (1 + i) * ms) == + InputEdge::None); + } + // Just inside the radius (0.35 along a diagonal is 0.247 per axis): nothing. + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(0.24f, 0.24f), 300 * ms) == InputEdge::None); + // Leaving it is an edge. + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(0.3f, 0.3f), 310 * ms) == InputEdge::Stick); + EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1); + // Held over the radius: no further edge from the same stick. + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(1.0f, 0.0f), 320 * ms) == InputEdge::None); + + // Triggers: resting at 0.29 is not a pull; rising past 0.3 is. + EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.29f, 0.0f), 700 * ms) == InputEdge::None); + EXPECT(t.active() == InputFamily::PlayStation5); + EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.31f, 0.0f), 710 * ms) == InputEdge::Trigger); + EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2); + // A trigger held further down does not count again. + EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.9f, 0.0f), 720 * ms) == InputEdge::None); + return 0; +} + +int test_min_switch_time() { + ActiveInputTracker t; + t.observe(xbox, InputFamily::Xbox, rest(), 0); + t.observe(dualsense, InputFamily::PlayStation5, rest(), 0); + + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(2), 1000 * ms) == InputEdge::Button); + EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1); + // 100 ms later the Xbox pad's press is inside the window: ignored, and not remembered for later. + EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1100 * ms) == InputEdge::None); + EXPECT(t.active() == InputFamily::PlayStation5); + EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1400 * ms) == InputEdge::None); // still held: no edge + EXPECT(t.active() == InputFamily::PlayStation5); + // Released and pressed again after the window: that one counts. + t.observe(xbox, InputFamily::Xbox, rest(), 1500 * ms); + EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1600 * ms) == InputEdge::Button); + EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2); + // Exactly at the window's end counts (the window is "less than min_switch_us"). + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(2 | 4), 1900 * ms) == InputEdge::Button); + EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 3); + + // A zero window lets every deliberate input switch at once. + ActiveInputTracker fast(InputFamily::Xbox, {0.35f, 0.3f, 0}); + fast.observe(xbox, InputFamily::Xbox, rest(), 0); + fast.observe(keyboard, InputFamily::Keyboard, rest(), 0); + EXPECT(fast.observe(keyboard, InputFamily::Keyboard, button(8), 1) == InputEdge::Button); + EXPECT(fast.observe(xbox, InputFamily::Xbox, button(8), 2) == InputEdge::Button); + EXPECT(fast.active() == InputFamily::Xbox && fast.generation() == 2); + return 0; +} + +int test_same_family_and_holds() { + ActiveInputTracker t; + for (std::uint64_t d : {xbox, xbox2}) t.observe(d, InputFamily::Xbox, rest(), 0); + t.observe(keyboard, InputFamily::Keyboard, rest(), 0); + + // Input from a second pad of the family already in use changes nothing. + EXPECT(t.observe(xbox2, InputFamily::Xbox, button(1), 10 * ms) == InputEdge::None); + EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0); + + // The keyboard pad: W held pushes the left stick to full. The first push is the edge; holding it is not. + EXPECT(t.observe(keyboard, InputFamily::Keyboard, left_stick(0.0f, 1.0f), 20 * ms) == InputEdge::Stick); + EXPECT(t.active() == InputFamily::Keyboard && t.generation() == 1); + // The player picks up the Xbox pad while W is still held down: the pad takes over after the window and the held + // key does not take it back. + EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 400 * ms) == InputEdge::Button); + for (int i = 0; i < 50; ++i) + EXPECT(t.observe(keyboard, InputFamily::Keyboard, left_stick(0.0f, 1.0f), (410 + 10 * i) * ms) == + InputEdge::None); + EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2); + + // The mouse moves the keyboard pad's right stick: a small jitter stays inside the radius, a real movement + // leaves it. + t.observe(keyboard, InputFamily::Keyboard, rest(), 1000 * ms); + EXPECT(t.observe(keyboard, InputFamily::Keyboard, right_stick(0.03f, 0.0f), 1010 * ms) == InputEdge::None); + EXPECT(t.observe(keyboard, InputFamily::Keyboard, right_stick(0.5f, -0.1f), 1020 * ms) == InputEdge::Stick); + EXPECT(t.active() == InputFamily::Keyboard && t.generation() == 3); + return 0; +} + +int test_reconnect() { + ActiveInputTracker t; + t.observe(ds4, InputFamily::PlayStation4, rest(), 0); + EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 10 * ms) == InputEdge::Button); + EXPECT(t.active() == InputFamily::PlayStation4); + + // Unplugged while the button was down; it comes back with the button still down. The new first sample is a + // baseline, so there is no edge to count, and no stale state from before. + t.forget(ds4); + t.observe(switch_pro, InputFamily::Nintendo, rest(), 0); + EXPECT(t.observe(switch_pro, InputFamily::Nintendo, button(1), 500 * ms) == InputEdge::Button); + EXPECT(t.active() == InputFamily::Nintendo); + EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 900 * ms) == InputEdge::None); + EXPECT(t.active() == InputFamily::Nintendo); + t.observe(ds4, InputFamily::PlayStation4, rest(), 910 * ms); + EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 920 * ms) == InputEdge::Button); + EXPECT(t.active() == InputFamily::PlayStation4 && t.generation() == 3); + return 0; +} + +int test_forced() { + ActiveInputTracker t; + t.observe(dualsense, InputFamily::PlayStation5, rest(), 0); + t.observe(keyboard, InputFamily::Keyboard, rest(), 0); + + t.force(InputFamily::Keyboard); + EXPECT(t.forced() && t.active() == InputFamily::Keyboard && t.generation() == 1); + // Forcing the same family again changes nothing. + t.force(InputFamily::Keyboard); + EXPECT(t.generation() == 1); + + // Tracking still runs underneath: the DualSense becomes the tracked family, but the answer stays forced and the + // generation does not move. + EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 10 * ms) == InputEdge::Button); + EXPECT(t.tracked() == InputFamily::PlayStation5 && t.active() == InputFamily::Keyboard && t.generation() == 1); + + // Clearing the force goes straight back to the device in use. + t.force(std::nullopt); + EXPECT(!t.forced() && t.active() == InputFamily::PlayStation5 && t.generation() == 2); + + // Forcing the family that is already tracked does not change the answer, so no new generation. + t.force(InputFamily::PlayStation5); + EXPECT(t.forced() && t.active() == InputFamily::PlayStation5 && t.generation() == 2); + t.force(std::nullopt); + EXPECT(t.generation() == 2); + return 0; +} + +int test_names() { + EXPECT(std::string_view(input_family_name(InputFamily::PlayStation5)) == "PlayStation 5"); + EXPECT(std::string_view(input_family_name(InputFamily::Keyboard)) == "keyboard and mouse"); + EXPECT(std::string_view(input_edge_name(InputEdge::Stick)) == "stick movement"); + return 0; +} + +} // namespace + +int main() { + struct Case { + const char* name; + int (*run)(); + }; + const Case cases[] = { + {"start and baseline", test_start_and_baseline}, + {"drift and thresholds", test_drift_and_thresholds}, + {"minimum time between changes", test_min_switch_time}, + {"one family, held input", test_same_family_and_holds}, + {"reconnect", test_reconnect}, + {"forced family", test_forced}, + {"names", test_names}, + }; + int failures = 0; + for (const Case& c : cases) { + const int r = c.run(); + std::printf("%s: %s\n", c.name, r ? "FAIL" : "ok"); + failures += r; + } + const int total = static_cast(std::size(cases)); + std::printf("active input: %d of %d cases pass\n", total - failures, total); + return failures ? 1 : 0; +} diff --git a/runtime/test/buffer_va_index_test.cpp b/runtime/test/buffer_va_index_test.cpp index 3368e8b8b..b5b5e997f 100644 --- a/runtime/test/buffer_va_index_test.cpp +++ b/runtime/test/buffer_va_index_test.cpp @@ -27,10 +27,10 @@ void check(bool ok, const char* what) { ++failures; } -// The id that holds `va`, 0 for none. -std::uintptr_t at(const Index& index, std::uint64_t va) { +// The id that holds `va` (preferring one that holds `bytes` from it), 0 for none. +std::uintptr_t at(const Index& index, std::uint64_t va, std::uint64_t bytes = 1) { Index::Hit hit{}; - return index.find(va, hit) ? hit.id : 0; + return index.find(va, hit, bytes) ? hit.id : 0; } void fixed_cases() { @@ -64,6 +64,13 @@ void fixed_cases() { check(at(alias, 0x1f000) == 10, "past every short buffer"); check(at(alias, 0x20000) == 0, "past the long buffer"); + // A view that starts in a short buffer and runs past its end: the long buffer around it holds all of it. + check(at(alias, 0x11080, 0x80) == 11, "a view that fits in the short buffer stays in it"); + check(at(alias, 0x11080, 0x81) == 10, "a view past the short buffer's end goes to the long one around it"); + check(at(alias, 0x1ff00, 0x200) == 10, "a view no range holds: the closest that holds its start"); + check(at(alias, 0x11080, 0x10000) == 11, "a view past the long buffer too: the closest start, as without a size"); + check(at(alias, 0x11080, 0) == 11, "a size of 0 counts as one byte"); + // Two resources placed at the same offset: the larger ID, either way they were added. alias.insert(0x30000, 0x100, 21); alias.insert(0x30000, 0x200, 20); @@ -100,19 +107,25 @@ void fixed_cases() { check(bound.longest() == 0 && bound.size() == 0, "an empty index has no bound"); } -// The rule BufferVaIndex follows, by a scan: among the ranges that hold va, the greatest (start, id). +// The rule BufferVaIndex follows, by a scan: among the ranges that hold all of [va, va + bytes), the greatest +// (start, id); when none does, the greatest among those that hold va. struct Range { std::uint64_t start, size; std::uintptr_t id; }; -std::uintptr_t scan(const std::vector& ranges, std::uint64_t va) { +std::uintptr_t scan(const std::vector& ranges, std::uint64_t va, std::uint64_t bytes = 1) { const Range* best = nullptr; + const Range* whole = nullptr; + const auto greater = [](const Range& a, const Range* b) { + return !b || a.start > b->start || (a.start == b->start && a.id > b->id); + }; for (const Range& r : ranges) { if (va < r.start || va - r.start >= r.size) continue; - if (!best || r.start > best->start || (r.start == best->start && r.id > best->id)) best = &r; + if (greater(r, best)) best = &r; + if (bytes <= r.size - (va - r.start) && greater(r, whole)) whole = &r; } - return best ? best->id : 0; + return whole ? whole->id : best ? best->id : 0; } void random_tables() { @@ -148,9 +161,12 @@ void random_tables() { } for (int q = 0; q < 2000; ++q) { const std::uint64_t va = 0x8000 + rng() % (next + 0x20000); - if (at(index, va) != scan(ranges, va)) { - std::printf("FAIL: round %d va 0x%llx: index %llu, scan %llu\n", round, (unsigned long long)va, - (unsigned long long)at(index, va), (unsigned long long)scan(ranges, va)); + // A quarter of the lookups name one byte, the rest a view of up to twice the largest buffer. + const std::uint64_t bytes = q % 4 ? 1 + rng() % 0x8000 : 1; + if (at(index, va, bytes) != scan(ranges, va, bytes)) { + std::printf("FAIL: round %d va 0x%llx bytes 0x%llx: index %llu, scan %llu\n", round, + (unsigned long long)va, (unsigned long long)bytes, + (unsigned long long)at(index, va, bytes), (unsigned long long)scan(ranges, va, bytes)); ++failures; return; } diff --git a/runtime/test/bvh_builder_test.cpp b/runtime/test/bvh_builder_test.cpp index 16e5db4d8..2635711c9 100644 --- a/runtime/test/bvh_builder_test.cpp +++ b/runtime/test/bvh_builder_test.cpp @@ -8,7 +8,8 @@ // LEONIDA_BVH_FLAG=1 (optional: pass true as the constructor's bool argument) // LEONIDA_BVH_WARP=1 (optional: use the WARP adapter; the default on an NVIDIA adapter, RT-54) // LEONIDA_BVH_HARDWARE=1 (optional: keep an NVIDIA adapter instead of switching to WARP) -// LEONIDA_BVH_RECORD62=1 (optional: print each CreateComputePipelineState's container shape) +// LEONIDA_BVH_RECORD62=1 (optional: print each CreateComputePipelineState's container shape, its ILDN +// module name and digest) // LEONIDA_BVH_DXIL=1 (optional, with RECORD62: dx.op counts and validator error kinds, needs // dxcompiler.dll and dxil.dll on PATH) // LEONIDA_BVH_DEVICE=vulkan (optional: the Vulkan-backed ID3D12Device from #119 instead of a PC device) @@ -309,7 +310,8 @@ bool looks_like_iid(uint64_t p, const IID& iid) { uint64_t g_slot62_ok = 0, g_slot62_failed = 0; // The shape of a DXBC container, for the record: its parts (four-character code and size), the DXIL part's shader -// model and DXIL version, the SFI0 feature flags, and whether the hash is zero (unsigned). Counts and flags only. +// model and DXIL version, the SFI0 feature flags, whether the hash is zero (unsigned), the ILDN module name and the +// first four bytes of the digest. Counts, flags and names only. std::string container_shape(const void* bytecode, size_t length) { const auto* b = static_cast(bytecode); auto u32 = [&](size_t o) { @@ -340,9 +342,23 @@ std::string container_shape(const void* bytecode, size_t length) { std::snprintf(item, sizeof(item), "(flags %#llx)", static_cast(u32(data) | (uint64_t(u32(data + 4)) << 32))); out += item; + } else if (!std::strcmp(fourcc, "ILDN") && size >= 4) { + // ILDN: u16 flags, u16 name length, the debug name (NUL-padded): the module's PDB path, which names the + // container (docs/embedded_shaders.md section 3). Only the file name is printed. + const uint32_t name_length = u32(data) >> 16; + if (size_t(data) + 4 + name_length <= length && name_length > 0) { + std::string name(reinterpret_cast(b + data + 4), name_length); + name.erase(name.find_last_not_of('\0') + 1); + name = name.substr(name.find_last_of("\\/") + 1); + out += "(" + name + ")"; + } } } - return out; + // The first four bytes of the container digest (bytes 4..19 of the header), to tell two creations of the same + // container from two containers with the same module name. + char digest[24]; + std::snprintf(digest, sizeof(digest), " digest %02x%02x%02x%02x", b[4], b[5], b[6], b[7]); + return out + digest; } // The module a container belongs to: the file name (without ".pdb") in its ILDN part, a DXIL debug-name record diff --git a/runtime/test/check_atexit.cmake b/runtime/test/check_atexit.cmake new file mode 100644 index 000000000..255bb3a4f --- /dev/null +++ b/runtime/test/check_atexit.cmake @@ -0,0 +1,71 @@ +# atexit handlers, static destructors and every way out: tiny_atexit run through `gta6rt --run` must print the +# sequence written below and end with its exit code. That is what the program does natively on Windows, and the +# native run is held to the same sequence, so the two cannot agree on a wrong answer. Under Wine both runs go through +# RUNNER, and Wine's own CRT differs in places (it drops a handler registered while handlers run, and its _exit does +# not wait for the exit lock), so there a native difference is reported without failing; --run is still held to the +# Windows sequence. +get_filename_component(guest_dir "${GUEST}" DIRECTORY) +get_filename_component(guest_name "${GUEST}" NAME) + +set(ctors "ctor first;ctor second;main") +set(handlers "atexit two;atexit registers late;atexit late;atexit one;dtor second;dtor first") +set(expect_return "${ctors};${handlers}") +set(code_return 3) +set(expect_exit "${ctors};${handlers}") +set(code_exit 7) +set(expect__exit "${ctors}") +set(code__exit 8) +set(expect_quick_exit "${ctors}") +set(code_quick_exit 9) +set(expect_ExitProcess "${ctors}") +set(code_ExitProcess 10) +set(expect_cexit "${ctors};${handlers};after _cexit") +set(code_cexit 11) +set(expect_c_exit "${ctors};after _c_exit;${handlers}") +set(code_c_exit 12) +# exit(7) is running a slow handler when a second thread calls _exit(7): the exit lock holds it back. +set(expect_concurrent_exit "${ctors};slow handler started;slow handler done;${handlers}") +set(code_concurrent_exit 7) + +# The program's own lines, in order, without the prefix; everything gta6rt prints is dropped. +function(guest_lines output result) + string(REPLACE "\r\n" "\n" output "${output}") + string(REPLACE ";" "," output "${output}") + string(REPLACE "\n" ";" output "${output}") + set(lines) + foreach(line IN LISTS output) + if(line MATCHES "^tiny_atexit: (.*)$") + list(APPEND lines "${CMAKE_MATCH_1}") + endif() + endforeach() + set(${result} "${lines}" PARENT_SCOPE) +endfunction() + +set(failures "") +foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit) + execute_process(COMMAND ${RUNNER} "${GUEST}" ${mode} + WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60 + RESULT_VARIABLE native_code OUTPUT_VARIABLE native_out ERROR_VARIABLE native_err) + execute_process(COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" -- ${mode} + WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60 + RESULT_VARIABLE run_code OUTPUT_VARIABLE run_out ERROR_VARIABLE run_err) + guest_lines("${native_out}" native_lines) + guest_lines("${run_out}" run_lines) + if(NOT native_code STREQUAL code_${mode} OR NOT native_lines STREQUAL expect_${mode}) + string(CONCAT native_diff "[${mode}] native run differs from the expected sequence" + "\n expected (${code_${mode}}): ${expect_${mode}}\n native (${native_code}): ${native_lines}") + if(RUNNER) + message(STATUS "${native_diff}\n (the host CRT differs from Windows; not a gta6rt failure)") + else() + string(APPEND failures "\n${native_diff}\n (the fixture or the host changed)") + endif() + endif() + if(NOT run_code STREQUAL code_${mode} OR NOT run_lines STREQUAL expect_${mode}) + string(APPEND failures "\n[${mode}] gta6rt --run differs from the expected sequence" + "\n expected (${code_${mode}}): ${expect_${mode}}\n --run (${run_code}): ${run_lines}\n${run_err}") + endif() +endforeach() +if(failures) + message(FATAL_ERROR "atexit/termination differences:${failures}") +endif() +message(STATUS "tiny_atexit: 8 termination paths match the Windows sequence") diff --git a/runtime/test/check_sparse_queue_family.py b/runtime/test/check_sparse_queue_family.py new file mode 100644 index 000000000..2a2ce7470 --- /dev/null +++ b/runtime/test/check_sparse_queue_family.py @@ -0,0 +1,117 @@ +"""Repo-friendly, optional GPU test: byte-exact Leonida COPY/COMPUTE tiled-buffer replay +AND actual VK_SHARING_MODE_CONCURRENT on *every* sparse VkBuffer created by the layer. + +Runs the original synthetic `d3d12_sparse_queue_family_test` target. +Invokes the SDK's VK_LAYER_LUNARG_api_dump in a short-lived isolated directory; +no private-game files, asset paths, device memory dumps, or committed logs. + + python -I check_sparse_queue_family.py path/to/d3d12_sparse_queue_family_test.exe + python -I check_sparse_queue_family.py path/to/baseline.exe --expect-baseline-exclusive + +By default the baseline fails (exit 1) and patched runtime passes (exit 0). +If the API dump layer is absent the result skips (exit 77, CTest SKIP_RETURN_CODE). +""" +from __future__ import annotations + +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + + +SPARSE_FLAGS = "VkBufferCreateFlags = 7 (VK_BUFFER_CREATE_SPARSE_BINDING_BIT" +MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)") +COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)") +INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)") +CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M) + + +def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]: + rows = path.read_text(encoding="utf-8", errors="replace").splitlines() + seen = [] + for i, line in enumerate(rows): + if SPARSE_FLAGS not in line: + continue + tail = "\n".join(rows[i + 1 : i + 13]) + mode, count = MODE.search(tail), COUNT.search(tail) + if not mode or not count: + raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}") + inds = tuple(int(index) for _, index in INDICES.findall(tail)) + seen.append((mode.group(1), int(count.group(1)), inds)) + if len(seen) < 6 or len(seen) % 2: + raise AssertionError(f"insufficient sparse VkBuffer create-info records: {len(seen)}") + if expect_exclusive: + assert all(mode == "VK_SHARING_MODE_EXCLUSIVE" and count == 0 + for mode, count, _ in seen), f"baseline negative control not reproduced: {set(seen)}" + else: + assert all(mode == "VK_SHARING_MODE_CONCURRENT" and count >= 2 and len(inds) == count + and len(set(inds)) == count + for mode, count, inds in seen), f"BUG: not all sparse buffers share active families: {set(seen)}" + return len(seen) // 2, len(seen) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("executable", type=Path, help="Compiled Leonida d3d12_sparse_queue_family_test binary") + parser.add_argument("--expect-baseline-exclusive", action="store_true", + help="negative-control mode: prove buggy EXCLUSIVE create infos instead of requiring fix") + args = parser.parse_args() + exe = args.executable.resolve() + if not exe.is_file(): + print(f"ERROR: missing executable {exe}", file=sys.stderr) + return 2 + env = os.environ.copy() + # An implicit Vulkan layer may be forced by the loader even if the application + # enabled VK_LAYER_KHRONOS_validation explicitly via LEONIDA_VK_VALIDATION. + env["VK_INSTANCE_LAYERS"] = "VK_LAYER_LUNARG_api_dump" + env["LEONIDA_VK_VALIDATION"] = "1" + with tempfile.TemporaryDirectory(prefix="leonida_sparse_trace_") as td: + path = Path(td) + dump_name = path / "sparse_create_info.log" + (path / "vk_layer_settings.txt").write_text( + "lunarg_api_dump.file = true\n" + f"lunarg_api_dump.log_filename = {dump_name}\n" + "lunarg_api_dump.output_format = text\n" + "lunarg_api_dump.pre_dump = true\n" + "lunarg_api_dump.detailed = true\n", + encoding="utf-8", + ) + env["VK_LAYER_SETTINGS_PATH"] = str(path) + run = subprocess.run([str(exe)], cwd=path, env=env, capture_output=True, + text=True, encoding="utf-8", errors="replace", timeout=40) + out = run.stdout + "\n" + run.stderr + if run.returncode == 77: + print("SKIP 77: Leonida Vulkan device / sparse features unavailable") + return 77 + # The loader refuses the instance when a layer named in VK_INSTANCE_LAYERS (or the validation layer + # LEONIDA_VK_VALIDATION asks for) is not installed: that is the "layer absent" skip, not a layer failure. + if run.returncode != 0 and "vkCreateInstance" in out and "failed" in out: + print("SKIP 77: VK_LAYER_LUNARG_api_dump or VK_LAYER_KHRONOS_validation unavailable (vkCreateInstance failed)") + return 77 + if run.returncode != 0: + print(out[-7000:], file=sys.stderr) + raise AssertionError(f"Leonida GPU test failed exit={run.returncode}") + kinds = sorted(CASE.findall(out)) + if len(kinds) != 3 or "LAYER_FINAL PASS" not in out: + raise AssertionError(f"GPU byte verification missing: cases={kinds}; tail={out[-2000:]}") + candidates = list(path.glob("sparse_create_info.log*")) + if not candidates: + print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace") + return 77 + calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive) + print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros") + print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = " + f"{'EXCLUSIVE negative-control' if args.expect_baseline_exclusive else 'CONCURRENT with 2+ unique families'}") + print("Khronos validation enabled; no validation errors observed (GPU does not need to corrupt data for this test)") + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except (AssertionError, subprocess.TimeoutExpired) as error: + print(f"FAIL: {error}", file=sys.stderr) + raise SystemExit(1) diff --git a/runtime/test/check_tiny_frame.py b/runtime/test/check_tiny_frame.py new file mode 100644 index 000000000..8d7dbd8ac --- /dev/null +++ b/runtime/test/check_tiny_frame.py @@ -0,0 +1,124 @@ +"""Run tiny_frame under `gta6rt --run --trace-d3d12` on the Vulkan D3D12 device and check the run from outside. + + python -I check_tiny_frame.py [--probe d3d12_com_test.exe] [--runner wine ...] + +Checks the guest's verdict and exit code, that the loader's report binds d3d12_xs.dll!D3D12XboxCreateDevice to the +shim, and that the D3D12 trace is a gapless numbered sequence in which the calls a first frame needs appear in +order. Exits 77 (ctest: skipped) when --probe, one of the Vulkan device tests, says +there is no usable Vulkan device on this machine. +""" + +import argparse +import os +import re +import subprocess +import sys + +SKIP = 77 + +# The first frame, in the order the fixture makes the calls, as the trace words them (`called` for a method that +# returns nothing). Other traced calls, such as the queue and fence proxies' own entries, may sit between them. +EXPECTED = [ + "D3D12XboxCreateDevice ok", + "ID3D12Device::CreateCommandQueue ok", + "ID3D12Device::CreateCommandAllocator ok", + "ID3D12Device::CreateCommandList ok", + "ID3D12Device::CreateFence ok", + "ID3D12Device::CreateDescriptorHeap ok", + "ID3D12Device::CreateCommittedResource ok", + "ID3D12Device::CreateCommittedResource ok", + "ID3D12Device::CreateRenderTargetView called", + "ID3D12GraphicsCommandList::ClearRenderTargetView called", + "ID3D12GraphicsCommandList::ResourceBarrier called", + "ID3D12GraphicsCommandList::CopyTextureRegion called", + "ID3D12GraphicsCommandList::Close ok", + "ID3D12CommandQueue::ExecuteCommandLists ok", + "ID3D12CommandQueue::Signal ok", +] + + +def ordered_subsequence(expected, entries): + """The first expected entry that does not appear, in order, in entries; None when all do.""" + position = 0 + for want in expected: + while position < len(entries) and entries[position] != want: + position += 1 + if position == len(entries): + return want + position += 1 + return None + + +def parse_trace(lines): + """[(method, outcome)] from the `[d3d12-trace] #N method outcome` lines; raises ValueError on a gap.""" + entries = [] + for line in lines: + if not line.startswith("[d3d12-trace]"): + continue + match = re.fullmatch(r"\[d3d12-trace\] #(\d+) (.+) (called|ok|failed|unsupported|ignored|refused)", line) + if not match or int(match[1]) != len(entries) + 1: + raise ValueError(f"invalid trace sequence at entry {len(entries) + 1}: {line}") + entries.append((match[2], match[3])) + return entries + + +def check_output(code, output): + """A list of problems with one run's exit code and combined output; empty when it is what the test expects.""" + problems = [] + lines = output.replace("\r\n", "\n").split("\n") + if code != 0: + problems.append(f"exit code {code}") + if "tiny_frame: OK" not in lines: + problems.append("the guest did not print `tiny_frame: OK`") + if any(line.startswith("tiny_frame: FAIL") for line in lines): + problems.append("the guest reported a failed check") + if "game exited with code 0" not in lines: + problems.append("gta6rt did not report `game exited with code 0`") + if not any(re.fullmatch(r" +shim +d3d12_xs\.dll!D3D12XboxCreateDevice", line) for line in lines): + problems.append("d3d12_xs.dll!D3D12XboxCreateDevice was not bound to the shim") + try: + entries = parse_trace(lines) + except ValueError as error: + return problems + [str(error)] + bad = [f"{method} {outcome}" for method, outcome in entries if outcome in ("failed", "unsupported", "refused")] + if bad: + problems.append("traced calls that did not succeed: " + ", ".join(bad)) + missing = ordered_subsequence(EXPECTED, [f"{method} {outcome}" for method, outcome in entries]) + if missing: + problems.append(f"the trace has no `{missing}` at its place in the first-frame order") + return problems + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("loader") + parser.add_argument("guest") + parser.add_argument("--probe", help="a Vulkan device test; its exit code 77 skips this test") + parser.add_argument("--runner", action="append", default=[], + help="run Windows executables through this command (repeat for its arguments), e.g. wine") + options = parser.parse_args() + timeout = 180 if options.runner else 90 # a first start of Wine in a fresh prefix can take tens of seconds + + if options.probe: + probe = subprocess.run([*options.runner, options.probe], capture_output=True, timeout=timeout) + if probe.returncode == SKIP: + print("SKIP: no usable Vulkan device (the probe test skipped)") + return SKIP + + environment = dict(os.environ, LEONIDA_D3D12="vulkan") + run = subprocess.run([*options.runner, options.loader, "--run", os.path.basename(options.guest), "--trace-d3d12"], + cwd=os.path.dirname(os.path.abspath(options.guest)), env=environment, capture_output=True, + text=True, encoding="utf-8", errors="replace", timeout=timeout) + output = run.stdout + run.stderr + problems = check_output(run.returncode, output) + if problems: + print(output) + for problem in problems: + print(f"FAIL: {problem}") + return 1 + print("tiny_frame under gta6rt --run on the Vulkan D3D12 device: OK") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp index e459b4cc8..4d877d429 100644 --- a/runtime/test/command_list_test.cpp +++ b/runtime/test/command_list_test.cpp @@ -306,6 +306,6 @@ int main() { CHECK(query_fits_heap(h::copy_queue_timestamp, q::timestamp) && !query_fits_heap(h::timestamp, q::occlusion)); CHECK(query_fits_heap(h::so_statistics, q::so_statistics_stream3) && !query_fits_heap(6, q::occlusion)); CHECK(query_result_size(q::occlusion) == 8 && query_result_size(q::timestamp) == 8); - CHECK(query_result_size(q::pipeline_statistics) == 88 && query_result_size(q::so_statistics_stream0) == 0); + CHECK(query_result_size(q::pipeline_statistics) == 88 && query_result_size(q::so_statistics_stream0) == 16); return 0; } diff --git a/runtime/test/cpp_unwind_test.cpp b/runtime/test/cpp_unwind_test.cpp new file mode 100644 index 000000000..30cfc6ca1 --- /dev/null +++ b/runtime/test/cpp_unwind_test.cpp @@ -0,0 +1,31 @@ +#include + +namespace { + +struct UnwindMarker { + bool& destroyed; + ~UnwindMarker() { destroyed = true; } +}; + +struct TestException {}; + +// Keep the object in a separate frame, outside the catch handler's function. +__declspec(noinline) void throw_with_marker(bool& destroyed) { + UnwindMarker marker{destroyed}; + throw TestException{}; +} + +} // namespace + +int main() { + bool destroyed = false; + try { + throw_with_marker(destroyed); + } catch (const TestException&) { + if (destroyed) return 0; + std::fputs("C++ exception unwound without running a destructor\n", stderr); + return 1; + } + std::fputs("Expected a C++ exception\n", stderr); + return 1; +} diff --git a/runtime/test/cs_wave_probe_spv.h b/runtime/test/cs_wave_probe_spv.h new file mode 100644 index 000000000..28745ac06 --- /dev/null +++ b/runtime/test/cs_wave_probe_spv.h @@ -0,0 +1,63 @@ +// runtime/test/glsl/cs_wave_probe.comp, generated with glslang 16.6.0 (tests/test_cs_wave_probe_spv.py checks it): +// glslangValidator -V --target-env vulkan1.2 -Os -o cs_wave_probe.spv runtime/test/glsl/cs_wave_probe.comp +// SPIR-V 1.5, as the translator emits, so varying subgroup sizes are not allowed in it either. +#pragma once +#include +namespace leonida::vk_test { +inline constexpr std::uint32_t cs_wave_probe_spirv[] = { + 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000042u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, + 0x0000003du, 0x00020011u, 0x00000040u, 0x00020011u, 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, + 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x000014e4u, 0x00000001u, 0x000a000fu, 0x00000005u, + 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000fu, 0x00000019u, 0x00000021u, 0x00000029u, 0x00000030u, + 0x00060010u, 0x00000004u, 0x00000011u, 0x00000001u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u, + 0x000001c2u, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, 0x0065636eu, + 0x00090004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, 0x5f65636eu, 0x63657675u, + 0x00000032u, 0x00090004u, 0x4b5f4c47u, 0x735f5248u, 0x65646168u, 0x75735f72u, 0x6f726762u, 0x625f7075u, + 0x6f6c6c61u, 0x00000074u, 0x00090004u, 0x4b5f4c47u, 0x735f5248u, 0x65646168u, 0x75735f72u, 0x6f726762u, + 0x625f7075u, 0x63697361u, 0x00000000u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u, + 0x00000009u, 0x64726f57u, 0x00000073u, 0x00040006u, 0x00000009u, 0x00000000u, 0x00000077u, 0x00050005u, + 0x0000000du, 0x72657355u, 0x61746144u, 0x00000000u, 0x00050006u, 0x0000000du, 0x00000000u, 0x65736162u, + 0x00000000u, 0x00030005u, 0x0000000fu, 0x00006370u, 0x00080005u, 0x00000019u, 0x4c5f6c67u, 0x6c61636fu, + 0x6f766e49u, 0x69746163u, 0x6e496e6fu, 0x00786564u, 0x00060005u, 0x00000021u, 0x535f6c67u, 0x72676275u, + 0x5370756fu, 0x00657a69u, 0x00080005u, 0x00000029u, 0x535f6c67u, 0x72676275u, 0x4970756fu, 0x636f766eu, + 0x6f697461u, 0x0044496eu, 0x00060005u, 0x00000030u, 0x535f6c67u, 0x72676275u, 0x4970756fu, 0x00000044u, + 0x00040047u, 0x00000008u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000009u, 0x00000002u, 0x00050048u, + 0x00000009u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x0000000du, 0x00000002u, 0x00050048u, + 0x0000000du, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000019u, 0x0000000bu, 0x0000001du, + 0x00030047u, 0x00000021u, 0x00000000u, 0x00040047u, 0x00000021u, 0x0000000bu, 0x00000024u, 0x00030047u, + 0x00000022u, 0x00000000u, 0x00030047u, 0x00000029u, 0x00000000u, 0x00040047u, 0x00000029u, 0x0000000bu, + 0x00000029u, 0x00030047u, 0x0000002au, 0x00000000u, 0x00040047u, 0x00000030u, 0x0000000bu, 0x00000028u, + 0x00040047u, 0x0000003du, 0x00000001u, 0x00000000u, 0x00040047u, 0x0000003eu, 0x00000001u, 0x00000001u, + 0x00040047u, 0x0000003fu, 0x00000001u, 0x00000002u, 0x00040047u, 0x00000041u, 0x0000000bu, 0x00000019u, + 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030027u, 0x00000006u, 0x000014e5u, + 0x00040015u, 0x00000007u, 0x00000020u, 0x00000000u, 0x0003001du, 0x00000008u, 0x00000007u, 0x0003001eu, + 0x00000009u, 0x00000008u, 0x00040020u, 0x00000006u, 0x000014e5u, 0x00000009u, 0x00040017u, 0x0000000cu, + 0x00000007u, 0x00000002u, 0x0003001eu, 0x0000000du, 0x0000000cu, 0x00040020u, 0x0000000eu, 0x00000009u, + 0x0000000du, 0x0004003bu, 0x0000000eu, 0x0000000fu, 0x00000009u, 0x00040015u, 0x00000010u, 0x00000020u, + 0x00000001u, 0x0004002bu, 0x00000010u, 0x00000011u, 0x00000000u, 0x00040020u, 0x00000012u, 0x00000009u, + 0x0000000cu, 0x00040020u, 0x00000018u, 0x00000001u, 0x00000007u, 0x0004003bu, 0x00000018u, 0x00000019u, + 0x00000001u, 0x0004002bu, 0x00000007u, 0x0000001bu, 0x00000004u, 0x0004003bu, 0x00000018u, 0x00000021u, + 0x00000001u, 0x00040020u, 0x00000023u, 0x000014e5u, 0x00000007u, 0x0004002bu, 0x00000007u, 0x00000027u, + 0x00000001u, 0x0004003bu, 0x00000018u, 0x00000029u, 0x00000001u, 0x0004002bu, 0x00000007u, 0x0000002eu, + 0x00000002u, 0x0004003bu, 0x00000018u, 0x00000030u, 0x00000001u, 0x0004002bu, 0x00000007u, 0x00000035u, + 0x00000003u, 0x00020014u, 0x00000037u, 0x00030029u, 0x00000037u, 0x00000038u, 0x00040017u, 0x00000039u, + 0x00000007u, 0x00000004u, 0x00040032u, 0x00000007u, 0x0000003du, 0x00000001u, 0x00040032u, 0x00000007u, + 0x0000003eu, 0x00000001u, 0x00040032u, 0x00000007u, 0x0000003fu, 0x00000001u, 0x00040017u, 0x00000040u, + 0x00000007u, 0x00000003u, 0x00060033u, 0x00000040u, 0x00000041u, 0x0000003du, 0x0000003eu, 0x0000003fu, + 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x00050041u, + 0x00000012u, 0x00000013u, 0x0000000fu, 0x00000011u, 0x0004003du, 0x0000000cu, 0x00000014u, 0x00000013u, + 0x0004007cu, 0x00000006u, 0x00000015u, 0x00000014u, 0x0004003du, 0x00000007u, 0x0000001au, 0x00000019u, + 0x00050084u, 0x00000007u, 0x0000001cu, 0x0000001au, 0x0000001bu, 0x0004003du, 0x00000007u, 0x00000022u, + 0x00000021u, 0x00060041u, 0x00000023u, 0x00000024u, 0x00000015u, 0x00000011u, 0x0000001cu, 0x0005003eu, + 0x00000024u, 0x00000022u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000007u, 0x00000028u, 0x0000001cu, + 0x00000027u, 0x0004003du, 0x00000007u, 0x0000002au, 0x00000029u, 0x00060041u, 0x00000023u, 0x0000002bu, + 0x00000015u, 0x00000011u, 0x00000028u, 0x0005003eu, 0x0000002bu, 0x0000002au, 0x00000002u, 0x00000004u, + 0x00050080u, 0x00000007u, 0x0000002fu, 0x0000001cu, 0x0000002eu, 0x0004003du, 0x00000007u, 0x00000031u, + 0x00000030u, 0x00060041u, 0x00000023u, 0x00000032u, 0x00000015u, 0x00000011u, 0x0000002fu, 0x0005003eu, + 0x00000032u, 0x00000031u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000007u, 0x00000036u, 0x0000001cu, + 0x00000035u, 0x00050153u, 0x00000039u, 0x0000003au, 0x00000035u, 0x00000038u, 0x00060156u, 0x00000007u, + 0x0000003bu, 0x00000035u, 0x00000000u, 0x0000003au, 0x00060041u, 0x00000023u, 0x0000003cu, 0x00000015u, + 0x00000011u, 0x00000036u, 0x0005003eu, 0x0000003cu, 0x0000003bu, 0x00000002u, 0x00000004u, 0x000100fdu, + 0x00010038u, +}; +} diff --git a/runtime/test/d3d12_buffer_tiles_test.cpp b/runtime/test/d3d12_buffer_tiles_test.cpp index 0e2b4bad7..8e6079bdd 100644 --- a/runtime/test/d3d12_buffer_tiles_test.cpp +++ b/runtime/test/d3d12_buffer_tiles_test.cpp @@ -6,8 +6,10 @@ #include #include +#include #include #include +#include #define EXPECT(condition) do { \ if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ @@ -170,25 +172,55 @@ bool run(ID3D12Device& device, Results& result, bool layer = false) { EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); const auto* data = static_cast(mapped); + // Every word of every tile, with the first wrong word of each tile printed, so a failure says which side, + // snapshot and tile differ and what was read there. + UINT wrong_tiles = 0; for (UINT i = 0; i < snapshots; ++i) { for (UINT tile = 0; tile < tiles_per_buffer; ++tile) { const auto* first = data + (i * tiles_per_buffer + tile) * words_per_tile; result[i][tile] = *first; - EXPECT(std::all_of(first, first + words_per_tile, [&](auto word) { return word == expected[i][tile]; })); + const auto* bad = std::find_if(first, first + words_per_tile, [&](auto word) { return word != expected[i][tile]; }); + if (bad == first + words_per_tile) continue; + ++wrong_tiles; + const auto wrong_words = std::count_if(bad, first + words_per_tile, + [&](auto word) { return word != expected[i][tile]; }); + std::fprintf(stderr, "%s snapshot %u tile %u: word %u reads %#010x, want %#010x (%lld of %llu words wrong)\n", + layer ? "Vulkan layer" : "native D3D12", i, tile, unsigned(bad - first), unsigned(*bad), + unsigned(expected[i][tile]), static_cast(wrong_words), + static_cast(words_per_tile)); } } readback->Unmap(0, &empty); + EXPECT(wrong_tiles == 0); return true; } +// The host adapter for the native half. LEONIDA_HOST_ADAPTER picks it as in d3d12_copy_compare.h: "warp", or part of +// an adapter name (case-insensitive); a value that names no adapter with tiled resources tier 2 skips the native half +// rather than testing another GPU. Unset: the first hardware adapter with tier 2 or more. ComPtr native_device() { ComPtr factory; if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {}; + char want[128] = {}; + GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)); + std::string needle(want); + std::transform(needle.begin(), needle.end(), needle.begin(), [](unsigned char c) { return char(std::tolower(c)); }); for (UINT i = 0;; ++i) { ComPtr adapter; - if (factory->EnumAdapters1(i, &adapter) != S_OK) return {}; + if (needle == "warp") { + if (i > 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) break; + } else if (factory->EnumAdapters1(i, &adapter) != S_OK) { + break; + } DXGI_ADAPTER_DESC1 desc{}; - if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue; + if (FAILED(adapter->GetDesc1(&desc))) continue; + if (needle.empty()) { + if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; + } else if (needle != "warp") { + std::string name; + for (const wchar_t* c = desc.Description; *c; ++c) name += char(std::tolower(*c < 128 ? *c : '?')); + if (name.find(needle) == std::string::npos) continue; + } ComPtr device; if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue; D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; @@ -197,6 +229,10 @@ ComPtr native_device() { std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier)); return device; } + if (!needle.empty()) + std::printf("Native D3D12: no adapter matching LEONIDA_HOST_ADAPTER=%s with tiled resources tier 2 or more; " + "native half skipped\n", want); + return {}; } } // namespace diff --git a/runtime/test/d3d12_bundle_test.cpp b/runtime/test/d3d12_bundle_test.cpp index fd14dc29b..9839f17f7 100644 --- a/runtime/test/d3d12_bundle_test.cpp +++ b/runtime/test/d3d12_bundle_test.cpp @@ -12,6 +12,7 @@ // (one line per call the application made, however often the bundle runs) and for object lifetimes. // Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped. // No game data. +#include "test_temp_dir.h" #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "host_wine.h" @@ -730,18 +731,10 @@ int main() { const auto vs_program = fssm_program({0x56530101, 0xbf810000}); const auto ps_program = fssm_program({0x50530101, 0xbf810000}); const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); - // Removed on every way out of main. - struct Scratch { - std::filesystem::path path = std::filesystem::temp_directory_path() / "leonida_bundle_test"; - Scratch() { std::filesystem::create_directories(path); } - ~Scratch() { - std::error_code ignored; - std::filesystem::remove_all(path, ignored); - } - } scratch; - const auto& library = scratch.path; - std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); - std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); + const testfiles::ScratchDir scratch("leonida_bundle_test"); // removed on every way out of main + const auto& library = scratch.path(); + REQUIRE(testfiles::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv")); + REQUIRE(testfiles::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv")); { std::ofstream index(library / "index.json", std::ios::binary); index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp index eb921ddce..e9eeed3a6 100644 --- a/runtime/test/d3d12_com_test.cpp +++ b/runtime/test/d3d12_com_test.cpp @@ -31,8 +31,10 @@ struct Ref { static_assert(std::is_move_constructible_v); static_assert(std::is_move_assignable_v); -static_assert(sizeof(leonida::Draw::render_targets) == sizeof(leonida::TargetView) * 8); -static_assert(sizeof(leonida::Draw::vertex_buffers) == sizeof(leonida::VertexBufferView) * 32); +static_assert(sizeof(leonida::DrawViews::render_targets) == sizeof(leonida::TargetView) * 8); +static_assert(sizeof(leonida::DrawViews::vertex_buffers) == sizeof(leonida::VertexBufferView) * 32); +// The views stay out of the variant: a recorded command is sized by its largest member, Draw included. +static_assert(sizeof(leonida::Draw) < sizeof(leonida::DrawViews)); int main(int argc, char** argv) { if (argc == 2 && std::strcmp(argv[1], "--trace-d3d12") == 0) rt::d3d12_trace::set_enabled(true); diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index 2b0b14cda..c8b29d29c 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -9,7 +9,9 @@ // The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract. // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "shader_fixture_path.h" +#include "test_temp_dir.h" #include "vk_test_device.h" +#include "host_wine.h" #include "../shims/d3d12_com.h" #include "../src/gfx10_descriptors.h" #include "../src/cached_pso.h" @@ -203,9 +205,11 @@ std::vector cached_pso_cases(Device* device, D3D12_COMPUTE_PIPELINE_STA } // The same cases on the PC runtime, with an empty compute shader from d3dcompiler_47: the default adapter, then WARP. -// Empty when the host has no D3D12 device or no compiler (Wine), which the caller reports as a skip. +// Empty when the host has no D3D12 device or no compiler, or is Wine's, which the caller reports as a skip: vkd3d has +// both, but its GetCachedBlob is a stub, so every host answered nothing and the comparison failed on each run. std::vector> host_cached_pso_cases(const std::vector& root_blob, const std::vector& other_root_blob) { + if (hostwine::host_is_wine()) return {}; using CompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT, ID3DBlob**, ID3DBlob**); using CreateDeviceFn = decltype(&::D3D12CreateDevice); @@ -268,10 +272,9 @@ int main() { for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); // filler, s_endpgm-like words const auto container = shader_container(fssm); EXPECT(leonida::fssm_program(container) == fssm); - const auto library = std::filesystem::temp_directory_path() / "leonida_compute_test"; - std::filesystem::create_directories(library); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv", - std::filesystem::copy_options::overwrite_existing); + const testfiles::ScratchDir scratch("leonida_compute_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv")); { std::ofstream index(library / "index.json", std::ios::binary); // An entry for the same program with set-0 bindings comes first, as in one group of the corpus: the PSO @@ -387,7 +390,9 @@ int main() { E_INVALIDARG, E_INVALIDARG, S_OK}; EXPECT(layer == expected); const auto hosts = host_cached_pso_cases(root_blob, other_root_blob); - if (hosts.empty()) std::printf("SKIP: no host D3D12 device or compiler for the CachedPSO comparison\n"); + if (hosts.empty()) + std::printf("SKIP: no host D3D12 reference (Wine, or no device or compiler) for the CachedPSO " + "comparison\n"); for (const auto& host : hosts) EXPECT(host == layer); if (!hosts.empty()) std::printf("cached PSO: %zu host adapter(s) gave the same %d answers\n", hosts.size(), cached_case_count); @@ -889,7 +894,6 @@ int main() { fence.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } - std::filesystem::remove_all(library); unsigned mismatches = 0; for (std::uint32_t i = 0; i < elements; ++i) { diff --git a/runtime/test/d3d12_copy_xfmt_test.cpp b/runtime/test/d3d12_copy_xfmt_test.cpp index 0a504b266..e4b22868c 100644 --- a/runtime/test/d3d12_copy_xfmt_test.cpp +++ b/runtime/test/d3d12_copy_xfmt_test.cpp @@ -49,11 +49,13 @@ D3D12_RESOURCE_DESC buf(UINT64 bytes) { struct Case { const char* name; D3D12_RESOURCE_DESC src, dst; - bool whole; // CopyResource, else CopyTextureRegion of subresource 0 with no box + bool whole; // CopyResource, else CopyTextureRegion bool depth_values; // also marks the depth <-> colour cases, counted apart from the BC ones (both fail the test) UINT x = 0, y = 0; // CopyTextureRegion destination offset bool has_box = false; D3D12_BOX box{}; + UINT dst_mip = 0; + bool check_edge_bytes = false; }; D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) { @@ -66,7 +68,11 @@ D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3 return x; } -// Returns false when the device refuses something; out: the destination's footprint rows, every mip. +unsigned char upload_byte(UINT64 index) { + return static_cast(index * 7 + 3); +} + +// Pack the destination footprint rows for the copied mip, or every mip for CopyResource. bool run(ID3D12Device* dev, const Case& c, std::vector& out, HRESULT& close_hr) { D3D12_COMMAND_QUEUE_DESC qd{}; Ref q; @@ -78,7 +84,7 @@ bool run(ID3D12Device* dev, const Case& c, std::vector& out, HRES FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, a.p, nullptr, IID_PPV_ARGS(&l.p))) || FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) return false; - // Every mip goes up and comes back (one array layer). + // One array layer. Upload every source mip so both copy calls have initialized input. const UINT ns = c.src.MipLevels, nd = c.dst.MipLevels; D3D12_PLACED_SUBRESOURCE_FOOTPRINT sf[16]{}, df[16]{}; UINT rows[16]{}; @@ -100,12 +106,21 @@ bool run(ID3D12Device* dev, const Case& c, std::vector& out, HRES return false; unsigned char* p = nullptr; if (FAILED(upload->Map(0, nullptr, reinterpret_cast(&p)))) return false; - for (UINT64 i = 0; i < sbytes; ++i) p[i] = static_cast(i * 7 + 3); + for (UINT64 i = 0; i < sbytes; ++i) p[i] = upload_byte(i); if (c.depth_values) // normal floats in [0, 1): a host driver may flush denormals for (UINT64 i = 0; i + 4 <= sbytes; i += 4) { const float v = float((i / 4) % 1000) / 1000.0f; std::memcpy(p + i, &v, 4); } + if (c.check_edge_bytes) { + // The edge fixtures copy whole R32G32_UINT source rows, one eight-byte texel per BC1 block. + // Count the data bytes, excluding padding, so each row contains a different pattern. + const UINT64 bytes_per_row = c.src.Width * 8; + for (UINT y = 0; y < c.src.Height; ++y) { + auto* row = p + sf[0].Offset + UINT64(y) * sf[0].Footprint.RowPitch; + for (UINT64 x = 0; x < bytes_per_row; ++x) row[x] = upload_byte(y * bytes_per_row + x); + } + } upload->Unmap(0, nullptr); if (FAILED(readback->Map(0, nullptr, reinterpret_cast(&p)))) return false; std::memset(p, 0xcd, size_t(dbytes)); @@ -123,11 +138,13 @@ bool run(ID3D12Device* dev, const Case& c, std::vector& out, HRES l->CopyResource(dst.p, src.p); } else { D3D12_TEXTURE_COPY_LOCATION s{src.p}, d{dst.p}; + d.SubresourceIndex = c.dst_mip; l->CopyTextureRegion(&d, c.x, c.y, 0, &s, c.has_box ? &c.box : nullptr); } b = transition(dst.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); l->ResourceBarrier(1, &b); - for (UINT i = 0; i < nd; ++i) { + const UINT first_mip = c.whole ? 0 : c.dst_mip, end_mip = c.whole ? nd : c.dst_mip + 1; + for (UINT i = first_mip; i < end_mip; ++i) { D3D12_TEXTURE_COPY_LOCATION rs{dst.p}, rd{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; rs.SubresourceIndex = i; rd.PlacedFootprint = df[i]; @@ -143,9 +160,9 @@ bool run(ID3D12Device* dev, const Case& c, std::vector& out, HRES WaitForSingleObject(e, 10000); CloseHandle(e); if (FAILED(readback->Map(0, nullptr, reinterpret_cast(&p)))) return false; - // Only the bytes inside each row, every mip. + // Compare the bytes inside the rows and leave footprint padding out. out.clear(); - for (UINT i = 0; i < nd; ++i) + for (UINT i = first_mip; i < end_mip; ++i) for (UINT r = 0; r < rows[i]; ++r) { const unsigned char* row = p + df[i].Offset + r * df[i].Footprint.RowPitch; out.insert(out.end(), row, row + row_bytes[i]); @@ -207,6 +224,12 @@ int main() { {"CopyTextureRegion BC7 16x16 -> R32G32B32A32_UINT 4x4", tex(DXGI_FORMAT_BC7_UNORM, 16, 16), tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), false, false}, {"CopyTextureRegion BC1 box 4..12 x 8..16 -> R16G16B16A16_UINT 8x8 at (3, 1)", tex(DXGI_FORMAT_BC1_UNORM, 16, 16), tex(DXGI_FORMAT_R16G16B16A16_UINT, 8, 8), false, false, 3, 1, true, {4, 8, 0, 12, 16, 1}}, {"CopyTextureRegion BC1 10x6 (padded box) -> R32G32_UINT 3x2", tex(DXGI_FORMAT_BC1_UNORM, 10, 6), tex(DXGI_FORMAT_R32G32_UINT, 3, 2), false, false}, + {.name = "CopyTextureRegion R32G32_UINT 3x2 -> BC1 10x6", + .src = tex(DXGI_FORMAT_R32G32_UINT, 3, 2), .dst = tex(DXGI_FORMAT_BC1_UNORM, 10, 6), + .whole = false, .depth_values = false, .check_edge_bytes = true}, + {.name = "CopyTextureRegion R32G32_UINT 2x1 -> BC1 12x8 mip 1 (6x4)", + .src = tex(DXGI_FORMAT_R32G32_UINT, 2, 1), .dst = mips(tex(DXGI_FORMAT_BC1_UNORM, 12, 8), 2), + .whole = false, .depth_values = false, .dst_mip = 1, .check_edge_bytes = true}, {"CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)", tex(DXGI_FORMAT_R32G32_UINT, 2, 2), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 8, 4}, {"negative control: CopyTextureRegion R32_UINT 4x4 -> BC1 16x16", tex(DXGI_FORMAT_R32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false}, {"negative control: CopyTextureRegion R32G32_UINT 4x4 -> BC1 16x16 at (12, 0)", tex(DXGI_FORMAT_R32G32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 12, 0}, @@ -225,6 +248,23 @@ int main() { unsigned differ = 0, differ_depth = 0, compared = 0; for (const bool warp : {false, true}) { for (const Case& c : cases) { + // Check the full output of the partial-edge fixtures against the upload bytes on every available + // Vulkan device. Compare the same cases against native D3D12 using WARP when available. + if (!warp && (c.check_edge_bytes || std::strncmp(c.name, "negative", 8) == 0)) continue; + std::vector h, o; + HRESULT hh = S_OK, oh = S_OK; + if (c.check_edge_bytes) { + std::vector expected(size_t(c.src.Width) * c.src.Height * 8); + for (size_t i = 0; i < expected.size(); ++i) expected[i] = upload_byte(i); + const bool ours_ok = run(ours.p, c, o, oh); + if (!ours_ok || o != expected) { + std::fprintf(stderr, "%s: expected %zu upload bytes (read %zu bytes, Close 0x%08lx)\n", + c.name, expected.size(), o.size(), (unsigned long)oh); + ++differ; + continue; + } + std::printf("%s: matches %zu upload bytes\n", c.name, expected.size()); + } // A fresh device per case: an invalid copy removes the host device. Ref adapter; Ref host; @@ -232,15 +272,12 @@ int main() { if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue; const char* hn = adapter_name.c_str(); if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; - // Only WARP validates; a hardware driver may run an invalid copy. - if (!warp && std::strncmp(c.name, "negative", 8) == 0) continue; - std::vector h, o; - HRESULT hh = S_OK, oh = S_OK; const bool host_ok = run(host.p, c, h, hh); drain(host.p); if (!host_ok) { std::printf("%s: %s refuses it (Close 0x%08lx, removed reason 0x%08lx), skipped\n", c.name, hn, (unsigned long)hh, (unsigned long)host->GetDeviceRemovedReason()); + if (c.check_edge_bytes) continue; // the layer's output was already checked against the upload // The layer must refuse it too (at Close or execution), never write out of bounds (validation). const unsigned before = vk.validation_errors(); run(ours.p, c, o, oh); @@ -248,7 +285,7 @@ int main() { vk.validation_errors() - before); continue; } - const bool ours_ok = run(ours.p, c, o, oh); + const bool ours_ok = c.check_edge_bytes || run(ours.p, c, o, oh); ++compared; if (ours_ok && o == h) { std::printf("%s: matches %s\n", c.name, hn); diff --git a/runtime/test/d3d12_depth24_draw_test.cpp b/runtime/test/d3d12_depth24_draw_test.cpp new file mode 100644 index 000000000..436336e02 --- /dev/null +++ b/runtime/test/d3d12_depth24_draw_test.cpp @@ -0,0 +1,464 @@ +// D24_UNORM_S8_UINT in draws (D3D-309): depth bias in D24 units and depth quantised to 24 bits, as D3D12 gives on +// any device. On a GPU without a D24 attachment (AMD) the layer stores D32_SFLOAT_S8_UINT and its pixel stage writes +// the depth D24 would hold (src/depth24_fragment.h); with a native D24 the same expectations hold, so the test runs +// on both and says which path it took. +// +// The cases of the finding (@marquezinii, measured by @Vonsek on #291, native D3D12 on an RTX 5080, a Radeon iGPU and +// WARP): with the target cleared to 0.15625 + 2^-24 and a LESS test, a flat triangle at 0.15625 passes with bias 0 +// and fails everywhere with bias +1 and +2; an EQUAL test at exactly the cleared 0.15625 passes everywhere. Passing +// pixels are counted through the stencil plane (INCR on pass), so pipelines without a pixel shader count too. Then +// stored depth is read back through a footprint: a flat triangle with a constant bias, a sloped one with a +// slope-scaled bias (with and without DepthBiasClamp, within one 24-bit step: the slope is the GPU's), and a pixel +// shader that writes its own depth (stored quantised, not biased). Each runs with and without a pixel shader. The +// finding's cases run once more through a pass-through geometry shader without a pixel shader, which also gets the +// built-in depth stage. +// +// The shaders are GLSL written to the translator's contract (test/glsl/vs_depth.vert, ps_depth_empty.frag, +// ps_depth_write.frag, gs_depth.geom). No game data. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/depth24.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#if !defined(LEONIDA_TEST_VS_DEPTH_SPV) || !defined(LEONIDA_TEST_PS_DEPTH_EMPTY_SPV) || \ + !defined(LEONIDA_TEST_PS_DEPTH_WRITE_SPV) || !defined(LEONIDA_TEST_GS_DEPTH_SPV) +#error "the compiled test shaders must be named" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX + +namespace { + +constexpr UINT target_side = 64; +int g_failures = 0; + +void check(bool ok, const std::string& what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str()); + if (!ok) ++g_failures; +} + +std::uint32_t f2u(float f) { + std::uint32_t u; + std::memcpy(&u, &f, 4); + return u; +} + +// D3D's bias for a UNORM24 target: (float)DepthBias * r + SlopeScaledDepthBias * MaxDepthSlope, clamped. +float d3d_bias(int constant, float slope, float clamp, float max_slope) { + float bias = float(constant) * float(1.0 / 16777215.0) + slope * max_slope; + if (clamp > 0.0f) bias = std::fmin(bias, clamp); + if (clamp < 0.0f) bias = std::fmax(bias, clamp); + return bias; +} + +struct Pass { + bool pixel_shader = false; // ps_depth_empty, else no pixel shader + bool shader_depth = false; // ps_depth_write instead + bool geometry_shader = false; // gs_depth between the VS and the (absent) pixel shader + int bias = 0; + float slope = 0.0f, clamp = 0.0f; + D3D12_COMPARISON_FUNC func = D3D12_COMPARISON_FUNC_ALWAYS; + bool write = true; + float clear = 1.0f; + float z = 0.5f, dz = 0.0f, shader_z = 0.0f; // s0, s1 (vs_depth.vert), s2 (ps_depth_write.frag) +}; + +struct Result { + std::vector depth; // 24-bit codes, target_side * target_side + std::vector stencil; +}; + +struct Harness { + ID3D12Device* device = nullptr; + ID3D12RootSignature* root = nullptr; + std::vector vs, ps_empty, ps_write, gs; + Ref depth, readback; + Ref dsv_heap; + D3D12_CPU_DESCRIPTOR_HANDLE dsv{}; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot[2]{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + UINT64 fence_value = 0; + + bool run(const Pass& p, Result& out, std::string& error) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.VS = {vs.data(), vs.size()}; + if (p.shader_depth) + desc.PS = {ps_write.data(), ps_write.size()}; + else if (p.pixel_shader) + desc.PS = {ps_empty.data(), ps_empty.size()}; + if (p.geometry_shader) desc.GS = {gs.data(), gs.size()}; + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.RasterizerState.DepthBias = p.bias; + desc.RasterizerState.SlopeScaledDepthBias = p.slope; + desc.RasterizerState.DepthBiasClamp = p.clamp; + desc.DepthStencilState.DepthEnable = TRUE; + desc.DepthStencilState.DepthWriteMask = p.write ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO; + desc.DepthStencilState.DepthFunc = p.func; + desc.DepthStencilState.StencilEnable = TRUE; + desc.DepthStencilState.StencilReadMask = 0xff; + desc.DepthStencilState.StencilWriteMask = 0xff; + const D3D12_DEPTH_STENCILOP_DESC count{D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, + D3D12_STENCIL_OP_INCR_SAT, D3D12_COMPARISON_FUNC_ALWAYS}; + desc.DepthStencilState.FrontFace = desc.DepthStencilState.BackFace = count; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; + desc.SampleDesc.Count = 1; + Ref pso; + if (FAILED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))) { + error = "CreateGraphicsPipelineState failed"; + return false; + } + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, pso.p))) { + error = "list reset failed"; + return false; + } + D3D12_RESOURCE_BARRIER to_write = transition(depth.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_DEPTH_WRITE); + list->ResourceBarrier(1, &to_write); + list->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, p.clear, 0, 0, nullptr); + list->SetGraphicsRootSignature(root); + const std::uint32_t constants[3] = {f2u(p.z), f2u(p.dz), f2u(p.shader_z)}; + list->SetGraphicsRoot32BitConstants(0, 3, constants, 0); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VIEWPORT viewport{0, 0, float(target_side), float(target_side), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_side), LONG(target_side)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(0, nullptr, FALSE, &dsv); + list->DrawInstanced(3, 1, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + for (UINT plane = 0; plane < 2; ++plane) { + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = foot[plane]; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = depth.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.SubresourceIndex = plane; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + if (list->Close() != S_OK) { + error = "Close failed"; + return false; + } + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) { + error = "the layer refused the list"; + return false; + } + if (FAILED(queue->Signal(fence.p, ++fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) { + error = "fence wait failed"; + return false; + } + std::uint8_t* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, reinterpret_cast(&mapped)))) { + error = "Map failed"; + return false; + } + out.depth.assign(target_side * target_side, 0); + out.stencil.assign(target_side * target_side, 0); + for (UINT y = 0; y < target_side; ++y) + for (UINT x = 0; x < target_side; ++x) { + std::uint32_t word; + std::memcpy(&word, mapped + foot[0].Offset + y * foot[0].Footprint.RowPitch + x * 4, 4); + out.depth[y * target_side + x] = word & leonida::depth24_max; + out.stencil[y * target_side + x] = mapped[foot[1].Offset + y * foot[1].Footprint.RowPitch + x]; + } + readback->Unmap(0, nullptr); + return true; + } +}; + +std::string describe(const Pass& p) { + char text[200]; + const char* stages = p.shader_depth ? "PS writes depth" + : p.pixel_shader ? "with PS" + : p.geometry_shader ? "GS, no PS" + : "no PS"; + std::snprintf(text, sizeof(text), "%s, bias %d, slope %g, clamp %g", stages, p.bias, p.slope, p.clamp); + return text; +} + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); + bool native = true; + { + const auto props = reinterpret_cast( + d.instance_proc(d.instance, "vkGetPhysicalDeviceFormatProperties")); + VkFormatProperties d24{}; + props(d.physical, VK_FORMAT_D24_UNORM_S8_UINT, &d24); + native = d24.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; + std::printf("D24_UNORM_S8_UINT: %s\n", native ? "native D24" : "stored as D32_SFLOAT_S8_UINT"); + } + + const auto vs_program = fssm_program({0x56530309, 0xbf810000}); + const auto ps_empty_program = fssm_program({0x50530309, 0xbf810000}); + const auto ps_write_program = fssm_program({0x50530310, 0xbf810000}); + const auto gs_program = fssm_program({0x47530309, 0xbf810000}); + const auto library = std::filesystem::temp_directory_path() / "leonida_depth24_draw_test"; + std::filesystem::create_directories(library); + const auto copy = std::filesystem::copy_options::overwrite_existing; + std::filesystem::copy_file(LEONIDA_TEST_VS_DEPTH_SPV, library / "vs_depth.spv", copy); + std::filesystem::copy_file(LEONIDA_TEST_PS_DEPTH_EMPTY_SPV, library / "ps_depth_empty.spv", copy); + std::filesystem::copy_file(LEONIDA_TEST_PS_DEPTH_WRITE_SPV, library / "ps_depth_write.spv", copy); + std::filesystem::copy_file(LEONIDA_TEST_GS_DEPTH_SPV, library / "gs_depth.spv", copy); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"vs_depth\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + " \"ps_depth_empty\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_empty_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": []},\n" + " \"ps_depth_write\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_write_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": []},\n" + " \"gs_depth\": {\"stage\": \"gs\", \"fssm_sha256\": \"" << leonida::sha256_hex(gs_program) + << "\", \"bindings\": [], \"push_constant_bytes\": 144}}"; + } + + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.subgroup = d.subgroup; + info.shader_dir = library.string(); + info.features = d.enabled; // depthBiasClamp and geometryShader among them + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants = {0, 0, 3}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + Harness h; + h.device = device.p; + h.root = root.p; + h.vs = shader_container(vs_program); + h.ps_empty = shader_container(ps_empty_program); + h.ps_write = shader_container(ps_write_program); + h.gs = shader_container(gs_program); + + D3D12_RESOURCE_DESC depth_desc{}; + depth_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + depth_desc.Width = depth_desc.Height = target_side; + depth_desc.DepthOrArraySize = 1; + depth_desc.MipLevels = 1; + depth_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + depth_desc.SampleDesc.Count = 1; + depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_CLEAR_VALUE clear{}; + clear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + clear.DepthStencil.Depth = 1.0f; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &depth_desc, + D3D12_RESOURCE_STATE_COPY_SOURCE, &clear, + IID_PPV_ARGS(&h.depth.p)))); + UINT64 total = 0; + device->GetCopyableFootprints(&depth_desc, 0, 2, 0, h.foot, nullptr, nullptr, &total); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC readback_desc = buffer_desc(total); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&h.readback.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&h.dsv_heap.p)))); + h.dsv = {SIZE_T(reinterpret_cast(slot(h.dsv_heap.p, 9))(h.dsv_heap.p))}; + device->CreateDepthStencilView(h.depth.p, nullptr, h.dsv); + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&h.queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&h.allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, h.allocator.p, nullptr, + IID_PPV_ARGS(&h.list.p)))); + EXPECT(SUCCEEDED(h.list->Close())); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&h.fence.p)))); + + const auto passing = [](const Result& r) { + int n = 0; + for (std::uint8_t s : r.stencil) n += s != 0; + return n; + }; + constexpr int all = int(target_side * target_side); + // Without a pixel shader, with one, and through a geometry shader without one. + for (int mode = 0; mode < 3; ++mode) { + const bool ps = mode == 1, gs = mode == 2; + if (gs && !d.enabled.geometryShader) { + std::printf("SKIP the geometry-shader cases: no geometryShader on this GPU\n"); + continue; + } + // The finding's cases: one 24-bit step above 0.15625, LESS, bias 0, +1, +2. + const float above = 0.15625f + 5.9604645e-8f; // 0.15625 + 2^-24 + for (int bias : {0, 1, 2}) { + Pass p; + p.pixel_shader = ps; + p.geometry_shader = gs; + p.bias = bias; + p.func = D3D12_COMPARISON_FUNC_LESS; + p.write = false; + p.clear = above; + p.z = 0.15625f; + Result r; + std::string error; + EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false)); + const int expected = bias == 0 ? all : 0; + check(passing(r) == expected, "LESS against 0.15625 + 2^-24, " + describe(p) + ": " + + std::to_string(passing(r)) + " of " + std::to_string(all) + + " pass, expected " + std::to_string(expected)); + } + { // EQUAL at exactly the cleared value. + Pass p; + p.pixel_shader = ps; + p.geometry_shader = gs; + p.func = D3D12_COMPARISON_FUNC_EQUAL; + p.write = false; + p.clear = 0.15625f; + p.z = 0.15625f; + Result r; + std::string error; + EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false)); + check(passing(r) == all, "EQUAL at the cleared 0.15625, " + describe(p) + ": " + + std::to_string(passing(r)) + " of " + std::to_string(all) + " pass"); + } + // Stored depth, flat: the D24 code of z + bias * r. z sits on a 24-bit step, so no rounding tie decides the + // code (NVIDIA breaks ties differently from WARP and AMD, depth24.h). + for (int bias : {0, 3, -5, 1000}) { + Pass p; + p.pixel_shader = ps; + p.geometry_shader = gs; + p.bias = bias; + p.z = leonida::depth24_to_float(5033000); + Result r; + std::string error; + EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false)); + const std::uint32_t expected = leonida::depth24_quantize(p.z + d3d_bias(bias, 0, 0, 0)); + int wrong = 0; + for (std::uint32_t c : r.depth) wrong += c != expected; + if (native && bias != 0 && wrong) { + // Vulkan lets a fixed-point attachment's r be up to 2 * 2^-24 without VK_EXT_depth_bias_control's + // depthBiasExact, and the layer doesn't ask for it yet: reported, not failed (follow-up). + std::printf("KNOWN stored depth, flat, %s: native D24 bias not exact (code %u, D3D gives %u)\n", + describe(p).c_str(), r.depth[0], expected); + continue; + } + check(wrong == 0, "stored depth, flat, " + describe(p) + ": " + std::to_string(wrong) + + " of " + std::to_string(all) + " differ from code " + std::to_string(expected) + + " (first " + std::to_string(r.depth[0]) + ")"); + } + // Stored depth, sloped: z = 0.5 + 0.25 * x_clip, so 1/128 per pixel in x. Within one 24-bit step without a + // slope term; with one, within two: on the D32 path the slope comes from the derivatives of the + // interpolated depth (a few float ulps), where D24 hardware uses the triangle's plane. + for (const auto& [slope, clamp] : {std::pair{0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 0.004f}, {-2.0f, -0.01f}}) { + Pass p; + p.pixel_shader = ps; + p.geometry_shader = gs; + p.bias = 2; + p.slope = slope; + p.clamp = clamp; + p.z = 0.5f; + p.dz = 0.25f; + if (clamp != 0.0f && native && !d.enabled.depthBiasClamp) { + // The native path clamps in the rasterizer, which needs the feature this device left off. + std::printf("SKIP stored depth, sloped, %s: no depthBiasClamp on a native D24\n", + describe(p).c_str()); + continue; + } + Result r; + std::string error; + EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false)); + int wrong = 0; + std::uint32_t first_bad = 0, first_expected = 0, worst = 0; + const std::uint32_t tolerance = slope != 0.0f ? 2 : 1; + for (UINT y = 0; y < target_side; ++y) + for (UINT x = 0; x < target_side; ++x) { + const float x_clip = (float(x) + 0.5f) * 2.0f / float(target_side) - 1.0f; + const float z = 0.5f + 0.25f * x_clip; + const std::uint32_t expected = + leonida::depth24_quantize(z + d3d_bias(p.bias, slope, clamp, 0.25f * 2.0f / float(target_side))); + const std::uint32_t got = r.depth[y * target_side + x]; + const std::uint32_t diff = got > expected ? got - expected : expected - got; + worst = std::max(worst, diff); + if (diff > tolerance) { + if (!wrong) first_bad = got, first_expected = expected; + ++wrong; + } + } + if (native && wrong) { + std::printf("KNOWN stored depth, sloped, %s: native D24 bias not exact (code %u, D3D gives %u)\n", + describe(p).c_str(), first_bad, first_expected); + continue; + } + check(wrong == 0, "stored depth, sloped, " + describe(p) + ": " + std::to_string(wrong) + " of " + + std::to_string(all) + " more than " + std::to_string(tolerance) + + " step(s) off, largest " + std::to_string(worst) + + (wrong ? " (got " + std::to_string(first_bad) + ", expected " + + std::to_string(first_expected) + ")" + : std::string())); + } + } + // A pixel shader that writes its own depth: stored quantised, and D3D adds no bias to it. + for (int bias : {0, 7}) { + Pass p; + p.shader_depth = true; + p.bias = bias; + p.shader_z = 0.7f; + Result r; + std::string error; + EXPECT(h.run(p, r, error) || (std::fprintf(stderr, "%s\n", error.c_str()), false)); + const std::uint32_t expected = leonida::depth24_quantize(0.7f); + int wrong = 0; + for (std::uint32_t c : r.depth) wrong += c != expected; + check(wrong == 0, "stored depth, " + describe(p) + " 0.7: " + std::to_string(wrong) + " of " + + std::to_string(all) + " differ from code " + std::to_string(expected) + " (first " + + std::to_string(r.depth[0]) + ")"); + } + } + std::filesystem::remove_all(library); + std::printf("%d failure(s)\n", g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp index 77d37fa1e..e89735782 100644 --- a/runtime/test/d3d12_descriptor_test.cpp +++ b/runtime/test/d3d12_descriptor_test.cpp @@ -58,6 +58,23 @@ struct Ref { void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } +// A root signature blob from the PC runtime's own serializer; empty when it has none for that version. +std::vector serialize_root_signature(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { + using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto fn = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) + : nullptr; + std::vector out; + ID3DBlob* blob = nullptr; + if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { + const auto* bytes = static_cast(blob->GetBufferPointer()); + out.assign(bytes, bytes + blob->GetBufferSize()); + blob->Release(); + } + return out; +} + D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -869,6 +886,90 @@ int main() { const g::SamplerWords biased_samplers[] = {negative_bias, positive_bias}; EXPECT(rt::d3d12::register_samplers(device.p, biased_samplers) == S_OK); + // Static samplers of a root signature (docs/d3d12_vulkan.md section 3.5): no heap slot and no root argument, + // the shader holds the S# by value, so CreateRootSignature has to register it. One per blob version, each + // the wrapping sampler above with its own LOD range (so its own key), and one that only the fourth has: + // a border sampler with the UINT white border of the static enum. None is in the hash table before its + // root signature is created, all are after. A version the PC serializer here does not write is skipped. + const auto sampler_index = [&](const g::SamplerWords& words) { + std::uint32_t key[8]{~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u}; + std::memcpy(key, words.data(), sizeof(words)); + return rt::d3d12::bindless_hash_lookup(device.p, key); + }; + struct StaticCase { + D3D_ROOT_SIGNATURE_VERSION version; + const char* name; + float max_lod; + bool uint_white_border; + g::SamplerWords words; + bool created; + } static_cases[] = {{D3D_ROOT_SIGNATURE_VERSION_1_0, "1.0", 6.0f, false, {}, false}, + {D3D_ROOT_SIGNATURE_VERSION_1_1, "1.1", 7.0f, false, {}, false}, + {D3D_ROOT_SIGNATURE_VERSION_1_2, "1.2", 8.0f, false, {}, false}, + {D3D_ROOT_SIGNATURE_VERSION_1_1, "1.1, UINT white border", 9.0f, true, {}, false}}; + std::vector> static_roots(std::size(static_cases)); + UINT static_created = 0; + for (std::size_t c = 0; c < std::size(static_cases); ++c) { + StaticCase& test = static_cases[c]; + g::Sampler expected = sampler; + expected.max_lod = test.max_lod; + if (test.uint_white_border) { + expected.address_u = g::AddressMode::clamp_border; + expected.border_color = g::BorderColor::opaque_white; + expected.integer_border = true; + } + test.words = g::encode(expected); + EXPECT(test.words != sampler_words && sampler_index(test.words) == 0); + + D3D12_STATIC_SAMPLER_DESC1 fixed{}; + fixed.Filter = sampler_desc.Filter; + fixed.AddressU = test.uint_white_border ? D3D12_TEXTURE_ADDRESS_MODE_BORDER : sampler_desc.AddressU; + fixed.AddressV = sampler_desc.AddressV; + fixed.AddressW = sampler_desc.AddressW; + fixed.MaxAnisotropy = sampler_desc.MaxAnisotropy; + fixed.ComparisonFunc = sampler_desc.ComparisonFunc; + fixed.BorderColor = test.uint_white_border ? D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT + : D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; + fixed.MaxLOD = test.max_lod; + fixed.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + // D3D12_STATIC_SAMPLER_DESC is D3D12_STATIC_SAMPLER_DESC1 without the trailing Flags. + D3D12_STATIC_SAMPLER_DESC fixed0{}; + std::memcpy(&fixed0, &fixed, sizeof(fixed0)); + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = test.version; + if (test.version == D3D_ROOT_SIGNATURE_VERSION_1_0) { + root_desc.Desc_1_0.NumStaticSamplers = 1; + root_desc.Desc_1_0.pStaticSamplers = &fixed0; + } else if (test.version == D3D_ROOT_SIGNATURE_VERSION_1_1) { + root_desc.Desc_1_1.NumStaticSamplers = 1; + root_desc.Desc_1_1.pStaticSamplers = &fixed0; + } else { + root_desc.Desc_1_2.NumStaticSamplers = 1; + root_desc.Desc_1_2.pStaticSamplers = &fixed; + } + const std::vector blob = serialize_root_signature(root_desc); + if (blob.empty()) { + std::printf("static sampler, root signature %s: the PC serializer does not write it, skipped\n", + test.name); + continue; + } + EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), + IID_PPV_ARGS(&static_roots[c].p)))); + EXPECT(sampler_index(test.words) != 0); + test.created = true; + ++static_created; + } + // The entries outlive their root signatures, as a heap slot's S# outlives the heap: the shader pass below + // samples with them after the last reference is gone. + for (std::size_t c = 0; c < std::size(static_cases); ++c) { + const std::uint32_t before = sampler_index(static_cases[c].words); + static_roots[c].reset(); + EXPECT(sampler_index(static_cases[c].words) == before); + } + std::printf("static samplers: %u of %u root signatures registered their S#\n", static_created, + UINT(std::size(static_cases))); + EXPECT(static_created >= 3); // 1.0 and 1.1 are in every d3d12.dll; 1.2 came later + // The UINT texture's view in slot 0, and three border samplers after the first: UINT (0,0,0,0) and // (1,1,1,1) from CreateSampler2, which the proxy does not have (the inner device does), and float white. constexpr UINT uint_slot = 0, uint_black = 1, uint_white = 2, float_white = 3; @@ -1551,6 +1652,24 @@ int main() { clamped, texels); EXPECT(wrapped == texels && clamped == texels); + // The static samplers' S#s: the three wrapping ones give the texture, texel for texel, as the registered + // literal does. Unregistered (CreateRootSignature dropping them) they would clamp like the second above. + for (const StaticCase& test : static_cases) { + if (!test.created || test.uint_white_border) continue; + SampleKeys key = keys[0]; + std::memcpy(key.ssharp, test.words.data(), sizeof(key.ssharp)); + std::array pixels{}; + EXPECT(sample_through_set(d, set0, set0_layout, {&key, 1}, pixels.data())); + UINT static_wrapped = 0, static_clamped = 0; + for (UINT i = 0; i < texels; ++i) { + static_wrapped += std::memcmp(pixels.data() + 4 * i, texel(i % size, i / size).data(), 4) == 0; + static_clamped += std::memcmp(pixels.data() + 4 * i, texel(size - 1, i / size).data(), 4) == 0; + } + std::printf("static sampler, root signature %s: %u/%u texels wrapped (%u would match a clamp)\n", + test.name, static_wrapped, texels, static_clamped); + EXPECT(static_wrapped == texels && static_clamped < texels); + } + // With LOD zero requested, opposite bias extremes select the first and last mips. for (const auto& words : biased_samplers) { SampleKeys key = keys[0]; diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index 25c198d7a..eb530b084 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -13,6 +13,7 @@ // The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "shader_fixture_path.h" +#include "test_temp_dir.h" #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -68,14 +69,13 @@ int main() { const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); const auto fullscreen_container = shader_container(fullscreen_program); const auto vs_int_container = shader_container(vs_int_program); - const auto library = std::filesystem::temp_directory_path() / "leonida_draw_test"; - std::filesystem::create_directories(library); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV), library / "vs_fullscreen.spv", - std::filesystem::copy_options::overwrite_existing); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_INT_SPV), library / "vs_draw_int.spv", - std::filesystem::copy_options::overwrite_existing); + const testfiles::ScratchDir scratch("leonida_draw_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV), + library / "vs_fullscreen.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_INT_SPV), library / "vs_draw_int.spv")); { std::ofstream index(library / "index.json", std::ios::binary); index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) @@ -895,7 +895,6 @@ int main() { fence.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } - std::filesystem::remove_all(library); unsigned mismatches = 0; for (UINT row = 0; row < size; ++row) { diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp index 22202dd50..2f788dc75 100644 --- a/runtime/test/d3d12_fspx_compute_test.cpp +++ b/runtime/test/d3d12_fspx_compute_test.cpp @@ -10,6 +10,7 @@ // The shader (test/glsl/cs_user_data.comp) stands in for a translated one. No game data. Set LEONIDA_VK_VALIDATION=1 // to run under VK_LAYER_KHRONOS_validation. #include "shader_fixture_path.h" +#include "test_temp_dir.h" #include "vk_test_device.h" #include "../shims/d3d12_com.h" #include "../src/shader_library.h" @@ -163,15 +164,18 @@ int main() { constexpr std::uint32_t marker_a = 5000, marker_b = 7000; const auto code_a = kind6(marker_a), code_b = kind6(marker_b); const auto container_a = container(payload(code_a)); - const auto library = std::filesystem::temp_directory_path() / "leonida_fspx_compute_test"; - std::filesystem::remove_all(library); + const testfiles::ScratchDir scratch("leonida_fspx_compute_test"); + const auto& library = scratch.path(); std::filesystem::create_directories(library / "fspx"); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_user_data.spv"); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_user_data_b.spv"); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), + library / "fspx" / "cs_user_data.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), + library / "fspx" / "cs_user_data_b.spv")); // The review case on #1911: program C in two containers whose kind-0 entries differ, translated to two // different modules (the second has another generator word in its header, still a valid module). const auto code_c = kind6(9100); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_c_state1.spv"); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), + library / "fspx" / "cs_c_state1.spv")); { std::ifstream in(LEONIDA_TEST_CS_SPV, std::ios::binary); std::vector words((std::istreambuf_iterator(in)), std::istreambuf_iterator()); @@ -395,7 +399,6 @@ int main() { fence.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } - std::filesystem::remove_all(library); unsigned mismatches = 0; for (std::uint32_t i = 0; i < elements; ++i) { diff --git a/runtime/test/d3d12_geometry_test.cpp b/runtime/test/d3d12_geometry_test.cpp index 3ee4420c3..1cfe035b7 100644 --- a/runtime/test/d3d12_geometry_test.cpp +++ b/runtime/test/d3d12_geometry_test.cpp @@ -40,7 +40,9 @@ struct Vertex { int main() { vktest::Device d; - EXPECT(d.create()); + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU (hosted CI): ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); if (!d.enabled.geometryShader) { std::printf("SKIP: no geometryShader on this GPU\n"); return 77; // ctest's SKIP_RETURN_CODE diff --git a/runtime/test/d3d12_heap_properties_test.cpp b/runtime/test/d3d12_heap_properties_test.cpp new file mode 100644 index 000000000..434a7522b --- /dev/null +++ b/runtime/test/d3d12_heap_properties_test.cpp @@ -0,0 +1,284 @@ +// ID3D12Resource::GetHeapProperties on the Vulkan-backed device, compared with the host PC runtime: the properties +// (type, CPU page property, memory pool, node masks) and heap flags it reports for committed resources in every heap +// type (custom ones included) and with SHARED, ALLOW_DISPLAY, CREATE_NOT_ZEROED and CREATE_NOT_RESIDENT, for placed +// resources in heaps of each kind, and for a reserved resource, with null arguments too. d3d12_node_mask_test covers +// the node masks and DENY bits of a few committed resources; this test covers the rest. Every value is recorded, +// with whether the call wrote its outputs (they start as a sentinel), and the two records must be the same. A +// resource one device refuses to create is reported and its steps aren't compared. No shaders or game data. Skips +// (77) without a Vulkan GPU or the standalone device; without a host D3D12 device only the layer's own record is +// printed. Set LEONIDA_D3D49_VERBOSE=1 to print every value. +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr std::uint64_t kFaulted = 0xFA017EDull; +constexpr std::uint64_t kNotCreated = 0x5C1F1Dull; // the resource couldn't be created on this device +constexpr UINT kSentinel = 0xCDCDCDCDu; + +D3D12_RESOURCE_DESC buffer(UINT64 bytes = 64 * 1024) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return d; +} + +D3D12_RESOURCE_DESC texture(DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = 64; + d.Height = 64; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.Format = format; + d.SampleDesc.Count = 1; + d.Flags = flags; + return d; +} + +D3D12_HEAP_PROPERTIES heap(D3D12_HEAP_TYPE type) { return D3D12_HEAP_PROPERTIES{type}; } +D3D12_HEAP_PROPERTIES custom(D3D12_CPU_PAGE_PROPERTY page, D3D12_MEMORY_POOL pool) { + return D3D12_HEAP_PROPERTIES{D3D12_HEAP_TYPE_CUSTOM, page, pool}; +} + +enum class Kind { committed, placed, reserved }; + +struct Case { + const char* name; + Kind kind; + D3D12_HEAP_PROPERTIES props; // the committed resource's, or the placed resource's heap + D3D12_HEAP_FLAGS flags; + D3D12_RESOURCE_DESC desc; + D3D12_RESOURCE_STATES state; +}; + +const D3D12_HEAP_FLAGS kNone = D3D12_HEAP_FLAG_NONE; +const D3D12_RESOURCE_STATES kCommon = D3D12_RESOURCE_STATE_COMMON; + +std::vector cases() { + const auto rt = texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + const auto ds = texture(DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + const auto uav = texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto uav_buffer = buffer(); + uav_buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const auto wb = custom(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0); + const auto wc = custom(D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L0); + const auto none_l0 = custom(D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, D3D12_MEMORY_POOL_L0); + const auto none_l1 = custom(D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, D3D12_MEMORY_POOL_L1); + auto masks = heap(D3D12_HEAP_TYPE_DEFAULT); + masks.CreationNodeMask = 1; + masks.VisibleNodeMask = 1; + return { + {"committed buffer, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, buffer(), kCommon}, + {"committed UAV buffer, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, uav_buffer, kCommon}, + {"committed buffer, UPLOAD", Kind::committed, heap(D3D12_HEAP_TYPE_UPLOAD), kNone, buffer(), + D3D12_RESOURCE_STATE_GENERIC_READ}, + {"committed buffer, READBACK", Kind::committed, heap(D3D12_HEAP_TYPE_READBACK), kNone, buffer(), + D3D12_RESOURCE_STATE_COPY_DEST}, + {"committed buffer, CUSTOM write-back L0", Kind::committed, wb, kNone, buffer(), kCommon}, + {"committed buffer, CUSTOM write-combine L0", Kind::committed, wc, kNone, buffer(), kCommon}, + {"committed buffer, CUSTOM not-available L0", Kind::committed, none_l0, kNone, buffer(), kCommon}, + {"committed buffer, CUSTOM not-available L1", Kind::committed, none_l1, kNone, buffer(), kCommon}, + {"committed buffer, DEFAULT with node masks 1", Kind::committed, masks, kNone, buffer(), kCommon}, + {"committed buffer, DEFAULT, SHARED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_SHARED, + buffer(), kCommon}, + {"committed buffer, DEFAULT, CREATE_NOT_ZEROED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon}, + {"committed buffer, DEFAULT, CREATE_NOT_RESIDENT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT, buffer(), kCommon}, + {"committed buffer, DEFAULT, SHARED | CREATE_NOT_ZEROED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon}, + {"committed texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, texture(), kCommon}, + {"committed render target, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, rt, kCommon}, + {"committed depth texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, ds, + D3D12_RESOURCE_STATE_DEPTH_WRITE}, + {"committed UAV texture, DEFAULT", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), kNone, uav, kCommon}, + {"committed render target, DEFAULT, ALLOW_DISPLAY", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_ALLOW_DISPLAY, rt, kCommon}, + {"committed render target, DEFAULT, SHARED", Kind::committed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_SHARED, rt, kCommon}, + {"committed texture, CUSTOM write-back L0", Kind::committed, wb, kNone, texture(), kCommon}, + {"committed texture, CUSTOM write-combine L0", Kind::committed, wc, kNone, texture(), kCommon}, + + {"placed buffer, DEFAULT heap, ALLOW_ONLY_BUFFERS", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), kCommon}, + {"placed buffer, DEFAULT heap, ALLOW_ALL", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES, buffer(), kCommon}, + {"placed texture, DEFAULT heap, ALLOW_ONLY_NON_RT_DS_TEXTURES", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, texture(), kCommon}, + {"placed render target, DEFAULT heap, ALLOW_ONLY_RT_DS_TEXTURES", Kind::placed, + heap(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES, rt, kCommon}, + {"placed texture, DEFAULT heap, ALLOW_ALL", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES, texture(), kCommon}, + {"placed buffer, UPLOAD heap", Kind::placed, heap(D3D12_HEAP_TYPE_UPLOAD), + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), D3D12_RESOURCE_STATE_GENERIC_READ}, + {"placed buffer, READBACK heap", Kind::placed, heap(D3D12_HEAP_TYPE_READBACK), + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), D3D12_RESOURCE_STATE_COPY_DEST}, + {"placed buffer, CUSTOM write-back L0 heap", Kind::placed, wb, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, buffer(), + kCommon}, + {"placed buffer, DEFAULT heap, SHARED", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_SHARED, buffer(), kCommon}, + {"placed buffer, DEFAULT heap, CREATE_NOT_ZEROED", Kind::placed, heap(D3D12_HEAP_TYPE_DEFAULT), + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, buffer(), kCommon}, + + {"reserved buffer", Kind::reserved, {}, kNone, buffer(), kCommon}, + {"reserved texture", Kind::reserved, {}, kNone, [] { + auto d = texture(); + d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + return d; + }(), kCommon}, + }; +} + +struct Record { + std::vector names; + std::vector values; + void add(const std::string& name, std::uint64_t value) { + names.push_back(name); + values.push_back(value); + } +}; + +HRESULT create(ID3D12Device* device, const Case& c, Ref& h, Ref& r) { + switch (c.kind) { + case Kind::committed: + return device->CreateCommittedResource(&c.props, c.flags, &c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p)); + case Kind::placed: { + D3D12_HEAP_DESC hd{}; + hd.SizeInBytes = 4 * 1024 * 1024; + hd.Properties = c.props; + hd.Flags = c.flags; + const HRESULT hr = device->CreateHeap(&hd, IID_PPV_ARGS(&h.p)); + if (FAILED(hr)) return hr; + return device->CreatePlacedResource(h.p, 0, &c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p)); + } + case Kind::reserved: + return device->CreateReservedResource(&c.desc, c.state, nullptr, IID_PPV_ARGS(&r.p)); + } + return E_FAIL; +} + +HRESULT get(ID3D12Resource* r, D3D12_HEAP_PROPERTIES* p, D3D12_HEAP_FLAGS* f) { + __try { + return r->GetHeapProperties(p, f); + } __except (EXCEPTION_EXECUTE_HANDLER) { + return HRESULT(kFaulted); + } +} + +void record_call(Record& out, const std::string& what, ID3D12Resource* r, bool want_props, bool want_flags) { + D3D12_HEAP_PROPERTIES p; + std::memset(&p, 0xCD, sizeof(p)); + auto f = D3D12_HEAP_FLAGS(kSentinel); + const HRESULT hr = get(r, want_props ? &p : nullptr, want_flags ? &f : nullptr); + out.add(what + ": hr", std::uint32_t(hr)); + if (want_props) { + out.add(what + ": Type", std::uint32_t(p.Type)); + out.add(what + ": CPUPageProperty", std::uint32_t(p.CPUPageProperty)); + out.add(what + ": MemoryPoolPreference", std::uint32_t(p.MemoryPoolPreference)); + out.add(what + ": CreationNodeMask", p.CreationNodeMask); + out.add(what + ": VisibleNodeMask", p.VisibleNodeMask); + } + if (want_flags) out.add(what + ": flags", std::uint32_t(f)); +} + +void run(ID3D12Device* device, Record& out) { + for (const Case& c : cases()) { + Ref h; + Ref r; + const HRESULT created = create(device, c, h, r); + out.add(std::string(c.name) + ": created", std::uint32_t(created)); + if (FAILED(created) || !r.p) { + out.add(std::string(c.name) + " [not created]", kNotCreated); + continue; + } + record_call(out, c.name, r.p, true, true); + record_call(out, std::string(c.name) + ", properties only", r.p, true, false); + record_call(out, std::string(c.name) + ", flags only", r.p, false, true); + record_call(out, std::string(c.name) + ", both null", r.p, false, false); + } +} + +} // namespace + +int main() { + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) { + std::printf("heap properties: no Vulkan device, skipped\n"); + return 77; + } + const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0; + Record ours; + run(device.p, ours); + + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto create_host = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))) + : nullptr; + Ref host; + if (!create_host || FAILED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { + std::printf("heap properties: no host D3D12 device to compare with; %zu values recorded, not compared\n", + ours.values.size()); + } else { + Record theirs; + run(host.p, theirs); + // A resource one side couldn't create has fewer entries: compare case by case on the names both have. + int mismatches = 0, compared = 0, skipped = 0; + std::size_t j = 0; + for (std::size_t i = 0; i < ours.names.size(); ++i) { + while (j < theirs.names.size() && theirs.names[j] != ours.names[i]) ++j; + if (j == theirs.names.size()) { + std::printf("heap properties %s: ours 0x%llx, the host has no such value (not compared)\n", + ours.names[i].c_str(), static_cast(ours.values[i])); + ++skipped; + j = 0; + continue; + } + const std::uint64_t a = ours.values[i], b = theirs.values[j]; + if (b == kFaulted) { + std::printf("heap properties %s: the host faults, not compared (ours 0x%llx)\n", ours.names[i].c_str(), + static_cast(a)); + ++skipped; + continue; + } + ++compared; + const bool same = a == b; + if (verbose || !same) + std::printf("heap properties %s: ours 0x%llx host 0x%llx%s\n", ours.names[i].c_str(), + static_cast(a), static_cast(b), + same ? "" : " MISMATCH"); + mismatches += !same; + } + std::printf("heap properties: %d values compared with the host (%d more not compared), %d mismatches\n", + compared, skipped, mismatches); + EXPECT(mismatches == 0); + } + std::printf("d3d12_heap_properties_test: OK\n"); + return 0; +} diff --git a/runtime/test/d3d12_indirect_dispatch_count_test.cpp b/runtime/test/d3d12_indirect_dispatch_count_test.cpp new file mode 100644 index 000000000..75a86b220 --- /dev/null +++ b/runtime/test/d3d12_indirect_dispatch_count_test.cpp @@ -0,0 +1,231 @@ +// D3D12 ExecuteIndirect with a GPU count buffer and one DISPATCH argument per record. +// The same synthetic workload runs on native WARP and on the Vulkan layer, with actual GPU readback. +// Set LEONIDA_VK_VALIDATION=1 to enable Vulkan core and synchronization validation. +#include "vk_test_device.h" +#include "shader_fixture_path.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_INDIRECT_COUNT_SPV +#error "LEONIDA_TEST_INDIRECT_COUNT_SPV must name the synthetic GLSL compute module" +#endif + +using namespace d3d12test; +namespace { +constexpr UINT kMaximum = 3, kStride = 20, kArgsOffset = 32, kCountOffset = 44; +const char native_shader[] = R"( +RWByteAddressBuffer output : register(u0); +[numthreads(1,1,1)] +void main(uint3 group : SV_GroupID) { + uint old; + output.InterlockedAdd(0, 1, old); + output.InterlockedAdd(4, group.x + 1, old); +} +)"; + +bool run(ID3D12Device* dev, const std::vector& shader, UINT count, bool gpu_update, + std::array& result, bool shim) { + Ref root; + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + param.Descriptor = {0, 0}; + param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto serialized = serialize_root_signature(root_desc); + if (serialized.empty() || + FAILED(dev->CreateRootSignature(0, serialized.data(), serialized.size(), IID_PPV_ARGS(&root.p)))) + return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root.p; + desc.CS = {shader.data(), shader.size()}; + Ref pso; + if (FAILED(dev->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso.p)))) return false; + const D3D12_INDIRECT_ARGUMENT_DESC argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{kStride, 1, &argument, 0}; + Ref signature; + if (FAILED(dev->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p)))) + return false; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref source, args, counts, output, readback; + const auto create = [&](Ref& dest, D3D12_HEAP_PROPERTIES heap, + D3D12_RESOURCE_STATES state, D3D12_RESOURCE_FLAGS flags) { + const auto buffer = buffer_desc(256, flags); + return SUCCEEDED(dev->CreateCommittedResource( + &heap, D3D12_HEAP_FLAG_NONE, &buffer, state, nullptr, IID_PPV_ARGS(&dest.p))); + }; + if (!create(source, upload_heap, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE) || + !create(args, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE) || + !create(counts, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE) || + !create(output, default_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || + !create(readback, readback_heap, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE)) + return false; + std::array input{}; + for (UINT i = 0; i < kMaximum; ++i) { + const UINT base = (kArgsOffset + i * kStride) / 4; + input[base] = i + 1; // number of groups in the record, 1 then 2 then 3 + input[base + 1] = input[base + 2] = 1; + input[base + 3] = 0xa5a5a5a5; // padding: must be ignored + input[base + 4] = 0x5a5a5a5a; + } + input[40] = count; // source offset 160, copied to destination +44 + input[41] = 3; // update count from source offset 164 + void* mapped = nullptr; + if (FAILED(source->Map(0, nullptr, &mapped)) || !mapped) return false; + std::memcpy(mapped, input.data(), sizeof(input)); + source->Unmap(0, nullptr); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_COMPUTE}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + if (FAILED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) || + FAILED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&allocator.p))) || + FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, allocator.p, + pso.p, IID_PPV_ARGS(&list.p))) || + FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) + return false; + list->CopyBufferRegion(args.p, kArgsOffset, source.p, kArgsOffset, kMaximum * kStride); + list->CopyBufferRegion(counts.p, kCountOffset, source.p, 160, 4); + list->CopyBufferRegion(output.p, 0, source.p, 0, 8); // initialize the UAV to zero + const D3D12_RESOURCE_BARRIER ready[] = { + transition(args.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + transition(counts.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + transition(output.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; + list->ResourceBarrier(3, ready); + list->SetComputeRootSignature(root.p); + list->SetPipelineState(pso.p); + list->SetComputeRootUnorderedAccessView(0, output->GetGPUVirtualAddress()); + list->ExecuteIndirect(signature.p, kMaximum, args.p, kArgsOffset, counts.p, kCountOffset); + if (gpu_update) { + auto to_copy = transition(counts.p, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_DEST); + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(counts.p, kCountOffset, source.p, 164, 4); + auto to_indirect = transition(counts.p, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list->ResourceBarrier(1, &to_indirect); + // Repeat with a count produced by a GPU copy after the previous indirect dispatch. + list->ExecuteIndirect(signature.p, kMaximum, args.p, kArgsOffset, counts.p, kCountOffset); + } + const auto to_copy = transition(output.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, 0, output.p, 0, 8); + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (shim && rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; + if (FAILED(queue->Signal(fence.p, 1))) return false; + const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) return false; + const bool completed = SUCCEEDED(fence->SetEventOnCompletion(1, event)) && + WaitForSingleObject(event, 20000) == WAIT_OBJECT_0; + CloseHandle(event); + if (!completed || FAILED(readback->Map(0, nullptr, &mapped)) || !mapped) return false; + std::memcpy(result.data(), mapped, sizeof(result)); + readback->Unmap(0, nullptr); + return true; +} + +std::array expected(UINT count, bool update) { + auto result = std::array{}; + const auto accumulate = [&](UINT c) { + for (UINT i = 0; i < std::min(c, kMaximum); ++i) { + result[0] += i + 1; + result[1] += (i + 1) * (i + 2) / 2; + } + }; + accumulate(count); + if (update) accumulate(3); + return result; +} +} // namespace + +int main() { + using Compile = decltype(&D3DCompile); + const HMODULE compiler = LoadLibraryExW(L"d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!compiler) return 77; + const auto compile = reinterpret_cast(GetProcAddress(compiler, "D3DCompile")); + if (!compile) return 77; + Ref native, errors; + if (FAILED(compile(native_shader, std::strlen(native_shader), nullptr, nullptr, nullptr, + "main", "cs_5_0", 0, 0, &native.p, &errors.p)) || !native.p) + return 1; + const auto* native_bytes = static_cast(native->GetBufferPointer()); + const std::vector native_code(native_bytes, native_bytes + native->GetBufferSize()); + Ref factory; + Ref warp; + Ref host; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || + FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || + FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) + return 77; + + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (!vk.buffer_device_address) return 77; + std::vector program = fssm_program({0x1100u, 0x44u, 0x55u, 0x66u, 0x77u, 0x88u}); + for (UINT i = 0; i < 12; ++i) put32(program, 0xbf810000 + i); + const auto container = shader_container(program); + const auto fixture = std::filesystem::temp_directory_path() / + ("leonida_indirect_dispatch_count_" + std::to_string(GetCurrentProcessId())); + std::filesystem::create_directories(fixture); + std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_INDIRECT_COUNT_SPV), + fixture / "count.spv", std::filesystem::copy_options::overwrite_existing); + { + std::ofstream index(fixture / "index.json", std::ios::binary); + index << "{\"count\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program) + << "\",\"bindings\":[],\"push_constant_bytes\":144,\"local_size\":[1,1,1]," + "\"uses_code_base\":false,\"wave64\":false}}"; + } + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.buffer_device_address = vk.buffer_device_address; + info.shader_dir = fixture.string(); + Ref layer; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&layer.p)))) return 1; + + unsigned cases = 0; + for (UINT count : {0u, 1u, 3u, 7u}) { + for (bool update : {false, true}) { + std::array native_result{}, layer_result{}; + if (!run(host.p, native_code, count, update, native_result, false) || + !run(layer.p, container, count, update, layer_result, true) || + native_result != expected(count, update) || layer_result != native_result) { + std::fprintf(stderr, "count %u update %d: host %u/%u, layer %u/%u, expected %u/%u\n", + count, int(update), native_result[0], native_result[1], + layer_result[0], layer_result[1], + expected(count, update)[0], expected(count, update)[1]); + return 1; + } + ++cases; + } + } + if (vk.validation_errors()) { + std::fprintf(stderr, "validation errors: %u\n", vk.validation_errors()); + return 1; + } + std::printf("counted ExecuteIndirect(DISPATCH): %u native WARP / Vulkan GPU comparisons passed; " + "count=0,1,max,>max, nonzero offsets and GPU count overwrite, no validation errors\n", cases); + return 0; +} diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp index e742de72e..cd9448c75 100644 --- a/runtime/test/d3d12_m2_textured_test.cpp +++ b/runtime/test/d3d12_m2_textured_test.cpp @@ -14,6 +14,9 @@ // the left half is drawn from the gradient, the right half (the second draw switches the SRV table to slot 1) from // the reflected texture. Compared byte for byte (error 0). The test also checks the hash table: the T# of each view and the S# // have distinct non-zero indices, and bytes that were never created have none (the fallback, 0). +// The same quad is also drawn with LINEAR/CLAMP. Each RGBA8 channel is checked against the four clamped +// texels at that pixel center, allowing one quantization level. +// // Sampler control (suggested and measured by @Vonsek in #1489): with U in range, POINT/CLAMP, POINT/WRAP and the // fallback sampler all give the same pixels, so the draw above cannot tell which sampler it used. A second pass draws // with ps_m2_uoff.asm, which adds 1 to U just before image_sample, and two sampler-heap slots, [0] POINT/CLAMP and @@ -30,6 +33,7 @@ #include #include +#include #include #include #include @@ -66,6 +70,26 @@ Texel gradient(UINT x, UINT y) { // The second texture: the first one point-reflected, so no texel of it is in the same place. Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); } +Texel linear_clamp(UINT col, UINT row) { + const float x = (col + 0.5f) * texture_size / target_size - 0.5f; + const float y = (row + 0.5f) * texture_size / target_size - 0.5f; + const int x0 = int(std::floor(x)), y0 = int(std::floor(y)); + const float fx = x - x0, fy = y - y0; + const auto texel = col < target_size / 2 ? gradient : reflected; + auto tap = [&](int dx, int dy) { + return texel(std::clamp(x0 + dx, 0, int(texture_size) - 1), + std::clamp(y0 + dy, 0, int(texture_size) - 1)); + }; + const Texel a = tap(0, 0), b = tap(1, 0), c = tap(0, 1), d = tap(1, 1); + Texel result{}; + for (unsigned k = 0; k < result.size(); ++k) { + const float top = a[k] + fx * (b[k] - a[k]); + const float bottom = c[k] + fx * (d[k] - c[k]); + result[k] = std::uint8_t(std::lround(top + fy * (bottom - top))); + } + return result; +} + } // namespace int main() { @@ -92,8 +116,15 @@ int main() { const auto uoff_program = read_file(root_dir / "fssm" / "ps_m2_uoff.fssm"); EXPECT(uoff_program.size() >= 4 && library.find("ps", leonida::sha256_hex(uoff_program))); const auto uoff_container = shader_container(uoff_program); + // ps_m2_literal builds its S# from immediates: the index lists it under literal_samplers. + const auto literal_program = read_file(root_dir / "fssm" / "ps_m2_literal.fssm"); + const auto* literal_entry = library.find("ps", leonida::sha256_hex(literal_program)); + EXPECT(literal_program.size() >= 4 && literal_entry); + const leonida::gfx10::SamplerWords literal_words{0x92u, 0xc00000u, 0x14500000u, 0u}; + EXPECT(literal_entry->literal_samplers.size() == 1 && literal_entry->literal_samplers[0] == literal_words); + const auto literal_container = shader_container(literal_program); - std::vector pixels(std::size_t(target_pitch) * target_size), control_pixels = pixels; + std::vector pixels(std::size_t(target_pitch) * target_size), control_pixels = pixels, linear_pixels = pixels; unsigned image_hits = 0, sampler_hits = 0; { rt::d3d12::VulkanDeviceInfo info{}; @@ -167,6 +198,20 @@ int main() { pso_desc.pRootSignature = indexed_root.p; pso_desc.PS = {uoff_container.data(), uoff_container.size()}; EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&uoff_pso.p)))); + { + // A pipeline with a literal-S# shader registers that S#: before it the hash table has no key for the + // words (a lookup gives the fallback, 0), after it a sampler index. Nothing else names this S#. + std::uint32_t key[8]; + std::memcpy(key, literal_words.data(), 16); + std::fill(key + 4, key + 8, 0xffffffffu); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) == 0); + D3D12_GRAPHICS_PIPELINE_STATE_DESC literal_desc = pso_desc; + literal_desc.pRootSignature = root.p; + literal_desc.PS = {literal_container.data(), literal_container.size()}; + Ref literal_pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&literal_desc, IID_PPV_ARGS(&literal_pso.p)))); + EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key) != 0); + } const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; @@ -218,7 +263,7 @@ int main() { // The two heaps; their start handles come back in RAX (heap slots 9 and 10). const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2, + const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 3, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref srv_heap, sampler_heap; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); @@ -252,6 +297,10 @@ int main() { EXPECT(sampler_step >= 16); sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + sampler_step)}); + sampler_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler_desc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; + device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + 2 * sampler_step)}); + // The hash table, after the descriptors were created and before anything has run: a T# is 8 dwords of the // heap slot, an S# 4 dwords followed by 0xFFFFFFFF x4. Each of the three has an index, they differ, and @@ -326,15 +375,18 @@ int main() { const D3D12_VIEWPORT viewport{0, 0, float(target_size), float(target_size), 0, 1}; list->RSSetViewports(1, &viewport); list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); - list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu}); - for (UINT half = 0; half < 2; ++half) { - // The same quad over the whole target; the scissor rectangle keeps one half, and the SRV table names - // the texture of that half. - const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)}; - list->RSSetScissorRects(1, &scissor); - list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step}); - list->DrawIndexedInstanced(6, 1, 0, 0, 0); - } + auto draw_halves = [&](std::uint64_t sampler) { + list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{sampler}); + for (UINT half = 0; half < 2; ++half) { + // The same quad over the whole target; the scissor rectangle keeps one half, and the SRV table names + // the texture of that half. + const D3D12_RECT scissor{LONG(half * target_size / 2), 0, LONG((half + 1) * target_size / 2), LONG(target_size)}; + list->RSSetScissorRects(1, &scissor); + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu + std::uint64_t(half) * step}); + list->DrawIndexedInstanced(6, 1, 0, 0, 0); + } + }; + draw_halves(sampler_gpu); D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -347,6 +399,13 @@ int main() { src.pResource = target.p; src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + auto to_render = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_render); + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + draw_halves(sampler_gpu + 2 * sampler_step); + list->ResourceBarrier(1, &to_copy); + dst.pResource = readback2.p; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); EXPECT(list->Close() == S_OK); ID3D12CommandList* lists[] = {list.p}; queue->ExecuteCommandLists(1, lists); @@ -357,6 +416,11 @@ int main() { EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); std::memcpy(pixels.data(), mapped, pixels.size()); + void* mapped_linear = nullptr; + EXPECT(SUCCEEDED(readback2->Map(0, nullptr, &mapped_linear))); + std::memcpy(linear_pixels.data(), mapped_linear, linear_pixels.size()); + readback2->Unmap(0, nullptr); + // The control pass: U + 1 in the PS, WRAP sampler (slot 1) on the left, CLAMP (slot 0) on the right. Ref allocator2; Ref list2; @@ -418,12 +482,22 @@ int main() { EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } - unsigned mismatches = 0; + unsigned mismatches = 0, linear_mismatches = 0; + int max_linear_error = 0; for (UINT row = 0; row < target_size; ++row) { for (UINT col = 0; col < target_size; ++col) { const UINT tx = col / (target_size / texture_size), ty = row / (target_size / texture_size); const Texel want = col < target_size / 2 ? gradient(tx, ty) : reflected(tx, ty); const std::uint8_t* got = &pixels[std::size_t(row) * target_pitch + col * 4]; + const Texel filtered = linear_clamp(col, row); + const auto* linear = &linear_pixels[std::size_t(row) * target_pitch + col * 4]; + for (unsigned k = 0; k < filtered.size(); ++k) { + const int error = std::abs(int(linear[k]) - filtered[k]); + max_linear_error = std::max(max_linear_error, error); + if (error > 1 && linear_mismatches++ < 8) + std::fprintf(stderr, "LINEAR (%u, %u) channel %u: got %u want %u\n", + col, row, k, unsigned(linear[k]), unsigned(filtered[k])); + } if (std::memcmp(got, want.data(), 4) == 0) continue; if (mismatches++ < 8) std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1], @@ -431,6 +505,8 @@ int main() { } } EXPECT(!mismatches); + EXPECT(!linear_mismatches); + std::printf("M2 LINEAR: %u pixels, maximum RGBA8 channel error %d\n", target_size * target_size, max_linear_error); // The control pass: left half the gradient (WRAP: U + 1 wraps back), right half the reflected texture's last // column per row (CLAMP: U + 1 is past the edge). Pixels that differ from the plain pass tell the clamp was used. diff --git a/runtime/test/d3d12_method_variants_test.cpp b/runtime/test/d3d12_method_variants_test.cpp index 943577fff..d1b8edf4a 100644 --- a/runtime/test/d3d12_method_variants_test.cpp +++ b/runtime/test/d3d12_method_variants_test.cpp @@ -1,5 +1,6 @@ // The 1/2/3 method variants of the Vulkan-backed ID3D12Device (D3D-28), each compared with the method it wraps: -// CreateCommittedResource1/2/3 with CreateCommittedResource, CreateCommandQueue1 with CreateCommandQueue and +// CreateCommittedResource1/2/3 with CreateCommittedResource, CreatePlacedResource2 with CreatePlacedResource, +// CreateReservedResource1/2 with CreateReservedResource, CreateCommandQueue1 with CreateCommandQueue and // GetCopyableFootprints1 with GetCopyableFootprints. The device is called directly, not through the Xbox-ABI proxy, // because the proxy's slot 76 is the Xbox texture method, not CreateCommittedResource3 (docs/d3d12_vulkan.md // section 7). The newer arguments' edge cases are checked against the PC runtime's answers, live when the host has @@ -215,22 +216,65 @@ struct Edge { // The edge cases of the newer arguments, run on any ID3D12Device10: ours, or the host's PC runtime to compare // with. A GetCopyableFootprints1 answer is S_FALSE when every output is all ones (the failure answer), S_OK when // the footprint is the ordinary one, E_FAIL otherwise. -std::vector edge_answers(ID3D12Device10* device) { - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD}; +std::vector edge_answers(ID3D12Device10* device, ID3D12Device10* placed_device, + ID3D12Device* size_host = nullptr) { + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD}, + readback_heap{D3D12_HEAP_TYPE_READBACK}, bad_heap{D3D12_HEAP_TYPE(99)}; D3D12_RESOURCE_DESC1 texture = desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)); + D3D12_RESOURCE_DESC1 rt_tex = + desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)); + D3D12_RESOURCE_DESC1 ds_tex = + desc1(texture_desc(8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); + D3D12_RESOURCE_DESC1 ds_deny_tex = desc1(texture_desc( + 8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)); + D3D12_RESOURCE_DESC1 uav_tex = + desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + D3D12_RESOURCE_DESC1 rt_ds_tex = desc1(texture_desc( + 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); + D3D12_RESOURCE_DESC1 ds_uav_tex = desc1(texture_desc( + 8, 8, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + D3D12_RESOURCE_DESC1 deny_only_tex = + desc1(texture_desc(8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)); + D3D12_RESOURCE_DESC1 zero_width_tex = desc1(texture_desc(0, 8, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)); + D3D12_RESOURCE_DESC1 big_tex = + desc1(texture_desc(1024, 1024, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)); + D3D12_RESOURCE_DESC1 tex_256x256 = + desc1(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)); + D3D12_RESOURCE_DESC base_1000x600_10m = + texture_desc(1000, 600, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 10); + D3D12_RESOURCE_DESC base_300x200_f16 = + texture_desc(300, 200, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_NONE); + D3D12_RESOURCE_DESC base_1x1024 = + texture_desc(1, 1024, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + D3D12_RESOURCE_DESC1 buffer = desc1(buffer_desc(300)); + D3D12_RESOURCE_DESC1 uav_buffer = desc1(buffer_desc(256)); + uav_buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_RESOURCE_DESC1 tall_buffer = desc1(buffer_desc(256)); + tall_buffer.Height = 2; + D3D12_RESOURCE_DESC1 texture_region = texture, buffer_region = buffer; texture_region.SamplerFeedbackMipRegion = buffer_region.SamplerFeedbackMipRegion = {4, 4, 1}; + + D3D12_CLEAR_VALUE cv_rt{DXGI_FORMAT_R8G8B8A8_UNORM, {0.f, 0.f, 0.f, 1.f}}; + D3D12_CLEAR_VALUE cv_ds{DXGI_FORMAT_D32_FLOAT, {1.f, 0}}; + D3D12_CLEAR_VALUE cv_bad{DXGI_FORMAT_R32_FLOAT, {0.f, 0.f, 0.f, 1.f}}; + + const DXGI_FORMAT srgb_cast[] = {DXGI_FORMAT_R8G8B8A8_UNORM_SRGB}; + const DXGI_FORMAT unknown_cast[] = {DXGI_FORMAT_UNKNOWN}; + const DXGI_FORMAT wide_cast[] = {DXGI_FORMAT_R16G16B16A16_FLOAT}; + const auto v2 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc) { Ref r; return device->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, IID_PPV_ARGS(&r.p)); }; const auto v3 = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC1& desc, D3D12_BARRIER_LAYOUT layout, - UINT32 castable_count = 0, bool output = true) { + UINT32 castable_count = 0, bool output = true, D3D12_HEAP_FLAGS heap_flags = D3D12_HEAP_FLAG_NONE, + const D3D12_CLEAR_VALUE* clear = nullptr, const DXGI_FORMAT* castable = nullptr) { Ref r; - return device->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &desc, layout, nullptr, nullptr, - castable_count, nullptr, __uuidof(ID3D12Resource), + return device->CreateCommittedResource3(&heap, heap_flags, &desc, layout, clear, nullptr, castable_count, + castable, __uuidof(ID3D12Resource), output ? reinterpret_cast(&r.p) : nullptr); }; const auto footprint = [&](const D3D12_RESOURCE_DESC1& desc) { @@ -245,6 +289,53 @@ std::vector edge_answers(ID3D12Device10* device) { void* queue = nullptr; const HRESULT null_queue = device->CreateCommandQueue1(nullptr, creator, __uuidof(ID3D12CommandQueue), &queue); if (queue) static_cast(queue)->Release(); + + // Placed v2 setup. + D3D12_HEAP_DESC placed_heap_desc{256 * 1024, default_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + D3D12_HEAP_FLAG_NONE}; + D3D12_HEAP_DESC upload_heap_desc{256 * 1024, upload_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS}; + Ref placed_heap, upload_placed_heap; + placed_device->CreateHeap(&placed_heap_desc, IID_PPV_ARGS(&placed_heap.p)); + placed_device->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p)); + const auto p2 = [&](ID3D12Heap* heap, UINT64 offset, const D3D12_RESOURCE_DESC1& desc, D3D12_BARRIER_LAYOUT layout, + const D3D12_CLEAR_VALUE* clear = nullptr, UINT32 cast_count = 0, + const DXGI_FORMAT* cast = nullptr) { + Ref r; + return placed_device->CreatePlacedResource2(heap, offset, &desc, layout, clear, cast_count, cast, + IID_PPV_ARGS(&r.p)); + }; + const auto p2_host_sized = [&](const D3D12_RESOURCE_DESC& base, UINT64 fallback_bytes) { + const UINT64 bytes = size_host ? size_host->GetResourceAllocationInfo(0, 1, &base).SizeInBytes + : fallback_bytes; + D3D12_HEAP_DESC hd{bytes, default_heap, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, D3D12_HEAP_FLAG_NONE}; + Ref h; + if (FAILED(placed_device->CreateHeap(&hd, IID_PPV_ARGS(&h.p)))) return E_FAIL; + return p2(h.p, 0, desc1(base), D3D12_BARRIER_LAYOUT_COMMON); + }; + + // Reserved v1/v2 setup. + D3D12_RESOURCE_DESC res_tex = texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + res_tex.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + D3D12_RESOURCE_DESC res_rt = res_tex; + res_rt.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + D3D12_RESOURCE_DESC res_uav = res_tex; + res_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_RESOURCE_DESC res_ds_deny = texture_desc( + 64, 64, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); + res_ds_deny.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + D3D12_RESOURCE_DESC res_buf = buffer_desc(65536); + const auto r1 = [&](const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) { + Ref r; + return device->CreateReservedResource1(&desc, state, clear, nullptr, IID_PPV_ARGS(&r.p)); + }; + const auto r2 = [&](const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout, + const D3D12_CLEAR_VALUE* clear = nullptr, UINT32 cast_count = 0, + const DXGI_FORMAT* cast = nullptr) { + Ref r; + return device->CreateReservedResource2(&desc, layout, clear, nullptr, cast_count, cast, IID_PPV_ARGS(&r.p)); + }; + return { {"CreateCommittedResource2, texture with a mip region", v2(default_heap, texture_region), E_INVALIDARG}, {"CreateCommittedResource2, buffer with a mip region", v2(upload_heap, buffer_region), S_OK}, @@ -254,12 +345,138 @@ std::vector edge_answers(ID3D12Device10* device) { v3(upload_heap, buffer_region, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, {"CreateCommittedResource3, buffer in layout COMMON", v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreateCommittedResource3, upload buffer in UNDEFINED", + v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, + {"CreateCommittedResource3, readback buffer in COMMON", + v3(readback_heap, buffer, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreateCommittedResource3, readback buffer in UNDEFINED", + v3(readback_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, + {"CreateCommittedResource3, upload buffer with ALLOW_UAV", + v3(upload_heap, uav_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG}, + {"CreateCommittedResource3, buffer with Height=2", + v3(default_heap, tall_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG}, {"CreateCommittedResource3, texture in layout UNDEFINED", v3(default_heap, texture, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, {"CreateCommittedResource3, castable count with a null list", v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 2), S_OK}, {"CreateCommittedResource3, null output", v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, false), S_FALSE}, + {"CreateCommittedResource3, bad heap type", + v3(bad_heap, texture, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreateCommittedResource3, DENY_BUFFERS heap flag", + v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_DENY_BUFFERS), E_INVALIDARG}, + {"CreateCommittedResource3, ALLOW_DISPLAY on buffer", + v3(default_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, 0, true, D3D12_HEAP_FLAG_ALLOW_DISPLAY), + E_INVALIDARG}, + {"CreateCommittedResource3, clear value on buffer", + v3(upload_heap, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), E_INVALIDARG}, + {"CreateCommittedResource3, clear value on plain texture", + v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), E_INVALIDARG}, + {"CreateCommittedResource3, mismatched clear value on RT", + v3(default_heap, rt_tex, D3D12_BARRIER_LAYOUT_COMMON, 0, true, D3D12_HEAP_FLAG_NONE, &cv_bad), E_INVALIDARG}, + {"CreateCommittedResource3, valid clear value on RT", + v3(default_heap, rt_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET, 0, true, D3D12_HEAP_FLAG_NONE, &cv_rt), S_OK}, + {"CreateCommittedResource3, valid clear value on DS", + v3(default_heap, ds_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, 0, true, D3D12_HEAP_FLAG_NONE, &cv_ds), + S_OK}, + {"CreateCommittedResource3, RT | DS flags", + v3(default_heap, rt_ds_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreateCommittedResource3, DS | UAV flags", + v3(default_heap, ds_uav_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreateCommittedResource3, DENY_SHADER_RESOURCE without DS", + v3(default_heap, deny_only_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreateCommittedResource3, texture Width=0", + v3(default_heap, zero_width_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreateCommittedResource3, non-RT texture in RENDER_TARGET", + v3(default_heap, texture, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG}, + {"CreateCommittedResource3, non-UAV texture in UNORDERED_ACCESS", + v3(default_heap, texture, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG}, + {"CreateCommittedResource3, non-UAV texture in DIRECT_QUEUE_UAV", + v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS), E_INVALIDARG}, + {"CreateCommittedResource3, non-UAV texture in COMPUTE_QUEUE_UAV", + v3(default_heap, texture, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS), E_INVALIDARG}, + {"CreateCommittedResource3, UAV texture in DIRECT_QUEUE_UAV", + v3(default_heap, uav_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS), S_OK}, + {"CreateCommittedResource3, non-DS texture in DEPTH_STENCIL_WRITE", + v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG}, + {"CreateCommittedResource3, non-DS texture in DEPTH_STENCIL_READ", + v3(default_heap, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ), E_INVALIDARG}, + {"CreateCommittedResource3, DS texture in DEPTH_STENCIL_READ", + v3(default_heap, ds_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ), S_OK}, + {"CreateCommittedResource3, DS+DENY_SR in SHADER_RESOURCE", + v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE), E_INVALIDARG}, + {"CreateCommittedResource3, DS+DENY_SR in DIRECT_QUEUE_SHADER_RESOURCE", + v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE), E_INVALIDARG}, + {"CreateCommittedResource3, DS+DENY_SR in COMPUTE_QUEUE_SHADER_RESOURCE", + v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE), E_INVALIDARG}, + {"CreateCommittedResource3, DS+DENY_SR in GENERIC_READ", + v3(default_heap, ds_deny_tex, D3D12_BARRIER_LAYOUT_GENERIC_READ), S_OK}, + {"CreatePlacedResource2, buffer in COMMON", + p2(upload_placed_heap.p, 0, buffer, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreatePlacedResource2, buffer with Height=2", + p2(placed_heap.p, 0, tall_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG}, + {"CreatePlacedResource2, upload buffer with ALLOW_UAV", + p2(upload_placed_heap.p, 0, uav_buffer, D3D12_BARRIER_LAYOUT_UNDEFINED), E_INVALIDARG}, + {"CreatePlacedResource2, clear value on buffer", + p2(placed_heap.p, 0, buffer, D3D12_BARRIER_LAYOUT_UNDEFINED, &cv_rt), E_INVALIDARG}, + {"CreatePlacedResource2, clear value on plain texture", + p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_COMMON, &cv_rt), E_INVALIDARG}, + {"CreatePlacedResource2, valid clear value on RT", + p2(placed_heap.p, 0, rt_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET, &cv_rt), S_OK}, + {"CreatePlacedResource2, oversized 1024x1024 texture in 256 KiB heap", + p2(placed_heap.p, 0, big_tex, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreatePlacedResource2, 256x256 at 64 KiB in 256 KiB heap", + p2(placed_heap.p, 65536, tex_256x256, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreatePlacedResource2, 1000x600 RGBA8 10 mips in host-sized heap", + p2_host_sized(base_1000x600_10m, 3538944), S_OK}, + {"CreatePlacedResource2, 300x200 RGBA16F in host-sized heap", + p2_host_sized(base_300x200_f16, 589824), S_OK}, + {"CreatePlacedResource2, 1x1024 RGBA8 in 64 KiB heap", + p2_host_sized(base_1x1024, 65536), S_OK}, + {"CreatePlacedResource2, 8x8 texture at 192 KiB in 256 KiB heap", + p2(placed_heap.p, 3 * 65536, texture, D3D12_BARRIER_LAYOUT_COMMON), S_OK}, + {"CreatePlacedResource2, non-RT texture in RENDER_TARGET", + p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG}, + {"CreatePlacedResource2, non-UAV texture in UNORDERED_ACCESS", + p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG}, + {"CreatePlacedResource2, non-DS texture in DEPTH_STENCIL_WRITE", + p2(placed_heap.p, 0, texture, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG}, + {"CreatePlacedResource2, DS+DENY_SR in DIRECT_QUEUE_SHADER_RESOURCE", + p2(placed_heap.p, 0, ds_deny_tex, D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE), E_INVALIDARG}, + {"CreateReservedResource1, clear value on plain texture", + r1(res_tex, D3D12_RESOURCE_STATE_COMMON, &cv_rt), E_INVALIDARG}, + {"CreateReservedResource2, buffer in COMMON", + r2(res_buf, D3D12_BARRIER_LAYOUT_COMMON), E_INVALIDARG}, + {"CreateReservedResource2, buffer in UNDEFINED", + r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED), S_OK}, + {"CreateReservedResource2, clear value on buffer", + r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, &cv_rt), E_INVALIDARG}, + {"CreateReservedResource2, clear value on plain texture", + r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, &cv_rt), E_INVALIDARG}, + {"CreateReservedResource2, mismatched clear value on RT", + r2(res_rt, D3D12_BARRIER_LAYOUT_COMMON, &cv_bad), E_INVALIDARG}, + {"CreateReservedResource2, valid clear value on RT", + r2(res_rt, D3D12_BARRIER_LAYOUT_RENDER_TARGET, &cv_rt), S_OK}, + {"CreateReservedResource2, non-RT texture in RENDER_TARGET", + r2(res_tex, D3D12_BARRIER_LAYOUT_RENDER_TARGET), E_INVALIDARG}, + {"CreateReservedResource2, non-UAV texture in UNORDERED_ACCESS", + r2(res_tex, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS), E_INVALIDARG}, + {"CreateReservedResource2, UAV texture in COMPUTE_QUEUE_UAV", + r2(res_uav, D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS), S_OK}, + {"CreateReservedResource2, non-DS texture in DEPTH_STENCIL_WRITE", + r2(res_tex, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE), E_INVALIDARG}, + {"CreateReservedResource2, DS+DENY_SR in SHADER_RESOURCE", + r2(res_ds_deny, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE), E_INVALIDARG}, + {"CreateReservedResource2, castable format on buffer", + r2(res_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 1, srgb_cast), E_INVALIDARG}, + {"CreateReservedResource2, unknown castable format on texture", + r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, unknown_cast), E_INVALIDARG}, + {"CreateReservedResource2, mismatched texel-size castable format", + r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, wide_cast), E_INVALIDARG}, + {"CreateReservedResource2, valid castable format on texture", + r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 1, srgb_cast), S_OK}, + {"CreateReservedResource2, castable count with null list", + r2(res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, 2, nullptr), S_OK}, {"CreateCommandQueue1, null description", null_queue, E_INVALIDARG}, {"GetCopyableFootprints1, texture with a mip region", footprint(texture_region), S_FALSE}, {"GetCopyableFootprints1, buffer with a mip region", footprint(buffer_region), S_OK}, @@ -297,32 +514,47 @@ int main() { EXPECT(create(device.p, via, upload_heap, buffer_desc(256), &out, fake_session()) == E_INVALIDARG); EXPECT(out == nullptr); } + { + D3D12_RESOURCE_DESC tiled_buf = buffer_desc(65536); + void* out = reinterpret_cast(1); + EXPECT(device->CreateReservedResource1(&tiled_buf, D3D12_RESOURCE_STATE_COMMON, nullptr, fake_session(), + __uuidof(ID3D12Resource), &out) == E_INVALIDARG); + EXPECT(out == nullptr); + out = reinterpret_cast(1); + EXPECT(device->CreateReservedResource2(&tiled_buf, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, fake_session(), + 0, nullptr, __uuidof(ID3D12Resource), &out) == E_INVALIDARG); + EXPECT(out == nullptr); + } // The newer arguments' edge cases, each with the answer the PC runtime gives (and, when the host has a - // D3D12 device, compared with it live). - const std::vector ours = edge_answers(device.p); + // D3D12 device, compared with it live). Placed cases use standalone_device so the heap arena is present. + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto create_host = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))) + : nullptr; + Ref host; + const bool have_host = + create_host && SUCCEEDED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p))); + Ref standalone_base; + Ref standalone_device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&standalone_base.p)))); + EXPECT(SUCCEEDED(standalone_base->QueryInterface(IID_PPV_ARGS(&standalone_device.p)))); + const std::vector ours = edge_answers(device.p, standalone_device.p, host.p); for (const Edge& e : ours) { if (e.got == e.want) continue; std::fprintf(stderr, "%s: got %08lx, want %08lx\n", e.name, e.got, e.want); return 1; } - { - const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const auto create_host = d3d12 ? reinterpret_cast( - reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))) - : nullptr; - Ref host; - if (create_host && SUCCEEDED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { - const std::vector theirs = edge_answers(host.p); - for (std::size_t i = 0; i < ours.size(); ++i) { - if (ours[i].got == theirs[i].got) continue; - std::fprintf(stderr, "%s: ours %08lx, host runtime %08lx\n", ours[i].name, ours[i].got, - theirs[i].got); - return 1; - } - } else { - std::printf("no host D3D12 device: edge cases checked against their recorded answers only\n"); + if (have_host) { + const std::vector theirs = edge_answers(host.p, host.p, host.p); + for (std::size_t i = 0; i < ours.size(); ++i) { + if (ours[i].got == theirs[i].got) continue; + std::fprintf(stderr, "%s: ours %08lx, host runtime %08lx\n", ours[i].name, ours[i].got, + theirs[i].got); + return 1; } + } else { + std::printf("no host D3D12 device: edge cases checked against their recorded answers only\n"); } // Castable formats: the layer reports relaxed format casting and passes a real list to @@ -359,7 +591,7 @@ int main() { Ref heap; D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - heap_desc.NumDescriptors = 3; + heap_desc.NumDescriptors = 4; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); D3D12_CPU_DESCRIPTOR_HANDLE slot = heap->GetCPUDescriptorHandleForHeapStart(); @@ -413,6 +645,30 @@ int main() { nonzero = false; for (std::uint32_t word : words) nonzero = nonzero || word != 0; EXPECT(nonzero); + + // CreateReservedResource2 forwards its castable list to the backing Vulkan image too. + const auto slot_is_zero = [](D3D12_CPU_DESCRIPTOR_HANDLE handle) { + std::uint32_t descriptor_words[8]{}; + std::memcpy(descriptor_words, reinterpret_cast(handle.ptr), sizeof(descriptor_words)); + for (std::uint32_t word : descriptor_words) + if (word != 0) return false; + return true; + }; + D3D12_RESOURCE_DESC res_tex = texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + res_tex.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + Ref reserved_srgb; + EXPECT(SUCCEEDED(device->CreateReservedResource2(&res_tex, D3D12_BARRIER_LAYOUT_COMMON, nullptr, nullptr, 1, + srgb_only, IID_PPV_ARGS(&reserved_srgb.p)))); + slot.ptr += stride; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + device->CreateShaderResourceView(reserved_srgb.p, &srv, slot); + EXPECT(!slot_is_zero(slot)); + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + device->CreateShaderResourceView(reserved_srgb.p, &srv, slot); + EXPECT(!slot_is_zero(slot)); + srv.Format = DXGI_FORMAT_R8G8B8A8_UINT; + device->CreateShaderResourceView(reserved_srgb.p, &srv, slot); + EXPECT(slot_is_zero(slot)); } // A texture from CreateCommittedResource3 (a castable count with a null list, which is no list) is @@ -523,7 +779,8 @@ int main() { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("D3D12 method variants: CreateCommittedResource1/2/3, CreateCommandQueue1 and GetCopyableFootprints1 " - "matched their base methods and the PC runtime's edge-case answers; a texture round-tripped\n"); + std::printf("D3D12 method variants: CreateCommittedResource1/2/3, CreatePlacedResource2, " + "CreateReservedResource1/2, CreateCommandQueue1 and GetCopyableFootprints1 matched their base methods " + "and the PC runtime's edge-case answers; a texture round-tripped\n"); return 0; } diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp index 9cafc994e..3437fe030 100644 --- a/runtime/test/d3d12_msaa_draw_test.cpp +++ b/runtime/test/d3d12_msaa_draw_test.cpp @@ -11,6 +11,7 @@ // (invalid_subresource) instead of reaching the driver. Shaders: test/glsl/vs_draw.vert, ps_draw.frag. No game data. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "shader_fixture_path.h" +#include "test_temp_dir.h" #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -54,10 +55,10 @@ int main() { const auto vs_program = fssm_program({0x56530001, 0xbf810000}); const auto ps_program = fssm_program({0x50530001, 0xbf810000}); const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); - const auto library = std::filesystem::temp_directory_path() / "leonida_msaa_draw_test"; - std::filesystem::create_directories(library); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); + const testfiles::ScratchDir scratch("leonida_msaa_draw_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv")); { std::ofstream index(library / "index.json", std::ios::binary); index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) @@ -310,7 +311,6 @@ int main() { fence.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } - std::filesystem::remove_all(library); // Pixel centre in clip space; the triangle covers y > x. Sample offsets are under half a pixel on each axis, // so a pixel whose centre is more than one pixel width (2 / size in clip space, over both axes) from the edge diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp index fbc7bb5fc..08d6a5323 100644 --- a/runtime/test/d3d12_pipeline_library_test.cpp +++ b/runtime/test/d3d12_pipeline_library_test.cpp @@ -9,6 +9,7 @@ // - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1. // No game data. #include "shader_fixture_path.h" +#include "test_temp_dir.h" #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -68,14 +69,11 @@ int main() { const auto vs_dxbc = shader_container(vs_prog); const auto ps_dxbc = shader_container(ps_prog); - const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_pipeline_library_test"; - std::filesystem::create_directories(lib_dir); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), lib_dir / "cs.spv", - std::filesystem::copy_options::overwrite_existing); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), lib_dir / "vs.spv", - std::filesystem::copy_options::overwrite_existing); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), lib_dir / "ps.spv", - std::filesystem::copy_options::overwrite_existing); + const testfiles::ScratchDir scratch("leonida_pipeline_library_test"); + const auto& lib_dir = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), lib_dir / "cs.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), lib_dir / "vs.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), lib_dir / "ps.spv")); { std::ofstream idx(lib_dir / "index.json", std::ios::binary); idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog) diff --git a/runtime/test/d3d12_placed_dimensions_test.cpp b/runtime/test/d3d12_placed_dimensions_test.cpp new file mode 100644 index 000000000..09b0894b4 --- /dev/null +++ b/runtime/test/d3d12_placed_dimensions_test.cpp @@ -0,0 +1,347 @@ +// Placed 1D and 3D textures (CreatePlacedResource) on the Vulkan-backed device: +// - compared with Windows D3D12 on the default adapter and on WARP: the answer for each description in a heap sized +// for both sides' GetResourceAllocationInfo, at offset 0 and at 64 KiB, and the description a placed resource +// reads back. A dimension outside the enum is refused alike; +// - on the layer alone: bytes copied through a buffer into every subresource of a placed 3D texture and a placed 1D +// array, and back out, come back unchanged. +// No game data or shaders. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation to the layer's device. +#include "host_wine.h" +#include "../shims/d3d12_com.h" +#include + +#include +#include +#include +#include + +namespace { +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + T* operator->() const { return p; } + void reset() { + if (p) p->Release(); + p = nullptr; + } +}; + +constexpr UINT64 k64 = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; +constexpr auto t1 = D3D12_RESOURCE_DIMENSION_TEXTURE1D, t2 = D3D12_RESOURCE_DIMENSION_TEXTURE2D, + t3 = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + +D3D12_RESOURCE_DESC texture(D3D12_RESOURCE_DIMENSION dimension, UINT64 width, UINT height, UINT16 depth_or_layers, + UINT16 mips, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = dimension; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = depth_or_layers; + desc.MipLevels = mips; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} + +D3D12_RESOURCE_DESC buffer(UINT64 bytes) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +UINT64 round_up(UINT64 value, UINT64 alignment) { return (value + alignment - 1) / alignment * alignment; } + +// A default heap of `bytes` that takes `desc`'s class of texture on any resource-heap tier. +HRESULT make_heap(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, UINT64 bytes, ID3D12Heap** heap) { + D3D12_HEAP_DESC heap_desc{}; + heap_desc.SizeInBytes = bytes; + heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; + heap_desc.Alignment = k64; + const bool rt_ds = + (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0; + heap_desc.Flags = rt_ds ? D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES : D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES; + return device->CreateHeap(&heap_desc, IID_PPV_ARGS(heap)); +} + +bool same(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) { + return a.Dimension == b.Dimension && a.Alignment == b.Alignment && a.Width == b.Width && a.Height == b.Height && + a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format && + a.SampleDesc.Count == b.SampleDesc.Count && a.SampleDesc.Quality == b.SampleDesc.Quality && + a.Layout == b.Layout && a.Flags == b.Flags; +} + +struct Case { + const char* name; + D3D12_RESOURCE_DESC desc; +}; + +struct Placed { + Ref heap; // declared first, so the resource is released before its heap + Ref resource; + HRESULT hr = E_FAIL; +}; + +void place(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, UINT64 heap_bytes, UINT64 offset, Placed& out) { + out.hr = make_heap(device, desc, heap_bytes, &out.heap.p); + if (FAILED(out.hr)) { + std::fprintf(stderr, "CreateHeap of %llu bytes failed (0x%08lx)\n", static_cast(heap_bytes), + static_cast(out.hr)); + return; + } + out.hr = device->CreatePlacedResource(out.heap.p, offset, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&out.resource.p)); +} + +// Every answer and every description read back must be the host's. Returns the number that differ. +unsigned compare(ID3D12Device* ours, ID3D12Device* host, const char* host_name, const std::vector& cases, + unsigned& compared) { + unsigned differ = 0; + for (const Case& c : cases) { + // The heap is sized for the larger of the two answers: each side checks the room in the heap against its own + // size (the layer's is Vulkan's, which can be larger than a host driver's), and what is compared here is + // whether a texture of that dimension is placed at all. A description with no size (an invalid dimension) + // still gets a heap, to see the refusal. + const D3D12_RESOURCE_ALLOCATION_INFO info = host->GetResourceAllocationInfo(0, 1, &c.desc); + const D3D12_RESOURCE_ALLOCATION_INFO mine = ours->GetResourceAllocationInfo(0, 1, &c.desc); + UINT64 bytes = 1024 * 1024; + if (info.SizeInBytes != UINT64_MAX) { + bytes = info.SizeInBytes; + if (mine.SizeInBytes != UINT64_MAX && mine.SizeInBytes != info.SizeInBytes) { + std::printf("%s: %s's size %llu, the layer's %llu; the heap takes the larger\n", c.name, host_name, + static_cast(info.SizeInBytes), + static_cast(mine.SizeInBytes)); + if (mine.SizeInBytes > bytes) bytes = mine.SizeInBytes; + } + bytes = round_up(bytes, k64); + } + for (const UINT64 offset : {UINT64(0), k64}) { + Placed expected, actual; + place(host, c.desc, bytes + offset, offset, expected); + place(ours, c.desc, bytes + offset, offset, actual); + ++compared; + if (expected.hr != actual.hr) { + ++differ; + std::fprintf(stderr, "%s at %llu: ours 0x%08lx, %s 0x%08lx\n", c.name, + static_cast(offset), static_cast(actual.hr), host_name, + static_cast(expected.hr)); + continue; + } + if (FAILED(expected.hr)) continue; + ++compared; + if (!same(actual.resource->GetDesc(), expected.resource->GetDesc())) { + ++differ; + std::fprintf(stderr, "%s at %llu: GetDesc differs from %s\n", c.name, + static_cast(offset), host_name); + } + ++compared; + if (actual.resource->GetGPUVirtualAddress() != 0) { // only buffers are addressable + ++differ; + std::fprintf(stderr, "%s at %llu: a placed texture has a GPU VA\n", c.name, + static_cast(offset)); + } + } + } + return differ; +} + +std::uint8_t pattern(UINT subresource, UINT z, UINT y, UINT64 x) { + return static_cast(subresource * 61 + z * 29 + y * 7 + x * 3 + 1); +} + +// Writes a pattern into every subresource of a placed texture through an upload buffer, copies it back out to a +// readback buffer and compares. True when every byte came back. +bool round_trip(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64& fence_value, + const char* name, const D3D12_RESOURCE_DESC& desc) { + const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc); + if (info.SizeInBytes == UINT64_MAX) { + std::fprintf(stderr, "%s: no allocation size\n", name); + return false; + } + Ref heap; + Ref placed; + if (FAILED(make_heap(device, desc, round_up(info.SizeInBytes, k64), &heap.p)) || + FAILED(device->CreatePlacedResource(heap.p, 0, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&placed.p)))) { + std::fprintf(stderr, "%s: not placed\n", name); + return false; + } + const UINT layers = desc.Dimension == t3 ? 1u : desc.DepthOrArraySize; + const UINT count = desc.MipLevels * layers; + std::vector layouts(count); + std::vector rows(count); + std::vector row_bytes(count); + UINT64 total = 0; + device->GetCopyableFootprints(&desc, 0, count, 0, layouts.data(), rows.data(), row_bytes.data(), &total); + + D3D12_HEAP_PROPERTIES upload_heap{}, readback_heap{}; + upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD; + readback_heap.Type = D3D12_HEAP_TYPE_READBACK; + const D3D12_RESOURCE_DESC staging = buffer(total); + Ref upload, readback; + if (FAILED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &staging, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload.p))) || + FAILED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &staging, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))) { + std::fprintf(stderr, "%s: no staging buffers\n", name); + return false; + } + // Where row y of slice z of subresource s starts in either staging buffer. + const auto row_at = [&](UINT s, UINT z, UINT y) { + const UINT64 pitch = layouts[s].Footprint.RowPitch; + return layouts[s].Offset + (UINT64(z) * rows[s] + y) * pitch; + }; + void* mapped = nullptr; + if (FAILED(upload->Map(0, nullptr, &mapped))) return false; + for (UINT s = 0; s < count; ++s) + for (UINT z = 0; z < layouts[s].Footprint.Depth; ++z) + for (UINT y = 0; y < rows[s]; ++y) { + auto* row = static_cast(mapped) + row_at(s, z, y); + for (UINT64 x = 0; x < row_bytes[s]; ++x) row[x] = pattern(s, z, y, x); + } + upload->Unmap(0, nullptr); + + Ref allocator; + Ref list; + if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))) + return false; + for (UINT s = 0; s < count; ++s) { + D3D12_TEXTURE_COPY_LOCATION dst{placed.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + dst.SubresourceIndex = s; + D3D12_TEXTURE_COPY_LOCATION src{upload.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + src.PlacedFootprint = layouts[s]; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {placed.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + list->ResourceBarrier(1, &barrier); + for (UINT s = 0; s < count; ++s) { + D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst.PlacedFootprint = layouts[s]; + D3D12_TEXTURE_COPY_LOCATION src{placed.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + src.SubresourceIndex = s; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + ++fence_value; + if (FAILED(queue->Signal(fence, fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) { + std::fprintf(stderr, "%s: the copies did not finish\n", name); + return false; + } + + if (FAILED(readback->Map(0, nullptr, &mapped))) return false; + UINT64 wrong = 0, checked = 0; + for (UINT s = 0; s < count; ++s) + for (UINT z = 0; z < layouts[s].Footprint.Depth; ++z) + for (UINT y = 0; y < rows[s]; ++y) { + const auto* row = static_cast(mapped) + row_at(s, z, y); + for (UINT64 x = 0; x < row_bytes[s]; ++x, ++checked) { + if (row[x] == pattern(s, z, y, x)) continue; + if (!wrong++) + std::fprintf(stderr, "%s: subresource %u slice %u row %u byte %llu reads 0x%02x, want 0x%02x\n", + name, s, z, y, static_cast(x), row[x], pattern(s, z, y, x)); + } + } + readback->Unmap(0, nullptr); + if (wrong) { + std::fprintf(stderr, "%s: %llu of %llu bytes differ\n", name, static_cast(wrong), + static_cast(checked)); + return false; + } + std::printf("%s: %u subresources, %llu bytes round-tripped\n", name, count, + static_cast(checked)); + return true; +} +} // namespace + +int main() { + Ref ours; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&ours.p))) || !ours.p) { + std::printf("SKIP: no Vulkan device\n"); + return 77; + } + unsigned failures = 0; + + { + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + Ref queue; + Ref fence; + if (FAILED(ours->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) || + FAILED(ours->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) { + std::fprintf(stderr, "no command queue or fence\n"); + return 1; + } + UINT64 fence_value = 0; + const Case trips[] = { + {"placed 3D R8G8B8A8_UNORM 8x8x4, 2 mips", texture(t3, 8, 8, 4, 2, DXGI_FORMAT_R8G8B8A8_UNORM)}, + {"placed 3D R16G16B16A16_FLOAT 4x4x4", texture(t3, 4, 4, 4, 1, DXGI_FORMAT_R16G16B16A16_FLOAT)}, + {"placed 1D array R8G8B8A8_UNORM 64 x3, 3 mips", texture(t1, 64, 1, 3, 3, DXGI_FORMAT_R8G8B8A8_UNORM)}, + }; + for (const Case& c : trips) + if (!round_trip(ours.p, queue.p, fence.p, fence_value, c.name, c.desc)) ++failures; + } + + // A desc with a dimension outside the enum, which the host refuses. + D3D12_RESOURCE_DESC unknown = texture(t2, 64, 64, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM); + unknown.Dimension = D3D12_RESOURCE_DIMENSION_UNKNOWN; + D3D12_RESOURCE_DESC past_3d = unknown; + past_3d.Dimension = D3D12_RESOURCE_DIMENSION(5); + constexpr auto rgba8 = DXGI_FORMAT_R8G8B8A8_UNORM; + constexpr auto uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, target = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const std::vector cases = { + {"1D 4096", texture(t1, 4096, 1, 1, 1, rgba8)}, + {"1D 256, all mips", texture(t1, 256, 1, 1, 0, rgba8)}, + {"1D array of 8, 13 mips", texture(t1, 4096, 1, 8, 13, rgba8)}, + {"1D R32_FLOAT unordered access", texture(t1, 1024, 1, 1, 1, DXGI_FORMAT_R32_FLOAT, uav)}, + {"1D render target", texture(t1, 1024, 1, 1, 1, rgba8, target)}, + {"3D 64x64x64", texture(t3, 64, 64, 64, 1, rgba8)}, + {"3D 32x32x32, all mips", texture(t3, 32, 32, 32, 0, rgba8)}, + {"3D 64x16x4, all mips", texture(t3, 64, 16, 4, 0, rgba8)}, + {"3D BC1 128x128x16", texture(t3, 128, 128, 16, 1, DXGI_FORMAT_BC1_UNORM)}, + {"3D R16G16B16A16_FLOAT 32x32x32", texture(t3, 32, 32, 32, 1, DXGI_FORMAT_R16G16B16A16_FLOAT)}, + {"3D R32_FLOAT unordered access", texture(t3, 64, 64, 64, 1, DXGI_FORMAT_R32_FLOAT, uav)}, + {"3D render target", texture(t3, 64, 64, 64, 1, rgba8, target)}, + {"2D 64x64 (control)", texture(t2, 64, 64, 1, 1, rgba8)}, + {"dimension UNKNOWN", unknown}, + {"dimension 5", past_3d}, + }; + + if (hostwine::host_is_wine()) { + std::printf("placed dimensions: the host comparison is skipped under Wine\n"); + return failures ? 1 : 0; + } + Ref factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { + std::fprintf(stderr, "no DXGI factory\n"); + return 1; + } + unsigned references = 0; + for (const bool warp : {false, true}) { + Ref adapter; + Ref host; + if (warp && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; + if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; + const char* name = warp ? "WARP" : "the default adapter"; + unsigned compared = 0; + const unsigned differ = compare(ours.p, host.p, name, cases, compared); + std::printf("placed dimensions against %s: %u answers compared, %u differ\n", name, compared, differ); + failures += differ; + ++references; + } + if (!references) { + std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n"); + return 1; + } + return failures ? 1 : 0; +} diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp index 520af0e98..9e638ae09 100644 --- a/runtime/test/d3d12_present_test.cpp +++ b/runtime/test/d3d12_present_test.cpp @@ -3,9 +3,9 @@ // moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence. // The window is then resized, which recreates the swapchain and scales the blit. The presented images are copied // back (the presenter's capture) and must hold the clear colour at the swapchain's size. Last, the colour on screen -// is read back with GDI on native Windows when the window is in front, the display is in SDR and GDI can read the -// screen. Under Wine, rootless XWayland can return black for desktop reads, so the swapchain checks confirm the -// colour there. No shaders or game data. +// is read back with GDI on native Windows when the window is in front with no other window over its centre, the +// display is in SDR and GDI can read the screen. Under Wine, rootless XWayland can return black for desktop reads, +// so the swapchain checks confirm the colour there. No shaders or game data. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. #include "vk_test_device.h" #include "../shims/d3d12_com.h" @@ -90,6 +90,17 @@ bool has_interactive_window_station() { return (flags.dwFlags & WSF_VISIBLE) != 0; } +// True when the window manager reports this window as the top-level window at a screen point. Being the foreground +// window does not make it so: an always-on-top window, or one another process showed without taking the foreground, +// can lie over it, and a GDI read of the screen then returns that window's pixel. WindowFromPoint passes over hidden +// and disabled windows and over windows that are transparent to hit testing (a click-through overlay, +// WS_EX_LAYERED | WS_EX_TRANSPARENT), so an overlay of that kind drawn over the point is not noticed, and neither +// is anything the compositor draws there itself. +bool is_top_window_at(HWND window, POINT screen_point) { + const HWND hit = WindowFromPoint(screen_point); + return hit && GetAncestor(hit, GA_ROOT) == window; +} + void set_client_size(HWND window, int width, int height) { RECT rect{0, 0, width, height}; AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); @@ -478,16 +489,44 @@ int main() { GetClientRect(window, &client); POINT centre{(client.right - client.left) / 2, (client.bottom - client.top) / 2}; ClientToScreen(window, ¢re); - HDC screen = GetDC(nullptr); - const COLORREF pixel = GetPixel(screen, centre.x, centre.y); - ReleaseDC(nullptr, screen); - if (pixel == CLR_INVALID) { + const auto is_clear_colour = [](COLORREF c) { + return std::abs(GetRValue(c) - 51) <= 3 && std::abs(GetGValue(c) - 153) <= 3 && + std::abs(GetBValue(c) - 230) <= 3; + }; + // The foreground window can still be covered at its centre, so a read counts only when this window + // was the top one there both before and after it. How long the compositor takes to show the last + // frame, or to stop showing a window that has just gone, is not known (the 200 ms above is a guess), + // so a pixel that is not the clear colour is read again for up to a second. Nothing is presented + // meanwhile: a late frame passes, a wrong colour that stays fails. + COLORREF pixel = CLR_INVALID, first_pixel = CLR_INVALID; + bool covered = false; + int reads = 0; + for (;;) { + covered = !is_top_window_at(window, centre); + if (covered) break; + HDC screen = GetDC(nullptr); + pixel = GetPixel(screen, centre.x, centre.y); + ReleaseDC(nullptr, screen); + covered = !is_top_window_at(window, centre); + if (covered) break; + if (++reads == 1) first_pixel = pixel; + if (pixel == CLR_INVALID || is_clear_colour(pixel) || reads > 20) break; + Sleep(50); + pump(); + } + if (covered) { + std::printf("another window covers the window centre: on-screen colour check skipped, the " + "colour was checked in the presented images\n"); + } else if (pixel == CLR_INVALID) { std::printf("GDI cannot read the screen here (GetPixel on the screen DC returns CLR_INVALID): " "on-screen colour check skipped, the colour was checked in the presented images\n"); } else { const int r = GetRValue(pixel), g = GetGValue(pixel), b = GetBValue(pixel); std::printf("screen pixel at the window centre: %d,%d,%d (cleared to 51,153,230)\n", r, g, b); - EXPECT(std::abs(r - 51) <= 3 && std::abs(g - 153) <= 3 && std::abs(b - 230) <= 3); + if (reads > 1) + std::printf("read %d times, 50 ms apart; the first read was %d,%d,%d\n", reads, + GetRValue(first_pixel), GetGValue(first_pixel), GetBValue(first_pixel)); + EXPECT(is_clear_colour(pixel)); screen_checked = true; } } diff --git a/runtime/test/d3d12_residency_test.cpp b/runtime/test/d3d12_residency_test.cpp new file mode 100644 index 000000000..d0f90d5fc --- /dev/null +++ b/runtime/test/d3d12_residency_test.cpp @@ -0,0 +1,421 @@ +// Residency on the Vulkan-backed device, compared with the host PC runtime: MakeResident, Evict, +// SetResidencyPriority (ID3D12Device1) and EnqueueMakeResident (ID3D12Device3). The same script runs on both devices +// with pageable objects of each (a committed buffer, a heap, a placed buffer, a descriptor heap, a query heap and a +// fence): counts of 0, null arrays, null entries, the same object twice, evicting twice, every named priority and a +// few others, residency flags, a null fence, and the fence values EnqueueMakeResident signals (the value the fence +// reaches is recorded too). Every HRESULT is recorded and the two records must be the same, step by step. A step the +// host runtime faults on is reported and not compared. No shaders or game data. Skips (77) without a Vulkan GPU; +// without a host D3D12 device only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every +// step. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr std::uint64_t kFaulted = 0xFA017EDull; // the call raised an exception + +struct Objects { + ID3D12Device1* device1 = nullptr; + ID3D12Device3* device3 = nullptr; + ID3D12Device* device = nullptr; + ID3D12Pageable* all[6] = {}; // buffer, heap, placed, descriptor heap, query heap, fence + ID3D12Fence* fence = nullptr; +}; + +using Call = HRESULT (*)(Objects&); + +HRESULT guarded(Call call, Objects* o) { + __try { + return call(*o); + } __except (EXCEPTION_EXECUTE_HANDLER) { + return HRESULT(kFaulted); + } +} + +HRESULT priority(Objects& o, std::uint32_t value) { + const auto p = D3D12_RESIDENCY_PRIORITY(value); + return o.device1->SetResidencyPriority(1, o.all, &p); +} + +HRESULT priority1(Objects& o, int which) { + const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL; + return o.device1->SetResidencyPriority(1, o.all + which, &p); +} + +struct Step { + const char* name; + Call call; + UINT64 fence_value = 0; // EnqueueMakeResident: also record the value the fence reaches (waits for this one) + bool isolated = false; // on the host, run in a process of its own (see below) +}; + +const Step kSteps[] = { + {"MakeResident 0, null", [](Objects& o) { return o.device->MakeResident(0, nullptr); }}, + {"MakeResident all six", [](Objects& o) { return o.device->MakeResident(6, o.all); }}, + {"MakeResident 0 with an array", [](Objects& o) { return o.device->MakeResident(0, o.all); }}, + {"MakeResident the buffer twice", [](Objects& o) { + ID3D12Pageable* twice[] = {o.all[0], o.all[0]}; + return o.device->MakeResident(2, twice); + }}, + {"MakeResident a resident buffer", [](Objects& o) { return o.device->MakeResident(1, o.all); }}, + {"Evict 0, null", [](Objects& o) { return o.device->Evict(0, nullptr); }}, + {"Evict 0 with an array", [](Objects& o) { return o.device->Evict(0, o.all); }}, + {"Evict the buffer", [](Objects& o) { return o.device->Evict(1, o.all); }}, + {"Evict the buffer again", [](Objects& o) { return o.device->Evict(1, o.all); }}, + {"MakeResident the evicted buffer", [](Objects& o) { return o.device->MakeResident(1, o.all); }}, + {"Evict all six", [](Objects& o) { return o.device->Evict(6, o.all); }}, + {"MakeResident all six after Evict", [](Objects& o) { return o.device->MakeResident(6, o.all); }}, + {"Evict the heap and the placed buffer", [](Objects& o) { return o.device->Evict(2, o.all + 1); }}, + {"MakeResident the placed buffer alone", [](Objects& o) { return o.device->MakeResident(1, o.all + 2); }}, + {"MakeResident the heap", [](Objects& o) { return o.device->MakeResident(1, o.all + 1); }}, + + {"SetResidencyPriority 0, null, null", [](Objects& o) { return o.device1->SetResidencyPriority(0, nullptr, nullptr); }}, + {"SetResidencyPriority 0 with arrays", [](Objects& o) { + const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL; + return o.device1->SetResidencyPriority(0, o.all, &p); + }}, + {"SetResidencyPriority the buffer", [](Objects& o) { return priority1(o, 0); }}, + {"SetResidencyPriority the heap", [](Objects& o) { return priority1(o, 1); }}, + {"SetResidencyPriority MINIMUM", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_MINIMUM)); }}, + {"SetResidencyPriority LOW", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_LOW)); }}, + {"SetResidencyPriority HIGH", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_HIGH)); }}, + {"SetResidencyPriority MAXIMUM", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_MAXIMUM)); }}, + {"SetResidencyPriority 0", [](Objects& o) { return priority(o, 0); }}, + {"SetResidencyPriority 1", [](Objects& o) { return priority(o, 1); }}, + {"SetResidencyPriority NORMAL + 0x1234", [](Objects& o) { return priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_NORMAL) + 0x1234); }}, + {"SetResidencyPriority 0x12345678", [](Objects& o) { return priority(o, 0x12345678u); }}, + {"SetResidencyPriority 0x9fffffff", [](Objects& o) { return priority(o, 0x9fffffffu); }}, + {"SetResidencyPriority 0xc8000000", [](Objects& o) { return priority(o, 0xc8000000u); }}, + {"SetResidencyPriority 0xffffffff", [](Objects& o) { return priority(o, 0xffffffffu); }}, + {"SetResidencyPriority an evicted object", [](Objects& o) { + o.device->Evict(1, o.all); + const HRESULT hr = priority(o, std::uint32_t(D3D12_RESIDENCY_PRIORITY_HIGH)); + o.device->MakeResident(1, o.all); + return hr; + }}, + + {"EnqueueMakeResident NONE, two objects, value 7", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 2, o.all, o.fence, 7); + }, 7}, + {"EnqueueMakeResident DENY_OVERBUDGET, 0, null, value 9", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET, 0, nullptr, o.fence, 9); + }, 9}, + {"EnqueueMakeResident all six, value 10", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 6, o.all, o.fence, 10); + }, 10}, + {"EnqueueMakeResident a null fence", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, nullptr, 11); + }}, + {"EnqueueMakeResident flags 0x2", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0x2), 1, o.all, o.fence, 11); + }}, + {"EnqueueMakeResident flags 0xffffffff", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0xffffffffu), 1, o.all, o.fence, 11); + }}, + {"EnqueueMakeResident 0 with an array, value 12", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 0, o.all, o.fence, 12); + }, 12}, + {"EnqueueMakeResident an evicted buffer, value 13", [](Objects& o) { + o.device->Evict(1, o.all); + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 13); + }, 13}, + {"EnqueueMakeResident the buffer twice, value 14", [](Objects& o) { + ID3D12Pageable* twice[] = {o.all[0], o.all[0]}; + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 2, twice, o.fence, 14); + }, 14}, + {"EnqueueMakeResident the fence it signals, value 15", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all + 5, o.fence, 15); + }, 15}, + {"EnqueueMakeResident a value below the fence's [backwards], value 3", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 3); + }, 3}, + {"EnqueueMakeResident the same value again [backwards], value 3", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, o.all, o.fence, 3); + }, 3}, + + // Steps after which the host runtime isn't usable any more. On the host each runs in a process of its own with a + // fresh device (--host-step): SetResidencyPriority on anything but a committed resource or a heap (the host + // answers E_INVALIDARG and removes its device, DXGI_ERROR_INVALID_CALL), and a count with a null array or a null + // entry in an array (the host dereferences them). + {"SetResidencyPriority the placed buffer", [](Objects& o) { return priority1(o, 2); }, 0, true}, + {"SetResidencyPriority the descriptor heap", [](Objects& o) { return priority1(o, 3); }, 0, true}, + {"SetResidencyPriority the query heap", [](Objects& o) { return priority1(o, 4); }, 0, true}, + {"SetResidencyPriority the fence", [](Objects& o) { return priority1(o, 5); }, 0, true}, + {"SetResidencyPriority all six NORMAL", [](Objects& o) { + const D3D12_RESIDENCY_PRIORITY p[6] = {D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL, + D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL, + D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL}; + return o.device1->SetResidencyPriority(6, o.all, p); + }, 0, true}, + {"SetResidencyPriority the buffer and the placed buffer", [](Objects& o) { + ID3D12Pageable* two[] = {o.all[0], o.all[2]}; + const D3D12_RESIDENCY_PRIORITY p[2] = {D3D12_RESIDENCY_PRIORITY_NORMAL, D3D12_RESIDENCY_PRIORITY_NORMAL}; + return o.device1->SetResidencyPriority(2, two, p); + }, 0, true}, + {"MakeResident 1, null", [](Objects& o) { return o.device->MakeResident(1, nullptr); }, 0, true}, + {"Evict 1, null", [](Objects& o) { return o.device->Evict(1, nullptr); }, 0, true}, + {"SetResidencyPriority 1, objects, null", [](Objects& o) { + return o.device1->SetResidencyPriority(1, o.all, nullptr); + }, 0, true}, + {"SetResidencyPriority 1, null, priorities", [](Objects& o) { + const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL; + return o.device1->SetResidencyPriority(1, nullptr, &p); + }, 0, true}, + {"EnqueueMakeResident 1, null objects", [](Objects& o) { + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, nullptr, o.fence, 11); + }, 0, true}, + {"MakeResident 1, [null]", [](Objects& o) { + ID3D12Pageable* none[] = {nullptr}; + return o.device->MakeResident(1, none); + }, 0, true}, + {"Evict 1, [null]", [](Objects& o) { + ID3D12Pageable* none[] = {nullptr}; + return o.device->Evict(1, none); + }, 0, true}, + {"SetResidencyPriority 1, [null]", [](Objects& o) { + ID3D12Pageable* none[] = {nullptr}; + const D3D12_RESIDENCY_PRIORITY p = D3D12_RESIDENCY_PRIORITY_NORMAL; + return o.device1->SetResidencyPriority(1, none, &p); + }, 0, true}, + {"EnqueueMakeResident 1, [null]", [](Objects& o) { + ID3D12Pageable* none[] = {nullptr}; + return o.device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, none, o.fence, 20); + }, 0, true}, +}; + +struct Record { + std::vector names; + std::vector values; + void add(const std::string& name, std::uint64_t value) { + names.push_back(name); + values.push_back(value); + } +}; + +// The value `fence` settles at after an EnqueueMakeResident that asked for `want`: the host signals it from a +// paging queue, so wait (up to 2 s) for it to reach `want`, or, for a value below the current one, to change. +UINT64 settled(ID3D12Fence* fence, UINT64 before, UINT64 want) { + for (int i = 0; i < 200; ++i) { + const UINT64 now = fence->GetCompletedValue(); + if (now == want || (want < before && now != before)) return now; + Sleep(10); + } + return fence->GetCompletedValue(); +} + +// The pageable objects of one device, and the references that keep them alive. +struct Holder { + Ref device1; + Ref device3; + Ref buffer, placed; + Ref heap; + Ref descriptors; + Ref queries; + Ref fence; + Objects o; +}; + +bool make(ID3D12Device* device, Holder& h) { + h.o.device = device; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&h.device1.p))) || + FAILED(device->QueryInterface(IID_PPV_ARGS(&h.device3.p)))) + return false; + h.o.device1 = h.device1.p; + h.o.device3 = h.device3.p; + const D3D12_HEAP_PROPERTIES gpu{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 64 * 1024; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_HEAP_DESC heap_desc{}; + heap_desc.SizeInBytes = 64 * 1024; + heap_desc.Properties = gpu; + heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; + const D3D12_DESCRIPTOR_HEAP_DESC dh{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + const D3D12_QUERY_HEAP_DESC qh{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 4, 0}; + if (FAILED(device->CreateCommittedResource(&gpu, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&h.buffer.p))) || + FAILED(device->CreateHeap(&heap_desc, IID_PPV_ARGS(&h.heap.p))) || + FAILED(device->CreatePlacedResource(h.heap.p, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&h.placed.p))) || + FAILED(device->CreateDescriptorHeap(&dh, IID_PPV_ARGS(&h.descriptors.p))) || + FAILED(device->CreateQueryHeap(&qh, IID_PPV_ARGS(&h.queries.p))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&h.fence.p)))) + return false; + h.o.all[0] = h.buffer.p; + h.o.all[1] = h.heap.p; + h.o.all[2] = h.placed.p; + h.o.all[3] = h.descriptors.p; + h.o.all[4] = h.queries.p; + h.o.all[5] = h.fence.p; + h.o.fence = h.fence.p; + return true; +} + +ID3D12Device* create_host() { + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto create = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))) + : nullptr; + ID3D12Device* host = nullptr; + if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host)))) return nullptr; + return host; +} + +constexpr std::uint64_t kNoChild = 0xC41DFA11ull; // the child process couldn't run the step +constexpr int kMaxNotCompared = 11; // values the host can't give: see the end of main + +// Step `index` on a fresh host device, in a child process (this executable with --host-step): its exit code is the +// HRESULT, or a crash status, which counts as a fault. +std::uint64_t isolated(std::size_t index) { + wchar_t exe[MAX_PATH] = {}; + GetModuleFileNameW(nullptr, exe, MAX_PATH); + std::wstring command = L"\"" + std::wstring(exe) + L"\" --host-step " + std::to_wstring(index); + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION process{}; + if (!CreateProcessW(nullptr, command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, + &startup, &process)) + return kNoChild; + DWORD code = DWORD(kNoChild); + if (WaitForSingleObject(process.hProcess, 60000) == WAIT_OBJECT_0) GetExitCodeProcess(process.hProcess, &code); + else TerminateProcess(process.hProcess, DWORD(kNoChild)); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + // Checked before the crash statuses below, which kNoChild would otherwise fall into: a child that couldn't run + // its step is a broken test, not a host fault, and fails it. + if (code == DWORD(kNoChild)) return kNoChild; + if ((code & 0xF0000000u) == 0xC0000000u) return kFaulted; // an access violation or fail-fast the guard missed + return code; +} + +// Runs the script on `device` and records it. `host`: run the isolated steps in child processes. +bool run(ID3D12Device* device, bool host, Record& out) { + Holder h; + if (!make(device, h)) return false; + for (std::size_t i = 0; i < sizeof(kSteps) / sizeof(kSteps[0]); ++i) { + const Step& s = kSteps[i]; + if (s.isolated) { + out.add(s.name, host ? isolated(i) : std::uint64_t(std::uint32_t(guarded(s.call, &h.o)))); + continue; + } + const UINT64 before = h.fence->GetCompletedValue(); + const HRESULT hr = guarded(s.call, &h.o); + out.add(s.name, std::uint64_t(std::uint32_t(hr))); + out.add(std::string(s.name) + " (removed reason)", std::uint64_t(std::uint32_t(device->GetDeviceRemovedReason()))); + if (s.fence_value) + out.add(std::string(s.name) + " (fence)", + hr == HRESULT(kFaulted) ? kFaulted : settled(h.fence.p, before, s.fence_value)); + } + return true; +} + +// --host-step N: one isolated step on a fresh host device; the exit code is its HRESULT. +int host_step(std::size_t index) { + if (index >= sizeof(kSteps) / sizeof(kSteps[0])) return int(kNoChild); + Ref host; + host.p = create_host(); + Holder h; + if (!host.p || !make(host.p, h)) return int(kNoChild); + return int(guarded(kSteps[index].call, &h.o)); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc == 3 && std::strcmp(argv[1], "--host-step") == 0) return host_step(std::size_t(std::atoi(argv[2]))); + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + if (device_status != vktest::DeviceStatus::ready) return 1; + const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; // heaps live in the GPU address arena + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + Record ours; + EXPECT(run(device.p, false, ours)); + + Ref host; + host.p = create_host(); + if (!host.p) { + std::printf("residency: no host D3D12 device to compare with; %zu steps recorded, not compared\n", + ours.values.size()); + } else { + Record theirs; + EXPECT(run(host.p, true, theirs)); + EXPECT(theirs.names == ours.names); + int mismatches = 0, faulted = 0; + for (std::size_t i = 0; i < ours.values.size(); ++i) { + if (theirs.values[i] == kNoChild) + std::printf("residency %s: the host step's child process didn't run it\n", ours.names[i].c_str()); + EXPECT(theirs.values[i] != kNoChild); + if (theirs.values[i] == kFaulted) { + std::printf("residency %s: the host faults, not compared (ours 0x%llx)\n", ours.names[i].c_str(), + static_cast(ours.values[i])); + ++faulted; + continue; + } + // A fence the layer would have to move backwards: Vulkan timelines only go up, so the layer's fence + // stays where it was (docs/d3d12_vulkan.md); the HRESULT is still compared. + if (ours.names[i].find("[backwards]") != std::string::npos && + ours.names[i].find("(fence)") != std::string::npos) { + std::printf("residency %s: ours 0x%llx host 0x%llx (a fence can't go backwards here; not " + "compared)\n", ours.names[i].c_str(), static_cast(ours.values[i]), + static_cast(theirs.values[i])); + ++faulted; + continue; + } + const bool same = ours.values[i] == theirs.values[i]; + if (verbose || !same) + std::printf("residency %s: ours 0x%llx host 0x%llx%s\n", ours.names[i].c_str(), + static_cast(ours.values[i]), + static_cast(theirs.values[i]), same ? "" : " MISMATCH"); + mismatches += !same; + } + std::printf("residency: %zu values from %zu steps compared with the host (%d more not compared), " + "%d mismatches\n", ours.values.size() - faulted, sizeof(kSteps) / sizeof(kSteps[0]), faulted, + mismatches); + EXPECT(mismatches == 0); + // The values left out are the null-pointer steps the host faults on and the backwards fence. A host that + // faulted on more would make the comparison vacuous while still passing, so the count is held to that. + EXPECT(faulted <= kMaxNotCompared); + } + } + std::printf("d3d12_residency_test: OK\n"); + return 0; +} diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp index 503492610..1d51c9e70 100644 --- a/runtime/test/d3d12_set0_compute_test.cpp +++ b/runtime/test/d3d12_set0_compute_test.cpp @@ -16,6 +16,7 @@ // GLSL written to the translator's contract. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). #include "shader_fixture_path.h" +#include "test_temp_dir.h" #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -68,10 +69,10 @@ int main() { // set-0 bindings for the shader, as the translator does for one that samples. const auto program = fssm_program({0x43530003, 0xbf810000}); const auto container = shader_container(program); - const auto library = std::filesystem::temp_directory_path() / "leonida_set0_compute_test"; - std::filesystem::create_directories(library); - std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SET0_SAMPLE_SPV), library / "cs_set0_sample.spv", - std::filesystem::copy_options::overwrite_existing); + const testfiles::ScratchDir scratch("leonida_set0_compute_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SET0_SAMPLE_SPV), + library / "cs_set0_sample.spv")); { std::ofstream index(library / "index.json", std::ios::binary); index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program) @@ -309,7 +310,6 @@ int main() { fence.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } - std::filesystem::remove_all(library); // Runs 0, 1 and 3 against the textures; run 2 is the fallback image, whose colour the test does not fix: it // must be one colour everywhere, which neither texture gives. diff --git a/runtime/test/d3d12_shader_cache_test.cpp b/runtime/test/d3d12_shader_cache_test.cpp index 8f6a68288..bc4b2704d 100644 --- a/runtime/test/d3d12_shader_cache_test.cpp +++ b/runtime/test/d3d12_shader_cache_test.cpp @@ -28,7 +28,7 @@ struct Ref { T* operator->() const { return p; } }; -int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_in_params) { +int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool is_vulkan_layer) { // {7c83f2a1-4b5e-4d19-9a32-1f2e3d4c5b6a} const GUID id1 = {0x7c83f2a1, 0x4b5e, 0x4d19, {0x9a, 0x32, 0x1f, 0x2e, 0x3d, 0x4c, 0x5b, 0x6a}}; const GUID id2 = {0x1b74e9d0, 0x2c3a, 0x4f81, {0x8e, 0x11, 0x5a, 0x6b, 0x7c, 0x8d, 0x9e, 0x0f}}; @@ -42,9 +42,9 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_ // 1. CreateShaderCacheSession argument validation & capability check (null output -> S_FALSE). // Passing nullptr for SAL _In_/_Inout_ parameters (pDesc, pKey, pValue, pValueSize) is undefined - // behaviour on older in-box Windows D3D12 runtimes (e.g. Win11 23H2 22621.5415 AVs), so those - // null-pointer guards are exercised only on the Vulkan layer. - if (test_null_in_params) { + // behaviour on older in-box Windows D3D12 runtimes, so those null-pointer guards are exercised + // only on the Vulkan layer. + if (is_vulkan_layer) { EXPECT(dev->CreateShaderCacheSession(nullptr, __uuidof(ID3D12ShaderCacheSession), nullptr) == E_INVALIDARG); } EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) == S_FALSE); @@ -81,16 +81,16 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_ UINT sz = sizeof(out_v); EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); EXPECT(sz == sizeof(out_v)); - if (test_null_in_params) { + if (is_vulkan_layer) { EXPECT(s1->FindValue(nullptr, sizeof(k1), &out_v, &sz) == E_INVALIDARG); } EXPECT(s1->FindValue(&k1, 0, &out_v, &sz) == E_INVALIDARG); - if (test_null_in_params) { + if (is_vulkan_layer) { EXPECT(s1->FindValue(&k1, sizeof(k1), &out_v, nullptr) == E_INVALIDARG); EXPECT(s1->StoreValue(nullptr, sizeof(k1), &v1, sizeof(v1)) == E_INVALIDARG); } EXPECT(s1->StoreValue(&k1, 0, &v1, sizeof(v1)) == E_INVALIDARG); - if (test_null_in_params) { + if (is_vulkan_layer) { EXPECT(s1->StoreValue(&k1, sizeof(k1), nullptr, sizeof(v1)) == E_INVALIDARG); } EXPECT(s1->StoreValue(&k1, sizeof(k1), &v1, 0) == E_INVALIDARG); @@ -118,17 +118,21 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_ EXPECT(s2->FindValue(&k1, sizeof(k1), &out_v, &sz) == S_OK && sz == sizeof(v1) && out_v == v1); // Different Identifier does not see k1. + // Older in-box Windows D3D12 runtimes (e.g. Win11 23H2 d3d12.dll 10.0.22621.5415) AV (0xC0000005) + // when releasing a D3D12_SHADER_CACHE_MODE_MEMORY session after SetDeleteOnDestroy(), so exercise + // SetDeleteOnDestroy() on MODE_MEMORY only on the Vulkan layer; MODE_MEMORY still discards on final + // release on both runtimes. D3D12_SHADER_CACHE_SESSION_DESC desc2 = desc; desc2.Identifier = id2; Ref other; EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc2, IID_PPV_ARGS(&other.p))) && other.p); sz = sizeof(out_v); EXPECT(other->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); - other->SetDeleteOnDestroy(); + if (is_vulkan_layer) other->SetDeleteOnDestroy(); other.reset(); - // Marking s1 delete-on-destroy keeps data alive while s2 is still open, then deletes once s2 releases. - s1->SetDeleteOnDestroy(); + // Releasing s1 keeps data alive while s2 is still open, then discards once s2 releases. + if (is_vulkan_layer) s1->SetDeleteOnDestroy(); s1.reset(); sz = sizeof(out_v); out_v = 0; @@ -139,7 +143,7 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool test_null_ EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s3.p))) && s3.p); sz = sizeof(out_v); EXPECT(s3->FindValue(&k1, sizeof(k1), &out_v, &sz) == DXGI_ERROR_NOT_FOUND); - s3->SetDeleteOnDestroy(); + if (is_vulkan_layer) s3->SetDeleteOnDestroy(); s3.reset(); // 4. ShaderCacheControl invalid-argument checks (same on host and layer). diff --git a/runtime/test/d3d12_sparse_queue_family_test.cpp b/runtime/test/d3d12_sparse_queue_family_test.cpp new file mode 100644 index 000000000..04caee442 --- /dev/null +++ b/runtime/test/d3d12_sparse_queue_family_test.cpp @@ -0,0 +1,175 @@ +// Synthetic D3D12 reserved-buffer mapping on DIRECT/COPY/COMPUTE queues, with GPU readback. +#include +#include +#include +#include "../shims/d3d12_com.h" +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +constexpr UINT64 PAGE_BYTES = 65536, BUFFER_BYTES = 2 * PAGE_BYTES; + +static void ok(HRESULT hr, const char* where) { + if (FAILED(hr)) { + std::printf("FAIL %s hr=0x%08lx\n", where, static_cast(hr)); + throw std::runtime_error(where); + } +} +static unsigned char pattern(size_t n) { + return static_cast((n * 131u + (n >> 7u) * 17u + 29u) & 255u); +} +static D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Alignment = 0; + d.Width = bytes; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.Format = DXGI_FORMAT_UNKNOWN; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return d; +} +static ComPtr committed(ID3D12Device* dev, UINT64 bytes, + D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state) { + ComPtr res; + D3D12_HEAP_PROPERTIES hp{}; + hp.Type = type; + auto desc = buffer_desc(bytes); + ok(dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&res)), "CreateCommittedResource"); + return res; +} +static ComPtr make_queue(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE type) { + D3D12_COMMAND_QUEUE_DESC desc{}; + desc.Type = type; + ComPtr q; + ok(dev->CreateCommandQueue(&desc, IID_PPV_ARGS(&q)), "CreateCommandQueue"); + return q; +} +struct CopyList { + ComPtr alloc; + ComPtr list; +}; +static CopyList copy_list(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE type, + ID3D12Resource* dst, ID3D12Resource* src, UINT64 bytes) { + CopyList cl; + ok(dev->CreateCommandAllocator(type, IID_PPV_ARGS(&cl.alloc)), "CreateCommandAllocator"); + ok(dev->CreateCommandList(0, type, cl.alloc.Get(), nullptr, IID_PPV_ARGS(&cl.list)), + "CreateCommandList"); + cl.list->CopyBufferRegion(dst, 0, src, 0, bytes); + ok(cl.list->Close(), "Close command list"); + return cl; +} + +static bool run_case(ID3D12Device* dev, D3D12_COMMAND_LIST_TYPE map_type, + ID3D12CommandQueue* direct, ID3D12CommandQueue* copy, + ID3D12CommandQueue* compute, const char* label) { + ID3D12CommandQueue* mapper = map_type == D3D12_COMMAND_LIST_TYPE_DIRECT ? direct : + map_type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? compute : copy; + + D3D12_HEAP_DESC hdesc{}; + hdesc.SizeInBytes = PAGE_BYTES; + hdesc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + hdesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; + hdesc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; + ComPtr heap; + ok(dev->CreateHeap(&hdesc, IID_PPV_ARGS(&heap)), "CreateHeap(one tile)"); + ComPtr sparse; + auto desc = buffer_desc(BUFFER_BYTES); + ok(dev->CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&sparse)), "CreateReservedResource(buffer)"); + UINT total_tiles = 0; + dev->GetResourceTiling(sparse.Get(), &total_tiles, nullptr, nullptr, nullptr, 0, nullptr); + std::printf("case=%s reserved_tiles=%u mapping_queue=%d\n", label, total_tiles, int(map_type)); + if (total_tiles != 2) throw std::runtime_error("unexpected reserved-buffer tile count"); + + auto upload = committed(dev, PAGE_BYTES, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto readback = committed(dev, BUFFER_BYTES, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + unsigned char* host = nullptr; + D3D12_RANGE empty{0, 0}; + ok(upload->Map(0, &empty, reinterpret_cast(&host)), "Upload Map"); + for (size_t i = 0; i < PAGE_BYTES; ++i) host[i] = pattern(i); + D3D12_RANGE written{0, size_t(PAGE_BYTES)}; + upload->Unmap(0, &written); + + ComPtr fence; + ok(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "CreateFence"); + D3D12_TILED_RESOURCE_COORDINATE coord{}; + D3D12_TILE_REGION_SIZE region{}; + region.NumTiles = 1; + region.UseBox = FALSE; + D3D12_TILE_RANGE_FLAGS range_flags = D3D12_TILE_RANGE_FLAG_NONE; + UINT heap_start = 0, range_count = 1; + mapper->UpdateTileMappings(sparse.Get(), 1, &coord, ®ion, heap.Get(), + 1, &range_flags, &heap_start, &range_count, D3D12_TILE_MAPPING_FLAG_NONE); + ok(mapper->Signal(fence.Get(), 1), "mapper Signal 1"); + + auto write = copy_list(dev, D3D12_COMMAND_LIST_TYPE_COPY, sparse.Get(), upload.Get(), PAGE_BYTES); + ok(copy->Wait(fence.Get(), 1), "copy Wait 1"); + ID3D12CommandList* write_lists[] = {write.list.Get()}; + copy->ExecuteCommandLists(1, write_lists); + ok(copy->Signal(fence.Get(), 2), "copy Signal 2"); + + auto read = copy_list(dev, D3D12_COMMAND_LIST_TYPE_COMPUTE, readback.Get(), sparse.Get(), BUFFER_BYTES); + ok(compute->Wait(fence.Get(), 2), "compute Wait 2"); + ID3D12CommandList* read_lists[] = {read.list.Get()}; + compute->ExecuteCommandLists(1, read_lists); + ok(compute->Signal(fence.Get(), 3), "compute Signal 3"); + + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!done) throw std::runtime_error("CreateEventW failed"); + ok(fence->SetEventOnCompletion(3, done), "SetEventOnCompletion"); + DWORD wait = WaitForSingleObject(done, 15000); + CloseHandle(done); + if (wait != WAIT_OBJECT_0) throw std::runtime_error("GPU fence timeout"); + + D3D12_RANGE read_range{0, size_t(BUFFER_BYTES)}; + unsigned char* data = nullptr; + ok(readback->Map(0, &read_range, reinterpret_cast(&data)), "Readback Map"); + size_t wrong_mapped = 0, wrong_unmapped = 0; + for (size_t i = 0; i < PAGE_BYTES; ++i) wrong_mapped += data[i] != pattern(i); + for (size_t i = PAGE_BYTES; i < BUFFER_BYTES; ++i) wrong_unmapped += data[i] != 0; + readback->Unmap(0, &empty); + const bool passed = wrong_mapped == 0 && wrong_unmapped == 0; + std::printf("RESULT %s %s mapped_mismatch=%zu/65536 unmapped_nonzero=%zu/65536\n", + label, passed ? "PASS" : "FAIL", wrong_mapped, wrong_unmapped); + return passed; +} + +int main() { + try { + ComPtr device; + ok(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)), + "Leonida create_vulkan_device_standalone"); + if (!rt::d3d12::device_sparse_buffer_tiles(device.Get())) { + std::puts("SKIP Leonida sparse_buffer_tiles not supported"); + return 77; + } + std::puts("LEONIDA Vulkan-layer test; independent D3D12 API surface, direct->copy->compute queues"); + auto direct = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + auto copy = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_COPY); + auto compute = make_queue(device.Get(), D3D12_COMMAND_LIST_TYPE_COMPUTE); + bool all_pass = true; + all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT, + direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_DIRECT_COPY_COMPUTE"); + all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_COPY, + direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_COPY_COPY_COMPUTE"); + all_pass &= run_case(device.Get(), D3D12_COMMAND_LIST_TYPE_COMPUTE, + direct.Get(), copy.Get(), compute.Get(), "LAYER_MAP_COMPUTE_COPY_COMPUTE"); + const HRESULT removed = device->GetDeviceRemovedReason(); + std::printf("DEVICE_REMOVED_HRESULT=0x%08lx\n", static_cast(removed)); + all_pass &= SUCCEEDED(removed); + std::printf("LAYER_FINAL %s\n", all_pass ? "PASS" : "FAIL"); + return all_pass ? 0 : 1; + } catch (const std::exception& e) { + std::fprintf(stderr, "LAYER_FATAL: %s\n", e.what()); + return 2; + } +} diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index 58a649437..d7466b781 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -660,6 +660,21 @@ int main() { CHECK(!resizable_bar(VkPhysicalDeviceMemoryProperties{})); } + // D3D-299: a texture (required 0, preferred DEVICE_LOCAL) in host memory has spilled; the arena (required + // HOST_VISIBLE | HOST_COHERENT, preferred DEVICE_LOCAL) in host memory has not, and neither has anything that + // got DEVICE_LOCAL or never asked for it. + { + constexpr VkMemoryPropertyFlags local = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + CHECK(spilled_to_host(0, local, host)); + CHECK(spilled_to_host(0, local, 0)); + CHECK(!spilled_to_host(0, local, local)); + CHECK(!spilled_to_host(0, local, local | host)); + CHECK(!spilled_to_host(host, local, host)); + CHECK(!spilled_to_host(host, 0, host)); + CHECK(!spilled_to_host(0, 0, host)); + } + // Memory type choice. Heaps as an RTX 3090 without Resizable BAR reports them: VRAM, system memory, and the // 214 MiB BAR heap that holds the only DEVICE_LOCAL | HOST_VISIBLE type. { diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp index 4894f70e2..abc6f2bd0 100644 --- a/runtime/test/d3d12_subgroup_test.cpp +++ b/runtime/test/d3d12_subgroup_test.cpp @@ -10,6 +10,7 @@ // Each case also prints a control run with the layer's size request switched off, to show what the request changes // on this GPU; the control is not judged. No game data. Set LEONIDA_VK_VALIDATION=1 to run under // VK_LAYER_KHRONOS_validation; validation errors fail the test. +#include "test_temp_dir.h" #include "vk_test_device.h" #include "../shims/d3d12_com.h" #include "../src/shader_library.h" @@ -313,14 +314,14 @@ struct LibraryEntry { // A translator-style folder with the entries' modules, every entry keyed by the fixture program's hash. std::filesystem::path make_library(const std::string& tag, const std::vector& entries) { - const auto dir = std::filesystem::temp_directory_path() / ("leonida_subgroup_" + tag); + const auto dir = testfiles::process_temp_dir("leonida_subgroup_" + tag); std::filesystem::remove_all(dir); std::filesystem::create_directories(dir); std::ofstream index(dir / "index.json", std::ios::binary); index << "{"; bool first = true; for (const LibraryEntry& e : entries) { - std::filesystem::copy_file(e.spv, dir / (e.name + ".spv"), std::filesystem::copy_options::overwrite_existing); + testfiles::copy_file(e.spv, dir / (e.name + ".spv")); // a missing module is reported, and the PSO fails index << (first ? "" : ",\n") << "\"" << e.name << "\": {\"stage\": \"" << e.stage << "\", \"fssm_sha256\": \"" << leonida::sha256_hex(fixture_fssm()) << "\", \"bindings\": [], \"push_constant_bytes\": 144, " << e.tail << "}"; diff --git a/runtime/test/d3d12_typeless_families_test.cpp b/runtime/test/d3d12_typeless_families_test.cpp index 936fbbbee..b6fe4ea86 100644 --- a/runtime/test/d3d12_typeless_families_test.cpp +++ b/runtime/test/d3d12_typeless_families_test.cpp @@ -10,6 +10,7 @@ // A view format the layer does not map yet (its CheckFeatureSupport gives no RENDER_TARGET) is reported and skipped, // so the R8 family and the 16-bit integer and normalized formats are covered as soon as their mapping lands. // Synthetic data only. LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation. +#include "test_temp_dir.h" #include "vk_test_device.h" #include "host_wine.h" #include "../shims/d3d12_com.h" @@ -260,12 +261,12 @@ int main() { const auto vs_container = d3d12test::shader_container(vs_program); const auto ps_float_container = d3d12test::shader_container(ps_float_program); const auto ps_uint_container = d3d12test::shader_container(ps_uint_program); - const auto library = std::filesystem::temp_directory_path() / "leonida_typeless_families_test"; - std::filesystem::create_directories(library); - const auto overwrite = std::filesystem::copy_options::overwrite_existing; - std::filesystem::copy_file(LEONIDA_TYPELESS_VS_SPV, library / "vs.spv", overwrite); - std::filesystem::copy_file(LEONIDA_TYPELESS_PS_FLOAT_SPV, library / "ps_float.spv", overwrite); - std::filesystem::copy_file(LEONIDA_TYPELESS_PS_UINT_SPV, library / "ps_uint.spv", overwrite); + const testfiles::ScratchDir scratch("leonida_typeless_families_test"); + const auto& library = scratch.path(); + if (!testfiles::copy_file(LEONIDA_TYPELESS_VS_SPV, library / "vs.spv") || + !testfiles::copy_file(LEONIDA_TYPELESS_PS_FLOAT_SPV, library / "ps_float.spv") || + !testfiles::copy_file(LEONIDA_TYPELESS_PS_UINT_SPV, library / "ps_uint.spv")) + return 1; { std::ofstream index(library / "index.json", std::ios::binary); index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index c16ecd6a7..f7a1ed319 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -867,6 +867,56 @@ int compare_allocation_info(ID3D12Device* ours) { if (empty_a.SizeInBytes != empty_b.SizeInBytes || empty_a.Alignment != empty_b.Alignment) mismatch("no resources", empty_a, empty_b); + // A visible mask above 1 names a node a single-node adapter does not have: the host answers the invalid + // allocation (size UINT64_MAX, 64 KiB alignment), for one resource and for none, through GetResourceAllocationInfo + // and its 1 and 2 variants, and leaves the per-resource array as it was. + { + Ref ours4, host4; + Ref ours8_mask, host8_mask; + ours->QueryInterface(IID_PPV_ARGS(&ours4.p)); + host->QueryInterface(IID_PPV_ARGS(&host4.p)); + ours->QueryInterface(IID_PPV_ARGS(&ours8_mask.p)); + host->QueryInterface(IID_PPV_ARGS(&host8_mask.p)); + const D3D12_RESOURCE_DESC buffer = buffer_desc(256); + D3D12_RESOURCE_DESC1 buffer1{}; + buffer1.Dimension = buffer.Dimension; + buffer1.Width = buffer.Width; + buffer1.Height = buffer1.DepthOrArraySize = buffer1.MipLevels = 1; + buffer1.SampleDesc.Count = 1; + buffer1.Layout = buffer.Layout; + const auto same_info = [](const D3D12_RESOURCE_ALLOCATION_INFO& x, const D3D12_RESOURCE_ALLOCATION_INFO& y) { + return x.SizeInBytes == y.SizeInBytes && x.Alignment == y.Alignment; + }; + for (const UINT mask : {0u, 1u, 2u, 3u, 0x80000000u}) { + char name[64]; + std::snprintf(name, sizeof(name), "visible mask 0x%x", mask); + for (const UINT count : {0u, 1u}) { + const D3D12_RESOURCE_DESC* descs = count ? &buffer : nullptr; + const auto ia = ours->GetResourceAllocationInfo(mask, count, descs); + const auto ib = host->GetResourceAllocationInfo(mask, count, descs); + if (!same_info(ia, ib)) mismatch(name, ia, ib); + } + if (ours4.p && host4.p) { + const D3D12_RESOURCE_ALLOCATION_INFO1 sentinel{0xdead, 0xbeef, 0xcafe}; + D3D12_RESOURCE_ALLOCATION_INFO1 each_a = sentinel, each_b = sentinel; + const auto ia = ours4->GetResourceAllocationInfo1(mask, 1, &buffer, &each_a); + const auto ib = host4->GetResourceAllocationInfo1(mask, 1, &buffer, &each_b); + if (!same_info(ia, ib) || each_a.Offset != each_b.Offset || each_a.SizeInBytes != each_b.SizeInBytes || + each_a.Alignment != each_b.Alignment) + mismatch("visible mask, GetResourceAllocationInfo1", ia, ib); + } + if (ours8_mask.p && host8_mask.p) { + const D3D12_RESOURCE_ALLOCATION_INFO1 sentinel{0xdead, 0xbeef, 0xcafe}; + D3D12_RESOURCE_ALLOCATION_INFO1 each_a = sentinel, each_b = sentinel; + const auto ia = ours8_mask->GetResourceAllocationInfo2(mask, 1, &buffer1, &each_a); + const auto ib = host8_mask->GetResourceAllocationInfo2(mask, 1, &buffer1, &each_b); + if (!same_info(ia, ib) || each_a.Offset != each_b.Offset || each_a.SizeInBytes != each_b.SizeInBytes || + each_a.Alignment != each_b.Alignment) + mismatch("visible mask, GetResourceAllocationInfo2", ia, ib); + } + } + } + Ref ours8; // MULTISAMPLE_QUALITY_LEVELS with TILED_RESOURCE: the same answers as the host, except 128-bit formats at 4x, // which the AMD drivers refuse and WARP and NVIDIA report (and GetResourceAllocationInfo allocates here). @@ -1968,6 +2018,7 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn }; constexpr UINT size = 4, pitch = 256, slot = 1024; int failures = 0; + unsigned host_compared = 0, host_lacking = 0; const auto fail = [&](DXGI_FORMAT format, const char* what) { if (failures++ < 16) std::fprintf(stderr, "new format %d: %s\n", int(format), what); }; @@ -2041,17 +2092,21 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn } if (host.p) { // A host runtime older than the format has nothing to match: A4B4G4R4_UNORM is not in Windows 10's D3D12, - // which reports no 2D texture support for it and refuses it. Compare only where the host itself says it - // has the format, so a host that reports it and still refuses the texture fails as before. + // which answers the query with an error (E_FAIL on Windows 10 build 19045, E_INVALIDARG on another 19041 + // host) or reports no 2D texture, and refuses the texture. Compare only where the host itself says it has + // the format, so a host that reports it and still refuses the texture fails as before. The answer is + // printed, so an unexpected code stays visible. D3D12_FEATURE_DATA_FORMAT_SUPPORT host_support{format}; - const bool host_has_format = - SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &host_support, - sizeof(host_support))) && - (host_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D); + const HRESULT query = host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &host_support, + sizeof(host_support)); + const bool host_has_format = SUCCEEDED(query) && (host_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D); if (!host_has_format) { - std::printf("new format %d: the host runtime has no such 2D texture (e.g. Windows 10), " - "host comparison skipped\n", int(format)); + ++host_lacking; + std::printf("new format %d: the host runtime has no such 2D texture (FORMAT_SUPPORT answered %08lx, " + "e.g. Windows 10), host comparison skipped\n", + int(format), static_cast(query)); } else { + ++host_compared; Ref native; if (FAILED(host->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, @@ -2172,9 +2227,12 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn } upload->Unmap(0, nullptr); readback->Unmap(0, nullptr); + char compared[64] = ""; + if (host.p) std::snprintf(compared, sizeof(compared), " (host compared on %u, host lacks %u)", host_compared, + host_lacking); std::printf("new formats: %u of %zu created and copied both ways bit for bit%s, %u render-target clears " "matched the host, A4B4G4R4 render target %s, %d failures\n", - round_trips, std::size(formats), host.p ? " (host compared)" : "", clears_matched, + round_trips, std::size(formats), compared, clears_matched, a4_target ? (a4_cleared == 4 ? "cleared to R, G, B and A" : "cleared wrong") : "not reported, skipped", failures); return failures; @@ -2236,8 +2294,8 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf D3D12_FEATURE_DATA_D3D12_OPTIONS16 o16{}; D3D12_FEATURE_DATA_D3D12_OPTIONS18 o18{}; D3D12_FEATURE_DATA_D3D12_OPTIONS19 o19{}; - D3D12_FEATURE_DATA_D3D12_OPTIONS20 o20{}; - D3D12_FEATURE_DATA_D3D12_OPTIONS21 o21{}; + rt::d3d12::compat::FeatureDataOptions20 o20{}; + rt::d3d12::compat::FeatureDataOptions21 o21{}; query_ours(std::pair{"OPTIONS2", D3D12_FEATURE_D3D12_OPTIONS2}, o2); query_ours(std::pair{"OPTIONS3", D3D12_FEATURE_D3D12_OPTIONS3}, o3); @@ -2252,14 +2310,14 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf query_ours(std::pair{"OPTIONS16", D3D12_FEATURE_D3D12_OPTIONS16}, o16); query_ours(std::pair{"OPTIONS18", D3D12_FEATURE_D3D12_OPTIONS18}, o18); query_ours(std::pair{"OPTIONS19", D3D12_FEATURE_D3D12_OPTIONS19}, o19); - query_ours(std::pair{"OPTIONS20", D3D12_FEATURE_D3D12_OPTIONS20}, o20); - query_ours(std::pair{"OPTIONS21", D3D12_FEATURE_D3D12_OPTIONS21}, o21); + query_ours(std::pair{"OPTIONS20", rt::d3d12::compat::kFeatureOptions20}, o20); + query_ours(std::pair{"OPTIONS21", rt::d3d12::compat::kFeatureOptions21}, o21); D3D12_FEATURE_DATA_SHADER_CACHE shader_cache{}; D3D12_FEATURE_DATA_EXISTING_HEAPS existing_heaps{}; D3D12_FEATURE_DATA_CROSS_NODE cross_node{}; D3D12_FEATURE_DATA_DISPLAYABLE displayable{}; - D3D12_FEATURE_DATA_PREDICATION predication{}; + rt::d3d12::compat::FeatureSupportFlag predication{}; rt::d3d12::compat::FeatureSupportFlag driver_state{}; rt::d3d12::compat::FeatureSupportFlag bypass_hash{}; D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT prot_support{}; @@ -2272,7 +2330,7 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf query_ours(std::pair{"EXISTING_HEAPS", D3D12_FEATURE_EXISTING_HEAPS}, existing_heaps); query_ours(std::pair{"CROSS_NODE", D3D12_FEATURE_CROSS_NODE}, cross_node); query_ours(std::pair{"DISPLAYABLE", D3D12_FEATURE_DISPLAYABLE}, displayable); - query_ours(std::pair{"PREDICATION", D3D12_FEATURE_PREDICATION}, predication); + query_ours(std::pair{"PREDICATION", rt::d3d12::compat::kFeaturePredication}, predication); query_ours(std::pair{"APPLICATION_SPECIFIC_DRIVER_STATE", rt::d3d12::compat::kFeatureApplicationSpecificDriverState}, driver_state); @@ -2341,11 +2399,11 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf o19.MaxViewDescriptorHeapSize != D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2 || o19.ComputeOnlyCustomHeapSupported) fail("OPTIONS19 mismatch"); - if (o20.ComputeOnlyWriteWatchSupported || o20.RecreateAtTier != D3D12_RECREATE_AT_TIER_NOT_SUPPORTED) + if (o20.ComputeOnlyWriteWatchSupported || o20.RecreateAtTier != rt::d3d12::compat::kRecreateAtTierNotSupported) fail("OPTIONS20 unexpected support"); - if (o21.WorkGraphsTier != D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED || - o21.ExecuteIndirectTier != D3D12_EXECUTE_INDIRECT_TIER_1_0 || o21.SampleCmpGradientAndBiasSupported || - o21.ExtendedCommandInfoSupported) + if (o21.WorkGraphsTier != rt::d3d12::compat::kWorkGraphsTierNotSupported || + o21.ExecuteIndirectTier != rt::d3d12::compat::kExecuteIndirectTier1_0 || + o21.SampleCmpGradientAndBiasSupported || o21.ExtendedCommandInfoSupported) fail("OPTIONS21 unexpected support"); // Verify OPTIONS19.AnisoFilterWithPointMipSupported follows VulkanDeviceInfo::sampler_anisotropy. @@ -2448,8 +2506,9 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf if (FAILED(rt::d3d12::create_vulkan_device(no_pred_info, IID_PPV_ARGS(&no_pred.p)))) { fail("failed to create conditional_rendering=false device"); } else { - D3D12_FEATURE_DATA_PREDICATION pred_off{TRUE}; - if (FAILED(no_pred->CheckFeatureSupport(D3D12_FEATURE_PREDICATION, &pred_off, sizeof(pred_off))) || + rt::d3d12::compat::FeatureSupportFlag pred_off{TRUE}; + if (FAILED(no_pred->CheckFeatureSupport(rt::d3d12::compat::kFeaturePredication, &pred_off, + sizeof(pred_off))) || pred_off.Supported != FALSE) fail("PREDICATION did not become FALSE when conditional_rendering is off"); } @@ -2629,13 +2688,13 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf check_bool(n, "ComputeOnlyCustomHeapSupported", a.ComputeOnlyCustomHeapSupported, b.ComputeOnlyCustomHeapSupported); }); - compare_host("OPTIONS20", D3D12_FEATURE_D3D12_OPTIONS20, o20, + compare_host("OPTIONS20", rt::d3d12::compat::kFeatureOptions20, o20, [&](const char* n, const auto& a, const auto& b) { check_bool(n, "ComputeOnlyWriteWatchSupported", a.ComputeOnlyWriteWatchSupported, b.ComputeOnlyWriteWatchSupported); check_tier(n, "RecreateAtTier", int(a.RecreateAtTier), int(b.RecreateAtTier)); }); - compare_host("OPTIONS21", D3D12_FEATURE_D3D12_OPTIONS21, o21, + compare_host("OPTIONS21", rt::d3d12::compat::kFeatureOptions21, o21, [&](const char* n, const auto& a, const auto& b) { check_tier(n, "WorkGraphsTier", int(a.WorkGraphsTier), int(b.WorkGraphsTier)); check_tier(n, "ExecuteIndirectTier", int(a.ExecuteIndirectTier), int(b.ExecuteIndirectTier)); @@ -2666,7 +2725,7 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf check_tier(n, "SharedResourceCompatibilityTier", int(a.SharedResourceCompatibilityTier), int(b.SharedResourceCompatibilityTier)); }); - compare_host("PREDICATION", D3D12_FEATURE_PREDICATION, predication, + compare_host("PREDICATION", rt::d3d12::compat::kFeaturePredication, predication, [&](const char* n, const auto& a, const auto& b) { check_bool(n, "Supported", a.Supported, b.Supported); }); @@ -2883,6 +2942,35 @@ HRESULT fence(ID3D12Device* device, D3D12_FENCE_FLAGS flags, REFIID riid = __uui return released(device->CreateFence(0, flags, riid, &out), &out); } +HRESULT command_allocator(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type, bool output = true, + REFIID riid = __uuidof(ID3D12CommandAllocator)) { + void* out = nullptr; + return released(device->CreateCommandAllocator(type, riid, output ? &out : nullptr), &out); +} + +// CreateCommandList with a fresh allocator of `allocator_type` (or none when it is -2). +HRESULT command_list(ID3D12Device* device, UINT node_mask, D3D12_COMMAND_LIST_TYPE type, + int allocator_type, bool output = true) { + void* allocator = nullptr; + if (allocator_type != -2) + device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(allocator_type), __uuidof(ID3D12CommandAllocator), + &allocator); + void* out = nullptr; + const HRESULT hr = device->CreateCommandList(node_mask, type, static_cast(allocator), + nullptr, __uuidof(ID3D12GraphicsCommandList), output ? &out : nullptr); + released(S_OK, &allocator); + return released(hr, &out); +} + +HRESULT command_list1(ID3D12Device* device, UINT node_mask, D3D12_COMMAND_LIST_TYPE type, bool output = true) { + Ref device4; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device4.p)))) return E_NOINTERFACE; + void* out = nullptr; + return released(device4->CreateCommandList1(node_mask, type, D3D12_COMMAND_LIST_FLAG_NONE, + __uuidof(ID3D12GraphicsCommandList), output ? &out : nullptr), + &out); +} + // A 64 KiB heap description for the CreateHeap cases (D3D-238). D3D12_HEAP_DESC heap_desc_of(UINT64 alignment, D3D12_HEAP_PROPERTIES properties = {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE, UINT64 size = 64 * 1024) { @@ -2977,6 +3065,19 @@ bool host_ray_tracing(ID3D12Device* host) { o5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED; } +// Windows 10's runtime (no ID3D12Device10) still checks a buffer's initial state and refuses a HARDWARE_PROTECTED +// heap, where newer runtimes and the layer accept them (measured on Windows 10 22H2 build 19045.5737). For a case +// marked windows10_refuses only that pair is excused: the layer's S_OK against the host's E_INVALIDARG, on a host +// without ID3D12Device10. Any other difference, and any difference on a newer host, is still a mismatch. +bool windows10_refusal(const char* name, ID3D12Device* host, HRESULT ours, HRESULT theirs) { + if (ours != S_OK || theirs != E_INVALIDARG) return false; + Ref newer; + if (SUCCEEDED(host->QueryInterface(IID_PPV_ARGS(&newer.p)))) return false; + std::printf("invalid arguments %s: Windows 10's runtime refuses it (ours 0x%08lx, host 0x%08lx)\n", name, ours, + theirs); + return true; +} + int compare_invalid_arguments(ID3D12Device* ours) { Ref host; if (!create_host_device(host)) return -1; @@ -2985,6 +3086,7 @@ int compare_invalid_arguments(ID3D12Device* ours) { const char* name; InvalidCase call; bool (*comparable)(ID3D12Device*) = nullptr; + bool windows10_refuses = false; }; const auto device10 = [](ID3D12Device* d) { Ref newer; @@ -3094,13 +3196,14 @@ int compare_invalid_arguments(ID3D12Device* ours) { {"committed: texture in RESOLVE_DEST state", [](ID3D12Device* d) { return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_RESOLVE_DEST); }}, + // A buffer's initial state: Windows 10's runtime refuses these two, newer ones accept them, as the layer does. {"committed: buffer in state 0x80000000", [](ID3D12Device* d) { return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), D3D12_RESOURCE_STATES(0x80000000u)); - }}, + }, nullptr, true}, {"committed: buffer in RENDER_TARGET | UNORDERED_ACCESS state", [](ID3D12Device* d) { return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - }}, + }, nullptr, true}, {"committed: buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) { return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE); @@ -3835,6 +3938,98 @@ int compare_invalid_arguments(ID3D12Device* ours) { {"command queue: high priority", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_HIGH}); }}, + // Command allocators and lists (video list types are only created here, not compared: the host hands out + // a video list, which is not an ID3D12GraphicsCommandList). Types past VIDEO_ENCODE and nodes other than 0 + // are refused first; a null output is then E_UNEXPECTED. + {"command allocator: type direct", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE(0)); + }}, + {"command allocator: type bundle", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE(1)); + }}, + {"command allocator: type compute", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE(2)); + }}, + {"command allocator: type copy", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE(3)); + }}, + {"command allocator: type video encode", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE(6)); + }}, + {"command allocator: type 7", [](ID3D12Device* d) { return command_allocator(d, D3D12_COMMAND_LIST_TYPE(7)); }}, + {"command allocator: type 99", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE(99)); + }}, + {"command allocator: type -1", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE(-1)); + }}, + {"command allocator: null output", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, false); + }}, + {"command allocator: null output, type 99", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE(99), false); + }}, + {"command allocator: null output, wrong interface", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, false, __uuidof(ID3D12Fence)); + }}, + {"command allocator: wrong interface", [](ID3D12Device* d) { + return command_allocator(d, D3D12_COMMAND_LIST_TYPE_DIRECT, true, __uuidof(ID3D12Fence)); + }}, + {"command list: direct", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0); }}, + {"command list: bundle", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_BUNDLE, 1); }}, + {"command list: node mask 1", [](ID3D12Device* d) { + return command_list(d, 1, D3D12_COMMAND_LIST_TYPE_DIRECT, 0); + }}, + {"command list: node mask 2", [](ID3D12Device* d) { + return command_list(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, 0); + }}, + {"command list: node mask 3", [](ID3D12Device* d) { + return command_list(d, 3, D3D12_COMMAND_LIST_TYPE_DIRECT, 0); + }}, + {"command list: compute allocator", [](ID3D12Device* d) { + return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 2); + }}, + {"command list: no allocator", [](ID3D12Device* d) { + return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, -2); + }}, + {"command list: type 99", [](ID3D12Device* d) { return command_list(d, 0, D3D12_COMMAND_LIST_TYPE(99), 0); }}, + {"command list: null output", [](ID3D12Device* d) { + return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, false); + }}, + {"command list: null output, node mask 2", [](ID3D12Device* d) { + return command_list(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, false); + }}, + {"command list: null output, no allocator", [](ID3D12Device* d) { + return command_list(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, -2, false); + }}, + {"command list1: type direct", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(0)); }}, + {"command list1: type bundle", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(1)); }}, + {"command list1: type compute", [](ID3D12Device* d) { + return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(2)); + }}, + {"command list1: type copy", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(3)); }}, + {"command list1: type 7", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(7)); }}, + {"command list1: type 99", [](ID3D12Device* d) { return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(99)); }}, + // NONE (-1): Windows 10's runtime (19045, no ID3D12Device10) creates the list and Windows 11's refuses it + // (measured on #2297), so it is compared only on a host with ID3D12Device10. + {"command list1: type -1", [](ID3D12Device* d) { + return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(-1)); + }, +device10}, + {"command list1: node mask 1", [](ID3D12Device* d) { + return command_list1(d, 1, D3D12_COMMAND_LIST_TYPE_DIRECT); + }}, + {"command list1: node mask 2", [](ID3D12Device* d) { + return command_list1(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT); + }}, + {"command list1: null output", [](ID3D12Device* d) { + return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, false); + }}, + {"command list1: null output, node mask 2", [](ID3D12Device* d) { + return command_list1(d, 2, D3D12_COMMAND_LIST_TYPE_DIRECT, false); + }}, + {"command list1: null output, type 99", [](ID3D12Device* d) { + return command_list1(d, 0, D3D12_COMMAND_LIST_TYPE(99), false); + }}, // CreateCommandSignature (no root signature). A null description faults in the host runtime, so it is not // compared. {"command signature: null output", [](ID3D12Device* d) { @@ -4004,6 +4199,7 @@ int compare_invalid_arguments(ID3D12Device* ours) { const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); if (a == b) continue; + if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue; if (c.comparable && !c.comparable(host.p)) { std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name, a, b); @@ -4074,6 +4270,7 @@ int compare_heap_neighbours(ID3D12Device* ours) { struct Case { const char* name; InvalidCase call; + bool windows10_refuses = false; }; static const Case cases[] = { {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }}, @@ -4100,15 +4297,16 @@ int compare_heap_neighbours(ID3D12Device* ours) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS)); }}, // The D3D12_HEAP_FLAGS documentation calls it unsupported, but the host accepts it (RTX 4070 SUPER and - // UHD 770, @CowBoYdu76). + // UHD 770, @CowBoYdu76). Windows 10's runtime refuses it, as it refuses the committed case above. {"heap: HARDWARE_PROTECTED", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_HARDWARE_PROTECTED)); - }}, + }, true}, }; int mismatches = 0; for (const Case& c : cases) { const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); if (a == b) continue; + if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue; ++mismatches; std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b); } @@ -4126,6 +4324,7 @@ int compare_placed_reserved(ID3D12Device* ours) { const char* name; InvalidCase call; bool (*comparable)(ID3D12Device*) = nullptr; + bool windows10_refuses = false; }; static const Case cases[] = { // The standalone device has acceleration structures (XDXR, or KHR with LEONIDA_RT_AS=khr) and accepts a UAV @@ -4339,7 +4538,7 @@ int compare_placed_reserved(ID3D12Device* ours) { a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD; a.state = D3D12_RESOURCE_STATE_COPY_DEST; return placed(d, buffer_desc(256), a); - }}, + }, nullptr, true}, {"placed: upload buffer with ALLOW_UNORDERED_ACCESS", [](ID3D12Device* d) { auto desc = buffer_desc(256); desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; @@ -4359,12 +4558,12 @@ int compare_placed_reserved(ID3D12Device* ours) { a.heap.Properties.Type = D3D12_HEAP_TYPE_READBACK; a.state = D3D12_RESOURCE_STATE_GENERIC_READ; return placed(d, buffer_desc(256), a); - }}, + }, nullptr, true}, {"placed: default buffer in state 0x80000000", [](ID3D12Device* d) { PlacedArgs a; a.state = D3D12_RESOURCE_STATES(0x80000000u); return placed(d, buffer_desc(256), a); - }}, + }, nullptr, true}, {"placed: depth texture in DEPTH_WRITE", [](ID3D12Device* d) { PlacedArgs a; a.state = D3D12_RESOURCE_STATE_DEPTH_WRITE; @@ -4460,7 +4659,7 @@ int compare_placed_reserved(ID3D12Device* ours) { }}, {"reserved: buffer in state 0x80000000", [](ID3D12Device* d) { return reserved(d, buffer_desc(64 * 1024), D3D12_RESOURCE_STATES(0x80000000u)); - }}, + }, nullptr, true}, {"reserved: texture", [](ID3D12Device* d) { return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE))); }}, @@ -4544,6 +4743,7 @@ int compare_placed_reserved(ID3D12Device* ours) { const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p); if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b); if (a == b) continue; + if (c.windows10_refuses && windows10_refusal(c.name, host.p, a, b)) continue; if (c.comparable && !c.comparable(host.p)) { std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name, a, b); @@ -5284,7 +5484,9 @@ int main() { EXPECT(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device1.p)))); const D3D12_RESIDENCY_PRIORITY priorities[] = {D3D12_RESIDENCY_PRIORITY_MAXIMUM, D3D12_RESIDENCY_PRIORITY(D3D12_RESIDENCY_PRIORITY_LOW + 5)}; - EXPECT(device1->SetResidencyPriority(2, pageables, priorities) == S_OK); + // Only committed resources and heaps take a priority, as on the host runtime (d3d12_residency_test): a + // fence and an allocator don't. + EXPECT(device1->SetResidencyPriority(2, pageables, priorities) == E_INVALIDARG); EXPECT(device1->SetResidencyPriority(0, nullptr, nullptr) == S_OK); EXPECT(device1->SetResidencyPriority(1, pageables, nullptr) == E_INVALIDARG); EXPECT(device1->SetResidencyPriority(1, nullptr, priorities) == E_INVALIDARG); @@ -5296,8 +5498,9 @@ int main() { EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET, 0, nullptr, residency.p, 9) == S_OK); EXPECT(residency->GetCompletedValue() == 9); - // Refused calls leave the fence alone. - EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, pageables, nullptr, 11) == E_INVALIDARG); + // A null fence is accepted (the host runtime's answer) and signals nothing; refused calls leave the fence + // alone. + EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, pageables, nullptr, 11) == S_OK); EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, 1, nullptr, residency.p, 11) == E_INVALIDARG); EXPECT(device3->EnqueueMakeResident(D3D12_RESIDENCY_FLAGS(0x2), 1, pageables, residency.p, 11) == @@ -6271,7 +6474,7 @@ int main() { UINT64 frequency = 0; EXPECT(SUCCEEDED(queue->GetTimestampFrequency(&frequency)) && frequency >= 1'000'000); EXPECT(queue->GetTimestampFrequency(nullptr) == E_INVALIDARG); - Ref occlusion, timestamps, statistics, refused; + Ref occlusion, timestamps, statistics, so, refused; D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4, 0}; EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&occlusion.p)))); // A null output is E_UNEXPECTED, as on the host runtime (compare_invalid_arguments, "query heap:"). @@ -6284,16 +6487,20 @@ int main() { EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(×tamps.p)))); query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0}; EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p); - query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 1, 0}; // no stream output path yet - EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_NOTIMPL && !refused.p); + // The layer has no stream output, so stream-output statistics heaps are made without a Vulkan pool and + // every query reads zero (D3D-302). + query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 3, 0}; + EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&so.p)))); query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0}; if (d.pipeline_statistics_query) EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&statistics.p)))); else std::printf("pipeline statistics: no pipelineStatisticsQuery, skipped\n"); - // Readback layout: timestamps at 0, occlusion at 64, statistics at 256, the second run's at 1024. - constexpr UINT64 ts_at = 0, occlusion_at = 64, statistics_at = 256, again_at = 1024; + // Readback layout: timestamps at 0, occlusion at 64, statistics at 256, stream output at 512, the second + // run's at 1024. + constexpr UINT64 ts_at = 0, occlusion_at = 64, statistics_at = 256, so_at = 512, again_at = 1024; + static_assert(sizeof(D3D12_QUERY_DATA_SO_STATISTICS) == 16); const auto u64 = [&](UINT64 offset) { UINT64 value; std::memcpy(&value, down + offset, sizeof(value)); @@ -6303,15 +6510,21 @@ int main() { EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0); if (statistics.p) list->BeginQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + // Two streams at once, inside the statistics query and crossing the occlusion one: none of them is a + // Vulkan query, so none overlaps. + list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0); + list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1); // A rectangle clear runs in a render pass inside a query; clears count no samples. device->CreateRenderTargetView(rt_resource.p, &rtv_desc, rtv1); // the resolve test reused it list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); barrier = transition(rt_resource.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); list->ResourceBarrier(1, &barrier); list->ClearRenderTargetView(rtv1, red, 1, &square); + list->EndQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0); list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1); list->CopyBufferRegion(readback.p, 8192, upload.p, 0, 32768); + list->EndQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1); list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1); if (statistics.p) list->EndQuery(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); list->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 1); @@ -6322,6 +6535,8 @@ int main() { if (statistics.p) list->ResolveQueryData(statistics.p, D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, 2, readback.p, statistics_at); + list->ResolveQueryData(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0, 0, 1, readback.p, so_at); + list->ResolveQueryData(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3, 1, 2, readback.p, so_at + 16); // 2: never EXPECT(list->Close() == S_OK); queue->ExecuteCommandLists(1, lists); EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); @@ -6334,6 +6549,8 @@ int main() { for (UINT i = 0; i < 4; ++i) EXPECT(u64(occlusion_at + 8 * i) == 0); for (UINT i = 0; statistics.p && i < 22; ++i) EXPECT(u64(statistics_at + 8 * i) == 0); EXPECT(u64(statistics.p ? statistics_at + 176 : statistics_at) == 0xcdcdcdcdcdcdcdcdull); // not past it + for (UINT i = 0; i < 6; ++i) EXPECT(u64(so_at + 8 * i) == 0); // written and needed, three queries + EXPECT(u64(so_at + 48) == 0xcdcdcdcdcdcdcdcdull); // not past them // A second execution reuses timestamp 0 (reset before it is written again) and resolves timestamp 1, // which keeps the result of the first execution. @@ -6393,6 +6610,12 @@ int main() { [&] { list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 3, 2, readback.p, 0); })); EXPECT(refuse(S_OK, R::invalid_query, // a type the heap does not hold [&] { list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_TIMESTAMP, 0); })); + EXPECT(refuse(S_OK, R::invalid_query, [&] { // a stream-output query in an occlusion heap + list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1, 0); + list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1, 0); + })); + EXPECT(refuse(E_INVALIDARG, R::invalid_query, // a stream-output query begun and never ended + [&] { list->BeginQuery(so.p, D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2, 0); })); EXPECT(refuse(S_OK, R::invalid_query, // into a texture [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 1, rt_resource.p, 0); })); EXPECT(refuse(S_OK, R::invalid_query, // past the end of the buffer @@ -6498,6 +6721,45 @@ int main() { } } + // D3D-71: a default-heap buffer outside the arena (this device has none) starts zeroed, as D3D12 committed + // resources do. Its memory is first dirtied through an earlier buffer, which is then released so the next + // allocation is likely to reuse it. CREATE_NOT_ZEROED skips the fill; a copy into the same list still lands. + { + constexpr UINT64 bytes = 4096; + const D3D12_HEAP_PROPERTIES default_buffer_heap{D3D12_HEAP_TYPE_DEFAULT}; + std::memset(up, 0xab, std::size_t(bytes)); + { + Ref dirty; + EXPECT(SUCCEEDED(create(default_buffer_heap, buffer_desc(bytes), D3D12_RESOURCE_STATE_COMMON, dirty))); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->CopyBufferRegion(dirty.p, 0, upload.p, 0, bytes); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(submit_and_wait()); + } + Ref fresh, not_zeroed; + EXPECT(SUCCEEDED(create(default_buffer_heap, buffer_desc(bytes), D3D12_RESOURCE_STATE_COMMON, fresh))); + const D3D12_RESOURCE_DESC zero_desc = buffer_desc(bytes); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_buffer_heap, D3D12_HEAP_FLAG_CREATE_NOT_ZEROED, + &zero_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(¬_zeroed.p)))); + std::memset(down, 0xcd, std::size_t(2 * bytes)); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->CopyBufferRegion(readback.p, 0, fresh.p, 0, bytes); + list->CopyBufferRegion(not_zeroed.p, 0, upload.p, 0, bytes); // written before it is read + auto readable = transition(not_zeroed.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &readable); + list->CopyBufferRegion(readback.p, bytes, not_zeroed.p, 0, bytes); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(submit_and_wait()); + const std::uint8_t zero[4] = {}, written[4] = {0xab, 0xab, 0xab, 0xab}; + for (UINT64 i = 0; i < bytes; i += 4) report("zero-filled buffer byte", UINT(i), down + i, zero, 4); + for (UINT64 i = 0; i < bytes; i += 4) + report("NOT_ZEROED buffer byte after a copy", UINT(i), down + bytes + i, written, 4); + } + // Every child holds the proxy; once they are gone the proxy holds the only reference. upload->Unmap(0, nullptr); readback->Unmap(0, nullptr); diff --git a/runtime/test/dxgi_device_test.cpp b/runtime/test/dxgi_device_test.cpp new file mode 100644 index 000000000..5b02cb762 --- /dev/null +++ b/runtime/test/dxgi_device_test.cpp @@ -0,0 +1,349 @@ +// IDXGIDevice1 on the Xbox-ABI device proxy (d3d12_xs_device.h): the step a GDKX title takes to find its output +// (docs/d3d12_vulkan.md section 4.5: QueryInterface the device for IDXGIDevice1, GetAdapter, EnumOutputs(0)). Walked +// on the host PC runtime (WARP, and the first hardware adapter when there is one) and on the Vulkan-backed device: +// - the PC device behind the proxy has no IDXGIDevice of its own (host runtime), so the proxy's answer is its own; +// - QueryInterface for IDXGIDevice, IDXGIDevice1 and IDXGIObject gives one pointer, which is not the device's but +// is the same COM object: one IUnknown, QueryInterface back to ID3D12Device gives the proxy, one reference count; +// - IDXGIDevice2 and later are refused; +// - GetAdapter and GetParent(IDXGIAdapter) give the adapter of the device behind the proxy: its LUID is the +// device's GetAdapterLuid. On the host runtime it is the host's adapter; on the Vulkan device it is the layer's +// own (rt::dxgi, which stops at IDXGIAdapter3 and whose parent is the layer's factory); +// - EnumOutputs(0) on that adapter answers S_OK with an output or DXGI_ERROR_NOT_FOUND, never anything else; +// - null arguments, the frame latency and the GPU thread priority, and private data shared with the device; +// - a device created as IDXGIDevice1 directly (a title may pass that IID to D3D12XboxCreateDevice): the pointer +// that comes back is the DXGI one, the proxy behind it is the device's identity (a fence's GetDevice gives it), +// and the adapter provider still reaches it, so the Vulkan device hands out the layer's adapter there too. +// Exits 77 when neither a host D3D12 device nor a Vulkan device can be made. No shaders, game data or Xbox DLLs. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" + +#include +#include + +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", label, __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +namespace xs = rt::d3d12_xs; + +template +struct Ref { + T* p = nullptr; + Ref() = default; + Ref(const Ref&) = delete; + Ref& operator=(const Ref&) = delete; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +// {8f3a1c52-6e0b-4d97-b1c4-2a7e9d5f0c36}: a private-data key of this test. +constexpr GUID kTestData{0x8f3a1c52, 0x6e0b, 0x4d97, {0xb1, 0xc4, 0x2a, 0x7e, 0x9d, 0x5f, 0x0c, 0x36}}; + +bool same_luid(const LUID& a, const LUID& b) { return a.LowPart == b.LowPart && a.HighPart == b.HighPart; } + +// `device` is the device proxy, `real` the device behind it. +int check_backend(const char* label, ID3D12Device* device, ID3D12Device* real, bool vulkan) { + const unsigned long device_refs = xs::device_proxy_ref_count(device); + + // The device behind the proxy: the PC runtime's has no IDXGIDevice, which is why the proxy answers it itself. + if (!vulkan) { + void* none = reinterpret_cast(1); + EXPECT(real->QueryInterface(__uuidof(IDXGIDevice1), &none) == E_NOINTERFACE && !none); + } + + Ref dxgi; + EXPECT(device->QueryInterface(__uuidof(IDXGIDevice1), reinterpret_cast(&dxgi.p)) == S_OK && dxgi.p); + EXPECT(static_cast(dxgi.p) != static_cast(device)); + EXPECT(xs::device_proxy_from_dxgi_device(dxgi.p) == device && !xs::device_proxy_from_dxgi_device(device)); + EXPECT(xs::device_proxy_ref_count(device) == device_refs + 1); + { + // One COM object: every DXGI interface is the same pointer, IUnknown is the device's, and QueryInterface + // leads back to the device proxy from each of them. + Ref dxgi0; + Ref object; + Ref unknown_a, unknown_b; + Ref back; + EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast(&dxgi0.p)) == S_OK); + EXPECT(device->QueryInterface(__uuidof(IDXGIObject), reinterpret_cast(&object.p)) == S_OK); + EXPECT(static_cast(dxgi0.p) == static_cast(dxgi.p) && + static_cast(object.p) == static_cast(dxgi.p)); + EXPECT(dxgi->QueryInterface(__uuidof(IUnknown), reinterpret_cast(&unknown_a.p)) == S_OK); + EXPECT(device->QueryInterface(__uuidof(IUnknown), reinterpret_cast(&unknown_b.p)) == S_OK); + EXPECT(unknown_a.p == unknown_b.p && static_cast(unknown_a.p) == static_cast(device)); + EXPECT(dxgi->QueryInterface(__uuidof(ID3D12Device), reinterpret_cast(&back.p)) == S_OK); + EXPECT(back.p == device); + EXPECT(xs::device_proxy_ref_count(device) == device_refs + 6); + // Later DXGI device interfaces, and a null output or IID. + void* none = reinterpret_cast(1); + EXPECT(device->QueryInterface(__uuidof(IDXGIDevice2), &none) == E_NOINTERFACE && !none); + none = reinterpret_cast(1); + EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice2), &none) == E_NOINTERFACE && !none); + EXPECT(dxgi->QueryInterface(__uuidof(IDXGIDevice1), nullptr) == E_POINTER); + } + EXPECT(xs::device_proxy_ref_count(device) == device_refs + 1); + // AddRef and Release on the DXGI pointer count on the device. + EXPECT(dxgi->AddRef() == device_refs + 2 && dxgi->Release() == device_refs + 1); + + // GetAdapter: the adapter of the device behind the proxy. + const LUID device_luid = device->GetAdapterLuid(); + EXPECT(same_luid(device_luid, real->GetAdapterLuid())); + Ref adapter; + EXPECT(dxgi->GetAdapter(&adapter.p) == S_OK && adapter.p); + DXGI_ADAPTER_DESC desc{}; + EXPECT(adapter->GetDesc(&desc) == S_OK && same_luid(desc.AdapterLuid, device_luid)); + char name[128] = {}; + WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, name, sizeof(name) - 1, nullptr, nullptr); + EXPECT(dxgi->GetAdapter(nullptr) == E_POINTER); + { + // GetParent is the same adapter by another road, as any interface it has; the device is not its own parent. + Ref parent; + EXPECT(dxgi->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast(&parent.p)) == S_OK && parent.p); + DXGI_ADAPTER_DESC parent_desc{}; + EXPECT(parent->GetDesc(&parent_desc) == S_OK && same_luid(parent_desc.AdapterLuid, device_luid)); + void* none = reinterpret_cast(1); + EXPECT(FAILED(dxgi->GetParent(__uuidof(ID3D12Device), &none)) && !none); + EXPECT(dxgi->GetParent(__uuidof(IDXGIAdapter), nullptr) == E_POINTER); + } + { + // Whose adapter it is. The layer's own stops at IDXGIAdapter3 and its parent is the layer's factory, which + // enumerates exactly that one adapter; the host's is the host DXGI's (IDXGIAdapter4 since Windows 10 1803). + Ref adapter4; + const HRESULT hr4 = adapter->QueryInterface(__uuidof(IDXGIAdapter4), reinterpret_cast(&adapter4.p)); + Ref factory; + EXPECT(adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast(&factory.p)) == S_OK); + Ref second; + const HRESULT second_hr = factory->EnumAdapters(1, &second.p); + if (vulkan) { + EXPECT(hr4 == E_NOINTERFACE && !adapter4.p); + EXPECT(second_hr == DXGI_ERROR_NOT_FOUND && !second.p); + } + } + // The next step of the sequence. Which answer comes back is the adapter's business (a software adapter has no + // output; the layer's adapter has none before D3D-313): it is one of the two, and an output only with S_OK. + Ref output; + const HRESULT output_hr = adapter->EnumOutputs(0, &output.p); + EXPECT((output_hr == S_OK && output.p) || (output_hr == DXGI_ERROR_NOT_FOUND && !output.p)); + + // IDXGIDevice1's own state: kept and read back. + UINT latency = 0; + EXPECT(dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 3); + EXPECT(dxgi->SetMaximumFrameLatency(1) == S_OK && dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 1); + EXPECT(dxgi->SetMaximumFrameLatency(17) == DXGI_ERROR_INVALID_CALL); + EXPECT(dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 1); + EXPECT(dxgi->SetMaximumFrameLatency(0) == S_OK && dxgi->GetMaximumFrameLatency(&latency) == S_OK && latency == 3); + EXPECT(dxgi->GetMaximumFrameLatency(nullptr) == E_POINTER); + INT priority = 99; + EXPECT(dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 0); + EXPECT(dxgi->SetGPUThreadPriority(7) == S_OK && dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 7); + EXPECT(dxgi->SetGPUThreadPriority(8) == E_INVALIDARG && dxgi->SetGPUThreadPriority(-8) == E_INVALIDARG); + EXPECT(dxgi->GetGPUThreadPriority(&priority) == S_OK && priority == 7); + EXPECT(dxgi->GetGPUThreadPriority(nullptr) == E_POINTER); + IDXGISurface* surface = reinterpret_cast(std::uintptr_t{1}); + EXPECT(dxgi->CreateSurface(nullptr, 0, 0, nullptr, &surface) == E_NOTIMPL && !surface); + EXPECT(dxgi->QueryResourceResidency(nullptr, nullptr, 0) == E_NOTIMPL); + + // Private data set through the DXGI interface is the device's, and the other way round. + const std::uint32_t written = 0x12345678; + std::uint32_t read = 0; + UINT size = sizeof(read); + EXPECT(dxgi->SetPrivateData(kTestData, sizeof(written), &written) == S_OK); + EXPECT(device->GetPrivateData(kTestData, &size, &read) == S_OK && size == sizeof(read) && read == written); + EXPECT(device->SetPrivateData(kTestData, 0, nullptr) == S_OK); + size = sizeof(read); + EXPECT(FAILED(dxgi->GetPrivateData(kTestData, &size, &read))); + + // The adapter does not keep the device alive, and the device outlives its DXGI pointer's last use. + adapter.reset(); + output.reset(); + dxgi.reset(); + EXPECT(xs::device_proxy_ref_count(device) == device_refs); + std::printf("%s: IDXGIDevice1 on the device proxy is one COM object with it; GetAdapter and GetParent give \"%s\" " + "(%s adapter, the device's LUID); EnumOutputs(0) %s\n", + label, name, vulkan ? "the layer's own" : "the host's", + output_hr == S_OK ? "gives an output" : "is DXGI_ERROR_NOT_FOUND"); + return 0; +} + +// The device created as IDXGIDevice1, the way D3D12XboxCreateDevice creates it when a title passes that IID: the +// proxy over `real` (which takes one reference to it), then set_device_outer with what came back for the Vulkan +// device. `real` is released by the proxy's last reference. +int check_direct(const char* label, ID3D12Device* real, bool vulkan) { + IDXGIDevice1* dxgi = nullptr; + EXPECT(xs::create_device_proxy(real, __uuidof(IDXGIDevice1), reinterpret_cast(&dxgi)) == S_OK && dxgi); + EXPECT(!xs::is_device_proxy(dxgi)); // the DXGI pointer, not the proxy + void* const proxy = xs::device_proxy_from_dxgi_device(dxgi); + EXPECT(proxy && xs::is_device_proxy(proxy) && xs::device_proxy_primary(dxgi) == proxy && + xs::device_proxy_primary(proxy) == proxy); + EXPECT(xs::device_proxy_ref_count(proxy) == 1); // the caller's one reference, held through the DXGI pointer + if (vulkan) rt::d3d12::set_device_outer(real, dxgi); + { + // QueryInterface back to the device gives the proxy, and the device's children name the proxy as their + // device: the outer identity is the proxy, not the DXGI pointer that creation returned. + Ref device; + EXPECT(dxgi->QueryInterface(__uuidof(ID3D12Device), reinterpret_cast(&device.p)) == S_OK); + EXPECT(static_cast(device.p) == proxy && xs::device_proxy_ref_count(proxy) == 2); + Ref fence; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + Ref owner; + EXPECT(SUCCEEDED(fence->GetDevice(IID_PPV_ARGS(&owner.p))) && static_cast(owner.p) == proxy); + // The adapter: the device's LUID, and on the Vulkan device the layer's own, as on the query path. + Ref adapter; + EXPECT(dxgi->GetAdapter(&adapter.p) == S_OK && adapter.p); + DXGI_ADAPTER_DESC desc{}; + EXPECT(adapter->GetDesc(&desc) == S_OK && same_luid(desc.AdapterLuid, real->GetAdapterLuid())); + Ref adapter4; + const HRESULT hr4 = adapter->QueryInterface(__uuidof(IDXGIAdapter4), reinterpret_cast(&adapter4.p)); + Ref factory; + EXPECT(adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast(&factory.p)) == S_OK); + Ref second; + const HRESULT second_hr = factory->EnumAdapters(1, &second.p); + if (vulkan) { + EXPECT(hr4 == E_NOINTERFACE && !adapter4.p); + EXPECT(second_hr == DXGI_ERROR_NOT_FOUND && !second.p); + } + } + EXPECT(xs::device_proxy_ref_count(proxy) == 1); + { + // A provider set through the DXGI pointer is the one GetAdapter asks, and one handed something that is not + // a proxy is refused (it says so on stderr) instead of leaving the default in place unnoticed. + const xs::DxgiAdapterProvider refuse = [](ID3D12Device*, REFIID, void** out) { + *out = reinterpret_cast(std::uintptr_t{1}); // a failing provider's output is not handed on + return E_ABORT; + }; + EXPECT(xs::set_device_adapter_provider(dxgi, refuse)); + IDXGIAdapter* none = reinterpret_cast(std::uintptr_t{1}); + EXPECT(dxgi->GetAdapter(&none) == E_ABORT && !none); + EXPECT(xs::set_device_adapter_provider(proxy, nullptr)); // back to the default (the host's adapter) + Ref host; + EXPECT(dxgi->GetAdapter(&host.p) == S_OK && host.p); + void* not_a_proxy = nullptr; // pointer-sized: the helpers read a vtable pointer from what they are given + EXPECT(!xs::set_device_adapter_provider(¬_a_proxy, refuse) && !xs::set_device_adapter_provider(real, refuse)); + EXPECT(!xs::device_proxy_primary(¬_a_proxy) && !xs::device_proxy_primary(nullptr)); + } + EXPECT(dxgi->Release() == 0); // the last reference: the proxy goes, and with it its reference to `real` + std::printf("%s: created as IDXGIDevice1: the proxy is the device's identity and the adapter is %s\n", label, + vulkan ? "the layer's own" : "the host's"); + return 0; +} + +int run_host(IDXGIAdapter1* adapter, const char* label) { + ID3D12Device* real = nullptr; + if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&real)))) { + std::printf("%s: no D3D12 device, skipped\n", label); + return 77; + } + real->AddRef(); // for the second proxy below: each proxy takes one reference + if (check_direct(label, real, false)) { + real->Release(); + return 1; + } + real->AddRef(); // the backend's own reference; the proxy takes the other + Ref device; + if (FAILED(xs::create_device_proxy(real, __uuidof(ID3D12Device), reinterpret_cast(&device.p)))) { + real->Release(); + real->Release(); + std::fprintf(stderr, "%s: device proxy creation failed\n", label); + return 1; + } + const int result = check_backend(label, device.p, real, false); + device.reset(); + if (result) return 1; + if (real->Release() != 0) { + std::fprintf(stderr, "%s: the PC device outlives its proxy\n", label); + return 1; + } + return 0; +} + +} // namespace + +// A failure ends the process with a message on stderr, never in a dialog a test run would wait on. +static void no_dialogs() { + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); +} + +int main() { + no_dialogs(); + std::setvbuf(stdout, nullptr, _IONBF, 0); + const char* label = "dxgi_device_test"; + int ran = 0; + + // Host PC runtime: WARP, then the first hardware adapter. Under Wine the host d3d12.dll is Wine's own, not the + // PC runtime the proxy is written against, so only Vulkan runs there. + const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr; + Ref factory; + if (wine) std::printf("host D3D12: under Wine, skipped\n"); + if (!wine && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { + Ref warp; + if (SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p)))) { + const int r = run_host(warp.p, "host WARP"); + if (r == 1) return 1; + ran += r == 0; + } + for (UINT i = 0;; ++i) { + Ref adapter; + if (factory->EnumAdapters1(i, &adapter.p) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue; + const int r = run_host(adapter.p, "host hardware adapter"); + if (r == 1) return 1; + ran += r == 0; + break; + } + } + + // The Vulkan-backed device, the way D3D12XboxCreateDevice hands it out with LEONIDA_D3D12=vulkan. + vktest::Device d; + if (d.create()) { + label = "Vulkan"; + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + inner->AddRef(); // the backend's own reference; the proxy takes the other + ID3D12Device* device = nullptr; + EXPECT(SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device)))); + rt::d3d12::set_device_outer(inner, device); + const int result = check_backend(label, device, inner, true); + device->Release(); + if (result) return 1; + EXPECT(inner->Release() == 0); // nothing the adapter or the factory made kept the layer's device alive + // A second device on the same Vulkan device, created as IDXGIDevice1. + ID3D12Device* direct = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&direct)))); + direct->AddRef(); // the backend's own reference; the proxy takes the other + if (check_direct(label, direct, true)) return 1; + EXPECT(direct->Release() == 0); + ++ran; + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + } else { + std::printf("Vulkan: no device, skipped\n"); + } + + if (!ran) { + std::printf("SKIP dxgi_device_test: neither a host D3D12 device nor a Vulkan device\n"); + return 77; + } + std::printf("dxgi_device_test: %d backend(s) passed\n", ran); + return 0; +} diff --git a/runtime/test/dxgi_swapchain_count_test.cpp b/runtime/test/dxgi_swapchain_count_test.cpp new file mode 100644 index 000000000..13da2028e --- /dev/null +++ b/runtime/test/dxgi_swapchain_count_test.cpp @@ -0,0 +1,354 @@ +// Synthetic regression test for the DXGI swapchain buffer-count contract (D3D-389), with no GPU and no +// window: VulkanSwapchain (runtime/shims/dxgi_swapchain.h) runs on a fake Vulkan function table, so +// vkGetSwapchainImagesKHR can report more images than the app's requested BufferCount. +// +// DXGI rule: GetDesc/GetDesc1 report the BufferCount the app created with, and GetCurrentBackBufferIndex is +// always below it, one stable resource per index. The shim must not expose images the driver added above +// minImageCount, and must hide a caps.minImageCount above the request. When the native count differs, the +// exposed buffers form an offscreen ring; each present blits the current slot into the acquired native image. +#include "../shims/dxgi_swapchain.h" + +#include +#include +#include +#include +#include + +namespace { + +constexpr std::uintptr_t kSurface = 0x5100; +constexpr std::uintptr_t kSwapchain = 0x5101; +constexpr std::uintptr_t kFence = 0x5102; +constexpr std::uintptr_t kPool = 0x5103; +constexpr std::uintptr_t kCmd = 0x5104; +constexpr std::uintptr_t kNativeBase = 0x6000; +constexpr std::uintptr_t kOffscreenBase = 0x7000; + +struct Fake { + std::uint32_t min_image_count = 2; + std::uint32_t max_image_count = 0; + std::uint32_t returned_images = 2; + std::uint32_t create_min_image_count = 0; + std::uint32_t acquire_cursor = 0; + std::uint32_t last_acquired = 0; + std::uint32_t presented_image = UINT32_MAX; + VkImage blit_src = VK_NULL_HANDLE; + VkImage blit_dst = VK_NULL_HANDLE; + unsigned presents = 0; + unsigned created_offscreen = 0; +}; +Fake g; + +VkImage native_image(std::uint32_t i) { + return reinterpret_cast(static_cast(kNativeBase + i)); +} + +template +PFN_vkVoidFunction as_function(T fn) { + return reinterpret_cast(fn); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_win32_surface(VkInstance, const VkWin32SurfaceCreateInfoKHR*, + const VkAllocationCallbacks*, VkSurfaceKHR* out) { + if (out) *out = reinterpret_cast(kSurface); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_surface(VkInstance, VkSurfaceKHR, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL surface_support(VkPhysicalDevice, std::uint32_t, VkSurfaceKHR, VkBool32* out) { + if (out) *out = VK_TRUE; + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL surface_caps(VkPhysicalDevice, VkSurfaceKHR, VkSurfaceCapabilitiesKHR* caps) { + if (!caps) return VK_ERROR_INITIALIZATION_FAILED; + std::memset(caps, 0, sizeof(*caps)); + caps->minImageCount = g.min_image_count; + caps->maxImageCount = g.max_image_count; + caps->currentExtent = {64, 64}; + caps->minImageExtent = {1, 1}; + caps->maxImageExtent = {4096, 4096}; + caps->supportedUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + caps->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL surface_formats(VkPhysicalDevice, VkSurfaceKHR, std::uint32_t* count, + VkSurfaceFormatKHR* formats) { + if (!count) return VK_ERROR_INITIALIZATION_FAILED; + if (formats && *count) { + formats[0].format = VK_FORMAT_B8G8R8A8_UNORM; + formats[0].colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; + } + *count = 1; + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL surface_present_modes(VkPhysicalDevice, VkSurfaceKHR, std::uint32_t* count, + VkPresentModeKHR* modes) { + if (!count) return VK_ERROR_INITIALIZATION_FAILED; + if (modes && *count) modes[0] = VK_PRESENT_MODE_FIFO_KHR; + *count = 1; + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties* props) { + std::memset(props, 0, sizeof(*props)); + props->memoryTypeCount = 1; + props->memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + props->memoryHeapCount = 1; + props->memoryHeaps[0].size = 1ull << 30; + props->memoryHeaps[0].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT; +} +VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice, const VkSwapchainCreateInfoKHR* info, + const VkAllocationCallbacks*, VkSwapchainKHR* out) { + if (!info || !out) return VK_ERROR_INITIALIZATION_FAILED; + g.create_min_image_count = info->minImageCount; + *out = reinterpret_cast(kSwapchain); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_swapchain(VkDevice, VkSwapchainKHR, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL get_images(VkDevice, VkSwapchainKHR, std::uint32_t* count, VkImage* images) { + if (!count) return VK_ERROR_INITIALIZATION_FAILED; + if (images) { + for (std::uint32_t i = 0; i < g.returned_images && i < *count; ++i) images[i] = native_image(i); + } + *count = g.returned_images; + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL acquire_next_image(VkDevice, VkSwapchainKHR, std::uint64_t, VkSemaphore, VkFence, + std::uint32_t* out) { + if (!out || g.returned_images == 0) return VK_ERROR_INITIALIZATION_FAILED; + g.last_acquired = g.acquire_cursor % g.returned_images; + ++g.acquire_cursor; + *out = g.last_acquired; + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue, const VkPresentInfoKHR* info) { + if (!info || info->swapchainCount != 1 || !info->pImageIndices) return VK_ERROR_INITIALIZATION_FAILED; + g.presented_image = info->pImageIndices[0]; + ++g.presents; + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL create_fence(VkDevice, const VkFenceCreateInfo*, const VkAllocationCallbacks*, + VkFence* out) { + if (out) *out = reinterpret_cast(kFence); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_fence(VkDevice, VkFence, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL wait_for_fences(VkDevice, std::uint32_t, const VkFence*, VkBool32, std::uint64_t) { + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL reset_fences(VkDevice, std::uint32_t, const VkFence*) { return VK_SUCCESS; } +VKAPI_ATTR VkResult VKAPI_CALL device_wait_idle(VkDevice) { return VK_SUCCESS; } +VKAPI_ATTR VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo*, const VkAllocationCallbacks*, + VkImage* out) { + if (!out) return VK_ERROR_INITIALIZATION_FAILED; + *out = reinterpret_cast(static_cast(kOffscreenBase + g.created_offscreen++)); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_image(VkDevice, VkImage, const VkAllocationCallbacks*) {} +VKAPI_ATTR void VKAPI_CALL image_mem_req(VkDevice, VkImage, VkMemoryRequirements* req) { + std::memset(req, 0, sizeof(*req)); + req->size = 4096; + req->alignment = 1; + req->memoryTypeBits = 1; +} +VKAPI_ATTR VkResult VKAPI_CALL alloc_mem(VkDevice, const VkMemoryAllocateInfo*, const VkAllocationCallbacks*, + VkDeviceMemory* out) { + if (out) *out = reinterpret_cast(kOffscreenBase); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL free_mem(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL bind_image_mem(VkDevice, VkImage, VkDeviceMemory, VkDeviceSize) { + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL create_cmd_pool(VkDevice, const VkCommandPoolCreateInfo*, + const VkAllocationCallbacks*, VkCommandPool* out) { + if (out) *out = reinterpret_cast(kPool); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_cmd_pool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL alloc_cmd_bufs(VkDevice, const VkCommandBufferAllocateInfo*, + VkCommandBuffer* out) { + if (out) *out = reinterpret_cast(kCmd); + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL reset_cmd_buf(VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; } +VKAPI_ATTR VkResult VKAPI_CALL begin_cmd_buf(VkCommandBuffer, const VkCommandBufferBeginInfo*) { + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL end_cmd_buf(VkCommandBuffer) { return VK_SUCCESS; } +VKAPI_ATTR void VKAPI_CALL cmd_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, std::uint32_t, + const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) {} +VKAPI_ATTR void VKAPI_CALL cmd_blit(VkCommandBuffer, VkImage src, VkImageLayout, VkImage dst, VkImageLayout, + std::uint32_t, const VkImageBlit*, VkFilter) { + g.blit_src = src; + g.blit_dst = dst; +} +VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) { + return VK_SUCCESS; +} + +struct Entry { + const char* name; + PFN_vkVoidFunction fn; +}; +const Entry kEntries[] = { + {"vkCreateWin32SurfaceKHR", as_function(create_win32_surface)}, + {"vkDestroySurfaceKHR", as_function(destroy_surface)}, + {"vkGetPhysicalDeviceSurfaceSupportKHR", as_function(surface_support)}, + {"vkGetPhysicalDeviceSurfaceCapabilitiesKHR", as_function(surface_caps)}, + {"vkGetPhysicalDeviceSurfaceFormatsKHR", as_function(surface_formats)}, + {"vkGetPhysicalDeviceSurfacePresentModesKHR", as_function(surface_present_modes)}, + {"vkGetPhysicalDeviceMemoryProperties", as_function(memory_properties)}, + {"vkCreateSwapchainKHR", as_function(create_swapchain)}, + {"vkDestroySwapchainKHR", as_function(destroy_swapchain)}, + {"vkGetSwapchainImagesKHR", as_function(get_images)}, + {"vkAcquireNextImageKHR", as_function(acquire_next_image)}, + {"vkQueuePresentKHR", as_function(queue_present)}, + {"vkCreateFence", as_function(create_fence)}, + {"vkDestroyFence", as_function(destroy_fence)}, + {"vkWaitForFences", as_function(wait_for_fences)}, + {"vkResetFences", as_function(reset_fences)}, + {"vkDeviceWaitIdle", as_function(device_wait_idle)}, + {"vkCreateImage", as_function(create_image)}, + {"vkDestroyImage", as_function(destroy_image)}, + {"vkGetImageMemoryRequirements", as_function(image_mem_req)}, + {"vkAllocateMemory", as_function(alloc_mem)}, + {"vkFreeMemory", as_function(free_mem)}, + {"vkBindImageMemory", as_function(bind_image_mem)}, + {"vkCreateCommandPool", as_function(create_cmd_pool)}, + {"vkDestroyCommandPool", as_function(destroy_cmd_pool)}, + {"vkAllocateCommandBuffers", as_function(alloc_cmd_bufs)}, + {"vkResetCommandBuffer", as_function(reset_cmd_buf)}, + {"vkBeginCommandBuffer", as_function(begin_cmd_buf)}, + {"vkEndCommandBuffer", as_function(end_cmd_buf)}, + {"vkCmdPipelineBarrier", as_function(cmd_barrier)}, + {"vkCmdBlitImage", as_function(cmd_blit)}, + {"vkQueueSubmit", as_function(queue_submit)}, +}; + +PFN_vkVoidFunction lookup(const char* name) { + for (const Entry& entry : kEntries) + if (name && std::strcmp(name, entry.name) == 0) return entry.fn; + return nullptr; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance_proc(VkInstance, const char* name) { return lookup(name); } +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device_proc(VkDevice, const char* name) { return lookup(name); } + +int fail(const char* what) { + std::fprintf(stderr, "FAIL: %s\n", what); + return 1; +} + +// Requests `requested` buffers while faking `native` images and a surface minimum of `minimum`. +int run_case(const char* label, std::uint32_t requested, std::uint32_t native, std::uint32_t minimum, + bool expect_offscreen) { + g = Fake{}; + g.min_image_count = minimum; + g.returned_images = native; + std::mutex mutex; + leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast(1), + reinterpret_cast(2), get_device_proc, + reinterpret_cast(3), reinterpret_cast(4), 0, mutex); + if (!swapchain.create(reinterpret_cast(static_cast(1)), 64, 64, + VK_FORMAT_B8G8R8A8_UNORM, requested)) + return fail("VulkanSwapchain::create"); + + // GetDesc/GetDesc1 read image_count(): the app's request, never the native count. + if (swapchain.image_count() != requested) { + std::fprintf(stderr, "FAIL: %s: exposed BufferCount %u, requested %u (native %u)\n", label, + swapchain.image_count(), requested, native); + return 1; + } + const std::uint32_t expected_min = minimum > requested ? minimum : requested; + if (g.create_min_image_count != expected_min) { + std::fprintf(stderr, "FAIL: %s: vkCreateSwapchainKHR minImageCount %u, expected %u\n", label, + g.create_min_image_count, expected_min); + return 1; + } + if (swapchain.is_offscreen() != expect_offscreen) + return fail(expect_offscreen ? "expected the offscreen ring" : "expected direct native images"); + + if (expect_offscreen) { + if (g.created_offscreen != requested) return fail("offscreen ring size != requested BufferCount"); + std::vector exposed; + for (std::uint32_t i = 0; i < requested; ++i) { + const leonida::ResourceBinding binding = swapchain.resource_binding(i); + if (!binding.image || binding.presentable) return fail("offscreen backbuffer binding is not offscreen"); + if (binding.image != swapchain.image(i)) return fail("binding/image disagree"); + for (VkImage other : exposed) + if (other == binding.image) return fail("two exposed backbuffers share one image"); + exposed.push_back(binding.image); + } + if (swapchain.current_back_buffer_index() >= requested) + return fail("initial current index out of range"); + + std::uint32_t index = 0; + if (!swapchain.acquire_next_image(index)) return fail("first acquire"); + constexpr unsigned kFrames = 20; + for (unsigned frame = 0; frame < kFrames; ++frame) { + const std::uint32_t current = swapchain.current_back_buffer_index(); + if (current >= requested) return fail("GetCurrentBackBufferIndex >= BufferCount"); + if (current != frame % requested) return fail("current index does not cycle over the exposed ring"); + const std::uint32_t acquired = g.last_acquired; + g.blit_src = g.blit_dst = VK_NULL_HANDLE; + g.presented_image = UINT32_MAX; + if (!swapchain.present(current)) return fail("present"); + if (g.blit_src != exposed[current]) return fail("present did not blit the current backbuffer"); + if (g.blit_dst != native_image(acquired)) return fail("present blitted to the wrong acquired image"); + if (g.presented_image != acquired) return fail("presented an image other than the acquired one"); + if (frame + 1 < kFrames && !swapchain.acquire_next_image(index)) return fail("acquire"); + } + // ResizeBuffers(count=0) keeps the exposed BufferCount, not the native image count. + if (!swapchain.resize(64, 64)) return fail("resize"); + if (swapchain.image_count() != requested) return fail("resize(count=0) changed the exposed BufferCount"); + if (!swapchain.is_offscreen()) return fail("resize dropped the offscreen ring"); + return 0; + } + + // Direct path: exposed index and native image index are the same, and nothing is blitted. + if (swapchain.current_back_buffer_index() != 0) return fail("direct initial index"); + std::uint32_t index = 0; + if (!swapchain.acquire_next_image(index)) return fail("direct first acquire"); + for (unsigned frame = 0; frame < 9; ++frame) { + const std::uint32_t current = swapchain.current_back_buffer_index(); + if (current >= requested) return fail("direct GetCurrentBackBufferIndex >= BufferCount"); + if (current != g.last_acquired) return fail("direct current index is not the acquired image"); + if (swapchain.resource_binding(current).image != native_image(current)) + return fail("direct binding is not the native image"); + g.blit_src = g.blit_dst = VK_NULL_HANDLE; + g.presented_image = UINT32_MAX; + if (!swapchain.present(current)) return fail("direct present"); + if (g.blit_src || g.blit_dst) return fail("direct present took the blit path"); + if (g.presented_image != current) return fail("direct present index"); + if (frame + 1 < 9 && !swapchain.acquire_next_image(index)) return fail("direct acquire"); + } + return 0; +} + +struct Case { + const char* label; + std::uint32_t requested; + std::uint32_t native; + std::uint32_t minimum; + bool offscreen; +}; + +} // namespace + +int main() { + const Case cases[] = { + // Vulkan returns more images than minImageCount: the app asked for 2 and must see 2. + {"driver returns 4 for BufferCount 2", 2, 4, 2, true}, + // The surface minimum exceeds the request (2): still expose the app's 2. + {"minImageCount 3 for BufferCount 2", 2, 3, 3, true}, + // Control: the app asks for more than minImageCount; native and exposed counts agree, no blit. + {"BufferCount 3 above minImageCount 2", 3, 3, 2, false}, + }; + for (const Case& c : cases) { + if (const int result = run_case(c.label, c.requested, c.native, c.minimum, c.offscreen)) return result; + } + std::printf("dxgi_swapchain_count_test: PASS (3 cases: extra native images, min above request, " + "request above min)\n"); + return 0; +} diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp index ca1491153..1ef864ff1 100644 --- a/runtime/test/dxgi_swapchain_test.cpp +++ b/runtime/test/dxgi_swapchain_test.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include namespace { @@ -91,8 +92,220 @@ bool check_statistics_disjoint(IDXGISwapChain* swapchain) { return swapchain->GetFrameStatistics(&stats) == S_OK; } +// Counts references: AddRef/Release of the private-data interface are observable through refs. +struct CountedUnknown final : IUnknown { + ULONG refs = 1; + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void** out) override { + if (out) *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; } + ULONG STDMETHODCALLTYPE Release() override { return --refs; } +}; + +// IDXGIObject private data (Microsoft: IDXGIObject::SetPrivateData / SetPrivateDataInterface / GetPrivateData): +// the bytes are copied, an interface is held with a reference until it is replaced or removed, and the same GUID +// replaces the entry. Returns null on success or the failing step. +const char* check_private_data(IDXGIObject* object) { + static constexpr GUID key{0x6c2c5b0e, 0x4d9a, 0x4f43, {0x9e, 0x1b, 0x3a, 0x57, 0x0c, 0x91, 0x2d, 0x44}}; + UINT size = 99; + if (object->GetPrivateData(key, &size, nullptr) != DXGI_ERROR_NOT_FOUND) return "GetPrivateData before any Set"; + std::uint32_t value = 0x12345678u; + if (object->SetPrivateData(key, sizeof(value), &value) != S_OK) return "SetPrivateData"; + value = 0; // SetPrivateData copies + size = 0; + if (object->GetPrivateData(key, &size, nullptr) != S_OK || size != sizeof(value)) return "GetPrivateData size query"; + std::uint32_t read = 0; + size = sizeof(read); + if (object->GetPrivateData(key, &size, &read) != S_OK || size != sizeof(read) || read != 0x12345678u) + return "GetPrivateData did not return the stored bytes"; + std::uint16_t too_small = 0; + size = sizeof(too_small); + if (object->GetPrivateData(key, &size, &too_small) != DXGI_ERROR_MORE_DATA || size != sizeof(read)) + return "GetPrivateData with a small buffer should be DXGI_ERROR_MORE_DATA and report the size"; + CountedUnknown counted; + if (object->SetPrivateDataInterface(key, &counted) != S_OK || counted.refs != 2) return "SetPrivateDataInterface"; + IUnknown* got = nullptr; + size = sizeof(got); + if (object->GetPrivateData(key, &size, &got) != S_OK || got != &counted || counted.refs != 3) + return "GetPrivateData did not return the interface with a reference added"; + got->Release(); + if (object->SetPrivateData(key, sizeof(read), &read) != S_OK || counted.refs != 1) + return "SetPrivateData with the same GUID should release the held interface"; + if (object->SetPrivateDataInterface(key, &counted) != S_OK || counted.refs != 2) return "SetPrivateDataInterface again"; + if (object->SetPrivateDataInterface(key, nullptr) != S_OK || counted.refs != 1) + return "SetPrivateDataInterface(null) should remove the entry and release the interface"; + size = 99; + if (object->GetPrivateData(key, &size, nullptr) != DXGI_ERROR_NOT_FOUND) return "GetPrivateData after removal"; + return nullptr; +} + } // namespace + +// CreateSwapChainForHwnd on a guarded call: a host runtime that faults on a case reports it instead of ending the test. +HRESULT create_guarded(IDXGIFactory4* factory, IUnknown* queue, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, + IDXGISwapChain1** out) { + __try { + return factory->CreateSwapChainForHwnd(queue, hwnd, desc, nullptr, nullptr, out); + } __except (EXCEPTION_EXECUTE_HANDLER) { + return HRESULT(0xC0000005); + } +} + +// CreateSwapChainForHwnd with descriptions D3D12 refuses (and the valid ones next to them), against the host runtime's +// DXGI: each case gets its own window on each side, and the HRESULTs must match. Returns the number of mismatches, +// or -1 without a host D3D12 device. +int compare_swap_chain_arguments(IDXGIFactory4* ours, ID3D12Device* our_device, ID3D12CommandQueue* our_queue) { + using CreateDevice = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**); + using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**); + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto create_device = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))) + : nullptr; + const auto create_factory = dxgi ? reinterpret_cast( + reinterpret_cast(GetProcAddress(dxgi, "CreateDXGIFactory2"))) + : nullptr; + ID3D12Device* host_device = nullptr; + IDXGIFactory4* host_factory = nullptr; + ID3D12CommandQueue* host_queue = nullptr; + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + if (!create_device || !create_factory || + FAILED(create_device(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host_device))) || + FAILED(create_factory(0, IID_PPV_ARGS(&host_factory))) || + FAILED(host_device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&host_queue)))) { + if (host_factory) host_factory->Release(); + if (host_device) host_device->Release(); + return -1; + } + DXGI_SWAP_CHAIN_DESC1 base{}; + base.Width = 64; + base.Height = 64; + base.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + base.SampleDesc.Count = 1; + base.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + base.BufferCount = 2; + base.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; + enum class Pass { queue, null_queue, device, null_window, null_desc, null_out }; + struct Case { + const char* name; + DXGI_SWAP_CHAIN_DESC1 desc; + Pass pass = Pass::queue; + }; + const auto with = [&](void (*edit)(DXGI_SWAP_CHAIN_DESC1&)) { + DXGI_SWAP_CHAIN_DESC1 d = base; + edit(d); + return d; + }; + const Case cases[] = { + {"valid", base}, + {"flip sequential, 3 buffers", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; + d.BufferCount = 3; + })}, + {"effect DISCARD", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; })}, + {"effect SEQUENTIAL", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL; })}, + {"effect 99", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SwapEffect = DXGI_SWAP_EFFECT(99); })}, + {"scaling NONE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING_NONE; })}, + {"scaling ASPECT_RATIO_STRETCH", + with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING_ASPECT_RATIO_STRETCH; })}, + {"scaling 7", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Scaling = DXGI_SCALING(7); })}, + {"alpha IGNORE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_IGNORE; })}, + {"alpha PREMULTIPLIED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED; })}, + {"alpha STRAIGHT", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE_STRAIGHT; })}, + {"alpha 9", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.AlphaMode = DXGI_ALPHA_MODE(9); })}, + {"flag NONPREROTATED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_NONPREROTATED; })}, + {"flag ALLOW_MODE_SWITCH", + with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; })}, + {"flag GDI_COMPATIBLE", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE; })}, + {"flag DISPLAY_ONLY", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY; })}, + {"flag FRAME_LATENCY_WAITABLE_OBJECT", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; + })}, + {"flag FOREGROUND_LAYER", + with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER; })}, + {"flag HW_PROTECTED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_HW_PROTECTED; })}, + {"flag ALLOW_TEARING", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING; })}, + {"flag 0x1000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x1000; })}, + {"flag 0x2000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x2000; })}, + {"flag 0x4000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x4000; })}, + {"flag 0x80000000", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Flags = 0x80000000u; })}, + {"usage 0", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = 0; })}, + {"usage SHADER_INPUT", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.BufferUsage = DXGI_USAGE_SHADER_INPUT | DXGI_USAGE_RENDER_TARGET_OUTPUT; + })}, + {"usage SHARED", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_SHARED; })}, + {"usage READ_ONLY", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_READ_ONLY; })}, + {"usage DISCARD_ON_PRESENT", + with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferUsage = DXGI_USAGE_DISCARD_ON_PRESENT; })}, + {"usage UNORDERED_ACCESS", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_UNORDERED_ACCESS; + })}, + {"16384 x 16", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.Width = 16384; + d.Height = 16; + })}, + {"width 16385", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Width = 16385; })}, + {"height 16385", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.Height = 16385; })}, + {"one buffer", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.BufferCount = 1; })}, + {"MSAA 4", with([](DXGI_SWAP_CHAIN_DESC1& d) { d.SampleDesc.Count = 4; })}, + {"width 16385 and MSAA 4", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.Width = 16385; + d.SampleDesc.Count = 4; + })}, + {"width 16385 and one buffer", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.Width = 16385; + d.BufferCount = 1; + })}, + {"width 16385 and format UNKNOWN", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.Width = 16385; + d.Format = DXGI_FORMAT_UNKNOWN; + })}, + {"height 16385 and format BC1", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.Height = 16385; + d.Format = DXGI_FORMAT_BC1_UNORM; + })}, + {"width 16385 and effect DISCARD", with([](DXGI_SWAP_CHAIN_DESC1& d) { + d.Width = 16385; + d.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + })}, + {"null queue", base, Pass::null_queue}, + {"a device, not a queue", base, Pass::device}, + {"null window", base, Pass::null_window}, + {"null description", base, Pass::null_desc}, + {"null output", base, Pass::null_out}, + }; + int mismatches = 0; + for (const Case& c : cases) { + HRESULT result[2]; + for (int side = 0; side < 2; ++side) { + IDXGIFactory4* factory = side ? host_factory : ours; + IUnknown* queue = side ? static_cast(host_queue) : static_cast(our_queue); + if (c.pass == Pass::null_queue) queue = nullptr; + if (c.pass == Pass::device) queue = side ? static_cast(host_device) : our_device; + HWND hwnd = create_test_window(64, 64); + IDXGISwapChain1* chain = nullptr; + result[side] = create_guarded(factory, queue, c.pass == Pass::null_window ? nullptr : hwnd, + c.pass == Pass::null_desc ? nullptr : &c.desc, + c.pass == Pass::null_out ? nullptr : &chain); + if (chain) chain->Release(); + if (hwnd) DestroyWindow(hwnd); + } + if (result[0] != result[1]) { + ++mismatches; + std::fprintf(stderr, "CreateSwapChainForHwnd %s: ours 0x%08lx, host 0x%08lx\n", c.name, + static_cast(result[0]), static_cast(result[1])); + } + } + std::printf("CreateSwapChainForHwnd: %zu descriptions compared with the host runtime, %d mismatches\n", + std::size(cases), mismatches); + host_queue->Release(); + host_factory->Release(); + host_device->Release(); + return mismatches; +} + int main() { const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); if (!gipa) { @@ -286,6 +499,11 @@ int main() { return fail("queue/alloc/cl/fence"); cl->Close(); + // Before the test's own swap chain: the host comparison creates and releases its own windows and chains. + const int argument_mismatches = compare_swap_chain_arguments(factory, dev, queue); + if (argument_mismatches < 0) std::printf("CreateSwapChainForHwnd: no host D3D12 device to compare with, skipped\n"); + if (argument_mismatches > 0) return fail("CreateSwapChainForHwnd answers differ from the host runtime"); + DXGI_SWAP_CHAIN_DESC1 scd{}; scd.Width = 128; scd.Height = 128; @@ -327,6 +545,16 @@ int main() { if (FAILED(sc1->QueryInterface(IID_PPV_ARGS(&sc))) || !sc) return fail("QI IDXGISwapChain3"); sc1->Release(); + // DXGI reports the BufferCount the app created with, never a larger native/Vulkan image count (D3D-389). + { + DXGI_SWAP_CHAIN_DESC1 created_desc{}; + DXGI_SWAP_CHAIN_DESC created_desc0{}; + if (FAILED(sc->GetDesc1(&created_desc)) || created_desc.BufferCount != scd.BufferCount) + return fail("GetDesc1 BufferCount is not the requested count"); + if (FAILED(sc->GetDesc(&created_desc0)) || created_desc0.BufferCount != scd.BufferCount) + return fail("GetDesc BufferCount is not the requested count"); + } + if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification"); ID3D12Device* got_device = nullptr; @@ -401,6 +629,7 @@ int main() { return 1; } const UINT idx = sc->GetCurrentBackBufferIndex(); + if (idx >= cur_desc.BufferCount) return fail("GetCurrentBackBufferIndex >= BufferCount"); ID3D12Resource* bb = nullptr; if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer"); @@ -610,6 +839,7 @@ int main() { return fail("GetDesc1 did not preserve 37x19 R10G10B10A2_UNORM"); const UINT idx = sc->GetCurrentBackBufferIndex(); + if (idx >= d10.BufferCount) return fail("GetCurrentBackBufferIndex >= BufferCount (10-bit)"); ID3D12Resource* bb = nullptr; if (FAILED(sc->GetBuffer(idx, IID_PPV_ARGS(&bb))) || !bb) return fail("GetBuffer (10-bit)"); const D3D12_RESOURCE_DESC bb_desc = bb->GetDesc(); @@ -822,6 +1052,16 @@ int main() { return fail("Non-waitable SetMaximumFrameLatency should return DXGI_ERROR_INVALID_CALL"); } + // IDXGIObject private data on the swapchain, the factory and an adapter. + { + if (const char* step = check_private_data(sc)) return fail(step); + if (const char* step = check_private_data(factory)) return fail(step); + IDXGIAdapter1* pd_adapter = nullptr; + if (FAILED(factory->EnumAdapters1(0, &pd_adapter)) || !pd_adapter) return fail("EnumAdapters1(0) for private data"); + if (const char* step = check_private_data(pd_adapter)) return fail(step); + pd_adapter->Release(); + } + // IDXGIFactory4 adapter enumeration, IDXGIAdapter3 descriptors, EnumAdapterByLuid, and QueryVideoMemoryInfo. { IDXGIAdapter1* adapter1 = nullptr; diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp index f51dd32e0..58233ee98 100644 --- a/runtime/test/file_system_test.cpp +++ b/runtime/test/file_system_test.cpp @@ -571,6 +571,52 @@ int main() { "CreateFile2 refuses a path above GAME:"); if (h_esc != INVALID_HANDLE_VALUE) ::CloseHandle(h_esc); + // MAXIMUM_ALLOWED asks for every right the file grants, write included, without naming one. Such an open of + // a package file is a write-open: it gets the overlay copy, so a write through the handle cannot reach the + // package. CreateFileW, CreateFileA and CreateFile2 share the rule. The write is shorter than the file, so + // the bytes after it show the overlay copy started as the package file's contents (OPEN_EXISTING keeps them). + { + write_path(package / "data" / "max_w.txt", "pkg-max"); + write_path(package / "data" / "max_a.txt", "pkg-max"); + write_path(package / "data" / "max_2.txt", "pkg-max"); + const auto write_through = [](HANDLE h) { + if (h == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const BOOL ok = ::WriteFile(h, "OV", 2, &written, nullptr); + ::CloseHandle(h); + return ok != FALSE && written == 2; + }; + check(write_through(create_w(L"GAME:\\data\\max_w.txt", MAXIMUM_ALLOWED, 0, nullptr, OPEN_EXISTING, 0, + nullptr)), + "CreateFileW(MAXIMUM_ALLOWED, OPEN_EXISTING) opens a package file for writing"); + check(read_path(package / "data" / "max_w.txt") == "pkg-max", + "a write through a MAXIMUM_ALLOWED handle does not reach the package (CreateFileW)"); + check(read_path(overlay / "data" / "max_w.txt") == "OVg-max", + "the write through a MAXIMUM_ALLOWED handle is in the overlay copy (CreateFileW)"); + + check(write_through(create_a("GAME:\\data\\max_a.txt", MAXIMUM_ALLOWED | GENERIC_READ, 0, nullptr, + OPEN_EXISTING, 0, nullptr)), + "CreateFileA(MAXIMUM_ALLOWED | GENERIC_READ, OPEN_EXISTING) opens a package file for writing"); + check(read_path(package / "data" / "max_a.txt") == "pkg-max" && + read_path(overlay / "data" / "max_a.txt") == "OVg-max", + "the write goes to the overlay and not the package (CreateFileA)"); + + check(write_through(create2(L"GAME:\\data\\max_2.txt", MAXIMUM_ALLOWED, 0, OPEN_EXISTING, &ext)), + "CreateFile2(MAXIMUM_ALLOWED, OPEN_EXISTING) opens a package file for writing"); + check(read_path(package / "data" / "max_2.txt") == "pkg-max" && + read_path(overlay / "data" / "max_2.txt") == "OVg-max", + "the write goes to the overlay and not the package (CreateFile2)"); + + // A plain read still opens the package file in place: no overlay copy appears for it. + write_path(package / "data" / "max_read.txt", "pkg-max"); + const HANDLE h_plain = create_w(L"GAME:\\data\\max_read.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, + OPEN_EXISTING, 0, nullptr); + check(h_plain != INVALID_HANDLE_VALUE && read_handle(h_plain) == "pkg-max" && + !std::filesystem::exists(overlay / "data" / "max_read.txt"), + "a GENERIC_READ open is still a read: no overlay copy is made"); + if (h_plain != INVALID_HANDLE_VALUE) ::CloseHandle(h_plain); + } + // FindFirstFileExW merges package + overlay and honours FindExInfoBasic & FindExSearchLimitToDirectories. WIN32_FIND_DATAW fd{}; std::vector basic_names; diff --git a/runtime/test/fixtures/d3d12_xs_stub.cpp b/runtime/test/fixtures/d3d12_xs_stub.cpp new file mode 100644 index 000000000..e60c9b388 --- /dev/null +++ b/runtime/test/fixtures/d3d12_xs_stub.cpp @@ -0,0 +1,10 @@ +// Link-time stand-in for the console's d3d12_xs.dll, so tiny_frame.exe gets a real import of +// D3D12XboxCreateDevice. Under `gta6rt --run` the shim registry answers the import and this DLL never loads; it is +// built into a folder the loader does not search. Test code, not game content. +#include +#include + +extern "C" HRESULT __stdcall D3D12XboxCreateDevice(IUnknown*, const void*, const IID*, void** out) { + if (out) *out = nullptr; + return E_FAIL; +} diff --git a/runtime/test/fixtures/d3d12_xs_stub.def b/runtime/test/fixtures/d3d12_xs_stub.def new file mode 100644 index 000000000..608feffc1 --- /dev/null +++ b/runtime/test/fixtures/d3d12_xs_stub.def @@ -0,0 +1,3 @@ +LIBRARY d3d12_xs +EXPORTS + D3D12XboxCreateDevice diff --git a/runtime/test/fixtures/dll_thread_calls.cpp b/runtime/test/fixtures/dll_thread_calls.cpp index 4f4d73eb8..4d50229c5 100644 --- a/runtime/test/fixtures/dll_thread_calls.cpp +++ b/runtime/test/fixtures/dll_thread_calls.cpp @@ -4,6 +4,15 @@ // data. #include +#ifdef __MSVC_RUNTIME_CHECKS +// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB +// leaves these unresolved (LNK1120). The checks have nothing to check here, so they do nothing. +extern "C" { +void __cdecl _RTC_InitBase() {} +void __cdecl _RTC_Shutdown() {} +} +#endif + extern "C" BOOL WINAPI dll_thread_calls_main(HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) return DisableThreadLibraryCalls(instance); return TRUE; diff --git a/runtime/test/fixtures/gameinput_host.cpp b/runtime/test/fixtures/gameinput_host.cpp new file mode 100644 index 000000000..f28945045 --- /dev/null +++ b/runtime/test/fixtures/gameinput_host.cpp @@ -0,0 +1,43 @@ +// A DLL that does what a title's input code does first: GameInputCreate, a timestamp, a gamepad reading. It uses the +// Windows SDK's public GameInput.h and links against the SDK's gameinput.lib, so GameInputCreate is imported from +// GameInput.dll (by ordinal) like any title's import. Built without the CRT: DllMain does nothing and the exports call +// only GameInput. gameinput_host_test maps it with the loader. No game data. +#include + +#include + +extern "C" BOOL WINAPI gameinput_host_main(HINSTANCE, DWORD, LPVOID) { return TRUE; } + +#ifdef __MSVC_RUNTIME_CHECKS +// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB +// leaves these three unresolved (LNK1120). The checks have nothing to check here, so they do nothing. +extern "C" { +void __cdecl _RTC_InitBase() {} +void __cdecl _RTC_Shutdown() {} +void __fastcall _RTC_CheckStackVars(void*, void*) {} +} +#endif + +// Returns 1 when the library was created. reading_hr is S_OK with a gamepad attached and +// GAMEINPUT_E_READING_NOT_FOUND without one (E_FAIL when the library was not created); state_ok is 1 when +// GetGamepadState succeeded on a reading. +extern "C" __declspec(dllexport) int gameinput_host_probe(long* create_hr, unsigned long long* timestamp, + long* reading_hr, int* state_ok) { + IGameInput* input = nullptr; + IGameInputReading* reading = nullptr; + const HRESULT hr = GameInputCreate(&input); + *create_hr = hr; + *timestamp = 0; + *reading_hr = E_FAIL; // not S_OK: a failed GameInputCreate must not look like an attached gamepad + *state_ok = 0; + if (FAILED(hr) || !input) return 0; + *timestamp = input->GetCurrentTimestamp(); + *reading_hr = input->GetCurrentReading(GameInputKindGamepad, nullptr, &reading); + if (SUCCEEDED(*reading_hr) && reading) { + GameInputGamepadState state; + *state_ok = reading->GetGamepadState(&state) ? 1 : 0; + reading->Release(); + } + input->Release(); + return 1; +} diff --git a/runtime/test/fixtures/tiny_atexit.cpp b/runtime/test/fixtures/tiny_atexit.cpp new file mode 100644 index 000000000..fbe071e7f --- /dev/null +++ b/runtime/test/fixtures/tiny_atexit.cpp @@ -0,0 +1,92 @@ +// A stand-in program for `gta6rt --run`: atexit handlers, static destructors and the ways a program ends. +// Test code, not game content. check_atexit.cmake runs it natively and through the loader with each mode below +// and compares the lines it prints. +// return main returns: handlers and static destructors run, in reverse order of registration +// exit exit(7): the same +// _exit _exit(8): no handlers, no destructors +// quick_exit quick_exit(9): no atexit handlers, no destructors +// ExitProcess ExitProcess(10): no handlers, no destructors +// cexit _cexit() runs every handler and returns; main then returns 11 +// c_exit _c_exit() runs none and returns; main then returns 12, and exit runs them all +// concurrent_exit a second thread calls _exit(7) while exit(7) runs a handler: it waits for them all +// One handler registers another while the handlers run: it must still run, next. +#include +#include // _cexit, _c_exit + +#include +#include +#include + +namespace { + +void say(const char* what) { + std::printf("tiny_atexit: %s\n", what); + std::fflush(stdout); // every line reaches the pipe before any way out, natively and under the loader +} + +struct Tracer { + const char* name; + explicit Tracer(const char* n) : name(n) { + std::printf("tiny_atexit: ctor %s\n", name); + std::fflush(stdout); + } + ~Tracer() { + std::printf("tiny_atexit: dtor %s\n", name); + std::fflush(stdout); + } +}; +Tracer g_first("first"); +Tracer g_second("second"); + +void handler_one() { say("atexit one"); } +void handler_two() { say("atexit two"); } +void handler_late() { say("atexit late"); } +void handler_registers() { + say("atexit registers late"); + std::atexit(handler_late); +} + +// concurrent_exit: while exit() runs this handler on the main thread, a second thread calls _exit(). The CRT lets +// it go once the handlers are done, so either call may set the exit code: both use 7. +HANDLE g_slow_started = nullptr; +void handler_slow() { + say("slow handler started"); + SetEvent(g_slow_started); + Sleep(300); + say("slow handler done"); +} +DWORD WINAPI quick_exit_thread(void*) { + WaitForSingleObject(g_slow_started, INFINITE); + _exit(7); +} + +} // namespace + +int main(int argc, char** argv) { + const char* mode = argc > 1 ? argv[1] : "return"; + std::atexit(handler_one); + std::atexit(handler_registers); + std::atexit(handler_two); + say("main"); + if (!std::strcmp(mode, "concurrent_exit")) { + g_slow_started = CreateEventW(nullptr, TRUE, FALSE, nullptr); + std::atexit(handler_slow); + CloseHandle(CreateThread(nullptr, 0, quick_exit_thread, nullptr, 0, nullptr)); + std::exit(7); + } + if (!std::strcmp(mode, "exit")) std::exit(7); + if (!std::strcmp(mode, "_exit")) _exit(8); + if (!std::strcmp(mode, "quick_exit")) std::quick_exit(9); + if (!std::strcmp(mode, "ExitProcess")) ExitProcess(10); + if (!std::strcmp(mode, "cexit")) { + _cexit(); + say("after _cexit"); + return 11; + } + if (!std::strcmp(mode, "c_exit")) { + _c_exit(); + say("after _c_exit"); + return 12; + } + return 3; +} diff --git a/runtime/test/fixtures/tiny_frame.cpp b/runtime/test/fixtures/tiny_frame.cpp new file mode 100644 index 000000000..c30f7cc5c --- /dev/null +++ b/runtime/test/fixtures/tiny_frame.cpp @@ -0,0 +1,166 @@ +// A stand-in title for `gta6rt --run` that reaches the D3D12 layer the way a title does: it imports +// d3d12_xs.dll!D3D12XboxCreateDevice (from a link-time stub; the shim registry answers it) and then does the least +// a title does before its first frame, on the device that call returns: a direct queue, an allocator, a command +// list, a fence, an RTV heap whose start handle is read in the console shape (the 8-byte handle in RAX, heap slot 9), +// a committed render target, a clear, a copy into a readback buffer, Signal and a fence wait, Map, and a check of +// every pixel. It then returns from main with the device, the queue and the fence still alive, as a title's exit +// does. With LEONIDA_D3D12=vulkan (check_tiny_frame.py sets it) that device is the Vulkan-backed one, so this is the +// loader, the game thread, the Xbox-ABI proxies and the Vulkan device in one process. Hand-written test code, public +// D3D12 API only; no game data and no shader. +#include +#include + +#include +#include +#include + +extern "C" __declspec(dllimport) HRESULT __stdcall D3D12XboxCreateDevice(IUnknown* adapter, const void* params, + const IID* riid, void** device); + +namespace { + +int g_failures = 0; + +bool check(bool ok, const char* what) { + std::printf("tiny_frame: %s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; + return ok; +} + +int finish() { + std::printf("tiny_frame: %s\n", g_failures ? "FAILED" : "OK"); + std::fflush(stdout); + return g_failures ? 1 : 0; +} + +// Descriptor-heap slot 9 on the console returns the handle in RAX (docs/d3d12_vulkan.md section 7); the PC header's +// GetCPUDescriptorHandleForHeapStart returns it through a hidden pointer, which the heap proxy does not serve. +using HeapStartFn = std::uint64_t(__stdcall*)(void* heap); + +constexpr UINT kWidth = 8, kHeight = 4; + +} // namespace + +int main() { + std::setvbuf(stdout, nullptr, _IONBF, 0); + + // The entry point's second argument is a block the shim logs and does not interpret; a title passes its own. + std::uint32_t params[24] = {}; + const IID device_iid = __uuidof(ID3D12Device); + ID3D12Device* device = nullptr; + HRESULT hr = D3D12XboxCreateDevice(nullptr, params, &device_iid, reinterpret_cast(&device)); + if (!check(hr == S_OK && device, "D3D12XboxCreateDevice returns a device")) { + std::printf("tiny_frame: hr=0x%08lx\n", static_cast(hr)); + return finish(); + } + + ID3D12CommandQueue* queue = nullptr; + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + check(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue))) && queue, "a direct command queue"); + check(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && + allocator, "a command allocator"); + if (allocator) + check(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, nullptr, + IID_PPV_ARGS(&list))) && list, "a command list"); + check(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))) && fence, "a fence"); + + ID3D12DescriptorHeap* rtv_heap = nullptr; + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; + heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + heap_desc.NumDescriptors = 1; + check(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap))) && rtv_heap, "an RTV heap"); + if (!queue || !list || !fence || !rtv_heap) return finish(); + const std::uint64_t start = reinterpret_cast((*reinterpret_cast(rtv_heap))[9])(rtv_heap); + check(start != 0, "the heap's start handle comes back in RAX (heap slot 9)"); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(start)}; + + D3D12_HEAP_PROPERTIES default_heap{}, readback_heap{}; + default_heap.Type = D3D12_HEAP_TYPE_DEFAULT; + readback_heap.Type = D3D12_HEAP_TYPE_READBACK; + D3D12_RESOURCE_DESC target_desc{}; + target_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + target_desc.Width = kWidth; + target_desc.Height = kHeight; + target_desc.DepthOrArraySize = 1; + target_desc.MipLevels = 1; + target_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + target_desc.SampleDesc.Count = 1; + target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + ID3D12Resource* target = nullptr; + check(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&target))) && target, "a committed render target"); + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{}; + UINT rows = 0; + UINT64 row_bytes = 0, total = 0; + device->GetCopyableFootprints(&target_desc, 0, 1, 0, &placed, &rows, &row_bytes, &total); + check(rows == kHeight && row_bytes == kWidth * 4 && placed.Footprint.RowPitch >= kWidth * 4 && total != 0, + "GetCopyableFootprints describes the target"); + D3D12_RESOURCE_DESC buffer_desc{}; + buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer_desc.Width = total ? total : 4096; + buffer_desc.Height = 1; + buffer_desc.DepthOrArraySize = 1; + buffer_desc.MipLevels = 1; + buffer_desc.SampleDesc.Count = 1; + buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource* readback = nullptr; + check(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback))) && readback, "a readback buffer"); + if (!target || !readback) return finish(); + + device->CreateRenderTargetView(target, nullptr, rtv); + const FLOAT colour[4] = {64.0f / 255.0f, 128.0f / 255.0f, 191.0f / 255.0f, 1.0f}; + list->ClearRenderTargetView(rtv, colour, 0, nullptr); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = target; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION from{}, to{}; + from.pResource = target; + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + to.pResource = readback; + to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + to.PlacedFootprint = placed; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + check(SUCCEEDED(list->Close()), "the list closes"); + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + check(SUCCEEDED(queue->Signal(fence, 1)), "Signal"); + check(done && SUCCEEDED(fence->SetEventOnCompletion(1, done)) && WaitForSingleObject(done, 30000) == WAIT_OBJECT_0, + "the fence reaches the signalled value"); + check(fence->GetCompletedValue() >= 1, "GetCompletedValue is past the signal"); + if (done) CloseHandle(done); + + void* bytes = nullptr; + if (check(SUCCEEDED(readback->Map(0, nullptr, &bytes)) && bytes, "Map of the readback buffer")) { + const std::uint8_t want[4] = {64, 128, 191, 255}; + unsigned wrong = 0; + for (UINT y = 0; y < kHeight; ++y) + for (UINT x = 0; x < kWidth; ++x) + wrong += std::memcmp(static_cast(bytes) + placed.Offset + + y * placed.Footprint.RowPitch + x * 4, want, 4) != 0; + check(wrong == 0, "all 32 pixels are the clear colour (64, 128, 191, 255)"); + readback->Unmap(0, nullptr); + } + + // What a frame owns is released; the device, the queue and the fence stay alive across the return from main, so + // the run ends through the CRT's exit with the layer still up. + readback->Release(); + target->Release(); + rtv_heap->Release(); + list->Release(); + allocator->Release(); + return finish(); +} diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp index b37307369..9b4ad4e90 100644 --- a/runtime/test/fixtures/tiny_gdk_load.cpp +++ b/runtime/test/fixtures/tiny_gdk_load.cpp @@ -98,8 +98,9 @@ int main() { reinterpret_cast(vtable[17])(obj, queue); reinterpret_cast(vtable[2])(obj); - // A class not served (an id no runtime class has) is refused, with the out pointer cleared. - const GUID unserved = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; + // A class not served (an id no runtime class has) is refused, with the out pointer cleared: XGameSaveImpl + // (xgameruntime include/xgamesave.idl), which is not served yet. + const GUID unserved = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}}; void* out = reinterpret_cast(1); hr = query(&unserved, unserved, &out); if (hr != static_cast(0x80070032) || out != nullptr) diff --git a/runtime/test/fixtures/tiny_tls_cb_only.cpp b/runtime/test/fixtures/tiny_tls_cb_only.cpp index d8062c073..e8f80010a 100644 --- a/runtime/test/fixtures/tiny_tls_cb_only.cpp +++ b/runtime/test/fixtures/tiny_tls_cb_only.cpp @@ -2,6 +2,15 @@ // and SizeOfZeroFill == 0 while providing a TLS callback (no CRT .tls section). Ordinary test code, not game data. #include +#ifdef __MSVC_RUNTIME_CHECKS +// Debug builds compile with /RTC1 (the Visual Studio generator's default), whose checks call into the CRT; /NODEFAULTLIB +// leaves these unresolved (LNK1120). The checks have nothing to check here, so they do nothing. +extern "C" { +void __cdecl _RTC_InitBase() {} +void __cdecl _RTC_Shutdown() {} +} +#endif + namespace { ULONG g_tls_index = 0; diff --git a/runtime/test/gameinput_host_test.cpp b/runtime/test/gameinput_host_test.cpp new file mode 100644 index 000000000..cdd071055 --- /dev/null +++ b/runtime/test/gameinput_host_test.cpp @@ -0,0 +1,90 @@ +// The host GameInput path: mapped code that imports GameInputCreate from GameInput.dll, with no GameInput shim. +// +// docs/gameinput.md: without the SDL3 shim, the loader binds GameInputCreate to the host's GameInput.dll. This checks +// that path with a synthetic DLL (test/fixtures/gameinput_host.cpp) mapped by rt::Loader: +// - its GameInput.dll import binds to the host's copy (this test links no shim table, so it cannot be a shim); +// - GameInputCreate succeeds from mapped code, and the library answers GetCurrentTimestamp; +// - GetCurrentReading says either "reading" or "no reading found": no crash, no other error. With a gamepad attached +// GetGamepadState must succeed on the reading; the test passes with or without one. +// Skips (exit 77) only where Windows itself cannot load GameInput.dll (asked before mapping, with LoadLibraryExW). +// When the DLL is there, an import that binds to nothing is a failure, not a skip. No game files. +#include + +#include +#include +#include +#include + +#include "pe_loader.h" + +namespace { + +using ProbeFn = int (*)(long*, unsigned long long*, long*, int*); +constexpr unsigned long kReadingNotFound = 0x838A0003UL; // GAMEINPUT_E_READING_NOT_FOUND + +int g_failures = 0; + +void check(bool ok, const std::string& what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str()); + std::fflush(stdout); + if (!ok) ++g_failures; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: gameinput_host_test \n"); + return 2; + } + const std::filesystem::path fixture = argv[1]; + + // Decide the skip from the machine, not from the loader's answer: a broken host binding must fail the test. + HMODULE const host_gameinput = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!host_gameinput) { + const DWORD error = GetLastError(); + if (error == ERROR_MOD_NOT_FOUND || error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) { + std::printf("SKIP: no GameInput.dll on this machine\n"); + return 77; + } + std::printf("FAIL GameInput.dll is present but does not load (error %lu)\n", static_cast(error)); + return 1; + } + + try { + rt::Loader loader(fixture.parent_path()); + rt::Module& m = loader.load(fixture); + + // The SDK's import library imports by ordinal, so match the DLL name, not the function name. + rt::Binding binding = rt::Binding::Unimplemented; + int seen = 0; + for (const auto& r : m.imports) + if (rt::lower(r.dll) == "gameinput.dll") { + binding = r.binding; + ++seen; + } + check(seen == 1 && binding == rt::Binding::Host, "the GameInput.dll import binds to the host's copy"); + + loader.initialise(); + const auto probe = reinterpret_cast(m.exports.at("gameinput_host_probe")); + long create_hr = -1, reading_hr = -1; + unsigned long long timestamp = 0; + int state_ok = 0; + const int created = probe(&create_hr, ×tamp, &reading_hr, &state_ok); + std::printf(" create hr=0x%08lX, timestamp=%llu, reading hr=0x%08lX\n", static_cast(create_hr), + timestamp, static_cast(reading_hr)); + check(created == 1 && create_hr == 0, "GameInputCreate succeeds from mapped code"); + check(timestamp != 0, "GetCurrentTimestamp returns a time"); + const bool pad = created == 1 && reading_hr == 0; + check(pad || static_cast(reading_hr) == kReadingNotFound, + "GetCurrentReading says either 'reading' or 'no reading found'"); + std::printf(" gamepad reading: %s\n", pad ? "yes (a gamepad is attached)" : "none (no gamepad attached)"); + if (pad) check(state_ok == 1, "GetGamepadState succeeds on a real reading"); + } catch (const std::exception& e) { + std::printf("FAIL unexpected exception: %s\n", e.what()); + ++g_failures; + } + FreeLibrary(host_gameinput); + std::printf("gameinput_host_test: %s (%d failures)\n", g_failures ? "FAILED" : "OK", g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index 1389b8f6d..679adf19f 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp @@ -6,7 +6,8 @@ // without trigger motors. The test covers enumeration and device callbacks, readings and their button/axis mapping, // UI navigation, the guide button, rumble and trigger rumble as SDL receives them, the DualSense effect bytes for // each LEONIDA_DS_TRIGGERS mode, the lightbar, a dispatcher, unplug/replug, reading history, -// and identification of two or three otherwise indistinguishable pads. No game data. +// identification of two or three otherwise indistinguishable pads, and which kind of device was used last +// (active_input, LEONIDA_PROMPTS). No game data. #include #include @@ -794,6 +795,156 @@ void test_keyboard_pad(IGameInput* input) { rt::gameinput::set_cursor_source(nullptr); } +// active_input(): which kind of device the player used last. Virtual pads with a DualSense, a DualShock 4 and an Xbox +// pad's vendor and product id (SDL takes the gamepad type from them) plus the keyboard pad; first with no wait +// between changes (LEONIDA_PROMPTS_SWITCH_MS=0), then with the default 300 ms window on the real clock, then a family +// forced by LEONIDA_PROMPTS. +void test_active_input() { + using leonida::InputFamily; + const auto family = [] { return rt::gameinput::active_input().family; }; + const auto generation = [] { return rt::gameinput::active_input().generation; }; + + set_env("LEONIDA_PROMPTS", nullptr); + set_env("LEONIDA_PROMPTS_SWITCH_MS", "0"); + rt::gameinput::reload_config(); + rt::gameinput::poll(); + check(!rt::gameinput::active_input().forced, "active input: not forced without LEONIDA_PROMPTS"); + + Pad ds, ds4, xbox; + attach(ds, "Leonida virtual DualSense", 0x054C, 0x0CE6, false); + attach(ds4, "Leonida virtual DualShock 4", 0x054C, 0x09CC, false); + attach(xbox, "Leonida virtual Xbox pad", 0x045E, 0x0B12, true); + SDL_SetJoystickVirtualButton(ds.js, SDL_GAMEPAD_BUTTON_SOUTH, true); // held while it connects + const uint64_t at_connect = generation(); + rt::gameinput::poll(); + check(rt::gameinput::connected_count() == 3, "active input: three pads open"); + check(generation() == at_connect, "active input: connecting pads (one with a button held) changes nothing"); + + auto press = [](Pad& p, SDL_GamepadButton b) { + SDL_SetJoystickVirtualButton(p.js, b, true); + rt::gameinput::poll(); + SDL_SetJoystickVirtualButton(p.js, b, false); + rt::gameinput::poll(); + }; + SDL_SetJoystickVirtualButton(ds.js, SDL_GAMEPAD_BUTTON_SOUTH, false); // the held button, let go + rt::gameinput::poll(); + check(generation() == at_connect, "active input: letting go of a button is not input"); + + // The tests before this one leave whichever pad they used last; an Xbox press makes the start known. + press(xbox, SDL_GAMEPAD_BUTTON_SOUTH); + check(family() == InputFamily::Xbox, "active input: the Xbox pad in use"); + const uint64_t g0 = generation(); + + press(ds, SDL_GAMEPAD_BUTTON_SOUTH); + check(family() == InputFamily::PlayStation5 && generation() == g0 + 1, "active input: DualSense press"); + press(ds4, SDL_GAMEPAD_BUTTON_EAST); + check(family() == InputFamily::PlayStation4 && generation() == g0 + 2, "active input: DualShock 4 press"); + + // Stick drift on the Xbox pad (0.18) is not input; the stick pushed over is. + SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 6000); + rt::gameinput::poll(); + check(family() == InputFamily::PlayStation4 && generation() == g0 + 2, "active input: stick drift changes nothing"); + SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 32767); + rt::gameinput::poll(); + check(family() == InputFamily::Xbox && generation() == g0 + 3, "active input: Xbox stick pushed over"); + SDL_SetJoystickVirtualAxis(xbox.js, SDL_GAMEPAD_AXIS_LEFTX, 0); + rt::gameinput::poll(); + + // Buttons GameInput's gamepad state leaves out count too: the DualSense touchpad. + press(ds, SDL_GAMEPAD_BUTTON_TOUCHPAD); + check(family() == InputFamily::PlayStation5 && generation() == g0 + 4, "active input: DualSense touchpad click"); + // A trigger pulled on the DualShock 4. + SDL_SetJoystickVirtualAxis(ds4.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 32767); + rt::gameinput::poll(); + check(family() == InputFamily::PlayStation4 && generation() == g0 + 5, "active input: DualShock 4 trigger pull"); + SDL_SetJoystickVirtualAxis(ds4.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, -32768); + rt::gameinput::poll(); + + // The keyboard pad: a key, and the mouse through the keyboard pad's right stick. + rt::gameinput::set_keyboard_source(fake_key_down, fake_focus); + rt::gameinput::set_cursor_source(fake_cursor); + std::memset(g_keys, 0, sizeof g_keys); + g_cursor_x = g_cursor_y = 0; + set_env("LEONIDA_KEYBOARD_PAD", "always"); + rt::gameinput::reload_config(); + rt::gameinput::poll(); // attaches the keyboard pad + rt::gameinput::poll(); // opens it: its first sample is the baseline + check(rt::gameinput::connected_count() == 4 && generation() == g0 + 5, + "active input: the keyboard pad connecting changes nothing"); + g_keys[VK_RETURN] = true; + rt::gameinput::poll(); + g_keys[VK_RETURN] = false; + rt::gameinput::poll(); + check(family() == InputFamily::Keyboard && generation() == g0 + 6, "active input: Enter on the keyboard pad"); + press(xbox, SDL_GAMEPAD_BUTTON_SOUTH); + check(family() == InputFamily::Xbox && generation() == g0 + 7, "active input: back to the Xbox pad"); + g_cursor_x += 1; // a 1-count jitter stays well inside the stick radius + rt::gameinput::poll(); + check(family() == InputFamily::Xbox, "active input: mouse jitter changes nothing"); + g_cursor_x += 20; // a real movement pushes the right stick past the radius + rt::gameinput::poll(); + check(family() == InputFamily::Keyboard && generation() == g0 + 8, "active input: mouse movement"); + for (int i = 0; i < 80; ++i) rt::gameinput::poll(); // the stick falls back to rest + + // The default window on the real clock: a second change within 300 ms of the last is ignored. + set_env("LEONIDA_PROMPTS_SWITCH_MS", nullptr); + rt::gameinput::reload_config(); + check(rt::gameinput::config().prompts_switch_ms == 300, "active input: 300 ms by default"); + Sleep(350); + press(ds, SDL_GAMEPAD_BUTTON_NORTH); + check(family() == InputFamily::PlayStation5 && generation() == g0 + 9, "active input: DualSense after the window"); + press(xbox, SDL_GAMEPAD_BUTTON_WEST); + check(family() == InputFamily::PlayStation5 && generation() == g0 + 9, + "active input: an Xbox press right after a change is ignored"); + Sleep(350); + press(xbox, SDL_GAMEPAD_BUTTON_WEST); + check(family() == InputFamily::Xbox && generation() == g0 + 10, + "active input: the Xbox press once the window passed"); + + // LEONIDA_PROMPTS forces a family; tracking goes on underneath and takes over again when it is cleared. + set_env("LEONIDA_PROMPTS_SWITCH_MS", "0"); + set_env("LEONIDA_PROMPTS", "keyboard"); + rt::gameinput::reload_config(); + rt::gameinput::poll(); + check(family() == InputFamily::Keyboard && rt::gameinput::active_input().forced && generation() == g0 + 11, + "active input: LEONIDA_PROMPTS=keyboard"); + press(ds, SDL_GAMEPAD_BUTTON_SOUTH); + check(family() == InputFamily::Keyboard && generation() == g0 + 11, + "active input: forced, a DualSense press shows nothing"); + set_env("LEONIDA_PROMPTS", "PlayStation"); // case does not matter + rt::gameinput::reload_config(); + rt::gameinput::poll(); + check(family() == InputFamily::PlayStation5 && rt::gameinput::active_input().forced && generation() == g0 + 12, + "active input: LEONIDA_PROMPTS=PlayStation (any case) is PlayStation 5"); + set_env("LEONIDA_PROMPTS", "ps4"); + rt::gameinput::reload_config(); + rt::gameinput::poll(); + check(family() == InputFamily::PlayStation4 && generation() == g0 + 13, "active input: LEONIDA_PROMPTS=ps4"); + set_env("LEONIDA_PROMPTS", "nonsense"); // warns and follows the devices + rt::gameinput::reload_config(); + rt::gameinput::poll(); + check(!rt::gameinput::active_input().forced && family() == InputFamily::PlayStation5 && generation() == g0 + 14, + "active input: an unknown LEONIDA_PROMPTS follows the devices (the DualSense pressed while forced)"); + set_env("LEONIDA_PROMPTS", "playstation"); + rt::gameinput::reload_config(); + rt::gameinput::poll(); + check(family() == InputFamily::PlayStation5 && rt::gameinput::active_input().forced && generation() == g0 + 14, + "active input: forcing the family already in use changes no generation"); + + // Clean up: everything off and unplugged. + set_env("LEONIDA_PROMPTS", nullptr); + set_env("LEONIDA_PROMPTS_SWITCH_MS", nullptr); + set_env("LEONIDA_KEYBOARD_PAD", nullptr); + rt::gameinput::reload_config(); + detach(ds); + detach(ds4); + detach(xbox); + rt::gameinput::poll(); + check(rt::gameinput::connected_count() == 0, "active input: all pads closed at the end"); + rt::gameinput::set_keyboard_source(nullptr, nullptr); + rt::gameinput::set_cursor_source(nullptr); +} + bool same_id(const AppLocalDeviceId& a, const AppLocalDeviceId& b) { return std::memcmp(&a, &b, sizeof a) == 0; } // The id the shim derives from SDL: the GUID, then two FNV-1a hashes of "s:" serial, "p:" path or nothing, with @@ -1815,6 +1966,7 @@ int main() { rt::gameinput::poll(); check(rt::gameinput::connected_count() == 0, "all pads closed after detaching"); + test_active_input(); test_twins(input); test_keyboard_pad(input); test_motion(input); diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp index 48724afae..523180ee7 100644 --- a/runtime/test/gfx10_descriptors_test.cpp +++ b/runtime/test/gfx10_descriptors_test.cpp @@ -362,6 +362,15 @@ int main() { .compare = CompareFunction::greater, .max_lod = 9.0f, .unnormalized = true}); CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST); CHECK(info.maxLod == 0.0f && info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE); + // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border, + // W is free; min and mag filter agree (VUID ...-01072). + CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && + info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && + info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter); + info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror, + .min_filter = Filter::bilinear, .unnormalized = true}); + CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER && + info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST); CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE); CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); diff --git a/runtime/test/glsl/cs_indirect_dispatch_count.comp b/runtime/test/glsl/cs_indirect_dispatch_count.comp new file mode 100644 index 000000000..234575467 --- /dev/null +++ b/runtime/test/glsl/cs_indirect_dispatch_count.comp @@ -0,0 +1,17 @@ +#version 460 +// Synthetic translated-shader stand-in: root UAV s0:s1, plus the 144-byte user-data contract. +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require +layout(local_size_x = 1) in; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; +layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc; +uvec2 add64(uvec2 a, uvec2 b) { + uint carry; + uint lo = uaddCarry(a.x, b.x, carry); + return uvec2(lo, a.y + b.y + carry); +} +void main() { + Words result = Words(add64(pc.heap_base, uvec2(pc.s[0], pc.s[1]))); + atomicAdd(result.w[0], 1u); + atomicAdd(result.w[1], gl_WorkGroupID.x + 1u); +} diff --git a/runtime/test/glsl/cs_wave_probe.comp b/runtime/test/glsl/cs_wave_probe.comp new file mode 100644 index 000000000..d18987908 --- /dev/null +++ b/runtime/test/glsl/cs_wave_probe.comp @@ -0,0 +1,31 @@ +#version 450 +// vk_compute_test's subgroup probe (cs_wave_probe_spv.h). Where the device can't pin a compute subgroup size +// (MoltenVK: requiredSubgroupSizeStages is 0), vk_compute_test runs this first, with the test shader's local size +// and pipeline flags, and checks what each invocation reports: its subgroup's size, its lane and subgroup number, +// and how many lanes a ballot of the whole subgroup counts. The ballot is the real width: MoltenVK's MSL declares +// SubgroupSize as the constant 32, while the lane, the subgroup number and simd_ballot come from the hardware. +// Four words per invocation at base + 16 * gl_LocalInvocationIndex, the buffer address in the first push-constant +// words (s0, s1), so the probe fits the 128-byte push-constant layout of --pc-tail-ubo as well as the 144-byte one. +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_ballot : require + +layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in; + +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { + uint w[]; +}; + +layout(push_constant) uniform UserData { + uvec2 base; +} pc; + +void main() { + Words o = Words(pc.base); + const uint i = gl_LocalInvocationIndex * 4u; + o.w[i + 0u] = gl_SubgroupSize; + o.w[i + 1u] = gl_SubgroupInvocationID; + o.w[i + 2u] = gl_SubgroupID; + o.w[i + 3u] = subgroupBallotBitCount(subgroupBallot(true)); +} diff --git a/runtime/test/glsl/gs_depth.geom b/runtime/test/glsl/gs_depth.geom new file mode 100644 index 000000000..0661c7acf --- /dev/null +++ b/runtime/test/glsl/gs_depth.geom @@ -0,0 +1,15 @@ +#version 460 +// A pass-through geometry shader with the interface of a translated one (docs/design.md, "Geometry shaders": +// triangles in, a triangle strip out), for d3d12_depth24_draw_test: a VS + GS pipeline without a pixel shader still +// gets the built-in D24 depth stage. It reads no input but the position and writes none but gl_Position. + +layout(triangles) in; +layout(triangle_strip, max_vertices = 3) out; + +void main() { + for (int i = 0; i < 3; ++i) { + gl_Position = gl_in[i].gl_Position; + EmitVertex(); + } + EndPrimitive(); +} diff --git a/runtime/test/glsl/ps_depth_empty.frag b/runtime/test/glsl/ps_depth_empty.frag new file mode 100644 index 000000000..8bc5bce70 --- /dev/null +++ b/runtime/test/glsl/ps_depth_empty.frag @@ -0,0 +1,11 @@ +#version 460 +// A pixel shader with no outputs, for d3d12_depth24_draw_test: it stands in for a translated shader in a pipeline +// with no render target, so the layer's D24 depth edit (src/depth24_fragment.h) runs on a shader it did not build. + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() {} diff --git a/runtime/test/glsl/ps_depth_write.frag b/runtime/test/glsl/ps_depth_write.frag new file mode 100644 index 000000000..959d1dd9d --- /dev/null +++ b/runtime/test/glsl/ps_depth_write.frag @@ -0,0 +1,13 @@ +#version 460 +// A pixel shader that writes its own depth (SV_Depth), for d3d12_depth24_draw_test: s2 is the depth it writes. On a +// D24 target the value is stored quantised to 24 bits, and D3D applies no depth bias to it. + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() { + gl_FragDepth = uintBitsToFloat(pc.s[2]); +} diff --git a/runtime/test/glsl/vs_depth.vert b/runtime/test/glsl/vs_depth.vert new file mode 100644 index 000000000..de1d6ee40 --- /dev/null +++ b/runtime/test/glsl/vs_depth.vert @@ -0,0 +1,16 @@ +#version 460 +// A full-screen triangle at a chosen depth, written to the translator's runtime contract (docs/design.md, "User +// data"), for d3d12_depth24_draw_test: s0 is the depth at the centre and s1 how much it changes per unit of clip-space +// x, so s1 = 0 gives a flat triangle and anything else a constant slope across the target. + +layout(push_constant) uniform UserData { + uint s[32]; + uvec2 heap_base; + uvec2 code_base; +} pc; + +void main() { + const vec2 corner = vec2(float(gl_VertexIndex & 2), float((gl_VertexIndex << 1) & 2)); + const vec2 xy = corner * 2.0 - 1.0; + gl_Position = vec4(xy, uintBitsToFloat(pc.s[0]) + uintBitsToFloat(pc.s[1]) * xy.x, 1.0); +} diff --git a/runtime/test/large_module_gate.h b/runtime/test/large_module_gate.h new file mode 100644 index 000000000..53aa61f2d --- /dev/null +++ b/runtime/test/large_module_gate.h @@ -0,0 +1,179 @@ +// How many large SPIR-V modules vk_pipeline_check lets into the driver at once, by a memory budget. +// +// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute +// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB. +// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6 +// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin +// over the measurement. +// +// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas +// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each +// large module. +#pragma once + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif +#if defined(__GLIBC__) +#include +#endif + +namespace leonida { + +inline constexpr uint64_t kBytesPerSpirvByte = 512; + +inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; } + +#if defined(__linux__) +// The first unsigned number in a file ("max" and unreadable files give no value). +inline bool read_u64_file(const std::string& path, uint64_t& value) { + std::FILE* f = std::fopen(path.c_str(), "r"); + if (!f) return false; + unsigned long long v = 0; + const bool ok = std::fscanf(f, "%llu", &v) == 1; + std::fclose(f); + value = v; + return ok; +} + +// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or +// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests. +inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup", + const std::string& cgroup_root = "/sys/fs/cgroup") { + std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r"); + if (!f) return UINT64_MAX; + char line[4096]; + std::string rel; + while (std::fgets(line, sizeof(line), f)) { + std::string l(line); + if (l.rfind("0::", 0) == 0) { // the cgroup v2 line + rel = l.substr(3); + while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back(); + break; + } + } + std::fclose(f); + uint64_t room = UINT64_MAX; + for (std::string dir = rel; !dir.empty() && dir != "/";) { + uint64_t max = 0, current = 0; + if (read_u64_file(cgroup_root + dir + "/memory.max", max) && + read_u64_file(cgroup_root + dir + "/memory.current", current)) + room = std::min(room, max > current ? max - current : 0); + const auto slash = dir.find_last_of('/'); + dir = slash == std::string::npos ? std::string() : dir.substr(0, slash); + } + return room; +} +#endif + +// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate). +inline uint64_t available_memory_bytes() { +#ifdef _WIN32 + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0; +#elif defined(__linux__) + std::FILE* f = std::fopen("/proc/meminfo", "r"); + if (!f) return 0; + char line[256]; + unsigned long long kb = 0; + bool found = false; + while (std::fgets(line, sizeof(line), f)) + if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; } + std::fclose(f); + if (!found) return 0; + const uint64_t room = cgroup_memory_room(); + return std::max(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown" +#else + return 0; +#endif +} + +// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it). +inline void release_free_memory() { +#if defined(__GLIBC__) + malloc_trim(0); +#endif +} + +// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in +// when none is, so a module bigger than the whole budget still compiles (alone among the large ones). +class LargeModuleGate { +public: + LargeModuleGate(uint64_t budget, unsigned max_inflight) + : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {} + + bool admits(uint64_t estimate) const { + std::lock_guard g(mu_); + return admits_locked(estimate); + } + void enter(uint64_t estimate) { + std::unique_lock l(mu_); + cv_.wait(l, [&] { return admits_locked(estimate); }); + used_ += estimate; + ++inflight_; + } + void leave(uint64_t estimate) { + { + std::lock_guard g(mu_); + used_ -= estimate; + --inflight_; + } + cv_.notify_all(); + } + unsigned inflight() const { + std::lock_guard g(mu_); + return inflight_; + } + uint64_t budget() const { return budget_; } + unsigned max_inflight() const { return max_inflight_; } + + // Holds a place from construction until destruction (or release()), then hands freed memory back. + class Ticket { + public: + Ticket() = default; + Ticket(LargeModuleGate& gate, uint64_t estimate) : gate_(&gate), estimate_(estimate) { gate.enter(estimate); } + Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; } + Ticket& operator=(Ticket&& o) noexcept { + if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; } + return *this; + } + Ticket(const Ticket&) = delete; + Ticket& operator=(const Ticket&) = delete; + ~Ticket() { release(); } + void release() { + if (!gate_) return; + gate_->leave(estimate_); + gate_ = nullptr; + release_free_memory(); + } + private: + LargeModuleGate* gate_ = nullptr; + uint64_t estimate_ = 0; + }; + +private: + bool admits_locked(uint64_t estimate) const { + if (inflight_ == 0) return true; + return inflight_ < max_inflight_ && used_ + estimate <= budget_; + } + + const uint64_t budget_; + const unsigned max_inflight_; + mutable std::mutex mu_; + std::condition_variable cv_; + uint64_t used_ = 0; + unsigned inflight_ = 0; +}; + +} // namespace leonida diff --git a/runtime/test/large_module_gate_test.cpp b/runtime/test/large_module_gate_test.cpp new file mode 100644 index 000000000..ed8d18a0c --- /dev/null +++ b/runtime/test/large_module_gate_test.cpp @@ -0,0 +1,159 @@ +// vk_pipeline_check's memory budget for large modules (large_module_gate.h), without a Vulkan device. +#include "large_module_gate.h" + +#include +#include +#ifndef _WIN32 +#include +#endif +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +using leonida::LargeModuleGate; + +static int budget_and_count() { + LargeModuleGate gate(10, 3); + CHECK(gate.admits(4)); + gate.enter(4); + CHECK(gate.admits(4)); + gate.enter(4); + CHECK(!gate.admits(4)); // 12 > 10 + CHECK(gate.admits(2)); // 10 fits exactly + gate.enter(2); + CHECK(!gate.admits(0)); // three in: max_inflight + gate.leave(4); + CHECK(gate.admits(4)); + gate.leave(4); + gate.leave(2); + CHECK(gate.inflight() == 0); + return 0; +} + +static int oversized_module_still_gets_in_alone() { + // Before: a module whose estimate exceeds the whole budget would wait forever. + LargeModuleGate gate(10, 4); + CHECK(gate.admits(100)); + gate.enter(100); + CHECK(!gate.admits(1)); // nothing joins it + gate.leave(100); + CHECK(gate.admits(1)); + return 0; +} + +static int max_inflight_zero_means_one() { + LargeModuleGate gate(100, 0); + CHECK(gate.max_inflight() == 1); + gate.enter(1); + CHECK(!gate.admits(1)); + gate.leave(1); + return 0; +} + +static int ticket_releases() { + LargeModuleGate gate(10, 2); + { + LargeModuleGate::Ticket a(gate, 6); + CHECK(gate.inflight() == 1); + LargeModuleGate::Ticket moved = std::move(a); // the moved-from ticket must not leave twice + CHECK(gate.inflight() == 1); + LargeModuleGate::Ticket b; + b = LargeModuleGate::Ticket(gate, 4); + CHECK(gate.inflight() == 2); + b.release(); + CHECK(gate.inflight() == 1); + } + CHECK(gate.inflight() == 0); + return 0; +} + +static int threads_never_exceed_the_budget() { + constexpr uint64_t kBudget = 10; + LargeModuleGate gate(kBudget, 3); + std::atomic used{0}; + std::atomic in{0}; + std::atomic over{false}; + std::vector threads; + for (int t = 0; t < 8; ++t) { + threads.emplace_back([&, t] { + for (int i = 0; i < 200; ++i) { + const uint64_t est = 1 + uint64_t((t + i) % 5); // 1..5 + LargeModuleGate::Ticket ticket(gate, est); + const uint64_t u = used += est; + const unsigned n = ++in; + if (n > 3 || (n > 1 && u > kBudget)) over = true; + std::this_thread::sleep_for(std::chrono::microseconds(50)); + --in; + used -= est; + } + }); + } + for (auto& th : threads) th.join(); + CHECK(!over); + CHECK(gate.inflight() == 0); + return 0; +} + +static int estimate_and_memory_query() { + CHECK(leonida::large_module_estimate(4u << 20) == (uint64_t(4) << 20) * leonida::kBytesPerSpirvByte); +#if defined(__linux__) || defined(_WIN32) + CHECK(leonida::available_memory_bytes() > 0); // Linux: MemAvailable; Windows: ullAvailPhys +#endif + leonida::release_free_memory(); // must be callable anywhere + return 0; +} + +#if defined(__linux__) +#include +#include + +static void write_file(const std::filesystem::path& p, const char* text) { + std::filesystem::create_directories(p.parent_path()); + std::ofstream(p) << text; +} + +static int cgroup_limits_are_read_up_the_tree() { + // Before: only MemAvailable was read, so under systemd-run -p MemoryMax=... (or in a container) the budget was + // the whole machine's and the checker could be killed by its own cgroup. + namespace fs = std::filesystem; + const fs::path root = fs::temp_directory_path() / ("lmg_test_" + std::to_string(::getpid())); + fs::remove_all(root); + write_file(root / "self", "0::/user.slice/app.scope\n"); + write_file(root / "cg/user.slice/memory.max", "10000\n"); + write_file(root / "cg/user.slice/memory.current", "4000\n"); // room 6000 + write_file(root / "cg/user.slice/app.scope/memory.max", "max\n"); // no limit of its own + write_file(root / "cg/user.slice/app.scope/memory.current", "3000\n"); + CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 6000); + write_file(root / "cg/user.slice/app.scope/memory.max", "5000\n"); // room 2000, the tighter one + CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 2000); + write_file(root / "cg/user.slice/app.scope/memory.current", "7000\n"); // over its limit: no room + CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == 0); + write_file(root / "self", "12:memory:/legacy\n"); // cgroup v1 only: no limit read + CHECK(leonida::cgroup_memory_room((root / "self").string(), (root / "cg").string()) == UINT64_MAX); + CHECK(leonida::cgroup_memory_room((root / "missing").string(), (root / "cg").string()) == UINT64_MAX); + fs::remove_all(root); + return 0; +} +#endif + +int main() { +#if defined(__linux__) + if (int r = cgroup_limits_are_read_up_the_tree()) return r; +#endif + if (int r = budget_and_count()) return r; + if (int r = oversized_module_still_gets_in_alone()) return r; + if (int r = max_inflight_zero_means_one()) return r; + if (int r = ticket_releases()) return r; + if (int r = threads_never_exceed_the_budget()) return r; + if (int r = estimate_and_memory_query()) return r; + std::puts("large_module_gate: ok"); + return 0; +} diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 58aae185b..7a4e10cfd 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -16,6 +17,7 @@ #include #include #include +#include #include #include "../shims/shims.h" @@ -1166,6 +1168,58 @@ void test_unwind_registration() { // An export whose address-table entry is past SizeOfImage (not a forwarder: outside the export directory) is // refused instead of being stored as base + rva, a pointer outside the mapping. +// The address-to-module lookup the shim registry uses (on every C++ throw from a mapped image, and for trace and +// stop lines) runs on whatever thread asks, while another thread may be inside load(). It used to walk the Loader's +// module vector with no lock while load() appended to it. Without the fix this fails for certain only under +// AddressSanitizer; here it checks that every answer given during 300 loads is right. +void test_lookup_during_loads() { + const char* what = "the address lookup is right while another thread loads modules"; + try { + rt::Loader loader(g_dir); + auto first = make_image(); + auto* first_nt = reinterpret_cast(first.data() + 0x80); + first_nt->OptionalHeader.ImageBase = 0x200000000ull; + rt::Module& anchor = loader.load(write_image(first)); + const uint64_t inside = reinterpret_cast(anchor.base) + 0x1004; + + std::atomic stop{false}; + std::atomic lookups{0}, wrong{0}; + std::thread reader([&] { + while (!stop.load()) { + uint64_t base = 0; + if (!rt::shims::mapped_image_base(inside, base) || base != reinterpret_cast(anchor.base)) + ++wrong; + if (rt::shims::module_offset(inside).find("+0x1004") == std::string::npos) ++wrong; + uint64_t none = 0; + if (rt::shims::mapped_image_base(0x10, none)) ++wrong; // in no image + ++lookups; + } + }); + unsigned loaded = 0; + for (unsigned i = 1; i <= 300; ++i) { + auto img = make_image(); + auto* nt = reinterpret_cast(img.data() + 0x80); + nt->OptionalHeader.ImageBase = 0x200000000ull + i * 0x10000ull; + rt::Module& m = loader.load(write_image(img)); + uint64_t base = 0; + if (rt::shims::mapped_image_base(reinterpret_cast(m.base) + 0x1000, base) && + base == reinterpret_cast(m.base)) + ++loaded; + } + while (lookups.load() < 1000) std::this_thread::yield(); + stop = true; + reader.join(); + if (wrong.load()) + failed(what, std::to_string(wrong.load()) + " wrong answers in " + std::to_string(lookups.load()) + " lookups"); + else if (loaded != 300) + failed(what, "only " + std::to_string(loaded) + " of 300 new modules were found by address"); + else + pass(what); + } catch (const std::exception& e) { + failed(what, e.what()); + } +} + void test_export_bounds() { auto outside = make_forwarder_image("KERNEL32.GetCurrentProcessId", 0x180000000); nt_of(outside)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sizeof(IMAGE_EXPORT_DIRECTORY); @@ -1273,6 +1327,7 @@ int main() { test_export_bounds(); test_tls_directory_count(); test_unwind_registration(); + test_lookup_during_loads(); } catch (const std::exception& e) { // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process. failed("writing the test images", e.what()); diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 2259cf5d3..75feecf15 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -1017,12 +1017,15 @@ int run_runner_child(const char* mode, unsigned long bytes) { int check_child_runner() { const char* label = "child runner"; ChildResult report; - ChildRun run = run_self(L"--child-flood 0", 30000); - EXPECT(run.end == ChildEnd::exited && run.exit_code == 0 && parse_diff_report(run.tail, report)); - EXPECT(report.ran == 1 && report.hr == 0 && report.removed == 0 && report.validation == 0); - // The first start and the first failed start make Windows load what it keeps for them (a failed CreateProcessW - // leaves 42 handles the first time on Windows 11 26200, none on every later one): both run once before the handle - // count is taken, and every case after it must leave the count as it was. + ChildRun run; + // The first two successful starts and the first failed start make Windows load and cache their persistent process + // handles (on Windows 11 26200, a second CreateProcessW caches the HKCU root key and a failed CreateProcessW keeps + // 41-42 AppCompat/PCA handles; later starts add none). Warm up both before reading handles_before. + for (int warmup = 0; warmup < 2; ++warmup) { + run = run_self(L"--child-flood 0", 30000); + EXPECT(run.end == ChildEnd::exited && run.exit_code == 0 && parse_diff_report(run.tail, report)); + EXPECT(report.ran == 1 && report.hr == 0 && report.removed == 0 && report.validation == 0); + } std::fprintf(stderr, "child runner: the next four errors are expected\n"); const std::wstring missing = self_path() + L".missing.exe"; run = run_process(missing.c_str(), L"", 5000); diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp index f3eb316c1..8de50299e 100644 --- a/runtime/test/replay_cpu_bench.cpp +++ b/runtime/test/replay_cpu_bench.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -276,11 +277,13 @@ bool uav_clear(CommandList& list, std::uint32_t index) { bool draw(CommandList& list, std::uint32_t index, bool indexed) { Draw d{}; d.pipeline = Scene::pipeline_id; - d.render_targets = {color_view}; + auto views = std::make_shared(); // out of line since D3D-391 + views->render_targets = {color_view}; d.depth = depth_view; const std::uint64_t base = Scene::geometry_va + (index % 256) * 65536ull; - d.vertex_buffers[0] = {base, 24576, 12}; // by input slot, inlined since D3D-289 - d.vertex_buffers[1] = {base + 24576, 16384, 8}; + views->vertex_buffers[0] = {base, 24576, 12}; // by input slot + views->vertex_buffers[1] = {base + 24576, 16384, 8}; + d.views = std::move(views); if (indexed) d.index = {base + 40960, 6144, 57}; d.topology = 4; // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST d.viewport = {0, 0, 1920, 1080, 0, 1}; @@ -577,7 +580,9 @@ int main(int argc, char** argv) { CommandList earlier, later; Draw plain{}; plain.pipeline = Scene::bare_id; - plain.render_targets = {color_view}; + auto plain_views = std::make_shared(); + plain_views->render_targets = {color_view}; + plain.views = std::move(plain_views); plain.topology = 4; plain.viewport = {0, 0, 1920, 1080, 0, 1}; plain.scissor = {0, 0, 1920, 1080}; diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp index df4e22718..e4a513676 100644 --- a/runtime/test/replay_query_predication_test.cpp +++ b/runtime/test/replay_query_predication_test.cpp @@ -5,7 +5,7 @@ // how resolves inside a pipeline-statistics query are replayed; cases 7 and 8 cover the other helper dispatches // and their no-pool fallback (D3D-162). Cases 9 to 13 check overlapping queries: statistics over statistics, binary // inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics -// queries, and the single-list refusal (D3D-252). No GPU or game data. +// queries, and the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). No GPU or game data. #include "../src/vulkan_replay.h" #include #include @@ -571,6 +571,54 @@ int main() { expect(trace.events.empty(), "no segment pool: nothing was emitted for the refused list"); } + // 14. D3D-399, the single-list replay() with a segment pool: the list case 13 refuses replays as on the batched + // path, and so does case 10's occlusion pair. The pools are created to the planned size and handed to `keep`. + { + Trace trace; + g_trace = &trace; + std::vector> created; + ReplayFunctions pooled = vk; + pooled.create_segment_pool = [&](VkQueryType type, std::uint32_t count) { + created.emplace_back(type, count); + auto pool = std::make_shared(); + pool->pool = handle(type == VK_QUERY_TYPE_OCCLUSION ? 8 : 9); + pool->destroy = mock_destroy_pool; + return std::shared_ptr(pool); + }; + CommandList statistics_list; // case 13's list + expect(statistics_list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "record pooled begin 0"); + expect(statistics_list.begin_query({6, d3d12_query::pipeline_statistics, 1}), "record pooled begin 1"); + expect(statistics_list.end_query({6, d3d12_query::pipeline_statistics, 0}), "record pooled end 0"); + expect(statistics_list.end_query({6, d3d12_query::pipeline_statistics, 1}), "record pooled end 1"); + expect(statistics_list.close(), "close pooled statistics list"); + CommandList occlusion_list; // case 10's list + expect(occlusion_list.begin_query({1, d3d12_query::occlusion, 0}), "record pooled occlusion begin"); + expect(occlusion_list.begin_query({1, d3d12_query::binary_occlusion, 1}), "record pooled binary begin"); + expect(occlusion_list.end_query({1, d3d12_query::binary_occlusion, 1}), "record pooled binary end"); + expect(occlusion_list.end_query({1, d3d12_query::occlusion, 0}), "record pooled occlusion end"); + expect(occlusion_list.resolve_queries({1, d3d12_query::occlusion, 0, 1, 1, 0}), "record pooled resolve"); + expect(occlusion_list.close(), "close pooled occlusion list"); + expect(replay(statistics_list, VK_NULL_HANDLE, resolve, pooled) == ReplayResult::unsupported && + replay(occlusion_list, VK_NULL_HANDLE, resolve, vk) == ReplayResult::unsupported && + created.empty() && trace.events.empty(), + "pooled: without `keep` or a pool both lists are still refused and no pool is made"); + std::vector> keep; + const auto r0 = replay(statistics_list, VK_NULL_HANDLE, resolve, pooled, nullptr, &keep); + const auto r1 = replay(occlusion_list, VK_NULL_HANDLE, resolve, pooled, nullptr, &keep); + expect(r0 == ReplayResult::success && r1 == ReplayResult::success, + "pooled: overlapping statistics and occlusion queries replay on the single-list path"); + const std::vector> sizes{{VK_QUERY_TYPE_PIPELINE_STATISTICS, 3}, + {VK_QUERY_TYPE_OCCLUSION, 3}}; + expect(created == sizes, "pooled: one pool of each type, sized to the planned segments"); + expect(keep.size() == 2, "pooled: both pools are handed to the caller"); + const std::vector want{"begin_query 9:0", "end_query 9:0", "begin_query 9:1", + "end_query 9:1", "begin_query 9:2", "end_query 9:2", + "begin_query 8:0", "end_query 8:0", "begin_query 8:1", + "end_query 8:1", "begin_query 8:2", "end_query 8:2", + "sum_occlusion 8:0+3"}; + expect(trace.events == want, "pooled: the same segments and sums as the batched path"); + } + if (failures) return 1; std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); return 0; diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp index 261004328..a5d90c141 100644 --- a/runtime/test/root_signature_oracle_test.cpp +++ b/runtime/test/root_signature_oracle_test.cpp @@ -25,6 +25,13 @@ void check(bool condition, const char* what) { if (!condition) ++g_failures; } +// One line per assertion: "case: what", so a failure names the signature and the field instead of just "false". +void check_named(bool condition, const char* name, const char* what) { + char line[256]; + std::snprintf(line, sizeof(line), "%s: %s", name, what); + check(condition, line); +} + struct Blobs { ID3DBlob* blob = nullptr; ID3DBlob* error = nullptr; @@ -70,6 +77,41 @@ bool parse_blob(ID3DBlob* blob, rt::rootsig::RootSignature& model) { return true; } +// Parses and logs "case: parses"; false means the caller must not index the model (that segfaulted CI). +bool parse_checked(ID3DBlob* blob, const char* name, rt::rootsig::RootSignature& model) { + const bool parsed = parse_blob(blob, model); + check_named(parsed, name, "parses"); + return parsed; +} + +// Serializes one synthetic desc and, on failure, prints the runtime's own complaint: that text is what tells a +// rejected flag apart from a rejected layout. +bool serialize_desc(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc, Blobs& out, const char* name) { + const HRESULT hr = D3D12SerializeVersionedRootSignature(&desc, &out.blob, &out.error); + check_named(hr == S_OK, name, "Microsoft serializer accepts it"); + if (hr != S_OK) { + if (out.error != nullptr) { + std::printf("serializer error: %s\n", + static_cast(out.error->GetBufferPointer())); + } + return false; + } + return true; +} + +// Every field of one static sampler, plus whether this root-signature version carries the 1.2 flags dword. +bool same_sampler(const rt::rootsig::StaticSampler& got, const D3D12_STATIC_SAMPLER_DESC1& want, bool flags) { + return got.filter == uint32_t(want.Filter) && got.address_u == uint32_t(want.AddressU) && + got.address_v == uint32_t(want.AddressV) && got.address_w == uint32_t(want.AddressW) && + got.mip_lod_bias == want.MipLODBias && got.max_anisotropy == want.MaxAnisotropy && + got.comparison_func == uint32_t(want.ComparisonFunc) && + got.border_color == uint32_t(want.BorderColor) && got.min_lod == want.MinLOD && + got.max_lod == want.MaxLOD && got.shader_register == want.ShaderRegister && + got.register_space == want.RegisterSpace && + got.visibility == static_cast(want.ShaderVisibility) && + got.flags == (flags ? uint32_t(want.Flags) : 0u); +} + } // namespace int main() { @@ -115,7 +157,9 @@ int main() { model.params[0].num_values == 4 && model.params[0].visibility == Visibility::Vertex, "oracle constants match"); - check(model.params[1].type == ParamType::Descriptor, + check(model.params[1].type == ParamType::Descriptor && + model.params[1].descriptor_register == 2 && + model.params[1].descriptor_space == 0, "oracle CBV matches"); const PackResult packed = pack(model); check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords"); @@ -213,17 +257,6 @@ int main() { params1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; params1[1].Descriptor = {5, 1, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE}; - const auto same_sampler = [](const StaticSampler& got, const D3D12_STATIC_SAMPLER_DESC1& want, bool flags) { - return got.filter == uint32_t(want.Filter) && got.address_u == uint32_t(want.AddressU) && - got.address_v == uint32_t(want.AddressV) && got.address_w == uint32_t(want.AddressW) && - got.mip_lod_bias == want.MipLODBias && got.max_anisotropy == want.MaxAnisotropy && - got.comparison_func == uint32_t(want.ComparisonFunc) && - got.border_color == uint32_t(want.BorderColor) && got.min_lod == want.MinLOD && - got.max_lod == want.MaxLOD && got.shader_register == want.ShaderRegister && - got.register_space == want.RegisterSpace && - got.visibility == static_cast(want.ShaderVisibility) && - got.flags == (flags ? uint32_t(want.Flags) : 0u); - }; // Ranges as the model should hold them: 1.0 has no range flags (0 in the model); 1.1 and 1.2 use range1. const auto same_ranges = [&](const std::vector& got, bool range_flags) { if (got.size() != 2) return false; @@ -242,19 +275,10 @@ int main() { bool sampler_flags) { const bool range_flags = version != Version::V1_0; Blobs out; - char what[160]; - const HRESULT result = D3D12SerializeVersionedRootSignature(&d, &out.blob, &out.error); - std::snprintf(what, sizeof(what), "%s: Microsoft serializer accepts it", name); - check(result == S_OK, what); - if (result != S_OK) { - if (out.error) std::printf("serializer error: %s\n", static_cast(out.error->GetBufferPointer())); - return; - } + if (!serialize_desc(d, out, name)) return; RootSignature got; - std::snprintf(what, sizeof(what), "%s: parses", name); - const bool parsed = parse_blob(out.blob, got); - check(parsed, what); - if (!parsed) return; + if (!parse_checked(out.blob, name, got)) return; + char what[160]; std::snprintf(what, sizeof(what), "%s: version, a two-range table, a root SRV and two samplers", name); check(got.version == version && got.params.size() == 2 && got.params[0].type == ParamType::Table && got.params[0].ranges.size() == 2 && got.params[0].ranges[0].range_type == 0 && @@ -291,6 +315,300 @@ int main() { v11.Desc_1_1 = {2, params1, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE}; serialize(v11, Version::V1_1, "1.1 with static samplers", false); + // An empty signature (no parameters, no samplers) is legal and is the shape of a bindless compute signature. + // It proves the header's count and offset words are believed when both are zero instead of being read as a + // truncated table, and the canonical codec has a model to keep. + D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty11{}; + empty11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + empty11.Desc_1_1 = {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + { + Blobs out; + RootSignature got; + if (serialize_desc(empty11, out, "1.1 empty") && parse_checked(out.blob, "1.1 empty", got)) { + check_named(got.version == Version::V1_1 && got.params.empty() && got.static_samplers.empty() && + got.flags == 0, + "1.1 empty", "version 1.1, no parameters, no samplers, flags 0"); + const std::vector bytes = encode_canonical(got); + const DecodeResult again = decode_canonical(bytes.data(), bytes.size()); + check_named(again.ok && again.sig.params.empty() && again.sig.static_samplers.empty() && + again.sig.flags == 0, + "1.1 empty", "canonical codec round-trips the empty model"); + } + } + + // Every root-signature flag that a signature with no parameters can legally carry, in one blob. A graphics + // signature sets ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT and a bindless one sets the heap-direct bits, so a parser + // that read the flags from the wrong header word would pick the other binding model without failing anywhere + // else. There are no parameters because the DENY_* bits are invalid next to a parameter any of those stages + // can see. + const uint32_t every_pc_flag = + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | + D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS | + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT | + D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC flagged11{}; + flagged11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + flagged11.Desc_1_1 = {0, nullptr, 0, nullptr, static_cast(every_pc_flag)}; + { + Blobs out; + RootSignature got; + if (serialize_desc(flagged11, out, "1.1 with every root-signature flag") && + parse_checked(out.blob, "1.1 with every root-signature flag", got)) { + check_named(got.flags == every_pc_flag, "1.1 with every root-signature flag", + "the whole PC flag word round-trips (heap-direct bits included)"); + const std::vector bytes = encode_canonical(got); + const DecodeResult again = decode_canonical(bytes.data(), bytes.size()); + check_named(again.ok && again.sig.flags == every_pc_flag, "1.1 with every root-signature flag", + "canonical codec keeps the flag word"); + } + } + + // A 1.0 signature with all three root view types and a table last. A root UAV opens most compute signatures, + // 1.0 root views have no flags dword, and the table last means its payload cannot be found by a fixed stride. + D3D12_DESCRIPTOR_RANGE view_range = + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 4, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}; + D3D12_ROOT_PARAMETER view_params[4]{}; + view_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + view_params[0].Descriptor = {2, 3}; + view_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + view_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + view_params[1].Descriptor = {5, 1}; + view_params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; + view_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + view_params[2].Descriptor = {7, 2}; + view_params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + view_params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + view_params[3].DescriptorTable = {1, &view_range}; + view_params[3].ShaderVisibility = D3D12_SHADER_VISIBILITY_GEOMETRY; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC views10{}; + views10.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + views10.Desc_1_0 = {4, view_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + { + Blobs out; + RootSignature got; + if (serialize_desc(views10, out, "1.0 root CBV, SRV and UAV with a table last") && + parse_checked(out.blob, "1.0 root CBV, SRV and UAV with a table last", got)) { + check_named(got.params.size() == 4 && + got.params[0].type == ParamType::Descriptor && + got.params[0].descriptor_register == 2 && got.params[0].descriptor_space == 3 && + uint32_t(got.params[0].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_ALL) && + got.params[1].type == ParamType::Descriptor && + got.params[1].descriptor_register == 5 && got.params[1].descriptor_space == 1 && + uint32_t(got.params[1].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_VERTEX) && + got.params[2].type == ParamType::Descriptor && + got.params[2].descriptor_register == 7 && got.params[2].descriptor_space == 2 && + uint32_t(got.params[2].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_PIXEL), + "1.0 root CBV, SRV and UAV with a table last", + "each root view type keeps its register, space and stage"); + check_named(got.params.size() == 4 && got.params[3].type == ParamType::Table && + uint32_t(got.params[3].visibility) == uint32_t(D3D12_SHADER_VISIBILITY_GEOMETRY) && + got.params[3].ranges.size() == 1 && + got.params[3].ranges[0].range_type == 0 && + got.params[3].ranges[0].num_descriptors == 4 && + got.params[3].ranges[0].offset_in_table == kRangeOffsetAppend, + "1.0 root CBV, SRV and UAV with a table last", + "the table after three views keeps its range"); + const PackResult packed_views = pack(got); + check_named(packed_views.ok && packed_views.dword_count == 8, + "1.0 root CBV, SRV and UAV with a table last", + "three views and a table use 8 user dwords in parameter order"); + } + } + + // 64 constants is the largest legal root-constant parameter and exactly fills the 64-dword D3D12 budget. It is + // legal D3D12 and impossible for the console's 32 user SGPRs, so the parse must recover all 64 and pack must + // refuse the signature by name instead of truncating every draw at 32. + D3D12_ROOT_PARAMETER1 huge_constants[1]{}; + huge_constants[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + huge_constants[0].Constants = {0, 1, 64}; + huge_constants[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC constants64{}; + constants64.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + constants64.Desc_1_1 = {1, huge_constants, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + { + Blobs out; + RootSignature got; + if (serialize_desc(constants64, out, "1.1 with 64 root constants") && + parse_checked(out.blob, "1.1 with 64 root constants", got)) { + check_named(got.params.size() == 1 && got.params[0].type == ParamType::Constants && + got.params[0].num_values == 64 && got.params[0].shader_register == 0 && + got.params[0].register_space == 1, + "1.1 with 64 root constants", + "all 64 constant dwords and the non-zero space survive"); + const PackResult packed_huge = pack(got); + check_named(!packed_huge.ok && packed_huge.error.find("spill") != std::string::npos, + "1.1 with 64 root constants", + "pack refuses 64 constants as spill instead of truncating"); + } + } + + // All eight D3D12 shader-visibility values in one signature, with the constant registers in descending order. + // The existing cases only reach ALL, VERTEX and PIXEL; a game with amplification and mesh shaders binds root + // parameters to stages 6 and 7, which no oracle case had put through the serializer before. + const D3D12_SHADER_VISIBILITY stages[8] = { + D3D12_SHADER_VISIBILITY_ALL, D3D12_SHADER_VISIBILITY_VERTEX, D3D12_SHADER_VISIBILITY_HULL, + D3D12_SHADER_VISIBILITY_DOMAIN, D3D12_SHADER_VISIBILITY_GEOMETRY, D3D12_SHADER_VISIBILITY_PIXEL, + D3D12_SHADER_VISIBILITY_AMPLIFICATION, D3D12_SHADER_VISIBILITY_MESH}; + D3D12_ROOT_PARAMETER1 staged_params[8]{}; + for (int i = 0; i < 8; ++i) { + staged_params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + staged_params[i].Constants = {static_cast(7 - i), 0, 1}; + staged_params[i].ShaderVisibility = stages[i]; + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC staged11{}; + staged11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + staged11.Desc_1_1 = {8, staged_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + { + Blobs out; + RootSignature got; + if (serialize_desc(staged11, out, "1.1 with all eight visibilities") && + parse_checked(out.blob, "1.1 with all eight visibilities", got)) { + bool stages_match = got.params.size() == 8; + for (uint32_t i = 0; stages_match && i < 8; ++i) { + stages_match = got.params[i].type == ParamType::Constants && + got.params[i].num_values == 1 && + got.params[i].shader_register == 7 - i && + uint32_t(got.params[i].visibility) == uint32_t(stages[i]); + } + check_named(stages_match, "1.1 with all eight visibilities", + "every stage value keeps its parameter and the descending registers stay in order"); + const PackResult packed_stages = pack(got); + check_named(packed_stages.ok && packed_stages.dword_count == 8, + "1.1 with all eight visibilities", + "eight single-dword constants pack in parameter order"); + } + } + + // Every descriptor range type, with an unbounded SRV range and a non-zero base register and space on each. + // Bindless signatures declare "all descriptors from here on" with NumDescriptors == UINT_MAX, and D3D12 forces + // sampler ranges into a table of their own (the serializer rejects a mixed table), so the signature carries two + // tables; a parser that treated UINT_MAX as an error or a signed count would lose the tail of every bindless + // table. + D3D12_DESCRIPTOR_RANGE1 resource_ranges[3] = { + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0xFFFFFFFFu, 0, 1, + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}, + {D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 2, 3, D3D12_DESCRIPTOR_RANGE_FLAG_NONE, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 8, 1, 2, + static_cast(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE | + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE), + 16}}; + D3D12_DESCRIPTOR_RANGE1 sampler_range = { + D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 4, 1, 4, D3D12_DESCRIPTOR_RANGE_FLAG_NONE, + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}; + D3D12_ROOT_PARAMETER1 range_params[2]{}; + range_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + range_params[0].DescriptorTable = {3, resource_ranges}; + range_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + range_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + range_params[1].DescriptorTable = {1, &sampler_range}; + range_params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC ranges11{}; + ranges11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + ranges11.Desc_1_1 = {2, range_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + { + Blobs out; + RootSignature got; + if (serialize_desc(ranges11, out, "1.1 with all four range types") && + parse_checked(out.blob, "1.1 with all four range types", got)) { + if (got.params.size() != 2 || got.params[0].ranges.size() != 3 || + got.params[1].ranges.size() != 1) { + check_named(false, "1.1 with all four range types", "two tables: three resources, one sampler"); + } else { + const std::vector& ranges = got.params[0].ranges; + check_named(ranges[0].range_type == 0 && ranges[0].num_descriptors == 0xFFFFFFFFu && + ranges[0].base_shader_register == 0 && ranges[0].register_space == 1 && + ranges[0].flags == D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE && + ranges[0].offset_in_table == kRangeOffsetAppend, + "1.1 with all four range types", + "unbounded SRV range keeps UINT_MAX, its space, flags and appended offset"); + check_named(ranges[1].range_type == 2 && ranges[1].num_descriptors == 1 && + ranges[1].base_shader_register == 2 && ranges[1].register_space == 3 && + ranges[1].flags == 0 && ranges[1].offset_in_table == 0, + "1.1 with all four range types", + "CBV range keeps base 2 space 3 and an explicit table offset of 0"); + check_named(ranges[2].range_type == 1 && ranges[2].num_descriptors == 8 && + ranges[2].base_shader_register == 1 && ranges[2].register_space == 2 && + ranges[2].flags == + uint32_t(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE | + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE) && + ranges[2].offset_in_table == 16, + "1.1 with all four range types", + "UAV range keeps the combined data and descriptor flags before offset 16"); + check_named(got.params[1].ranges[0].range_type == 3 && + got.params[1].ranges[0].num_descriptors == 4 && + got.params[1].ranges[0].base_shader_register == 1 && + got.params[1].ranges[0].register_space == 4 && + got.params[1].ranges[0].offset_in_table == kRangeOffsetAppend, + "1.1 with all four range types", + "the sampler table keeps its own range, base register and space"); + const std::vector bytes = encode_canonical(got); + const DecodeResult again = decode_canonical(bytes.data(), bytes.size()); + check_named(again.ok && again.sig.params.size() == 2 && + again.sig.params[0].ranges.size() == 3 && + again.sig.params[0].ranges[0].num_descriptors == 0xFFFFFFFFu && + again.sig.params[0].ranges[2].flags == + uint32_t(D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE | + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE) && + again.sig.params[1].ranges.size() == 1 && + again.sig.params[1].ranges[0].range_type == 3, + "1.1 with all four range types", + "canonical codec keeps the unbounded count, the flags and the second table"); + } + } + } + + // A shadow sampler: comparison filter, MIRROR_ONCE addressing, a non-zero min LOD and GEOMETRY visibility. The + // existing samplers are anisotropic and point-clamp, so no comparison filter or MIRROR_ONCE value reached the + // parser; the single root constant beside it uses a non-zero register and space, which the first case cannot + // distinguish from a swapped register/space read. + D3D12_STATIC_SAMPLER_DESC1 shadow_sampler{}; + shadow_sampler.Filter = D3D12_FILTER_COMPARISON_ANISOTROPIC; + shadow_sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE; + shadow_sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE; + shadow_sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE; + shadow_sampler.MipLODBias = 0.25f; + shadow_sampler.MaxAnisotropy = 16; + shadow_sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; + shadow_sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; + shadow_sampler.MinLOD = 0.5f; + shadow_sampler.MaxLOD = 12.0f; + shadow_sampler.ShaderRegister = 9; + shadow_sampler.RegisterSpace = 5; + shadow_sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_GEOMETRY; + const D3D12_STATIC_SAMPLER_DESC shadow_sampler0 = { + shadow_sampler.Filter, shadow_sampler.AddressU, shadow_sampler.AddressV, shadow_sampler.AddressW, + shadow_sampler.MipLODBias, shadow_sampler.MaxAnisotropy, shadow_sampler.ComparisonFunc, + shadow_sampler.BorderColor, shadow_sampler.MinLOD, shadow_sampler.MaxLOD, shadow_sampler.ShaderRegister, + shadow_sampler.RegisterSpace, shadow_sampler.ShaderVisibility}; + D3D12_ROOT_PARAMETER1 shadow_params[1]{}; + shadow_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + shadow_params[0].Constants = {3, 2, 1}; + shadow_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC shadow11{}; + shadow11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + shadow11.Desc_1_1 = {1, shadow_params, 1, &shadow_sampler0, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + { + Blobs out; + RootSignature got; + if (serialize_desc(shadow11, out, "1.1 with a comparison sampler") && + parse_checked(out.blob, "1.1 with a comparison sampler", got)) { + check_named(got.params.size() == 1 && got.params[0].type == ParamType::Constants && + got.params[0].num_values == 1 && got.params[0].shader_register == 3 && + got.params[0].register_space == 2, + "1.1 with a comparison sampler", + "one constant at b3 space 2 keeps every field"); + check_named(got.static_samplers.size() == 1 && + same_sampler(got.static_samplers[0], shadow_sampler, false), + "1.1 with a comparison sampler", + "comparison filter, MIRROR_ONCE, GEOMETRY and every other sampler field round-trip"); + } + } + // The 1.2 cases below need a host that serializes 1.2. Windows 10's built-in d3d12.dll stops at 1.1 and rejects // even an empty 1.2 description; their sampler flags have no 1.1 form, so they are skipped there. D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty12{}; diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 85d7a2b6a..ba8b4f9e2 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -2,6 +2,7 @@ // Huffman blocks, compressed from synthetic data with Python's zlib), the JSON reader, FSSM extraction from a // synthetic DXBC container, and index lookup by content hash. No game data. #include "../src/shader_library.h" +#include "test_temp_dir.h" #include #include @@ -343,7 +344,8 @@ int main() { CHECK(fssm_program(container({{dynamic, 600}, {fixed, 25}})) == bytes("hello hello hello leonida")); // An index with one findable shader, one without a hash, and the module next to it. - const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_test"; + const testfiles::ScratchDir scratch("leonida_shader_library_test"); + const auto& dir = scratch.path(); std::filesystem::create_directories(dir); const std::string hash = sha256_hex(skewed(600)); const std::string hash2 = sha256_hex(bytes("another program")); diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index b002201c9..ec9251dfa 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -16,8 +16,9 @@ are also what a shader reads through s_getpc_b64 (the code base) at that offset. The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container). The comment at the top of each .asm says which test program to run on the result and what it should print. -With LEONIDA_FMA=khr (or glsl), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs -VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77) or --fma glsl. +With LEONIDA_FMA=khr (or glsl, or exact), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs +VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77), --fma glsl, or --fma exact +(a single rounding built from plain f32 ops, for a driver that splits GLSL Fma and has no VK_KHR_shader_fma). With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and each gets a pass-through geometry shader, .bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR @@ -164,7 +165,7 @@ def translate_tests(work, names): cmd.append("--wave64-emulate") if os.environ.get("LEONIDA_BARY_FALLBACK") == "1": # raw barycentrics without VK_KHR_fragment_shader_barycentric cmd.append("--bary-fallback") - if os.environ.get("LEONIDA_FMA") in ("glsl", "khr"): # fused multiply-add as GLSL Fma (default) or OpFmaKHR + if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma (default), OpFmaKHR, or emulated cmd += ["--fma", os.environ["LEONIDA_FMA"]] if os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1": # f16 interpolation without PerVertexKHR (MoltenVK) cmd.append("--f16-interp-fallback") diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 330af9f4f..de286fa77 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -163,6 +163,8 @@ CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE]), ("cs_smem_bounds", [0, 0x5eed0010, 0x5eed000c, 0, 0x5eed000c, 0x5eed0010, 0, 0]), ("cs_smem_stride_align", [0x5eed0010, 0, 0, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0004]), + # SHADER-328: a constant SGPR offset gives what the run-time one gives (no 32-bit wrap) + ("cs_smem_sconst_off", [0, 0x5eed0018, 0x5eed0018, 0x5eed0014]), ("cs_smem_sload_neg", [0x5eed0004, 0x5eed0000, 0x5eed0004, 0x5eed0004, 0x5eed0008, 0x5eed000c, 0xeeeeeeee, 0xeeeeeeee]), ("cs_buf_tail", [0, 0x5eed000c, 0x5eed0008, 0x5eed000c, 0, 0, 0x5eed0010, 0]), @@ -364,6 +366,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000), "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000), + # far branches: s_getpc/s_add|s_sub/s_addc|s_subb/s_setpc forward, backward loops, conditional (.asm header) + "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000b), # 16-bit float v_cmp, all 16 predicates, e32 and e64 with swapped operands (.asm headers) "ps_vcmp_f16": (0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba), "ps_vcmp_f16_e64": (0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9), @@ -533,6 +537,19 @@ def run(*cmd, env=None): return r.returncode, r.stdout + r.stderr +def run_readback(path, launch, *args, **kwargs): + """Require this invocation to write its framebuffer before comparing it.""" + path = Path(path) + try: + path.unlink(missing_ok=True) + except OSError as err: + return 1, f"could not remove the previous readback {path.name}: {err}" + code, output = launch(*args, **kwargs) + if code == 0 and not path.is_file(): + return 1, f"{output.rstrip()}\nmissing readback: {path.name}".lstrip() + return code, output + + def failure(code, output, lines): details = "\n".join(output.strip().splitlines()[-lines:]) return f"exit {code}: {details or 'no test output'}" @@ -643,11 +660,11 @@ def mesh_v5_test(tools, spirv, raw): fs = Path(spirv) / "fs_passthru.spv" if not fs.is_file(): return "missing fs_passthru.spv" - code, out = run(os.path.join(tools, "vk_harness" + EXE), shader, fs, raw, "--mesh-group-readback", "2", "3", "4", - env=mesh_env(spirv, "ms_v5_workgroup")) + code, out = run_readback(raw, run, os.path.join(tools, "vk_harness" + EXE), shader, fs, raw, + "--mesh-group-readback", "2", "3", "4", env=mesh_env(spirv, "ms_v5_workgroup")) if code == UNSUPPORTED: return Skip("SKIP (mesh shading unavailable)") - if code or not raw.is_file(): + if code: return failure(code, out, 3) return check_mesh_v5(raw.read_bytes()) @@ -688,7 +705,9 @@ def narrow_subgroup_skip(out): def unpinned_subgroup_skip(out): """A Skip when vk_compute_test says the VKC_SUBGROUP_SIZE it was given can't be pinned on this device, else None. - Output without the line (an older vk_compute_test) is judged as before.""" + Output without the line (an older vk_compute_test) is judged as before. "compute subgroup size: 32 (observed: ...)" + (MoltenVK: not requirable, but its probe saw 32 lanes) is judged, and "observed wrong" comes with exit 1, a + failure.""" m = re.search(r"^compute subgroup size: (\d+) not available$", out, re.MULTILINE) if m: return Skip(f"SKIP (the device can't run this shader at {m.group(1)} lanes on request)") @@ -939,14 +958,17 @@ def bindless_test(tools, spirv, pixel="ps_tex"): # Samples with a16 coordinates after whole-VGPR arguments (gradients, a bias, a clamp). On the 8x8 gradient every # pixel must be the texel its own (u, v) reads. ps_texture_grad_cl_a16 draws on the two-mip texture instead, where its # clamp picks mip 0 left of x = 32 and mip 1 from there on. -GRADIENT_TESTS = ("ps_texture_grad_a16", "ps_texture_bias_a16", "ps_texture_grad_cl_a16") +GRADIENT_TESTS = ("ps_texture_grad_a16", "ps_texture_bias_a16", "ps_texture_grad_cl_a16", "ps_texture_cl", "ps_texture_b_cl") +# ps_texture_cl / ps_texture_b_cl (image_sample_cl / _b_cl) draw on the two-mip texture too: the left half reads mip 0 (red, +# the top-left quadrant), the right half mip 1 (cyan) where the clamp is 1. +CLAMP_TESTS = ("ps_texture_cl", "ps_texture_b_cl") def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_grad_a16") -> str: """Check every pixel of one of the GRADIENT_TESTS samples.""" vs = os.path.join(spirv, "vs_ids.spv") fs = os.path.join(spirv, name + ".spv") - two_mip = name == "ps_texture_grad_cl_a16" + two_mip = name == "ps_texture_grad_cl_a16" or name in CLAMP_TESTS with tempfile.TemporaryDirectory(prefix="leonida-texture-") as tmp: raw = Path(tmp) / "pixels.raw" code, out = run(os.path.join(tools, "vk_texture_test" + EXE), vs, fs, raw, @@ -963,7 +985,9 @@ def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_gr first = "" for index, pixel in enumerate(struct.iter_unpack("<4f", data)): x, y = index % 64, index // 64 - if two_mip: # mip 1 (cyan) where the clamp is 1, else mip 0's red and blue quadrants + if name in CLAMP_TESTS: # mip 1 (cyan) where the clamp is 1, else mip 0's top-left quadrant (red) + want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0) + elif two_mip: # mip 1 (cyan) where the clamp is 1, else mip 0's red and blue quadrants want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0) if y < 32 else (0.0, 0.0, 1.0, 1.0) else: want = (32 * (x // 8) / 255, 32 * (y // 8) / 255, 128 / 255, 1.0) diff --git a/runtime/test/shaders/cs_bvh.asm b/runtime/test/shaders/cs_bvh.asm index 92caa125f..465816a6c 100644 --- a/runtime/test/shaders/cs_bvh.asm +++ b/runtime/test/shaders/cs_bvh.asm @@ -1,6 +1,8 @@ ; image_bvh64_intersect_ray emulation: vk_compute_test writes an AMD-format BVH into the heap (box32 root 0x100 -> triangle -; z=10 node 0x40, triangle z=5 node 0x48, missed box, NaN box). Ray (0.25,0.25,0) +z. Run: vk_compute_test cs_bvh.spv 1 bvh -; -> box result 0x48 0x40 0xffffffff 0xffffffff (sorted), triangle result -10 -1 -0.25 -0.25 (t = 10, bary 0.25/0.25). +; z=10 node 0x40, triangle z=5 node 0x48, missed box, box 0x68 with a NaN min.x). Ray (0.25,0.25,0) +z. Run: +; vk_compute_test cs_bvh.spv 1 bvh +; -> box result 0x68 0x48 0x40 0xffffffff (sorted; RDNA2 skips the NaN plane and enters box 0x68 at t = 0, SHADER-650), +; triangle result -10 -1 -0.25 -0.25 (t = 10, bary 0.25/0.25). v_cmpx_eq_u32_e32 0, v0 v_mov_b32_e32 v1, 0x25 v_mov_b32_e32 v2, 0 diff --git a/runtime/test/shaders/cs_bvh32.asm b/runtime/test/shaders/cs_bvh32.asm index c73f6cd9d..4fe0f78e0 100644 --- a/runtime/test/shaders/cs_bvh32.asm +++ b/runtime/test/shaders/cs_bvh32.asm @@ -2,13 +2,15 @@ ; is 11 dwords: node, ray extent (t max), origin xyz, direction xyz, inverse direction xyz. The 64-bit form has the ; node's high dword after the low one, so read with that layout every operand here would be one register off. ; Same scene and ray as cs_bvh.asm: vk_compute_test writes an AMD-format BVH into the heap (box32 root at 0x100 -> -; triangle z=10 node 0x40, triangle z=5 node 0x48, a box the ray misses, a NaN box). Ray origin (0.25, 0.25, 0), -; direction +z, t max 100. Run: vk_compute_test cs_bvh32.spv 1 bvh -; Expected, from the "Ray tracing" row of docs/design.md (one traversal step, RADV's software box and triangle tests): +; triangle z=10 node 0x40, triangle z=5 node 0x48, a box the ray misses, a box with a NaN min.x). Ray origin +; (0.25, 0.25, 0), direction +z, t max 100. Run: vk_compute_test cs_bvh32.spv 1 bvh +; Expected, from the "Ray tracing" row of docs/design.md (one traversal step; the box test as measured on RDNA2, +; SHADER-650, and RADV's software triangle test): ; box node 0x25 (address 0x100 >> 3 | type 5): along +z the ray enters a box that contains its x and y at the ; box's near z, so child 0x40 (z = 10) at 10 and child 0x48 (z = 5) at 5. The third box lies at x in [5, 6], which -; the ray never reaches, and the fourth has a NaN corner: both give 0xffffffff. box_sort_enable (descriptor bit 63, -; set in s5) orders the children by entry distance: out[0..3] = 0x48 0x40 0xffffffff 0xffffffff. +; the ray never reaches: 0xffffffff. The fourth (0x68) has min.x = NaN; the hardware skips a NaN plane, so the box +; is x <= 1, y and z in [0, 1], which the ray is in at t = 0. box_sort_enable (descriptor bit 63, set in s5) orders +; the children by entry distance clamped to 0: out[0..3] = 0x68 0x48 0x40 0xffffffff (native gfx1030 gives the same). ; triangle node 0x40 (address 0x200, vertices (0,0,10) (1,0,10) (0,1,10)): the ray runs along z, so the vertices ; relative to the origin project onto xy unsheared: A = (-0.25, -0.25), B = (0.75, -0.25), C = (-0.25, 0.75). The ; edge functions are u = Cx By - Cy Bx = -0.5, v = Ax Cy - Ay Cx = -0.25 and w = Bx Ay - By Ax = -0.25, all of one diff --git a/runtime/test/shaders/cs_smem_sconst_off.asm b/runtime/test/shaders/cs_smem_sconst_off.asm new file mode 100644 index 000000000..1da78df89 --- /dev/null +++ b/runtime/test/shaders/cs_smem_sconst_off.asm @@ -0,0 +1,47 @@ +; SHADER-328: an s_buffer_load SGPR offset the translator can see as a constant gives what the same offset gives at run +; time. The rule (docs/design.md, Scalar/buffer memory): off = zext(soffset & ~3) + (imm & ~3) in 64 bits, and the +; dword is 0 when off + 4 > limit. #1686 folded a constant soffset as a 32-bit sum, so 0xfffffffc + 20 wrapped to 16 +; and read data; gfx1036 (tools/hw_oracle, #1686) reads 0. +; Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X and byte 0x60 with +; 4, then loads through a V# it builds itself (base 0x40, stride 0, NUM_RECORDS 0x40, word3 0x31016fac): +; s_buffer_load_dword s24, s8=-4 offset:20 (constant) -> 0xfffffffc + 0x14 > 0x40: 0 (32-bit wrap: 0x5eed0010) +; s_buffer_load_dword s25, s9=4 offset:20 (from heap 0x60) -> run time, in range: 0x5eed0018, as s26 +; s_buffer_load_dword s26, s10=4 offset:20 (constant) -> 0x18: 0x5eed0018 +; s_buffer_load_dword s27, s11=0x10 offset:4 (constant) -> 0x14: 0x5eed0014 +; and writes s24..s27 to out[0..3]. The run-time load stays in range: an out-of-range run-time sOFF (-4) made llvmpipe +; (Mesa 26.0.8) do the guarded load anyway and segfault (#1938 review); the CPU tests cover that path. +; Run: vk_compute_test cs_smem_sconst_off.spv 1 dump -> out[0..3] = 0x00000000 0x5eed0018 0x5eed0018 0x5eed0014. +v_cmpx_eq_u32_e32 0, v0 +v_mov_b32 v1, 0x5eed0000 +v_mov_b32 v2, 0x5eed0004 +v_mov_b32 v3, 0x5eed0008 +v_mov_b32 v4, 0x5eed000c +buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 +v_mov_b32 v1, 0x5eed0010 +v_mov_b32 v2, 0x5eed0014 +v_mov_b32 v3, 0x5eed0018 +v_mov_b32 v4, 0x5eed001c +buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 +v_mov_b32 v5, 4 +buffer_store_dword v5, off, s[0:3], 0 offset:96 +s_waitcnt vmcnt(0) +s_mov_b32 s4, 0x40 +s_mov_b32 s5, 0 +s_mov_b32 s6, 0x40 +s_mov_b32 s7, 0x31016fac +s_mov_b32 s8, -4 +s_buffer_load_dword s9, s[0:3], 0x60 +s_mov_b32 s10, 4 +s_mov_b32 s11, 0x10 +s_waitcnt lgkmcnt(0) +s_buffer_load_dword s24, s[4:7], s8 offset:0x14 +s_buffer_load_dword s25, s[4:7], s9 offset:0x14 +s_buffer_load_dword s26, s[4:7], s10 offset:0x14 +s_buffer_load_dword s27, s[4:7], s11 offset:0x4 +s_waitcnt lgkmcnt(0) +v_mov_b32 v1, s24 +v_mov_b32 v2, s25 +v_mov_b32 v3, s26 +v_mov_b32 v4, s27 +buffer_store_dwordx4 v[1:4], off, s[0:3], 0 +s_endpgm diff --git a/runtime/test/shaders/ps_far_branch.asm b/runtime/test/shaders/ps_far_branch.asm new file mode 100644 index 000000000..15f807291 --- /dev/null +++ b/runtime/test/shaders/ps_far_branch.asm @@ -0,0 +1,321 @@ +; Far branches: the idiom s_getpc_b64 s[a:a+1]; s_add_u32 sa, sa, K; s_addc_u32 sa+1, sa+1, 0|-1; s_setpc_b64 s[a:a+1] (and the +; s_sub_u32/s_subb_u32 form), which jumps beyond the +-32K dwords an s_branch reaches. docs/design.md "Far branches": the +; translator folds the four instructions into one branch. RDNA2 ISA: S_GETPC_B64 returns the address of the next +; instruction; S_ADD_U32 / S_ADDC_U32 add K to that 64-bit address (carry through SCC; the high word is 0 for a forward +; K and 0xffffffff, as -1, with K = 2^32 - |K| for a backward one; S_SUB_U32 / S_SUBB_U32 subtract |K|); S_SETPC_B64 +; sets PC. K is in bytes from the instruction after s_getpc. The block between a far branch and its target holds +; "poison" ORs that must never run, and 40 s_nop (4 bytes each, 160 bytes) so that K > 64 is a 32-bit literal. +; Sizes (bytes): s_nop 4, s_or_b32 with an inline constant 4, with a literal 8, s_add_u32/s_sub_u32/s_cmp with a literal 8. +; x (s10 = 1 to start): two forward far branches, one through s[4:5], one through s[8:9]: +; K = add (8) + addc (4) + setpc (4) + poison s_or literal (8) + 40 nops (160) = 184 = 0xb8, landing on "s_or s10, 2"; +; the poison ORs 0x100 / 0x200 are skipped, the targets OR 2 and 4: x = 1 | 2 | 4 = 0x00000007. +; y (s11 = 0): a backward loop with s_sub_u32 / s_subb_u32 (hi = 0). The body is s_add_u32 s11, 1 (4) + 40 nops (160) + +; s_cmp_ge_u32 s11, 3 (4) + s_cbranch_scc1 (4) + s_getpc (4) = 176 bytes from the loop top to the instruction after +; s_getpc, so K = 176 = 0xb0. The far branch back is taken after iterations 1 and 2 and not after iteration 3 +; (scc = 1 jumps over it), so s11 counts 3; then s_or s11, 0x10: y = 0x00000013. +; z (s12 = 0): a backward loop with s_add_u32 K / s_addc_u32 -1, K = -180 = 0xffffff4c: body s_add_u32 s12, 0x10 (4) + +; 40 nops (160) + s_cmp_ge_u32 s12, 0x50 (literal, 8) + s_cbranch_scc1 (4) + s_getpc (4) = 180. s12 steps by 0x10 and +; the loop leaves when s12 >= 0x50, after 5 iterations (the far branch back taken 4 times): s12 = 0x50, then +; s_or s12, 1: z = 0x00000051. +; w (s13 = 0): a far forward branch behind a conditional branch that skips it (s_cbranch_scc0 over the 5 dwords of the +; sequence), run twice. First scc = (s13 == 1) = 0: the sequence is skipped, the code after it runs: s13 |= 1, then +; the target ORs 2 (K = 8+4+4 + 4 + 160 = 180 = 0xb4), s13 = 3. Second scc = (s13 == 3) = 1: the sequence runs, it +; jumps over "s_or s13, 4" and the nops to the target: s13 |= 8: w = 0x0000000b. +; A translation that folded a far branch to the wrong target runs a poison OR (x gains 0x300), repeats or skips a +; loop iteration (y, z), or mishandles the conditional case (w). The loops count on s11/s12, so a wrong target shows +; as a different count, not just a hang. +; Expected mrt0 bits: 0x00000007, 0x00000013, 0x00000051, 0x0000000b +s_mov_b32 s10, 1 +s_getpc_b64 s[4:5] +s_add_u32 s4, s4, 184 +s_addc_u32 s5, s5, 0 +s_setpc_b64 s[4:5] +s_or_b32 s10, s10, 0x100 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_or_b32 s10, s10, 2 +s_getpc_b64 s[8:9] +s_add_u32 s8, s8, 184 +s_addc_u32 s9, s9, 0 +s_setpc_b64 s[8:9] +s_or_b32 s10, s10, 0x200 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_or_b32 s10, s10, 4 +s_mov_b32 s11, 0 +s_add_u32 s11, s11, 1 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_cmp_ge_u32 s11, 3 +s_cbranch_scc1 5 +s_getpc_b64 s[6:7] +s_sub_u32 s6, s6, 176 +s_subb_u32 s7, s7, 0 +s_setpc_b64 s[6:7] +s_or_b32 s11, s11, 0x10 +s_mov_b32 s12, 0 +s_add_u32 s12, s12, 0x10 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_cmp_ge_u32 s12, 0x50 +s_cbranch_scc1 5 +s_getpc_b64 s[8:9] +s_add_u32 s8, s8, 0xffffff4c +s_addc_u32 s9, s9, -1 +s_setpc_b64 s[8:9] +s_or_b32 s12, s12, 1 +s_mov_b32 s13, 0 +s_cmp_eq_u32 s13, 1 +s_cbranch_scc0 5 +s_getpc_b64 s[4:5] +s_add_u32 s4, s4, 180 +s_addc_u32 s5, s5, 0 +s_setpc_b64 s[4:5] +s_or_b32 s13, s13, 1 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_or_b32 s13, s13, 2 +s_cmp_eq_u32 s13, 3 +s_cbranch_scc0 5 +s_getpc_b64 s[4:5] +s_add_u32 s4, s4, 180 +s_addc_u32 s5, s5, 0 +s_setpc_b64 s[4:5] +s_or_b32 s13, s13, 4 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_nop 0 +s_or_b32 s13, s13, 8 +v_mov_b32_e32 v10, s10 +v_mov_b32_e32 v11, s11 +v_mov_b32_e32 v12, s12 +v_mov_b32_e32 v13, s13 +exp mrt0 v10, v11, v12, v13 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_m2_literal.asm b/runtime/test/shaders/ps_m2_literal.asm new file mode 100644 index 000000000..f77ef197f --- /dev/null +++ b/runtime/test/shaders/ps_m2_literal.asm @@ -0,0 +1,21 @@ +; M2 literal sampler: ps_m2.asm with its S# built from immediates instead of loaded from the sampler table, as game +; shaders do (docs/design.md, Literal samplers): CLAMP_LAST_TEXEL on all axes, bilinear min/mag, point mip, MAX_LOD +; 12. No heap slot names this S#, so the layer registers it when a pipeline uses the shader; otherwise the shader's +; hash lookup finds the fallback sampler. Run: d3d12_m2_textured_test. +; s[0:1] = console VA of the SRV table's first slot (the T#). attr0.xy = (u, v). mrt0 = the sampled texel. +; fssm-at: 0x10 +; fssm-data: 0x324d5350 0x4c544c20 +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_movk_i32 s16, 0x92 +s_mov_b32 s17, 0xc00000 +s_mov_b32 s18, 0x14500000 +s_mov_b32 s19, 0 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_sample_c.asm b/runtime/test/shaders/ps_sample_c.asm new file mode 100644 index 000000000..8d6616cdc --- /dev/null +++ b/runtime/test/shaders/ps_sample_c.asm @@ -0,0 +1,25 @@ +; Depth-compare sampling with implicit LOD: image_sample_c of an 8x8 D32 texture whose texel x holds depth (x + 0.5) / 8, +; reference 0.5 against a LESS_OR_EQUAL compare sampler (S# DEPTH_COMPARE_FUNC 3 at s[16:19]), at u, v from attr0 (a +; pixel shader, so the LOD comes from the derivatives: OpImageSampleDrefImplicitLod). Address v[4:6] = (z-compare, +; u, v). The same sample without and with d16; the d16 result (an f16 in the low half) is widened with v_cvt_f32_f16. +; The one-level texture makes the LOD 0 whatever the derivatives. mrt0 = (f32 result, widened d16 result, u, v). +; Run: vk_texture_test dref_c -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0 +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mov_b32_e32 v4, 0.5 +v_mov_b32_e32 v5, v2 +v_mov_b32_e32 v6, v3 +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_waitcnt lgkmcnt(0) +s_mov_b32 s16, 0x3092 +s_mov_b32 s17, 0xc00000 +s_mov_b32 s18, 0x14500000 +s_mov_b32 s19, 0 +image_sample_c v9, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D +image_sample_c v10, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 +s_waitcnt vmcnt(0) +v_cvt_f32_f16_e32 v11, v10 +exp mrt0 v9, v11, v2, v3 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_sample_c_b.asm b/runtime/test/shaders/ps_sample_c_b.asm new file mode 100644 index 000000000..ad86f20df --- /dev/null +++ b/runtime/test/shaders/ps_sample_c_b.asm @@ -0,0 +1,25 @@ +; Depth-compare sampling with a LOD bias: image_sample_c_b, as ps_sample_c with the bias 1.0 in front of the z-compare +; (address v[4:7] = bias, z-compare 0.5, u, v). A bias read as the reference (1.0 compares false everywhere) or the +; reference as the bias would change every result; on the one-level texture the bias itself has no other effect. +; mrt0 = (f32 result, widened d16 result, u, v). +; Run: vk_texture_test dref_c_b -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0 +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mov_b32_e32 v4, 1.0 +v_mov_b32_e32 v5, 0.5 +v_mov_b32_e32 v6, v2 +v_mov_b32_e32 v7, v3 +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_waitcnt lgkmcnt(0) +s_mov_b32 s16, 0x3092 +s_mov_b32 s17, 0xc00000 +s_mov_b32 s18, 0x14500000 +s_mov_b32 s19, 0 +image_sample_c_b v9, v[4:7], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D +image_sample_c_b v10, v[4:7], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 +s_waitcnt vmcnt(0) +v_cvt_f32_f16_e32 v11, v10 +exp mrt0 v9, v11, v2, v3 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_texture_b_cl.asm b/runtime/test/shaders/ps_texture_b_cl.asm new file mode 100644 index 000000000..ba8970667 --- /dev/null +++ b/runtime/test/shaders/ps_texture_b_cl.asm @@ -0,0 +1,23 @@ +; image_sample_b_cl: as ps_texture_cl with a LOD bias of 0.0 in front of the coordinates (address v[3:6] = bias, +; u / 4, v / 4, clamp), so the bias and the clamp each have to come from their own VGPR. Left half mip 0 (red), right +; half mip 1 (cyan). A bias read from the clamp's register (1.0) would still give cyan on the right but also move the +; left half to mip 1; the clamp read as the bias would never clamp. +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_waitcnt lgkmcnt(0) +s_mov_b32 s16, 0x92 +s_mov_b32 s17, 0xc00000 +s_mov_b32 s18, 0x14500000 +s_mov_b32 s19, 0 +v_cmp_le_f32_e32 vcc_lo, 0.5, v2 +v_mul_f32_e32 v4, 0.25, v2 +v_mul_f32_e32 v5, 0.25, v3 +v_mov_b32_e32 v3, 0 +v_cndmask_b32_e64 v6, 0, 1.0, vcc_lo +image_sample_b_cl v[8:11], v[3:6], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v8, v9, v10, v11 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_texture_cl.asm b/runtime/test/shaders/ps_texture_cl.asm new file mode 100644 index 000000000..932427c9d --- /dev/null +++ b/runtime/test/shaders/ps_texture_cl.asm @@ -0,0 +1,23 @@ +; image_sample_cl on vk_texture_test's two-mip texture (--two-mip: 128x128 quadrants, solid cyan mip 1) drawn on 64x64: +; the coordinates are u / 4, v / 4, so the unclamped LOD is -1 (mip 0, the top-left quadrant, red). The min-LOD clamp +; after the coordinates is 0.0 left of x = 32 and 1.0 from there on: the left half must read mip 0 (red), the right half +; mip 1 (cyan). A clamp read from the wrong register, or ignored, makes the right half red too. +; Address v[4:6] = (u / 4, v / 4, clamp); MinLod on an implicit-LOD sample (OpImageSampleImplicitLod ... MinLod). +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_waitcnt lgkmcnt(0) +s_mov_b32 s16, 0x92 +s_mov_b32 s17, 0xc00000 +s_mov_b32 s18, 0x14500000 +s_mov_b32 s19, 0 +v_cmp_le_f32_e32 vcc_lo, 0.5, v2 +v_mul_f32_e32 v4, 0.25, v2 +v_mul_f32_e32 v5, 0.25, v3 +v_cndmask_b32_e64 v6, 0, 1.0, vcc_lo +image_sample_cl v[8:11], v[4:6], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v8, v9, v10, v11 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_w64_a_discard.asm b/runtime/test/shaders/ps_w64_a_discard.asm new file mode 100644 index 000000000..b8f4c16a5 --- /dev/null +++ b/runtime/test/shaders/ps_w64_a_discard.asm @@ -0,0 +1,65 @@ +; SHADER-10 tier A (docs/design.md, "Wave64 graphics: partition invariance"): the early exit of a pixel kill. A wave64 +; pixel shader whose 32-lane halves can lose every pixel while the other half lives on gives the same image when its +; 64 lanes are cut into two 32-lane subgroups. x = floor(u * 64), y = floor(v * 64) are the pixel's coordinates on +; the 64x64 target (u, v = attr0.xy of vs_ids), so every expected word is a function of (x, y) and not of the lane +; the pixel landed on. +; Three kills, each `s_andn2_b64 live, live, ` then `s_cbranch_scc0` to its own exit block, which only +; sets EXEC from the (empty) live mask, exports null with done vm and ends (an exit shared by several kills reads a +; mask redefined behind the earlier votes: tier C tainted-exec, a stale scalar). The run side narrows EXEC into the +; whole quads of the live mask (s_wqm_b64, s_and_b64 exec) and never widens it. +; (1) x < 30, through v_cmpx (EXEC = the pixels to kill); (2) y >= 50, through VCC; (3) x % 4 == 3 and y odd +; ((y & 1) * 4 + (x & 3) == 7), through VCC. +; The first two discard large regions: whole waves and, at x = 30 and y = 50, halves whose pixels are all dead +; next to halves that live (for a wave tiled as 8x8 cut into 8x4 or 4x8 halves, among others). +; Before the export EXEC is narrowed to the live mask itself, so the helper lanes of the quads are discarded. +; Live pixel: r0 = 7 * y + x, r1 = 1, r2 = 2000 + y, r3 = x % 4 + 1. A discarded pixel keeps the harness clear +; value, -1.0f in every word (0xbf800000). +; Run: vk_harness vs_ids.spv ps_w64_a_discard.spv out.raw, once with VKH_SUBGROUP_SIZE=64 and once with 32: the two +; images must be equal (and equal to the expected words). Output is raw bits (r0, r1, r2, r3) per pixel. +; mattr: +wavefrontsize64,-wavefrontsize32 +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mul_f32_e32 v2, 0x42800000, v2 +v_mul_f32_e32 v3, 0x42800000, v3 +v_cvt_u32_f32_e32 v2, v2 +v_cvt_u32_f32_e32 v3, v3 +s_mov_b64 s[10:11], exec +s_mov_b64 s[20:21], exec +v_cmpx_gt_u32_e32 30, v2 +s_andn2_b64 s[20:21], s[20:21], exec +s_cbranch_scc0 34 +s_wqm_b64 s[22:23], s[20:21] +s_and_b64 exec, s[10:11], s[22:23] +v_cmp_lt_u32_e32 vcc, 49, v3 +s_andn2_b64 s[20:21], s[20:21], vcc +s_cbranch_scc0 25 +s_wqm_b64 s[22:23], s[20:21] +s_and_b64 exec, exec, s[22:23] +v_and_b32_e32 v4, 3, v2 +v_and_b32_e32 v5, 1, v3 +v_lshlrev_b32_e32 v5, 2, v5 +v_add_nc_u32_e32 v5, v5, v4 +v_cmp_eq_u32_e32 vcc, 7, v5 +s_andn2_b64 s[20:21], s[20:21], vcc +s_cbranch_scc0 12 +s_wqm_b64 s[22:23], s[20:21] +s_and_b64 exec, exec, s[22:23] +v_mul_u32_u24_e32 v6, 7, v3 +v_add_nc_u32_e32 v6, v6, v2 +v_mov_b32_e32 v7, 1 +v_add_nc_u32_e32 v8, 0x7d0, v3 +v_add_nc_u32_e32 v9, 1, v4 +s_and_b64 exec, exec, s[20:21] +exp mrt0 v6, v7, v8, v9 done vm +s_endpgm +s_mov_b64 exec, s[20:21] +exp null off, off, off, off done vm +s_endpgm +s_mov_b64 exec, s[20:21] +exp null off, off, off, off done vm +s_endpgm +s_mov_b64 exec, s[20:21] +exp null off, off, off, off done vm +s_endpgm diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py index cea4f29c0..64aa532b7 100644 --- a/runtime/test/shaders/w64_graphics.py +++ b/runtime/test/shaders/w64_graphics.py @@ -63,6 +63,16 @@ def _a_skip(i): return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 < 2), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1) +CLEAR = 0xBF800000 # the harness clears the target to -1.0f: the words of a pixel no shader wrote + + +def _a_discard(i): + x, y = _x(i), _y(i) + if x < 30 or y >= 50 or (x % 4 == 3 and y % 2 == 1): + return (CLEAR,) * 4 + return (7 * y + x, 1, 2000 + y, x % 4 + 1) + + def _b_waterfall(i): x, y = _x(i), _y(i) a = x % 4 + 4 * (y % 4) @@ -169,6 +179,7 @@ FIXTURES = { "ps_w64_a_permlane": ("A", _a_permlane, {}), "ps_w64_a_swizzle": ("A", _a_swizzle, {}), "ps_w64_a_bpermute": ("A", _a_bpermute, {}), + "ps_w64_a_discard": ("A", _a_discard, {}), "ps_w64_b_waterfall": ("B", _b_waterfall, {}), "ps_w64_b_readfirstlane": ("B", _b_readfirstlane, {"VKH_SGPRS": "0,0,0,0,123"}), "ps_w64_b_readlane_uniform": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}), diff --git a/runtime/test/test_runtime_types.cpp b/runtime/test/test_runtime_types.cpp index 1a0b5ed2a..a71deb000 100644 --- a/runtime/test/test_runtime_types.cpp +++ b/runtime/test/test_runtime_types.cpp @@ -525,18 +525,27 @@ void test_xmem_working_set_statistics_abi_layout() { check(ok != FALSE && pmc.WorkingSetSize > 0, "GetProcessMemoryInfo succeeds and returns non-zero WorkingSetSize"); - // Verify FidelityFX / XMem layout contract: - // stats[0..7] = 0 (unknown/reserved), stats[8..15] = WorkingSetSize (uint64_t) + // Verify FidelityFX / XMem layout contract (RT-220): + // The measured FSR sites establish argument shape, kind and the +8 working-set read; +0's title-total memory + // limit is inferred from other Series implementations (xcl, xbox-emulator). + // stats[0..7] = TotalMemoryLimit (uint64_t), stats[8..15] = WorkingSetSize (uint64_t) alignas(64) uint8_t stats[64]; std::memset(stats, 0xA5, sizeof(stats)); std::memset(stats, 0, 16); + MEMORYSTATUSEX ms{sizeof(ms)}; + uint64_t total_memory = 12ULL * 1024 * 1024 * 1024; + if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { + total_memory = ms.ullTotalPhys; + } + std::memcpy(stats + 0, &total_memory, sizeof(total_memory)); const uint64_t working_set = static_cast(pmc.WorkingSetSize); std::memcpy(stats + 8, &working_set, sizeof(working_set)); uint64_t prefix0 = 0; std::memcpy(&prefix0, stats, sizeof(prefix0)); - check(prefix0 == 0, "Working set statistics prefix at +0 is 0"); + check(prefix0 == total_memory && prefix0 >= working_set, + "Working set statistics total memory at +0 holds title memory limit >= working set"); uint64_t extracted_ws = 0; std::memcpy(&extracted_ws, stats + 8, sizeof(extracted_ws)); diff --git a/runtime/test/test_temp_dir.h b/runtime/test/test_temp_dir.h new file mode 100644 index 000000000..3601f35d0 --- /dev/null +++ b/runtime/test/test_temp_dir.h @@ -0,0 +1,67 @@ +// Scratch folders for tests that write files (a translator-style shader library, an index) under the temp directory. +// +// The folder name carries the process id. Under one fixed name, every copy of a test running at the same time (ctest +// -j, or two suites sharing one Wine prefix or one TMPDIR) used the same folder, and one copy's remove_all deleted the +// modules another copy was still loading: with four copies of d3d12_compute at once, 6 of 40 runs failed at PSO +// creation or in copy_file, while 125 runs one at a time all passed (Apple M3 Max, MoltenVK 1.4.3 under Wine 11). +#pragma once + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace testfiles { + +// /_: a folder no other running process uses. +inline std::filesystem::path process_temp_dir(std::string_view name) { +#ifdef _WIN32 + const long pid = long(_getpid()); +#else + const long pid = long(getpid()); +#endif + return std::filesystem::temp_directory_path() / (std::string(name) + "_" + std::to_string(pid)); +} + +// process_temp_dir(name), emptied and created on construction (a crashed run may have left the same name behind) and +// removed with its contents on destruction, so early returns don't leave one folder per failed run. +class ScratchDir { +public: + explicit ScratchDir(std::string_view name) : path_(process_temp_dir(name)) { + std::error_code ec; + std::filesystem::remove_all(path_, ec); + std::filesystem::create_directories(path_, ec); + if (ec) std::fprintf(stderr, "cannot create %s: %s\n", path_.string().c_str(), ec.message().c_str()); + } + ~ScratchDir() { + std::error_code ec; + std::filesystem::remove_all(path_, ec); + } + ScratchDir(const ScratchDir&) = delete; + ScratchDir& operator=(const ScratchDir&) = delete; + + const std::filesystem::path& path() const { return path_; } + +private: + std::filesystem::path path_; +}; + +// Copies `from` (a file the build compiled into the test, LEONIDA_TEST_*_SPV) to `to`, overwriting it. Returns false +// and says why when it can't: std::filesystem::copy_file would throw instead, and the uncaught exception ends the +// test without a message (abort; exit code 3 under Wine), which reads as a crash rather than a missing file. +inline bool copy_file(const std::filesystem::path& from, const std::filesystem::path& to) { + std::error_code ec; + std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec); + if (ec) std::fprintf(stderr, "cannot copy %s to %s: %s\n", from.string().c_str(), to.string().c_str(), + ec.message().c_str()); + return !ec; +} + +} // namespace testfiles diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp index cf32f094b..9769e70be 100644 --- a/runtime/test/vk_command_replay_test.cpp +++ b/runtime/test/vk_command_replay_test.cpp @@ -7,7 +7,8 @@ // Part F (D3D-26) runs immediate buffer writes, atomic copies and discards. Part G copies one subresource twice in one // list, which D3D12 orders on the queue and needs an explicit dependency for on Vulkan. Part H copies depth to colour // and back (D32_FLOAT <-> R32_FLOAT), which the replay stages through a scratch buffer. Part I resolves a depth -// rectangle (MIN) and checks that the texels around it keep their values. +// rectangle (MIN) and checks that the texels around it keep their values. Part J copies between disjoint regions +// of one texture subresource. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. #include "vk_test_device.h" #include "../src/vulkan_replay.h" @@ -1188,6 +1189,82 @@ int part_i(vktest::Device& d) { return 0; } +int part_j(vktest::Device& d) { + constexpr std::uint32_t width = 4, height = 2, pitch = texture_data_pitch_alignment; + constexpr VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; + const VkImage image = d.image(format, width, height, 1, 0); + void* upload_data = nullptr; + const VkBuffer upload = d.buffer(pitch * height, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &upload_data); + void* readback_data = nullptr; + const VkBuffer readback = d.buffer(width * height * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback_data); + EXPECT(image && upload && readback); + for (std::uint32_t y = 0; y < height; ++y) + std::memcpy(static_cast(upload_data) + pitch * y, (y ? green : red).data(), 4); + + constexpr ResourceId image_id = 40, upload_id = 41; + ResourceBinding image_binding{}, upload_binding{}; + image_binding.image = image; + image_binding.format = format; + image_binding.width = width; + image_binding.height = height; + upload_binding.buffer = upload; + upload_binding.size = pitch * height; + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { + if (id == image_id) return &image_binding; + if (id == upload_id) return &upload_binding; + return nullptr; + }; + LayoutTracker tracker; + tracker.track(image_id, image_binding, VK_IMAGE_LAYOUT_UNDEFINED); + ReplayFunctions vk{}; + vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); + vk.pipeline_barrier2 = d.fn("vkCmdPipelineBarrier2"); + vk.clear_color_image = d.fn("vkCmdClearColorImage"); + vk.copy_buffer = d.fn("vkCmdCopyBuffer"); + vk.copy_image_to_buffer = d.fn("vkCmdCopyImageToBuffer"); + vk.copy_buffer_to_image = d.fn("vkCmdCopyBufferToImage"); + vk.copy_image = d.fn("vkCmdCopyImage"); + + namespace a = d3d12_access; + namespace l = d3d12_layout; + namespace y = d3d12_sync; + const CopyLocation texture{image_id, false, 0, 0, 0, 0, 0, 0}; + const CopyLocation footprint{upload_id, true, 0, 0, 1, height, 1, pitch}; + const CopyBox column{0, 0, 0, 1, height, 1}; + const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0}; + CommandList first; + EXPECT(first.copy_texture({texture, 2, 0, 0, texture, true, column})); + EXPECT(first.close()); + CommandList list; + EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_dest, + l::common, l::copy_dest, image_id, all, 0})); + EXPECT(list.copy_texture({texture, 0, 0, 0, footprint, false, {}})); + EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source | a::copy_dest, + l::copy_dest, l::common, image_id, all, 0})); + EXPECT(list.copy_texture({texture, 1, 0, 0, texture, true, column})); // touching edges, not overlapping + EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source, + l::common, l::copy_source, image_id, all, 0})); + EXPECT(list.close()); + CommandList overlap; + EXPECT(overlap.copy_texture({texture, 1, 0, 0, texture, true, {0, 0, 0, 2, height, 1}})); + EXPECT(overlap.close()); + EXPECT(d.run([&](VkCommandBuffer cb) { + if (replay(overlap, cb, resolve, vk, &tracker) != ReplayResult::invalid_copy) return false; + if (replay(first, cb, resolve, vk, &tracker) != ReplayResult::success || + tracker.layout(image_id, 0) != VK_IMAGE_LAYOUT_GENERAL) return false; + if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false; + d.read_back(cb, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, width, height, 1, + readback, 0); + return true; + })); + const auto* pixels = static_cast(readback_data); + for (std::uint32_t y = 0; y < height; ++y) + for (std::uint32_t x = 0; x < width; ++x) + expect_rgba("J self-copy", pixels, y * width + x, x < 2 ? (y ? green : red) : Rgba{}); + std::printf("J: disjoint same-subresource copies, overlapping copy rejected\n"); + return 0; +} + } // namespace int main() { @@ -1199,7 +1276,7 @@ int main() { } EXPECT(status == vktest::DeviceStatus::ready); if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || - part_g(device) || part_h(device) || part_i(device)) + part_g(device) || part_h(device) || part_i(device) || part_j(device)) return 1; if (g_mismatches) return 1; if (device.validation_errors()) { diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp index 69e3bd014..f962cdff6 100644 --- a/runtime/test/vk_compute_test.cpp +++ b/runtime/test/vk_compute_test.cpp @@ -11,6 +11,11 @@ // and before the dispatch, so a program can read prepared inputs (a root table, descriptors, data) from the heap. // The file must fit in the buffer (raise VKC_OUT_WORDS); bytes past it keep the fill. // --require-wave64: require full 64-wide subgroups (local size X must be a multiple of 64), or exit 77. +// VKC_SUBGROUP_SIZE=N (env): run at N lanes. Where the device can't require a compute subgroup size but N is its +// default subgroupSize (MoltenVK: 32, and requiredSubgroupSizeStages 0), the size is still fixed for a SPIR-V 1.5 +// module (no varying subgroup size); cs_wave_probe.comp then checks, with the test's local size and flags, that every +// subgroup is N lanes wide (by its lane numbers and a ballot), or the test fails (exit 1) without running; N-lane +// subgroups not in invocation order print "not available", as a size that can't be pinned does. // VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#, // so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS. // Contract (docs/design.md): push constants = s0..s31 (128 bytes), heap base lo/hi, code base lo/hi (144 bytes). @@ -20,6 +25,7 @@ #include "vk_device_pick.h" #include "vk_shader_fma.h" #include "vk_pc_tail.h" +#include "cs_wave_probe_spv.h" #include #include @@ -54,6 +60,37 @@ static bool parse_u32(const char*& s, uint32_t& v) { return true; } +// The module's SPIR-V version and the OpExecutionMode LocalSize of its GLCompute entry point "main", the one the +// pipeline is made from. All zero when there is none (no such entry point, or LocalSizeId), and then the size is +// unknown: nothing that needs it (the subgroup probe, full subgroups) is done. +static uint32_t spirv_local_size(const std::vector& code, uint32_t local[3]) { + local[0] = local[1] = local[2] = 0; + const std::size_t n = code.size() / 4; + std::vector w(n); + if (n) std::memcpy(w.data(), code.data(), n * 4); + if (n < 5 || w[0] != 0x07230203u) return 0; + constexpr uint32_t kOpEntryPoint = 15, kOpExecutionMode = 16, kGLCompute = 5, kLocalSize = 17; + uint32_t main_id = 0; + bool have_main = false; + for (std::size_t i = 5; i < n;) { + const uint32_t len = w[i] >> 16, op = w[i] & 0xFFFFu; + if (!len || i + len > n) break; + // OpEntryPoint model id "name" ...: the name is a nul-terminated string packed little-endian into words. + if (op == kOpEntryPoint && len >= 4 && w[i + 1] == kGLCompute) { + const char* name = reinterpret_cast(&w[i + 3]); + if (std::strncmp(name, "main", 4 * (len - 3)) == 0 && std::memchr(name, 0, 4 * (len - 3))) { + main_id = w[i + 2]; + have_main = true; + } + } + if (op == kOpExecutionMode && len == 6 && have_main && w[i + 1] == main_id && w[i + 2] == kLocalSize) { + local[0] = w[i + 3]; local[1] = w[i + 4]; local[2] = w[i + 5]; + } + i += len; + } + return w[1]; +} + static bool next_item(const char*& s) { if (!*s) return true; return *s++ == ',' && *s; @@ -110,6 +147,10 @@ int main(int argc, char** argv) { } out_words = uint32_t(n); } + std::ifstream f(argv[1], std::ios::binary); + std::vector code((std::istreambuf_iterator(f)), {}); + uint32_t local[3]; + const uint32_t spirv_version = spirv_local_size(code, local); gipa = load_vulkan(); if (!gipa) return 1; #define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) @@ -166,19 +207,31 @@ int main(int argc, char** argv) { std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n"); return 77; } - std::ifstream f(argv[1], std::ios::binary); - std::vector code((std::istreambuf_iterator(f)), {}); const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64 if (needs_float64 && !f2q.features.shaderFloat64) { std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]); return 77; } + // A size the device can't require but runs anyway: one min..max range (fixed), or its default subgroupSize in a + // module below SPIR-V 1.6 (Vulkan "Varying Subgroup Size": SubgroupSize then always equals subgroupSize), which + // cs_wave_probe checks before the test runs (observed). Full subgroups where local size X is a multiple of + // maxSubgroupSize (VUID-VkPipelineShaderStageCreateInfo-flags-02759). + const bool fixed = req_sg && sgProps.minSubgroupSize == sgProps.maxSubgroupSize && subgroup.subgroupSize == req_sg; + const uint32_t local_total = local[0] * local[1] * local[2]; + // The probe itself needs subgroup operations in compute: the basic built-ins and a ballot. + const bool probe_runs = (subgroup.supportedStages & VK_SHADER_STAGE_COMPUTE_BIT) && + (subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT) && + (subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT); + const bool observed = req_sg && !require_wave64 && !can_request_size && !fixed && probe_runs && + subgroup.subgroupSize == req_sg && spirv_version && spirv_version < 0x00010600u && + local_total && local_total <= 1024; + const bool observed_full = observed && f13q.computeFullSubgroups && local[0] % sgProps.maxSubgroupSize == 0; VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; f12.bufferDeviceAddress = VK_TRUE; if (f13q.subgroupSizeControl || require_wave64) { f13.subgroupSizeControl = f13q.subgroupSizeControl; - f13.computeFullSubgroups = require_wave64 ? VK_TRUE : VK_FALSE; + f13.computeFullSubgroups = require_wave64 || observed_full ? VK_TRUE : VK_FALSE; f12.pNext = &f13; } VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; @@ -242,7 +295,7 @@ int main(int argc, char** argv) { if (!std::strcmp(argv[3], "bvh")) { // AMD-format BVH in the heap (runtime/test/shaders/cs_bvh.asm): box32 root at 0x100 whose children are a // triangle at z=10 (node 0x40, addr 0x200), a triangle at z=5 (node 0x48, addr 0x240), a box the ray - // misses, and an inactive (NaN) box. Node id = address >> 3 | type. + // misses, and a box with a NaN min.x that RDNA2 still enters at t = 0 (SHADER-650). Node id = address >> 3 | type. auto f32 = [&](uint32_t at, float v) { std::memcpy(static_cast(map) + at, &v, 4); }; auto u32 = [&](uint32_t at, uint32_t v) { std::memcpy(static_cast(map) + at, &v, 4); }; u32(0x100, 0x40); u32(0x104, 0x48); u32(0x108, 0x60); u32(0x10C, 0x68); @@ -290,7 +343,7 @@ int main(int argc, char** argv) { reqSg.requiredSubgroupSize = req_sg; if (can_request_size) cpi.stage.pNext = &reqSg; - if (require_wave64) + if (require_wave64 || observed_full) cpi.stage.flags = VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT; cpi.layout = pl; VkPipeline pipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &cpi, nullptr, &pipe)); @@ -298,9 +351,8 @@ int main(int argc, char** argv) { else if (req_sg) { // VKC_SUBGROUP_SIZE: say whether the pipeline really runs at that size, so a runner can skip a test the device // can't pin instead of judging words from whatever size the driver picked (#774). - const bool fixed = sgProps.minSubgroupSize == sgProps.maxSubgroupSize && subgroup.subgroupSize == req_sg; if (can_request_size || fixed) std::printf("compute subgroup size: %u\n", req_sg); - else std::printf("compute subgroup size: %u not available\n", req_sg); + else if (!observed) std::printf("compute subgroup size: %u not available\n", req_sg); } pc[0] = 0; pc[1] = 0; pc[2] = 0xFFFFFFFFu; pc[3] = 0x31016FACu; // V#: base 0, stride 0, num_records max, OOB_SELECT 3 (raw) @@ -311,6 +363,95 @@ int main(int argc, char** argv) { VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1; VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); + if (observed) { + // cs_wave_probe with the test's local size and flags, one group, four words per invocation in its own buffer. + VkBufferCreateInfo pbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + pbi.size = VkDeviceSize(local_total) * 16; + pbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + VkBuffer pbuf; CHECK(vkCreateBuffer(dev, &pbi, nullptr, &pbuf)); + VkMemoryRequirements pmr; vkGetBufferMemoryRequirements(dev, pbuf, &pmr); + VkMemoryAllocateInfo pmai = mai; + pmai.allocationSize = pmr.size; + VkDeviceMemory pmem; CHECK(vkAllocateMemory(dev, &pmai, nullptr, &pmem)); + CHECK(vkBindBufferMemory(dev, pbuf, pmem, 0)); + void* pmap; CHECK(vkMapMemory(dev, pmem, 0, pbi.size, 0, &pmap)); + std::memset(pmap, 0xEE, size_t(pbi.size)); + VkBufferDeviceAddressInfo pbai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + pbai.buffer = pbuf; + const uint64_t paddr = vkGetBufferDeviceAddress(dev, &pbai); + VkShaderModuleCreateInfo psmi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + psmi.codeSize = sizeof(leonida::vk_test::cs_wave_probe_spirv); + psmi.pCode = leonida::vk_test::cs_wave_probe_spirv; + VkShaderModule psm; CHECK(vkCreateShaderModule(dev, &psmi, nullptr, &psm)); + const VkSpecializationMapEntry entries[3] = {{0, 0, 4}, {1, 4, 4}, {2, 8, 4}}; + const VkSpecializationInfo spec{3, entries, sizeof(local), local}; + VkComputePipelineCreateInfo pcpi = cpi; + pcpi.flags = 0; + pcpi.stage.module = psm; + pcpi.stage.pSpecializationInfo = &spec; + VkPipeline ppipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pcpi, nullptr, &ppipe)); + const uint32_t ppc[2] = {uint32_t(paddr), uint32_t(paddr >> 32)}; // cs_wave_probe's buffer address + VkCommandBuffer pcmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &pcmd)); + VkCommandBufferBeginInfo pcbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + CHECK(vkBeginCommandBuffer(pcmd, &pcbi)); + vkCmdBindPipeline(pcmd, VK_PIPELINE_BIND_POINT_COMPUTE, ppipe); + vkCmdPushConstants(pcmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ppc), ppc); + vkCmdDispatch(pcmd, 1, 1, 1); + VkMemoryBarrier pread{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + pread.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + pread.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + vkCmdPipelineBarrier(pcmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, + 1, &pread, 0, nullptr, 0, nullptr); + CHECK(vkEndCommandBuffer(pcmd)); + VkSubmitInfo psi{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + psi.commandBufferCount = 1; psi.pCommandBuffers = &pcmd; + CHECK(vkQueueSubmit(q, 1, &psi, VK_NULL_HANDLE)); + CHECK(vkQueueWaitIdle(q)); + // Width first, from what each invocation reports: every subgroup has N lanes (one may have the rest of a + // group that isn't a multiple of N), each lane once, and a ballot of the subgroup counts them all. A wrong + // width fails the test. Then the order: the translator takes a wave32 lane as LocalInvocationIndex % N, so + // invocation l must be lane l % N of subgroup l / N. Vulkan doesn't promise that mapping; where it differs, + // the size is reported as not available, as on a device that can't give N at all (the runners skip). + const uint32_t* pw = static_cast(pmap); + const uint32_t subgroups = (local_total + req_sg - 1) / req_sg, tail = local_total % req_sg; + std::vector count(subgroups, 0), seen(std::size_t(subgroups) * req_sg, 0); + std::vector bad(local_total, false); + for (uint32_t l = 0; l < local_total; l++) { + const uint32_t* w = pw + 4 * l; + if (w[0] == req_sg && w[2] < subgroups && w[1] < req_sg && !seen[std::size_t(w[2]) * req_sg + w[1]]++) + count[w[2]]++; + else + bad[l] = true; + } + uint32_t wrong = 0, first = 0, misplaced = 0, first_misplaced = 0, partial = 0; + for (uint32_t c : count) + if (c != req_sg) partial++; + for (uint32_t l = 0; l < local_total; l++) { + const uint32_t* w = pw + 4 * l; + if (bad[l] || w[3] != count[w[2]]) { + if (!wrong++) first = l; + } + if ((w[1] != l % req_sg || w[2] != l / req_sg) && !misplaced++) first_misplaced = l; + } + if (!wrong && partial > (tail ? 1u : 0u)) wrong = partial; // e.g. two half-filled subgroups + if (wrong) { + const uint32_t* w = pw + 4 * first; + std::printf("compute subgroup size: %u observed wrong in %u of %u invocations; invocation %u has " + "SubgroupSize %u, lane %u, subgroup %u, a ballot of %u lanes\n", req_sg, wrong, local_total, + first, w[0], w[1], w[2], w[3]); + return 1; + } + if (misplaced) { + const uint32_t* w = pw + 4 * first_misplaced; + std::fprintf(stderr, "%u-lane subgroups, but not in invocation order: invocation %u is lane %u of " + "subgroup %u\n", req_sg, first_misplaced, w[1], w[2]); + // As where the size can't be pinned at all: say so, run the test, and let the runner skip it. + std::printf("compute subgroup size: %u not available\n", req_sg); + } else { + std::printf("compute subgroup size: %u (observed: all %u invocations of a %ux%ux%u group%s)\n", req_sg, + local_total, local[0], local[1], local[2], observed_full ? ", full subgroups" : ""); + } + } VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); @@ -432,7 +573,7 @@ int main(int argc, char** argv) { } } if (!std::strcmp(argv[3], "bvh")) { - const uint32_t want[8] = {0x48, 0x40, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xC1200000u, 0xBF800000u, 0xBE800000u, 0xBE800000u}; + const uint32_t want[8] = {0x68, 0x48, 0x40, 0xFFFFFFFFu, 0xC1200000u, 0xBF800000u, 0xBE800000u, 0xBE800000u}; for (int i = 0; i < 8; i++) if (out[i] != want[i]) { if (!bad) first_bad = i; bad++; } std::printf("bvh out = %08x %08x %08x %08x | %08x %08x %08x %08x\n", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); } diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 0312b48a4..a3e886d51 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -3,7 +3,8 @@ // pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash // table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants // sized from push_constant_bytes, default 144 or 128 with pc_tail): -// - cs: compute pipeline via vkCreateComputePipelines +// - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for +// descriptor-free shaders with the standard push-constant range // - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) // paired with minimal partner stubs from /stubs/ (generated by tools/spirv_stubs.py) // Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders @@ -11,7 +12,11 @@ // [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every // 10 minutes and at the end // --jobs N compile on up to N worker threads (default: half the hardware threads) -// --large-module-bytes N compile modules larger than N bytes alone (default: 4194304; 0 disables isolation) +// --large-module-bytes N modules larger than N bytes are "large" (default: 4194304; 0 disables the gate) +// --large-parallel N how many large modules may be in the driver at once: 0 (default) = as many as fit 3/4 of +// the memory available at start, at large_module_gate.h's estimate per module, up to --jobs, with the +// small ones compiling alongside; 1 = each large module alone, the other threads waiting (the +// behaviour before; also what 0 falls back to when the available memory can't be read) // --start I --count N check only index entries [I, I+N) (sorted by name) // --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running // --max-bytes N skip modules whose .spv is larger than N bytes (0 = no limit; names every skip) @@ -30,8 +35,10 @@ // --inflight-file F keep the modules that are in the driver in F, one "namephase" line each (phase: module // while vkCreateShaderModule runs, pipeline while its pipeline is created), so whoever ran the check // can tell which module was there when the process died. F is rewritten when a module over -// --large-module-bytes enters or leaves the driver (it is alone then, so F names exactly it) and by -// the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage reads it. +// --large-module-bytes enters or leaves the driver (with --large-parallel 1 it is alone then, so F +// names exactly it; otherwise F names every module in flight and make_game.py retries each alone) +// and by the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage +// reads it. // --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted // as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F // after a crash, so the next run checks everything else instead of dying on the same module. @@ -42,9 +49,12 @@ #include "vk_device_pick.h" #include "pipeline_cache_file.h" #include "pipeline_cache_snapshot.h" +#include "large_module_gate.h" #include "../src/spirv_words.h" +#include "../src/subgroup_size.h" #include +#include #include #include #include @@ -90,6 +100,10 @@ struct ShaderMeta { uint32_t lds_bytes = 0; uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144) uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0 + bool no_set0_bindings = false; + bool wave64 = false; + std::array local_size{1, 1, 1}; + std::string wave64_exchange; bool writes_depth = false; bool needs_maintenance8 = false; std::vector features; @@ -222,6 +236,22 @@ struct JsonParser { if (!error) fail("unterminated u32 array"); return out; } + void parse_local_size(std::array& out) { + if (!consume('[')) { skip_value(); return; } + for (size_t dim = 0; !error && i < s.size(); ++dim) { + if (consume(']')) return; + const char* start = s.data() + i; + skip_value(); + if (dim < out.size()) { + char* end = nullptr; + const double size = std::strtod(start, &end); + out[dim] = end == s.data() + i && size >= 0 && size <= UINT32_MAX ? uint32_t(size) : 0; + } + if (consume(']')) return; + if (!consume(',')) { fail("expected ',' or ']' in local size"); return; } + } + if (!error) fail("unterminated local size"); + } std::vector parse_str_array() { std::vector out; if (!consume('[')) { skip_value(); return out; } @@ -318,6 +348,25 @@ struct JsonParser { else if (k == "push_constant_bytes") m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes"); else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes(); + else if (k == "bindings") { + const size_t start = i; + m.no_set0_bindings = consume('[') && consume(']'); + if (!m.no_set0_bindings) { + i = start; + skip_value(); + } + } + else if (k == "wave64") { + ws(); + if (s.compare(i, 4, "true") == 0 || s.compare(i, 5, "false") == 0) m.wave64 = parse_bool(); + else skip_value(); + } + else if (k == "wave64_exchange") { + ws(); + if (i < s.size() && s[i] == '"') m.wave64_exchange = parse_string(); + else skip_value(); + } + else if (k == "local_size") parse_local_size(m.local_size); else if (k == "writes_depth") m.writes_depth = parse_bool(); else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); else if (k == "features") m.features = parse_str_array(); @@ -452,6 +501,13 @@ constexpr uint32_t required_push_bytes(uint32_t push_constant_bytes, uint32_t pc return raw > (std::numeric_limits::max() - 3u) ? raw : ((raw + 3u) & ~3u); } +constexpr uint32_t runtime_compute_push_bytes = 144; // sizeof(leonida::ShaderUserData) + +bool uses_runtime_compute_layout(const ShaderMeta& meta) { + return meta.stage == "cs" && meta.no_set0_bindings && !meta.pc_tail_bytes && + required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes) == runtime_compute_push_bytes; +} + static_assert(required_push_bytes(0, 0) == 144); static_assert(required_push_bytes(0, 16) == 128); static_assert(required_push_bytes(128, 0) == 128); @@ -588,7 +644,7 @@ int main(int argc, char** argv) { if (argc < 2) { std::fprintf(stderr, "usage: vk_pipeline_check [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " - "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] " + "[--max-bytes N] [--large-module-bytes N] [--large-parallel N] [--stage all|cs|graphics | --compute-only | --graphics-only] " "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] " "[--skip-file F]\n"); return 2; @@ -599,6 +655,7 @@ int main(int argc, char** argv) { uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2); size_t start = 0, count = 0, max_bytes = 0; size_t large_module_bytes = 4 * 1024 * 1024; + unsigned large_parallel = 0; // 0 = by the memory budget double slow = 30.0; std::string stage_filter = "all"; bool cache_feedback = false, isolate = false, iso_child = false; @@ -640,6 +697,7 @@ int main(int argc, char** argv) { else if (a == "--graphics-only") stage_filter = "graphics"; else if (a == "--max-bytes") valid = number(max_bytes); else if (a == "--large-module-bytes") valid = number(large_module_bytes); + else if (a == "--large-parallel") valid = number(large_parallel); else if (a == "--stats") valid = !(stats_path = value()).empty(); else if (a == "--inflight-file") valid = !(inflight_path = value()).empty(); else if (a == "--skip-file") valid = !(skip_path = value()).empty(); @@ -726,7 +784,8 @@ int main(int argc, char** argv) { if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string(); std::vector pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter, "--max-bytes", std::to_string(max_bytes), - "--large-module-bytes", std::to_string(large_module_bytes)}; + "--large-module-bytes", std::to_string(large_module_bytes), + "--large-parallel", std::to_string(large_parallel)}; if (cache_feedback) pass.push_back("--cache-feedback"); if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path}); struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; }; @@ -958,15 +1017,33 @@ int main(int argc, char** argv) { dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); VkDevice dev; if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } + leonida::SubgroupSizeCaps runtime_subgroups; + leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, pd, f13.subgroupSizeControl, + f13.computeFullSubgroups, runtime_subgroups); auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool { return f13.subgroupSizeControl && sg >= sgProps.minSubgroupSize && sg <= sgProps.maxSubgroupSize && (sgProps.requiredSubgroupSizeStages & bit); }; + auto runtime_compute_subgroup = [&](const ShaderMeta& meta) { + leonida::ShaderEntry entry; + entry.stage = meta.stage; + entry.subgroup_size = meta.subgroup_size; + entry.wave64 = meta.wave64; + entry.wave64_exchange = meta.wave64_exchange; + entry.local_size = meta.local_size; + return leonida::decide_subgroup_size(entry, runtime_subgroups); + }; { std::map> unforced_by_sg; for (const auto& [_, meta] : work) { + if (uses_runtime_compute_layout(*meta)) { + const auto request = runtime_compute_subgroup(*meta); + if (request.outcome == leonida::SubgroupOutcome::unavailable) + unforced_by_sg[request.wanted].insert(meta->stage); + continue; + } const VkShaderStageFlagBits bit = stage_bit(meta->stage); if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) { unforced_by_sg[meta->subgroup_size].insert(meta->stage); @@ -1097,6 +1174,20 @@ int main(int argc, char** argv) { const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes); return layouts.at({need_pc, meta.pc_tail_bytes != 0}); }; + VkPipelineLayout runtime_compute_layout = VK_NULL_HANDLE; + if (runtime_compute_push_bytes <= props.limits.maxPushConstantsSize && + std::any_of(work.begin(), work.end(), [](const Item& item) { + return uses_runtime_compute_layout(*item.second); + })) { + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, runtime_compute_push_bytes}; + VkPipelineLayoutCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + info.pushConstantRangeCount = 1; + info.pPushConstantRanges = &push; + if (VkResult r = vkCreatePipelineLayout(dev, &info, nullptr, &runtime_compute_layout)) { + std::fprintf(stderr, "runtime compute pipeline layout %d\n", r); + return 1; + } + } VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; std::vector seed; if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly @@ -1136,8 +1227,26 @@ int main(int argc, char** argv) { work.size(), lo, hi, stage_filter.c_str(), worker_count); std::mutex mu; // guards counters, stdout, stub cache and in-flight table - std::shared_mutex compile_gate; // large modules exclude other shader and pipeline work + std::shared_mutex compile_gate; // --large-parallel 1: large modules exclude other shader and pipeline work size_t isolated_modules = 0; + // Otherwise large modules share a memory budget and the small ones are never held back (large_module_gate.h). + const uint64_t available_memory = leonida::available_memory_bytes(); + const bool large_exclusive = large_parallel == 1 || (large_parallel == 0 && available_memory == 0); + leonida::LargeModuleGate large_gate( + large_parallel == 0 ? available_memory / 4 * 3 : UINT64_MAX, + large_parallel == 0 ? jobs : std::min(large_parallel, jobs)); + if (large_module_bytes) { + if (large_exclusive) + std::fprintf(stderr, "large modules (over %zu bytes): one at a time, the other threads waiting\n", + large_module_bytes); + else if (large_parallel == 0) + std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once within %.1f GB " + "(3/4 of the %.1f GB available)\n", large_module_bytes, large_gate.max_inflight(), + large_gate.budget() / 1e9, available_memory / 1e9); + else + std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once\n", large_module_bytes, + large_gate.max_inflight()); + } std::map modules_ok, modules_bad, big_skipped; std::map stats; std::map stub_cache; @@ -1234,7 +1343,7 @@ int main(int argc, char** argv) { VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) { std::lock_guard g(mu); inflight.erase(std::this_thread::get_id()); - if (inflight.empty()) write_inflight(); // a large module just finished (it compiles alone) + if (inflight.empty()) write_inflight(); // a large module just finished (alone with --large-parallel 1) auto& st = stats[stage]; st.seconds += sec; if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; } @@ -1310,12 +1419,18 @@ int main(int argc, char** argv) { const bool isolated = large_module_bytes && std::cmp_greater(file_size, large_module_bytes); std::unique_lock exclusive(compile_gate, std::defer_lock); std::shared_lock parallel(compile_gate, std::defer_lock); - if (isolated) exclusive.lock(); - else if (large_module_bytes) parallel.lock(); + leonida::LargeModuleGate::Ticket large_ticket; // left after the module and its pipeline are gone + if (large_exclusive) { + if (isolated) exclusive.lock(); + else if (large_module_bytes) parallel.lock(); + } else if (isolated) { + large_ticket = leonida::LargeModuleGate::Ticket(large_gate, + leonida::large_module_estimate(file_size)); + } { // in flight from here: vkCreateShaderModule can also take long or die in the driver std::lock_guard g(mu); inflight[std::this_thread::get_id()] = {name, std::chrono::steady_clock::now(), "module"}; - if (isolated) write_inflight(); // alone in flight: the file names exactly this module + if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1) } const auto code = leonida::read_spirv_words(f, file_size); @@ -1338,15 +1453,23 @@ int main(int argc, char** argv) { if (!miss.empty()) { record_skip(name, stage, miss); } else { - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{ - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO}; - reqSg.requiredSubgroupSize = meta.subgroup_size; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{}; VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main"; - const bool sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT); - if (sg_forced) cpi.stage.pNext = &reqSg; - cpi.layout = layout_for(meta); + bool sg_forced = false; + if (uses_runtime_compute_layout(meta)) { + const auto request = runtime_compute_subgroup(meta); + leonida::apply_subgroup_request(request, reqSg, cpi.stage); + sg_forced = request.size != 0; + cpi.layout = runtime_compute_layout; + } else { + reqSg.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO; + reqSg.requiredSubgroupSize = meta.subgroup_size; + sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT); + if (sg_forced) cpi.stage.pNext = &reqSg; + cpi.layout = layout_for(meta); + } cpi.flags = capture; // Only whole-pipeline feedback is reported. VkPipelineCreationFeedback fb{}; @@ -1357,7 +1480,7 @@ int main(int argc, char** argv) { { std::lock_guard g(mu); inflight[std::this_thread::get_id()] = {name, t0, "pipeline"}; - if (isolated) write_inflight(); // alone in flight: the file names exactly this module + if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1) } VkPipeline p = VK_NULL_HANDLE; maybe_simulate_crash(name); @@ -1531,7 +1654,7 @@ int main(int argc, char** argv) { { std::lock_guard g(mu); inflight[std::this_thread::get_id()] = {name, t0, "pipeline"}; - if (isolated) write_inflight(); // alone in flight: the file names exactly this module + if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1) } VkPipeline p = VK_NULL_HANDLE; maybe_simulate_crash(name); @@ -1658,7 +1781,8 @@ int main(int argc, char** argv) { std::printf("; checked %zu of %zu\n", work.size() - big_total, work.size()); } if (isolated_modules) - std::printf("large modules checked exclusively: %zu (over %zu bytes)\n", isolated_modules, + std::printf("large modules checked %s: %zu (over %zu bytes)\n", + large_exclusive ? "exclusively" : "within the memory budget", isolated_modules, large_module_bytes); std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count); const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp index c26703ef5..3834c5c08 100644 --- a/runtime/test/vk_presenter_sync_test.cpp +++ b/runtime/test/vk_presenter_sync_test.cpp @@ -6,6 +6,7 @@ // A failed capture fence wait also leaves the caller's outputs untouched. // 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's // resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks. +// 4. A swapchain-destroy WSI layer which calls vkDeviceWaitIdle cannot overlap vkQueueSubmit on another thread. // Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN @@ -58,6 +59,8 @@ PFN_vkQueuePresentKHR real_present = nullptr; PFN_vkWaitForFences real_wait = nullptr; PFN_vkCmdPipelineBarrier real_barrier = nullptr; PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; +PFN_vkDestroySwapchainKHR real_destroy_swapchain = nullptr; +PFN_vkDeviceWaitIdle real_device_wait_idle = nullptr; std::atomic fail_next_submit{VK_SUCCESS}; std::atomic fail_next_wait{VK_SUCCESS}; @@ -66,9 +69,36 @@ std::atomic observe_capture{false}; std::atomic saw_capture_waw{false}; std::atomic capture_copies{0}; std::atomic capture_waw_barriers{0}; +std::atomic check_swapchain_destroy{false}; +std::atomic destroy_entered{false}; +std::atomic submit_entered{false}; +std::atomic overlap_detected{false}; +std::atomic unexpected_submit_error{false}; +std::mutex destroy_mutex; +std::condition_variable destroy_cv; +bool allow_destroy_finish = false; + +// Synthetic WSI layer: a destroy hook initiates vkDeviceWaitIdle, as a capture layer may do internally. +// Holding the hook behind a condition variable makes the concurrency window deterministic rather than dependent +// on the installed capture software or validation logging overhead. Only the test hook waits on this condition. +VKAPI_ATTR void VKAPI_CALL destroy_swapchain(VkDevice device, VkSwapchainKHR swapchain, + const VkAllocationCallbacks* alloc) { + if (check_swapchain_destroy.load(std::memory_order_relaxed)) { + destroy_entered.store(true, std::memory_order_release); + destroy_cv.notify_all(); + { + std::unique_lock lock(destroy_mutex); + destroy_cv.wait(lock, [] { return allow_destroy_finish; }); + } + overlap_detected.store(submit_entered.load(std::memory_order_acquire), std::memory_order_release); + if (real_device_wait_idle(device) != VK_SUCCESS) unexpected_submit_error.store(true); + } + real_destroy_swapchain(device, swapchain, alloc); +} VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) { + submit_entered.store(true, std::memory_order_release); const VkResult armed = fail_next_submit.exchange(VK_SUCCESS); if (armed != VK_SUCCESS) return armed; return real_submit(queue, count, submits, fence); @@ -124,6 +154,7 @@ VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { const std::string_view n = name; + if (n == "vkDestroySwapchainKHR") return reinterpret_cast(destroy_swapchain); if (n == "vkQueueSubmit") return reinterpret_cast(queue_submit); if (n == "vkQueuePresentKHR") return reinterpret_cast(queue_present); if (n == "vkWaitForFences") return reinterpret_cast(wait_for_fences); @@ -140,6 +171,8 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) { real_get_instance = instance_proc; real_get_device = reinterpret_cast(instance_proc(instance, "vkGetDeviceProcAddr")); + real_destroy_swapchain = reinterpret_cast(real_get_device(device, "vkDestroySwapchainKHR")); + real_device_wait_idle = reinterpret_cast(real_get_device(device, "vkDeviceWaitIdle")); real_submit = reinterpret_cast(real_get_device(device, "vkQueueSubmit")); real_present = reinterpret_cast(real_get_device(device, "vkQueuePresentKHR")); real_wait = reinterpret_cast(real_get_device(device, "vkWaitForFences")); @@ -350,6 +383,59 @@ int main() { EXPECT(!worker_failed.load()); EXPECT(queue.idle() && worker_queue.idle()); std::printf("presenter sync: concurrent present + queue.execute + tracker mutations ok\n"); + + // 4. Emulate a WSI capture layer that performs device-idle inside vkDestroySwapchainKHR. + // The presenter first enters the destroy hook; a second thread then attempts a real queue submission. + // Once the hook is released, that submission must not have entered the Vulkan driver while the hook ran. + driver::destroy_entered.store(false); + driver::submit_entered.store(false); + driver::overlap_detected.store(false); + driver::unexpected_submit_error.store(false); + { + std::lock_guard lock(driver::destroy_mutex); + driver::allow_destroy_finish = false; + } + driver::check_swapchain_destroy.store(true); + VkResult recreated = VK_ERROR_UNKNOWN; + std::thread destroy_thread([&] { recreated = presenter.present(1, true); }); + bool entered = false; + { + std::unique_lock lock(driver::destroy_mutex); + entered = driver::destroy_cv.wait_for(lock, std::chrono::seconds(5), + [] { return driver::destroy_entered.load(); }); + } + std::atomic submit_started{false}; + ReplayResult submit_result = ReplayResult::unsupported; + std::thread submit_thread; + if (entered) { + submit_thread = std::thread([&] { + submit_started.store(true); + CommandList list; + if (!list.clear_render_target({1, 0, 0, 1}, {0.3f, 0.2f, 0.1f, 1.0f}) || !list.close()) return; + const CommandList* ptr = &list; + submit_result = worker_queue.execute({&ptr, 1}); + }); + for (int attempt = 0; attempt < 100 && !submit_started.load(); ++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + // Give the competing thread time to reach the submit point if no mutex is protecting destruction. + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + { + std::lock_guard lock(driver::destroy_mutex); + driver::allow_destroy_finish = true; + } + driver::destroy_cv.notify_all(); + destroy_thread.join(); + if (submit_thread.joinable()) submit_thread.join(); + driver::check_swapchain_destroy.store(false); + EXPECT(entered); + EXPECT(recreated == VK_SUCCESS); + EXPECT(submit_started.load()); + EXPECT(submit_result == ReplayResult::success); + EXPECT(!driver::overlap_detected.load()); + EXPECT(!driver::unexpected_submit_error.load()); + EXPECT(queue.idle() && worker_queue.idle()); + std::printf("presenter sync: synthetic WSI device-idle during swapchain destruction serialized ok\n"); } DestroyWindow(window); diff --git a/runtime/test/vk_queue_test.cpp b/runtime/test/vk_queue_test.cpp index 84289198c..9df720356 100644 --- a/runtime/test/vk_queue_test.cpp +++ b/runtime/test/vk_queue_test.cpp @@ -61,7 +61,33 @@ int check_picker() { const auto q = pick_queue_families(f, 0); EXPECT(q.copy == 2); } - std::printf("queue family picker: 4 layouts ok\n"); + // D3D12 tile mapping is legal on all queue kinds. Dedicated async queues that cannot + // bind sparse pages must use the graphics family when sparse buffers are offered. + { + constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT; + const std::array f{fam(G | S), fam(T), fam(C)}; + const auto preferred = pick_queue_families(f, 0); + EXPECT(preferred.compute == 2 && preferred.copy == 1); + const auto corrected = sparse_capable_queue_families(f, preferred, true); + EXPECT(corrected.direct == 0 && corrected.compute == 0 && corrected.copy == 0); + const auto no_sparse = sparse_capable_queue_families(f, preferred, false); + EXPECT(no_sparse.compute == 2 && no_sparse.copy == 1); + } + { + constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT; + const std::array f{fam(G | S), fam(T | S), fam(C | S)}; + const auto preferred = pick_queue_families(f, 0); + const auto corrected = sparse_capable_queue_families(f, preferred, true); + EXPECT(corrected.compute == 2 && corrected.copy == 1); // preserve dedicated queues + } + { + constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT; + const std::array f{fam(G | S), fam(T), fam(C | S)}; + const auto preferred = pick_queue_families(f, 0); + const auto corrected = sparse_capable_queue_families(f, preferred, true); + EXPECT(corrected.compute == 2 && corrected.copy == 0); // mixed capabilities + } + std::printf("queue family picker: 7 layouts ok\n"); return 0; } diff --git a/runtime/test/vk_sandbox.cpp b/runtime/test/vk_sandbox.cpp new file mode 100644 index 000000000..b5de7bd13 --- /dev/null +++ b/runtime/test/vk_sandbox.cpp @@ -0,0 +1,734 @@ +// Real-shader sandbox: draws a tools/sandbox_scene.py scene through two translated game shaders. +// +// vk_sandbox --out [--size W H] [--cam x y z yaw pitch] [--fov deg] +// vk_sandbox --window [--size W H] [--cam ...] [--mode fly|walk|drive] (Windows only) +// --window --frames N --out : test run, the window shows without activation and quits after N frames +// +// The pair (chosen by tools/sandbox.py) is a transform VS with POSITION/NORMAL/TEXCOORD inputs and a textured PS, both reading user SGPR 8: +// a 32-bit pointer (high dword forced to 0) to one table of descriptors in the heap, laid out as the shaders load it: +// +0x00 V# of the object constants: world rows 0..2 at 0x00/0x10/0x20, translation at 0x30 +// +0x20 T# of the albedo texture (8 dwords) +// +0x40 V# of the view constants: light direction at 0xa0, view-projection rows at 0x160 (row-vector convention) +// +0x60 V# of the colour constants: rgba at 0x00 +// Every draw gets its own table and object constants; view and colour constants are shared. The PS samples with the +// S# literal in its own code, so the sampler is built from those words (gfx10::decode). Nothing here is game data: +// the scene file and the shaders come from the user's work folder. +// +// Window keys (only while the window has focus): WASD move, mouse with the right button held looks, Q/E down/up, +// Shift faster, 1 fly, 2 walk (eye 1.7 m over the ground under the camera), 3 drive (eye 1.2 m, accelerates), +// P writes sandbox_shot.ppm, Esc quits. +#define VK_NO_PROTOTYPES +#ifdef _WIN32 +#define VK_USE_PLATFORM_WIN32_KHR +#include +#endif +#include "vulkan_loader.h" +#include "vk_device_pick.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../src/descriptor_table.h" +#include "../src/gfx10_descriptors.h" + +static PFN_vkGetInstanceProcAddr gipa; +#define CHECK(x) \ + do { \ + VkResult r_ = (x); \ + if (r_ != VK_SUCCESS) { \ + std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ + return 1; \ + } \ + } while (0) + +namespace { + +struct Texture { uint32_t w, h; std::vector rgba; }; +struct Mesh { uint32_t first_vertex, vertex_count, first_index, index_count; }; +struct Draw { uint32_t mesh; int32_t texture; float rows[4][3]; }; +struct Scene { + std::vector textures; + std::vector meshes; + std::vector draws; + std::vector vertices; // 8 floats each + std::vector indices; + float center[3]; +}; + +bool load_scene(const char* path, Scene& s) { + std::ifstream f(path, std::ios::binary | std::ios::ate); + const uint64_t file_size = f ? uint64_t(f.tellg()) : 0; + f.seekg(0); + char magic[4]; + uint32_t hdr[4]; + if (!f.read(magic, 4) || std::memcmp(magic, "LSB1", 4) || !f.read(reinterpret_cast(hdr), 16) || + hdr[0] != 1 || !f.read(reinterpret_cast(s.center), 12)) + return false; + for (uint32_t i = 0; i < hdr[1]; ++i) { + Texture t; + f.read(reinterpret_cast(&t.w), 4).read(reinterpret_cast(&t.h), 4); + if (!f || !t.w || !t.h || t.w > 16384 || t.h > 16384 || uint64_t(t.w) * t.h * 4 > file_size) return false; + t.rgba.resize(size_t(t.w) * t.h * 4); + f.read(reinterpret_cast(t.rgba.data()), std::streamsize(t.rgba.size())); + s.textures.push_back(std::move(t)); + } + for (uint32_t i = 0; i < hdr[2]; ++i) { + uint32_t vc = 0, ic = 0; + f.read(reinterpret_cast(&vc), 4).read(reinterpret_cast(&ic), 4); + if (!f || uint64_t(vc) * 32 + uint64_t(ic) * 4 > file_size) return false; + Mesh m{uint32_t(s.vertices.size() / 8), vc, uint32_t(s.indices.size()), ic}; + s.vertices.resize(s.vertices.size() + size_t(vc) * 8); + s.indices.resize(s.indices.size() + ic); + f.read(reinterpret_cast(s.vertices.data() + size_t(m.first_vertex) * 8), std::streamsize(vc) * 32); + f.read(reinterpret_cast(s.indices.data() + m.first_index), std::streamsize(ic) * 4); + if (!f) return false; + for (uint32_t k = 0; k < ic; ++k) + if (s.indices[m.first_index + k] >= vc) return false; + s.meshes.push_back(m); + } + for (uint32_t i = 0; i < hdr[3]; ++i) { + Draw d; + f.read(reinterpret_cast(&d), sizeof(d)); + if (!f || d.mesh >= s.meshes.size() || d.texture >= int32_t(s.textures.size())) return false; + s.draws.push_back(d); + } + return bool(f); +} + +std::vector read_spv(const char* p) { + std::ifstream f(p, std::ios::binary); + std::vector b((std::istreambuf_iterator(f)), {}); + std::vector w(b.size() / 4); + std::memcpy(w.data(), b.data(), w.size() * 4); + return w; +} + +struct Camera { + float pos[3], yaw = 0, pitch = 0, fov = 70, speed = 0; + int mode = 0; // 0 fly, 1 walk, 2 drive + void forward(float f[3]) const { + f[0] = std::cos(pitch) * std::cos(yaw); f[1] = std::cos(pitch) * std::sin(yaw); f[2] = std::sin(pitch); + } +}; + +// clip = wx*row0 + wy*row1 + wz*row2 + row3 (D3D clip space: y up, z 0..1), stored as 16 floats. +void view_projection(const Camera& c, float aspect, float out[16]) { + float f[3]; c.forward(f); + float r[3] = {f[1], -f[0], 0}; + const float rl = std::sqrt(r[0] * r[0] + r[1] * r[1]); + if (rl < 1e-6f) { r[0] = std::sin(c.yaw); r[1] = -std::cos(c.yaw); } else { r[0] /= rl; r[1] /= rl; } + const float u[3] = {r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]}; + const float n = 0.1f, fa = 5000.f, sy = 1.f / std::tan(c.fov * 3.14159265f / 360.f), sx = sy / aspect; + const float A = fa / (fa - n), B = -n * fa / (fa - n); + // view = (dot(w - p, r), dot(w - p, u), dot(w - p, f)); clip = (vx*sx, vy*sy, vz*A + B, vz) + const float* axes[3] = {r, u, f}; + const float scale[4] = {sx, sy, A, 1}; + for (int k = 0; k < 4; ++k) { + const float* a = axes[k < 3 ? k : 2]; + for (int j = 0; j < 3; ++j) out[j * 4 + k] = a[j] * scale[k]; + out[12 + k] = -(a[0] * c.pos[0] + a[1] * c.pos[1] + a[2] * c.pos[2]) * scale[k] + (k == 2 ? B : 0); + } +} + +// Ground under a point: highest scene triangle below z + 1 at (x, y), from a 4 m grid built once. +struct Ground { + float cell = 4, x0 = 0, y0 = 0; + int nx = 0, ny = 0; + std::vector> tris; // per cell: 9 floats a triangle + void build(const Scene& s) { + float lo[2] = {1e30f, 1e30f}, hi[2] = {-1e30f, -1e30f}; + std::vector all; + for (const Draw& d : s.draws) { + const Mesh& m = s.meshes[d.mesh]; + for (uint32_t i = 0; i + 2 < m.index_count; i += 3) + for (int k = 0; k < 3; ++k) { + const float* v = &s.vertices[size_t(m.first_vertex + s.indices[m.first_index + i + k]) * 8]; + for (int j = 0; j < 3; ++j) { + const float w = v[0] * d.rows[0][j] + v[1] * d.rows[1][j] + v[2] * d.rows[2][j] + d.rows[3][j]; + all.push_back(w); + if (j < 2) { lo[j] = std::min(lo[j], w); hi[j] = std::max(hi[j], w); } + } + } + } + if (all.empty()) return; + x0 = lo[0]; y0 = lo[1]; + nx = std::min(4096, int((hi[0] - lo[0]) / cell) + 1); ny = std::min(4096, int((hi[1] - lo[1]) / cell) + 1); + tris.assign(size_t(nx) * ny, {}); + for (size_t t = 0; t < all.size(); t += 9) { + const float* p = &all[t]; + const float ax = std::min({p[0], p[3], p[6]}), bx = std::max({p[0], p[3], p[6]}); + const float ay = std::min({p[1], p[4], p[7]}), by = std::max({p[1], p[4], p[7]}); + if (bx - ax > 64 || by - ay > 64) continue; // skip huge sheets (skydomes, water planes) + for (int cy = std::max(0, int(std::floor((ay - y0) / cell))); cy <= std::min(ny - 1, int(std::floor((by - y0) / cell))); ++cy) + for (int cx = std::max(0, int(std::floor((ax - x0) / cell))); cx <= std::min(nx - 1, int(std::floor((bx - x0) / cell))); ++cx) + tris[size_t(cy) * nx + cx].insert(tris[size_t(cy) * nx + cx].end(), p, p + 9); + } + } + bool height(float x, float y, float below, float& out) const { + const int cx = int(std::floor((x - x0) / cell)), cy = int(std::floor((y - y0) / cell)); + if (cx < 0 || cy < 0 || cx >= nx || cy >= ny) return false; + bool hit = false; + const auto& v = tris[size_t(cy) * nx + cx]; + for (size_t t = 0; t < v.size(); t += 9) { + const float* p = &v[t]; + const float d = (p[3] - p[0]) * (p[7] - p[1]) - (p[6] - p[0]) * (p[4] - p[1]); + if (std::fabs(d) < 1e-9f) continue; + const float a = ((p[3] - x) * (p[7] - y) - (p[6] - x) * (p[4] - y)) / d; + const float b = ((p[6] - x) * (p[1] - y) - (p[0] - x) * (p[7] - y)) / d; + const float c = 1 - a - b; + if (a < 0 || b < 0 || c < 0) continue; + const float z = a * p[2] + b * p[5] + c * p[8]; + if (z <= below && (!hit || z > out)) { out = z; hit = true; } + } + return hit; + } +}; + +#ifdef _WIN32 +bool g_quit = false, g_look = false; +int g_mx = 0, g_my = 0, g_dx = 0, g_dy = 0; +LRESULT CALLBACK wndproc(HWND h, UINT m, WPARAM w, LPARAM l) { + switch (m) { + case WM_CLOSE: g_quit = true; return 0; + case WM_RBUTTONDOWN: g_look = true; g_mx = short(LOWORD(l)); g_my = short(HIWORD(l)); SetCapture(h); return 0; + case WM_RBUTTONUP: g_look = false; ReleaseCapture(); return 0; + case WM_MOUSEMOVE: + if (g_look) { const int x = short(LOWORD(l)), y = short(HIWORD(l)); g_dx += x - g_mx; g_dy += y - g_my; g_mx = x; g_my = y; } + return 0; + } + return DefWindowProcW(h, m, w, l); +} +#endif + +bool write_ppm(const char* path, const uint8_t* bgra_or_rgba, uint32_t w, uint32_t h, bool bgra) { + std::ofstream o(path, std::ios::binary); + o << "P6\n" << w << " " << h << "\n255\n"; + for (size_t i = 0; i < size_t(w) * h; ++i) { + const uint8_t* p = bgra_or_rgba + i * 4; + const char px[3] = {char(p[bgra ? 2 : 0]), char(p[1]), char(p[bgra ? 0 : 2])}; + o.write(px, 3); + } + return bool(o); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 4) { + std::fprintf(stderr, "usage: vk_sandbox scene.bin vs.spv ps.spv (--out image.ppm | --window) [--size W H] " + "[--cam x y z yaw pitch] [--fov deg]\n"); + return 2; + } + Scene scene; + if (!load_scene(argv[1], scene)) { std::fprintf(stderr, "bad scene file %s\n", argv[1]); return 2; } + uint32_t W = 1280, H = 720; + const char* out_path = nullptr; + bool window = false; + int frames = 0; // --frames N: window test run, shown without activation, quits after N frames + Camera cam{}; + cam.pos[0] = scene.center[0] - 40; cam.pos[1] = scene.center[1] - 40; cam.pos[2] = scene.center[2] + 25; + cam.yaw = 0.785398f; cam.pitch = -0.35f; + for (int i = 4; i < argc; ++i) { + if (!std::strcmp(argv[i], "--out") && i + 1 < argc) out_path = argv[++i]; + else if (!std::strcmp(argv[i], "--window")) window = true; + else if (!std::strcmp(argv[i], "--frames") && i + 1 < argc) frames = std::atoi(argv[++i]); + else if (!std::strcmp(argv[i], "--mode") && i + 1 < argc) { + const char* m = argv[++i]; + cam.mode = !std::strcmp(m, "walk") ? 1 : !std::strcmp(m, "drive") ? 2 : 0; + } + else if (!std::strcmp(argv[i], "--size") && i + 2 < argc) { W = std::atoi(argv[++i]); H = std::atoi(argv[++i]); } + else if (!std::strcmp(argv[i], "--fov") && i + 1 < argc) cam.fov = float(std::atof(argv[++i])); + else if (!std::strcmp(argv[i], "--cam") && i + 5 < argc) { + for (int k = 0; k < 3; ++k) cam.pos[k] = float(std::atof(argv[++i])); + cam.yaw = float(std::atof(argv[++i])) * 3.14159265f / 180; cam.pitch = float(std::atof(argv[++i])) * 3.14159265f / 180; + } else { std::fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; } + } +#ifndef _WIN32 + if (window) { std::fprintf(stderr, "--window needs Windows\n"); return 2; } +#endif + if (window && frames && !out_path) { std::fprintf(stderr, "--frames needs --out\n"); return 2; } + if (!out_path && !window) { std::fprintf(stderr, "give --out or --window\n"); return 2; } + std::fprintf(stderr, "scene: %zu draws, %zu meshes, %zu textures, %zu triangles\n", scene.draws.size(), + scene.meshes.size(), scene.textures.size(), scene.indices.size() / 3); + + gipa = load_vulkan(); + if (!gipa) { std::fprintf(stderr, "the Vulkan loader was not found\n"); return 77; } + VkInstance inst = VK_NULL_HANDLE; +#define LI(n) auto n = reinterpret_cast(gipa(inst, #n)) + LI(vkCreateInstance); + VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.apiVersion = VK_API_VERSION_1_2; + const char* inst_ext[2] = {"VK_KHR_surface", "VK_KHR_win32_surface"}; + VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; ici.pApplicationInfo = &app; + if (window) { ici.enabledExtensionCount = 2; ici.ppEnabledExtensionNames = inst_ext; } + if (vkCreateInstance(&ici, nullptr, &inst) != VK_SUCCESS) { std::fprintf(stderr, "unsupported: no Vulkan instance\n"); return 77; } + LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties); + LI(vkGetPhysicalDeviceMemoryProperties); LI(vkCreateDevice); LI(vkGetDeviceProcAddr); + uint32_t n = 0; + CHECK(vkEnumeratePhysicalDevices(inst, &n, nullptr)); + if (!n) { std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); return 77; } + std::vector pds(n); + CHECK(vkEnumeratePhysicalDevices(inst, &n, pds.data())); + VkPhysicalDevice pd = VK_NULL_HANDLE; + VkPhysicalDeviceProperties props{}; + int best = -1; + for (auto p : pds) { + VkPhysicalDeviceProperties pp; vkGetPhysicalDeviceProperties(p, &pp); + if (int r = leonida::vk_test::device_rank(pp.deviceType, pp.vendorID); r > best) { pd = p; props = pp; best = r; } + } + constexpr uint32_t push_words = 36, push_bytes = push_words * 4; + if (props.limits.maxPushConstantsSize < push_bytes) { std::fprintf(stderr, "unsupported: push constants\n"); return 77; } + std::fprintf(stderr, "device: %s\n", props.deviceName); + uint32_t qn = 0; vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); + std::vector qf(qn); vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); + uint32_t qi = 0; + while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi; + if (qi == qn) { std::fprintf(stderr, "unsupported: no graphics queue\n"); return 77; } + +#ifdef _WIN32 + HWND hwnd = nullptr; + VkSurfaceKHR surface = VK_NULL_HANDLE; + if (window) { + WNDCLASSW wc{}; wc.lpfnWndProc = wndproc; wc.hInstance = GetModuleHandleW(nullptr); wc.lpszClassName = L"vk_sandbox"; + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); + RegisterClassW(&wc); + RECT rc{0, 0, LONG(W), LONG(H)}; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); + hwnd = CreateWindowExW(0, L"vk_sandbox", L"Leonida real-shader sandbox", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, + CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, wc.hInstance, nullptr); + ShowWindow(hwnd, frames ? SW_SHOWNOACTIVATE : SW_SHOWNORMAL); + LI(vkCreateWin32SurfaceKHR); + VkWin32SurfaceCreateInfoKHR sci{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + sci.hinstance = wc.hInstance; sci.hwnd = hwnd; + CHECK(vkCreateWin32SurfaceKHR(inst, &sci, nullptr, &surface)); + } +#endif + + float prio = 1; + VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; + qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; + VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE; + f12.shaderSampledImageArrayNonUniformIndexing = VK_TRUE; + VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12; + f2.features.shaderInt64 = VK_TRUE; + const char* dev_ext[1] = {"VK_KHR_swapchain"}; + VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; + dci.pNext = &f2; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; + if (window) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = dev_ext; } + VkDevice dev; CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); +#define LD(n) auto n = reinterpret_cast(vkGetDeviceProcAddr(dev, #n)) + LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory); + LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer); + LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool); + LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline); + LD(vkCmdDrawIndexed); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage); + LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); LD(vkResetCommandBuffer); + LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress); + LD(vkCreateSampler); LD(vkCreateDescriptorSetLayout); LD(vkCreateDescriptorPool); LD(vkAllocateDescriptorSets); + LD(vkUpdateDescriptorSets); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier); + LD(vkCmdBindVertexBuffers); LD(vkCmdBindIndexBuffer); LD(vkCmdBlitImage); + VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); + VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); + auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) { + for (uint32_t i = 0; i < mp.memoryTypeCount; i++) + if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; + return 0u; + }; + auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) { + VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bi.size = size; bi.usage = usage; + VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); if (r) return r; + VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, *b, &mr); + VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.pNext = &fi; ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r; + r = vkBindBufferMemory(dev, *b, m, 0); if (r) return r; + return vkMapMemory(dev, m, 0, size, 0, map); + }; + auto make_image = [&](uint32_t w, uint32_t h, VkFormat fmt, VkImageUsageFlags usage, VkImageAspectFlags aspect, + VkImage* img, VkImageView* view) { + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = fmt; ii.extent = {w, h, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; + ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = usage; + VkResult r = vkCreateImage(dev, &ii, nullptr, img); if (r) return r; + VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, *img, &mr); + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r; + r = vkBindImageMemory(dev, *img, m, 0); if (r) return r; + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = *img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = fmt; vi.subresourceRange = {aspect, 0, 1, 0, 1}; + return vkCreateImageView(dev, &vi, nullptr, view); + }; + + // Heap: the Xbox GPU VA window. 0x1000 view constants, 0x1200 colour constants, then 0x80 per draw: the + // descriptor table at +0 (0x70 bytes used) and nothing else; object constants follow all tables. + const uint32_t view_va = 0x1000, colour_va = 0x1200, table_va = 0x2000; + const uint32_t ndraw = uint32_t(scene.draws.size()); + const uint32_t object_va = table_va + ndraw * 0x80; + const VkDeviceSize heap_bytes = object_va + VkDeviceSize(ndraw) * 0x40 + 0x1000; + VkBuffer heap; void* heapp; + CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapp)); + std::memset(heapp, 0, size_t(heap_bytes)); + auto heap_u32 = [&](uint32_t va) { return reinterpret_cast(static_cast(heapp) + va); }; + auto heap_f32 = [&](uint32_t va) { return reinterpret_cast(static_cast(heapp) + va); }; + VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap; + const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai); + // A raw V#: base in word0/word1[15:0], stride 0, NUM_RECORDS bytes, OOB_SELECT 3 (raw byte range). + auto vsharp = [&](uint32_t at, uint32_t base, uint32_t bytes) { + uint32_t* p = heap_u32(at); p[0] = base; p[1] = 0; p[2] = bytes; p[3] = 3u << 28; + }; + // T# keys: unique words per texture with the RGBA8 UNORM format in word 1 (the numeric type the shader reads). + const uint32_t fmt_word = leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM) << 20; + auto tsharp = [&](uint32_t image) { + std::array t{0x5A000000u | image, fmt_word, 0x7FF7FFu, 0, 0, 0, 0, 0}; + return t; + }; + const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws + leonida::DescriptorTable table(2 * (nimg + 2)); + for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i); + uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S# + table.insert(ssharp, 0); + for (uint32_t d = 0; d < ndraw; ++d) { + const Draw& dr = scene.draws[d]; + const uint32_t t = table_va + d * 0x80, o = object_va + d * 0x40; + vsharp(t + 0x00, o, 0x40); + const auto ts = tsharp(dr.texture < 0 ? 0 : uint32_t(dr.texture) + 1); + std::memcpy(heap_u32(t + 0x20), ts.data(), 32); + vsharp(t + 0x40, view_va, 0x1a0); + vsharp(t + 0x60, colour_va, 0x10); + float* ob = heap_f32(o); + for (int r = 0; r < 4; ++r) for (int j = 0; j < 3; ++j) ob[r * 4 + j] = dr.rows[r][j]; + } + float* colour = heap_f32(colour_va); colour[0] = colour[1] = colour[2] = colour[3] = 1; + float* light = heap_f32(view_va + 0xa0); + { const float l[3] = {-0.55f, -0.45f, 0.7f}; const float ln = std::sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]); + for (int k = 0; k < 3; ++k) light[k] = l[k] / ln; } + const auto gpu_table = table.build_gpu_buffer(true); + VkBuffer tb; void* tbp; + CHECK(make_buffer(gpu_table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); + std::memcpy(tbp, gpu_table.data(), gpu_table.size() * 4); + + // Geometry. + VkBuffer vb, ib; void* vbp; void* ibp; + CHECK(make_buffer(std::max(32, scene.vertices.size() * 4), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, &vb, &vbp)); + CHECK(make_buffer(std::max(4, scene.indices.size() * 4), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, &ib, &ibp)); + std::memcpy(vbp, scene.vertices.data(), scene.vertices.size() * 4); + std::memcpy(ibp, scene.indices.data(), scene.indices.size() * 4); + + // Textures. + std::vector timg(nimg); std::vector tview(nimg); + VkDeviceSize up_bytes = 4; + for (const auto& t : scene.textures) up_bytes += t.rgba.size(); + VkBuffer up; void* upp; + CHECK(make_buffer(up_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up, &upp)); + std::vector up_off(nimg); + { const uint32_t white = 0xFFFFFFFFu; std::memcpy(upp, &white, 4); VkDeviceSize at = 4; + for (uint32_t i = 1; i < nimg; ++i) { up_off[i] = at; std::memcpy(static_cast(upp) + at, scene.textures[i - 1].rgba.data(), scene.textures[i - 1].rgba.size()); at += scene.textures[i - 1].rgba.size(); } } + for (uint32_t i = 0; i < nimg; ++i) + CHECK(make_image(i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, VK_FORMAT_R8G8B8A8_UNORM, + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &timg[i], &tview[i])); + VkSamplerCreateInfo sci = leonida::gfx10::vulkan_sampler(leonida::gfx10::decode( + leonida::gfx10::SamplerWords{ssharp[0], ssharp[1], ssharp[2], ssharp[3]})); + sci.maxLod = 0; // the scene stores mip 0 only + VkSampler smp; CHECK(vkCreateSampler(dev, &sci, nullptr, &smp)); + + // Targets: RGBA8 colour + D32 depth. + const VkFormat cfmt = VK_FORMAT_R8G8B8A8_UNORM, dfmt = VK_FORMAT_D32_SFLOAT; + VkImage rt, dt; VkImageView rtv, dtv; + CHECK(make_image(W, H, cfmt, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &rt, &rtv)); + CHECK(make_image(W, H, dfmt, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, &dt, &dtv)); + VkAttachmentDescription ad[2]{}; + ad[0].format = cfmt; ad[0].samples = VK_SAMPLE_COUNT_1_BIT; ad[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + ad[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; ad[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + ad[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + ad[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; ad[0].finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + ad[1] = ad[0]; ad[1].format = dfmt; ad[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + ad[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + VkAttachmentReference car{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, dar{1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}; + VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + sd.colorAttachmentCount = 1; sd.pColorAttachments = &car; sd.pDepthStencilAttachment = &dar; + VkSubpassDependency dep{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT}; + VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; + rpi.attachmentCount = 2; rpi.pAttachments = ad; rpi.subpassCount = 1; rpi.pSubpasses = &sd; + rpi.dependencyCount = 1; rpi.pDependencies = &dep; + VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp)); + VkImageView fbv[2] = {rtv, dtv}; + VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; + fbi.renderPass = rp; fbi.attachmentCount = 2; fbi.pAttachments = fbv; fbi.width = W; fbi.height = H; fbi.layers = 1; + VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb)); + + // Descriptor set: binding 0 images[], 1 samplers[], 2 the descriptor hash table. + VkDescriptorSetLayoutBinding b[3]{}; + b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr}; + b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr}; + b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr}; + VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; dli.bindingCount = 3; dli.pBindings = b; + VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); + VkDescriptorPoolSize ps[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}; + VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; dpi.poolSizeCount = 3; dpi.pPoolSizes = ps; + VkDescriptorPool dp; CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp)); + VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; + VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); + std::vector iinfo(nimg); + for (uint32_t i = 0; i < nimg; ++i) iinfo[i] = {VK_NULL_HANDLE, tview[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; + VkDescriptorImageInfo sinfo{smp}; + VkDescriptorBufferInfo tinfo{tb, 0, VK_WHOLE_SIZE}; + VkWriteDescriptorSet wr[3]{}; + for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; } + wr[0].dstBinding = 0; wr[0].descriptorCount = nimg; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = iinfo.data(); + wr[1].dstBinding = 1; wr[1].descriptorCount = 1; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = &sinfo; + wr[2].dstBinding = 2; wr[2].descriptorCount = 1; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tinfo; + vkUpdateDescriptorSets(dev, 3, wr, 0, nullptr); + + // Pipeline: the translated VS and PS, vertices (pos, normal, uv) at locations 0..2, depth test, no culling. + auto module = [&](const char* p, VkShaderModule* m) { + auto code = read_spv(p); + if (code.empty()) { std::fprintf(stderr, "cannot read %s\n", p); return VK_ERROR_INITIALIZATION_FAILED; } + VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data(); + return vkCreateShaderModule(dev, &smi, nullptr, m); + }; + VkShaderModule vs, fs; CHECK(module(argv[2], &vs)); CHECK(module(argv[3], &fs)); + VkPipelineShaderStageCreateInfo st[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; + st[0].stage = VK_SHADER_STAGE_VERTEX_BIT; st[0].module = vs; st[0].pName = "main"; + st[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; st[1].module = fs; st[1].pName = "main"; + VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes}; + VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; + VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); + VkVertexInputBindingDescription vbd{0, 32, VK_VERTEX_INPUT_RATE_VERTEX}; + VkVertexInputAttributeDescription vad[3]{{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32_SFLOAT, 12}, + {2, 0, VK_FORMAT_R32G32_SFLOAT, 24}}; + VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + vin.vertexBindingDescriptionCount = 1; vin.pVertexBindingDescriptions = &vbd; + vin.vertexAttributeDescriptionCount = 3; vin.pVertexAttributeDescriptions = vad; + VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + // D3D clip space has y up: a negative-height viewport (Vulkan 1.1) keeps the game's matrices unchanged. + VkViewport vp{0, float(H), float(W), -float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}}; + VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = ≻ + VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1; + VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + VkPipelineDepthStencilStateCreateInfo dss{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; + dss.depthTestEnable = VK_TRUE; dss.depthWriteEnable = VK_TRUE; dss.depthCompareOp = VK_COMPARE_OP_LESS; + VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; + VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; cb.attachmentCount = 1; cb.pAttachments = &cba; + VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; + gpi.stageCount = 2; gpi.pStages = st; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; gpi.pViewportState = &vps; + gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pDepthStencilState = &dss; gpi.pColorBlendState = &cb; + gpi.layout = pl; gpi.renderPass = rp; + VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe)); + + VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi; + cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); + VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cai.commandPool = pool; cai.commandBufferCount = 1; + VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); + auto barrier = [&](VkImage img, VkImageLayout from, VkImageLayout to, VkAccessFlags sa, VkAccessFlags da, + VkPipelineStageFlags ss, VkPipelineStageFlags dst) { + VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + ib.oldLayout = from; ib.newLayout = to; ib.image = img; ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + ib.srcAccessMask = sa; ib.dstAccessMask = da; ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + vkCmdPipelineBarrier(cmd, ss, dst, 0, 0, nullptr, 0, nullptr, 1, &ib); + }; + auto submit = [&]() { VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; + VkResult r = vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE); return r ? r : vkQueueWaitIdle(q); }; + { // Upload the textures once. + VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); + for (uint32_t i = 0; i < nimg; ++i) { + barrier(timg[i], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + VkBufferImageCopy c{}; c.bufferOffset = up_off[i]; c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + c.imageExtent = {i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, 1}; + vkCmdCopyBufferToImage(cmd, up, timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); + barrier(timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + } + CHECK(vkEndCommandBuffer(cmd)); CHECK(submit()); + } + // Records the scene into rt (left in TRANSFER_SRC_OPTIMAL). The caller ends and submits. + auto record = [&]() { + view_projection(cam, float(W) / float(H), heap_f32(view_va + 0x160)); + VkClearValue clear[2]{}; clear[0].color = {{0.55f, 0.68f, 0.85f, 1}}; clear[1].depthStencil = {1, 0}; + VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; + rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = 2; rbi.pClearValues = clear; + vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); + vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); + vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr); + VkDeviceSize zero = 0; + vkCmdBindVertexBuffers(cmd, 0, 1, &vb, &zero); + vkCmdBindIndexBuffer(cmd, ib, 0, VK_INDEX_TYPE_UINT32); + uint32_t pc[push_words] = {}; + pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32); + for (uint32_t d = 0; d < ndraw; ++d) { + const Mesh& m = scene.meshes[scene.draws[d].mesh]; + pc[8] = table_va + d * 0x80; // s8: the descriptor table; s9 (the PS's M0) stays 0 + vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes, pc); + vkCmdDrawIndexed(cmd, m.index_count, 1, m.first_index, int32_t(m.first_vertex), 0); + } + vkCmdEndRenderPass(cmd); + }; + VkBuffer rb; void* rbp; + CHECK(make_buffer(VkDeviceSize(W) * H * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb, &rbp)); + auto read_back = [&]() { + VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1}; + vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc); + }; + + if (!window) { + VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); + record(); read_back(); + CHECK(vkEndCommandBuffer(cmd)); CHECK(submit()); + if (!write_ppm(out_path, static_cast(rbp), W, H, false)) { std::fprintf(stderr, "cannot write %s\n", out_path); return 1; } + // Coverage: pixels that differ from the clear colour were written by the translated PS. + const uint8_t* px = static_cast(rbp); + const uint8_t clear_px[3] = {uint8_t(0.55f * 255 + 0.5f), uint8_t(0.68f * 255 + 0.5f), uint8_t(0.85f * 255 + 0.5f)}; + size_t covered = 0; + for (size_t i = 0; i < size_t(W) * H; ++i) + covered += std::abs(px[i * 4] - clear_px[0]) > 1 || std::abs(px[i * 4 + 1] - clear_px[1]) > 1 || std::abs(px[i * 4 + 2] - clear_px[2]) > 1; + std::printf("vk_sandbox: %u draws, %zu of %u pixels covered -> %s\n", ndraw, covered, W * H, out_path); + return 0; + } + +#ifdef _WIN32 + LI(vkGetPhysicalDeviceSurfaceCapabilitiesKHR); LI(vkGetPhysicalDeviceSurfaceFormatsKHR); LI(vkGetPhysicalDeviceSurfaceSupportKHR); + LD(vkCreateSwapchainKHR); LD(vkDestroySwapchainKHR); LD(vkGetSwapchainImagesKHR); LD(vkAcquireNextImageKHR); + LD(vkQueuePresentKHR); LD(vkCreateSemaphore); + VkBool32 can_present = VK_FALSE; vkGetPhysicalDeviceSurfaceSupportKHR(pd, qi, surface, &can_present); + if (!can_present) { std::fprintf(stderr, "the graphics queue cannot present\n"); return 1; } + uint32_t nf = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, nullptr); + std::vector sfs(nf); vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, sfs.data()); + if (sfs.empty()) { std::fprintf(stderr, "the surface has no formats\n"); return 1; } + VkSurfaceFormatKHR sf = sfs[0]; // a UNORM format keeps the blit byte-exact with the headless render + for (const VkSurfaceFormatKHR& c : sfs) + if (c.format == VK_FORMAT_B8G8R8A8_UNORM || c.format == VK_FORMAT_R8G8B8A8_UNORM) { sf = c; break; } + VkSwapchainCreateInfoKHR swi{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; + VkSwapchainKHR swap = VK_NULL_HANDLE; + std::vector simg; + // (Re)creates the swapchain for the window's current size; false while it is minimised (extent 0). + auto make_swap = [&]() -> int { + VkSurfaceCapabilitiesKHR caps; + if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(pd, surface, &caps) != VK_SUCCESS) return -1; + if (!(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) return -1; + const VkExtent2D ext = caps.currentExtent.width != 0xFFFFFFFFu ? caps.currentExtent : VkExtent2D{W, H}; + if (!ext.width || !ext.height) return 0; + vkQueueWaitIdle(q); + swi.surface = surface; swi.minImageCount = std::max(2u, caps.minImageCount); + if (caps.maxImageCount) swi.minImageCount = std::min(swi.minImageCount, caps.maxImageCount); + swi.imageFormat = sf.format; swi.imageColorSpace = sf.colorSpace; swi.imageExtent = ext; + swi.imageArrayLayers = 1; swi.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; swi.preTransform = caps.currentTransform; + swi.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swi.presentMode = VK_PRESENT_MODE_FIFO_KHR; swi.clipped = VK_TRUE; + swi.oldSwapchain = swap; + VkSwapchainKHR next; + if (vkCreateSwapchainKHR(dev, &swi, nullptr, &next) != VK_SUCCESS) return -1; + if (swap) vkDestroySwapchainKHR(dev, swap, nullptr); + swap = next; + uint32_t ns = 0; vkGetSwapchainImagesKHR(dev, swap, &ns, nullptr); + simg.resize(ns); vkGetSwapchainImagesKHR(dev, swap, &ns, simg.data()); + return 1; + }; + if (make_swap() < 0) { std::fprintf(stderr, "cannot create a swapchain (TRANSFER_DST unsupported?)\n"); return 1; } + VkSemaphoreCreateInfo semi{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; + VkSemaphore acquired; CHECK(vkCreateSemaphore(dev, &semi, nullptr, &acquired)); + Ground ground; ground.build(scene); + auto last = std::chrono::steady_clock::now(); + bool shot_held = false; + int frame = 0; + while (!g_quit) { + MSG msg; + while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); } + const auto now = std::chrono::steady_clock::now(); + const float dt = std::min(0.1f, std::chrono::duration(now - last).count()); last = now; + const bool focus = GetForegroundWindow() == hwnd; + auto key = [&](int vk) { return focus && (GetAsyncKeyState(vk) & 0x8000); }; + if (key(VK_ESCAPE)) break; + if (key('1')) cam.mode = 0; if (key('2')) cam.mode = 1; if (key('3')) cam.mode = 2; + cam.yaw -= g_dx * 0.004f; cam.pitch = std::clamp(cam.pitch - g_dy * 0.004f, -1.5f, 1.5f); g_dx = g_dy = 0; + float f[3]; cam.forward(f); + const float r[2] = {std::sin(cam.yaw), -std::cos(cam.yaw)}; + const float fwd = float(key('W')) - float(key('S')), side = float(key('D')) - float(key('A')); + if (cam.mode == 0) { + const float v = (key(VK_SHIFT) ? 60.f : 12.f) * dt; + for (int k = 0; k < 3; ++k) cam.pos[k] += f[k] * fwd * v; + cam.pos[0] += r[0] * side * v; cam.pos[1] += r[1] * side * v; + cam.pos[2] += (float(key('E')) - float(key('Q'))) * v; + } else { + const float h = std::hypot(f[0], f[1]) > 1e-4f ? std::hypot(f[0], f[1]) : 1; + if (cam.mode == 1) cam.speed = fwd * (key(VK_SHIFT) ? 7.f : 2.5f); + else { cam.speed += fwd * 12.f * dt; cam.speed *= std::pow(0.6f, dt); cam.yaw -= side * dt * std::clamp(cam.speed / 10.f, -1.f, 1.f); } + cam.pos[0] += f[0] / h * cam.speed * dt; cam.pos[1] += f[1] / h * cam.speed * dt; + if (cam.mode == 1) { cam.pos[0] += r[0] * side * 2.5f * dt; cam.pos[1] += r[1] * side * 2.5f * dt; } + const float eye = cam.mode == 1 ? 1.7f : 1.2f; + float gz; + if (ground.height(cam.pos[0], cam.pos[1], cam.pos[2] - eye + 0.6f, gz)) cam.pos[2] = gz + eye; + } + uint32_t idx = 0; + if (!swap) { // minimised at start or since the last resize + const int made = make_swap(); + if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; } + if (!made) { Sleep(50); continue; } + } + const VkResult acq = vkAcquireNextImageKHR(dev, swap, UINT64_MAX, acquired, VK_NULL_HANDLE, &idx); + if (acq == VK_ERROR_OUT_OF_DATE_KHR) { + const int made = make_swap(); + if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; } + if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; Sleep(50); } + continue; + } + if (acq != VK_SUCCESS && acq != VK_SUBOPTIMAL_KHR) { std::fprintf(stderr, "vkAcquireNextImageKHR failed (%d)\n", int(acq)); return 1; } + CHECK(vkResetCommandBuffer(cmd, 0)); + VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); + record(); + const bool last_frame = frames && ++frame >= frames; + const bool shot = (key('P') && !shot_held) || last_frame; shot_held = key('P'); + if (shot) read_back(); + barrier(simg[idx], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + VkImageBlit bl{}; bl.srcSubresource = bl.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + bl.srcOffsets[1] = {int32_t(W), int32_t(H), 1}; + bl.dstOffsets[1] = {int32_t(swi.imageExtent.width), int32_t(swi.imageExtent.height), 1}; + vkCmdBlitImage(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bl, VK_FILTER_LINEAR); + barrier(simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_ACCESS_TRANSFER_WRITE_BIT, 0, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); + CHECK(vkEndCommandBuffer(cmd)); + VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; + VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.waitSemaphoreCount = 1; si.pWaitSemaphores = &acquired; + si.pWaitDstStageMask = &wait_stage; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; + CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q)); + if (shot) { + const char* path = last_frame ? out_path : "sandbox_shot.ppm"; + if (!write_ppm(path, static_cast(rbp), W, H, false)) { + std::fprintf(stderr, "cannot write %s\n", path); + if (last_frame) return 1; + } + } + VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; pi.swapchainCount = 1; pi.pSwapchains = &swap; pi.pImageIndices = &idx; + const VkResult pres = vkQueuePresentKHR(q, &pi); + if ((pres == VK_ERROR_OUT_OF_DATE_KHR || pres == VK_SUBOPTIMAL_KHR || acq == VK_SUBOPTIMAL_KHR) && !last_frame) { + const int made = make_swap(); + if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; } + if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; } + } + char title[160]; + std::snprintf(title, sizeof title, "Leonida real-shader sandbox [%s] %.0f %.0f %.0f %.0f fps", cam.mode == 0 ? "fly" : cam.mode == 1 ? "walk" : "drive", + cam.pos[0], cam.pos[1], cam.pos[2], 1.f / std::max(dt, 1e-4f)); + SetWindowTextA(hwnd, title); + if (last_frame) { + std::printf("vk_sandbox: window ran %d frames -> %s, camera %.2f %.2f %.2f\n", frame, out_path, + cam.pos[0], cam.pos[1], cam.pos[2]); + break; + } + } + vkQueueWaitIdle(q); +#endif + return 0; +} diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp index a2191eae3..474264dcf 100644 --- a/runtime/test/vk_texture_test.cpp +++ b/runtime/test/vk_texture_test.cpp @@ -13,6 +13,7 @@ // (x + 0.5) / 8) and a LESS_OR_EQUAL compare sampler at index 1; both of its results, f32 and d16, must be the // 1.0 or 0.0 the reference 0.5 gives against the texel each pixel reads. // vk_texture_test dref_a16 [out.raw]: the same with ps_sample_c_lz_a16 (16-bit coordinates). +// vk_texture_test dref_c / dref_c_b [out.raw]: the same with ps_sample_c (implicit LOD) / ps_sample_c_b (LOD bias). // VKT_HEAP_MB=: size of the heap in MiB (default 64 KiB) // VKT_NEED_MAINTENANCE8=1: the shader has a non-constant texel Offset outside gather (image_sample*_o, see // ps_texoff.asm); print "unsupported: ..." and exit 77 when VK_KHR_maintenance8 cannot be enabled. @@ -72,8 +73,15 @@ int main(int argc, char** argv) { std::string vs_path, fs_path, out_path; int ptr_sgpr = 0; const bool cube = argc >= 2 && !std::strcmp(argv[1], "cube"); - const bool dref_a16 = argc >= 2 && !std::strcmp(argv[1], "dref_a16"); - const bool dref = dref_a16 || (argc >= 2 && !std::strcmp(argv[1], "dref")); + // dref_c / dref_c_b: image_sample_c / image_sample_c_b (implicit LOD, bias), same texture and expected results. + const char* dref_ps = nullptr; + if (argc >= 2) { + if (!std::strcmp(argv[1], "dref")) dref_ps = "ps_sample_c_lz.spv"; + else if (!std::strcmp(argv[1], "dref_a16")) dref_ps = "ps_sample_c_lz_a16.spv"; + else if (!std::strcmp(argv[1], "dref_c")) dref_ps = "ps_sample_c.spv"; + else if (!std::strcmp(argv[1], "dref_c_b")) dref_ps = "ps_sample_c_b.spv"; + } + const bool dref = dref_ps != nullptr; bool autonomous = false; uint32_t ssharp[8] = {0x92, 0xc00000, 0x14500000, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; @@ -102,15 +110,14 @@ int main(int argc, char** argv) { return std::string("runtime/build/shaders/spirv/") + name; }; vs_path = find_spv("vs_ids.spv"); - fs_path = find_spv(cube ? "ps_cube_sample.spv" : dref_a16 ? "ps_sample_c_lz_a16.spv" - : dref ? "ps_sample_c_lz.spv" : "ps_texture_sample.spv"); + fs_path = find_spv(cube ? "ps_cube_sample.spv" : dref ? dref_ps : "ps_texture_sample.spv"); const int out_arg = cube || dref ? 2 : 1; out_path = argc > out_arg ? argv[out_arg] : "runtime/build/vk_texture_test_out.raw"; ptr_sgpr = 0; if (dref) ssharp[0] |= 3u << 12; // the shader's S#: DEPTH_COMPARE_FUNC = LESSEQUAL } else { - std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint]\n"); + std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16|dref_c|dref_c_b] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint]\n"); return 2; } // Word 1 also selects the numeric type when the shader fetches through this key. Word 3 keeps BASE_LEVEL [15:12] @@ -144,18 +151,16 @@ int main(int argc, char** argv) { std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); return 77; // a missing device is a skip in every texture-test mode } - VkPhysicalDevice pd = VK_NULL_HANDLE; - VkPhysicalDeviceProperties properties{}; - int best_rank = -1; - for (uint32_t i = 0; i < n; ++i) { - VkPhysicalDeviceProperties p; - vkGetPhysicalDeviceProperties(pds[i], &p); - if (const int rank = leonida::vk_test::device_rank(p.deviceType, p.vendorID); rank > best_rank) { - pd = pds[i]; - properties = p; - best_rank = rank; - } + // LEONIDA_VK_DEVICE picks one GPU on a machine with several, as in the other test programs. + std::vector candidates(n); + for (uint32_t i = 0; i < n; ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]); + const size_t chosen = leonida::vk_test::pick_device(candidates); + if (chosen >= n) { + leonida::vk_test::report_no_device(); + return 1; } + VkPhysicalDevice pd = pds[chosen]; + VkPhysicalDeviceProperties properties = candidates[chosen]; constexpr uint32_t push_words = 36; // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only; the heap base is in a uniform block at set 1 // (vk_pc_tail.h), so a 128-byte device runs these tests too. @@ -211,7 +216,7 @@ int main(int argc, char** argv) { for (auto& x : exts) m8_on = m8_on || !std::strcmp(x.extensionName, VK_KHR_MAINTENANCE_8_EXTENSION_NAME); if (m8_on) { enable.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); - m8.maintenance8 = VK_TRUE; f12.pNext = &m8; + m8.maintenance8 = VK_TRUE; f11.pNext = &m8; std::fprintf(stderr, "enabled %s\n", VK_KHR_MAINTENANCE_8_EXTENSION_NAME); } #endif diff --git a/runtime/test/vulkan13_features_test.cpp b/runtime/test/vulkan13_features_test.cpp index cf1b4d99c..d0c446495 100644 --- a/runtime/test/vulkan13_features_test.cpp +++ b/runtime/test/vulkan13_features_test.cpp @@ -248,11 +248,30 @@ int main() { EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); + const auto* rendering = static_cast(head); + const auto* sync2 = static_cast(rendering->pNext); + EXPECT(rendering->dynamicRendering == VK_TRUE); + EXPECT(sync2->synchronization2 == VK_TRUE); + std::vector exts; v13.add_extensions(exts); EXPECT(exts.size() == 2); EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0); EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0); + + // Extensions advertised, but each required feature bit cleared in turn after a successful query. + dev.features2_calls = 0; + dev.dynamic_rendering = VK_FALSE; + dev.synchronization2 = VK_TRUE; + v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); + EXPECT(dev.features2_calls == 1); + EXPECT(!v13.core && !v13.dynamic_rendering && v13.synchronization2 && !v13.usable()); + + dev.dynamic_rendering = VK_TRUE; + dev.synchronization2 = VK_FALSE; + v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); + EXPECT(dev.features2_calls == 2); + EXPECT(!v13.core && v13.dynamic_rendering && !v13.synchronization2 && !v13.usable()); } // Vulkan 1.2 with only EDS1 (missing EDS2), or both extensions with one feature bit false: EDS stays off. @@ -323,6 +342,15 @@ int main() { EXPECT(types[4] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); EXPECT(types[5] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); + const auto* rendering = static_cast(head); + const auto* sync2 = static_cast(rendering->pNext); + const auto* eds = static_cast(sync2->pNext); + const auto* eds2 = static_cast(eds->pNext); + EXPECT(rendering->dynamicRendering == VK_TRUE); + EXPECT(sync2->synchronization2 == VK_TRUE); + EXPECT(eds->extendedDynamicState == VK_TRUE); + EXPECT(eds2->extendedDynamicState2 == VK_TRUE); + std::vector exts; chosen.add_extensions(exts); EXPECT(exts.size() == 4); @@ -332,6 +360,39 @@ int main() { EXPECT(std::strcmp(exts[3], VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0); } + // choose() with a Vulkan 1.3 candidate preserves core=true and subgroup flags after source overwrite. + { + FakeDevice dev; + dev.dynamic_rendering = VK_TRUE; + dev.synchronization2 = VK_TRUE; + dev.subgroup_size_control = VK_TRUE; + dev.compute_full_subgroups = VK_TRUE; + g_device = &dev; + + Vulkan13Features candidate; + candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr); + EXPECT(candidate.core && candidate.usable()); + + Vulkan13Features chosen; + chosen.choose(candidate); + candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_1, fake_get_features2, fake_enumerate_extensions); + EXPECT(!candidate.core && !candidate.usable()); + EXPECT(chosen.core && chosen.usable() && chosen.extended_dynamic_state); + EXPECT(chosen.subgroup_size_control && chosen.compute_full_subgroups); + + VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr}; + void* head = chosen.enable(&tail); + const auto* enable13 = static_cast(head); + EXPECT(enable13->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES); + EXPECT(enable13->dynamicRendering == VK_TRUE && enable13->synchronization2 == VK_TRUE); + EXPECT(enable13->subgroupSizeControl == VK_TRUE && enable13->computeFullSubgroups == VK_TRUE); + EXPECT(enable13->pNext == &tail); + + std::vector exts; + chosen.add_extensions(exts); + EXPECT(exts.empty()); + } + // device_proc_or_khr resolves core first, then KHR, then EXT, else null. { ProcLookup lookup; diff --git a/runtime/test/winhttp_offline_test.cpp b/runtime/test/winhttp_offline_test.cpp index 4181103fd..f7ea661de 100644 --- a/runtime/test/winhttp_offline_test.cpp +++ b/runtime/test/winhttp_offline_test.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include "shims.h" @@ -84,6 +85,13 @@ double ms_since(std::chrono::steady_clock::time_point start) { return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } +// HANDLE_CLOSING arrives on the callback thread, so a count read right after WinHttpCloseHandle can be short, and a +// notification that comes late lands in the next block's count (TEST-721). Waits up to two seconds for `n`. +bool wait_for_closing(const Seen& s, int n) { + for (int i = 0; i < 200 && s.closing.load() < n; ++i) Sleep(10); + return s.closing.load() >= n; +} + } // namespace int main() { @@ -256,7 +264,7 @@ int main() { "and HANDLE_CLOSING follows once, after the error"); close(connection); close(session); - check(seen.closing.load() == 3, "every handle reports HANDLE_CLOSING once"); + check(wait_for_closing(seen, 3) && seen.closing.load() == 3, "every handle reports HANDLE_CLOSING once"); } // A callback that closes its request while handling the error, as libHttpClient-style code does. @@ -277,6 +285,8 @@ int main() { seen.close_in_callback = nullptr; close(connection); close(session); + check(wait_for_closing(seen, 3) && seen.closing.load() == 3, + "the connection and the session report HANDLE_CLOSING before the next block counts its own"); } // A request closed before its queued failure is delivered gets no error callback, only HANDLE_CLOSING. @@ -300,6 +310,69 @@ int main() { CloseHandle(seen.error_event); CloseHandle(seen.closing_event); + // WINHTTP_OPTION_CONTEXT_VALUE is inherited like the callback: a handle starts with the context its parent has + // when it is created, and keeps it when the parent's changes later. The host's winhttp.dll gave these values. + { + struct Event { + HINTERNET handle; + DWORD status; + DWORD_PTR context; + }; + static std::vector events; // a synchronous session: every callback runs on this thread + const WINHTTP_STATUS_CALLBACK record = [](HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID, DWORD) { + events.push_back({handle, status, context}); + }; + const auto context_of = [&](HINTERNET handle) -> DWORD_PTR { + DWORD_PTR value = ~DWORD_PTR{0}; + DWORD size = sizeof(value); + return query_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, &size) ? value : ~DWORD_PTR{0}; + }; + const auto set_context = [&](HINTERNET handle, DWORD_PTR value) { + return set_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)) != FALSE; + }; + const auto context_at = [&](HINTERNET handle, DWORD status) -> DWORD_PTR { + for (const Event& e : events) + if (e.handle == handle && e.status == status) return e.context; + return ~DWORD_PTR{0}; + }; + + const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0); + set_callback(session, record, WINHTTP_CALLBACK_FLAG_HANDLES, 0); + check(set_context(session, 7), "WINHTTP_OPTION_CONTEXT_VALUE can be set on a session"); + const HINTERNET connection = connect(session, L"127.0.0.1", 1, 0); + const HINTERNET request = open_request(connection, L"GET", L"/", nullptr, WINHTTP_NO_REFERER, + WINHTTP_DEFAULT_ACCEPT_TYPES, 0); + check(context_of(connection) == 7 && context_of(request) == 7, + "a connection and a request start with the session's context"); + check(context_at(connection, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) == 7 && + context_at(request, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) == 7, + "and their HANDLE_CREATED callbacks carry it"); + + check(set_context(request, 9) && context_of(request) == 9 && context_of(connection) == 7, + "a context set on the request replaces the inherited one for that request only"); + check(set_context(session, 11) && context_of(connection) == 7 && context_of(request) == 9, + "a context set on the session later does not change handles that exist"); + const HINTERNET late = connect(session, L"127.0.0.1", 1, 0); + check(context_of(late) == 11, "a connection made after that starts with the new one"); + + const HINTERNET sent = open_request(connection, L"GET", L"/", nullptr, WINHTTP_NO_REFERER, + WINHTTP_DEFAULT_ACCEPT_TYPES, 0); + check(context_of(sent) == 7, "a request starts with its connection's context, not the session's"); + send(sent, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0x51); + check(context_of(sent) == 0x51, "the context WinHttpSendRequest is given replaces the inherited one"); + + close(sent); + close(request); + close(late); + close(connection); + close(session); + check(context_at(sent, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 0x51 && + context_at(request, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 9 && + context_at(late, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 11 && + context_at(connection, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == 7, + "HANDLE_CLOSING carries each handle's own context"); + } + // WinHttpCrackUrl is parsing only and stays the host's. { wchar_t host[64] = {}, path[64] = {}; diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp index 6ea54280a..bcea1e2a7 100644 --- a/runtime/test/xbox_present_test.cpp +++ b/runtime/test/xbox_present_test.cpp @@ -1263,21 +1263,63 @@ int main() { constexpr int frames = 30; const auto start = std::chrono::steady_clock::now(); std::uint64_t last = 0; - for (int i = 0; i < frames; ++i) { + // One real-time frame: wait for the origin, present colour `c`. True with `shown` false when the present was + // skipped because the window is minimised (PresentX still S_OK, nothing on screen, nothing to read back). + const auto real_frame = [&](int c, bool& shown) -> bool { pump(); std::uint64_t t = 0; - EXPECT(real.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 1000, 0, &t) == S_OK); - EXPECT(t == last + 1); + if (real.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 1000, 0, &t) != S_OK || t != last + 1) { + std::fprintf(stderr, "real time: token %llu after %llu\n", static_cast(t), + static_cast(last)); + return false; + } last = t; - auto p = plane_of(colours[i % 3], t); - EXPECT(real.PresentX(1, &p, nullptr) == S_OK); - EXPECT(real.presenter().read_back(frame.bytes, &frame.extent, &frame.format)); - EXPECT(close_to(frame.at(width / 2, height / 2), expect_rgb[i % 3], 0)); + auto p = plane_of(colours[c], t); + if (real.PresentX(1, &p, nullptr) != S_OK) return false; + shown = real.presenter().read_back(frame.bytes, &frame.extent, &frame.format); + if (!shown) return IsIconic(window) != FALSE; // skipped only while minimised + const Px got = frame.at(width / 2, height / 2); + if (close_to(got, expect_rgb[c], 0)) return true; + std::fprintf(stderr, "real time: centre %d,%d,%d, presented %d,%d,%d\n", got.r, got.g, got.b, expect_rgb[c].r, + expect_rgb[c].g, expect_rgb[c].b); + return false; + }; + // Someone at the desktop can minimise the window during the loop (Win+D in the middle of a CTest run): those + // presents are skipped, and the window is restored so the rest of the loop is seen again. + int unseen = 0; + for (int i = 0; i < frames; ++i) { + bool shown = false; + EXPECT(real_frame(i % 3, shown)); + if (!shown) { + ++unseen; + ShowWindow(window, SW_RESTORE); + } } const auto ms = std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); - std::printf("real time: %d frames at 60 Hz in %lld ms (ideal %d)\n", frames, static_cast(ms), - frames * int(period) / 1000); + std::printf("real time: %d frames at 60 Hz in %lld ms (ideal %d), %d skipped while minimised\n", frames, + static_cast(ms), frames * int(period) / 1000, unseen); EXPECT(ms >= (frames - 1) * int(period) / 1000 * 9 / 10 && ms < 5000); + EXPECT(unseen < frames); + + // Minimised on purpose: the surface is 0x0 (VK_KHR_win32_surface), so PresentX succeeds without showing the + // frame, and read_back must say so rather than hand out the frame before it (TEST-378: the real-time loop + // above once compared that older frame). Each colour differs from the one shown last, so a stale frame fails. + // Restored, the next frame is shown and read back again. + { + ShowWindow(window, SW_MINIMIZE); + int skipped_presents = 0; + for (int i = 0; i < 3; ++i) { // the first present can still reach the old swapchain (then out of date) + bool shown = true; + EXPECT(real_frame(i, shown)); + if (!shown) ++skipped_presents; + } + EXPECT(skipped_presents > 0); + ShowWindow(window, SW_RESTORE); + bool shown = false; + for (int i = 0; i < 3 && !shown; ++i) EXPECT(real_frame((i + 1) % 3, shown)); // stale, then recreated + EXPECT(shown); + std::printf("minimised: %d of 3 presents skipped and not read back; restored: shown again\n", skipped_presents); + } EXPECT(real.PresentX(0, nullptr, nullptr) == S_OK); // the shutdown blank } DestroyWindow(window); diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp index 6464b4907..5102c54ab 100644 --- a/runtime/test/xgameruntime_test.cpp +++ b/runtime/test/xgameruntime_test.cpp @@ -231,7 +231,8 @@ void check_run_time_load() { auto query = reinterpret_cast(get_proc(rt_mod, "QueryApiImpl")); auto uninit_api = reinterpret_cast(get_proc(rt_mod, "UninitializeApiImpl")); check(init_ex2(0x2410, 0x0, 0x02, &options) == S_OK, "InitializeApiImplEx2 succeeds offline"); - const GUID some_class = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; + // XGameSaveImpl (xgameruntime include/xgamesave.idl), not served yet. + const GUID some_class = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}}; void* out = reinterpret_cast(1); check(query(&some_class, some_class, &out) == static_cast(0x80070032) && out == nullptr, "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer"); @@ -489,13 +490,13 @@ void check_run_time_load() { {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}}, {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}}, system5}; - bool all = true; + bool all_inherited = true; for (const GUID& iid : chain) { void* same = nullptr; - all = all && query(&system_cls, iid, &same) == S_OK && same == sy; + all_inherited = all_inherited && query(&system_cls, iid, &same) == S_OK && same == sy; if (same) release(same); } - check(all, "IXSystemImpl5 answers for every interface it inherits (IXSystemImpl .. IXSystemImpl4)"); + check(all_inherited, "IXSystemImpl5 answers for every interface it inherits (IXSystemImpl .. IXSystemImpl4)"); check(reinterpret_cast(slot(sy, 5))(sy, sizeof(buf), buf, &used) == S_OK && used == 45 && reinterpret_cast(slot(sy, 5))(sy, 44, buf, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && @@ -512,6 +513,186 @@ void check_run_time_load() { "slots 6-8 (handle tracking, handle check, download bandwidth) answer offline"); release(sy); } + + // XPackageImpl, asked for as libHttpClient.GDK.dll does: the class id with IXPackageImpl3's interface id. The + // slots with an offline answer agree with the named exports; the others are E_NOTIMPL. + const GUID package_cls = {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}}; + const GUID package3 = {0xe2a4734b, 0x2f4a, 0x456d, {0xaa, 0x8f, 0xd0, 0x65, 0xe0, 0x4f, 0xb2, 0x09}}; + void* pk = nullptr; + check(query(&package_cls, package3, &pk) == S_OK && pk, "QueryApiImpl hands out XPackageImpl for IXPackageImpl3"); + if (pk) { + using Ident = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*); + using IdentExport = HRESULT(__stdcall*)(size_t, char*); + char a[64] = {}, b[64] = {}; + const auto ident_export = reinterpret_cast( + rt::shims::find("xgameruntime.dll", "XPackageGetCurrentProcessPackageIdentifier")); + check(reinterpret_cast(slot(pk, 3))(pk, sizeof(a), a) == S_OK && ident_export && + ident_export(sizeof(b), b) == S_OK && std::strcmp(a, b) == 0, + "slot 3 is XPackageGetCurrentProcessPackageIdentifier, the same answer as the export"); + using IsPackaged = bool(STDMETHODCALLTYPE*)(void*); + using IsPackagedExport = bool(__stdcall*)(); + const auto packaged_export = + reinterpret_cast(rt::shims::find("xgameruntime.dll", "XPackageIsPackagedProcess")); + check(packaged_export && reinterpret_cast(slot(pk, 4))(pk) == packaged_export(), + "slot 4 is XPackageIsPackagedProcess"); + // Slot 11, XPackageGetUserLocale: one of the package's declared locales, never the host's; nothing written + // (but S_OK) when the package declares none. + using Locale = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*); + char tmp[MAX_PATH] = {}; + GetTempPathA(sizeof(tmp), tmp); + const std::string game = std::string(tmp) + "leonida_xpackage_locale_test"; + CreateDirectoryA(game.c_str(), nullptr); + SetEnvironmentVariableA("LEONIDA_GAME_DIR", game.c_str()); + char locale[128]; + std::memset(locale, 'z', sizeof(locale)); + check(reinterpret_cast(slot(pk, 11))(pk, sizeof(locale), locale) == S_OK && locale[0] == 'z', + "slot 11 without declared locales: S_OK and nothing written"); + if (FILE* f = std::fopen((game + "\\MicrosoftGame.Config").c_str(), "wb")) { + std::fputs("", + f); + std::fclose(f); + } + check(reinterpret_cast(slot(pk, 11))(pk, sizeof(locale), locale) == S_OK && + (std::strcmp(locale, "zz-ZZ") == 0 || std::strcmp(locale, "xx-YY") == 0) && + reinterpret_cast(slot(pk, 11))(pk, 3, locale) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER), + "slot 11 gives one of the package's declared locales, not the host's; a short buffer is refused"); + DeleteFileA((game + "\\MicrosoftGame.Config").c_str()); + RemoveDirectoryA(game.c_str()); + SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr); + { + // A game folder outside every ANSI code page (U+16A0, a runic letter) reaches MicrosoftGame.Config intact. + wchar_t wtmp[MAX_PATH] = {}; + GetTempPathW(MAX_PATH, wtmp); + const std::wstring wide = std::wstring(wtmp) + L"leonida_xpackage_\u16a0ocale"; + CreateDirectoryW(wide.c_str(), nullptr); + SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", wide.c_str()); + const std::wstring wconfig = wide + L"\\MicrosoftGame.Config"; + if (FILE* f = _wfopen(wconfig.c_str(), L"wb")) { + std::fputs("", f); + std::fclose(f); + } + char wlocale[32] = {}; + check(reinterpret_cast(slot(pk, 11))(pk, sizeof(wlocale), wlocale) == S_OK && + std::strcmp(wlocale, "qq-QQ") == 0, + "slot 11 reads MicrosoftGame.Config from a game folder named outside the ANSI code page"); + DeleteFileW(wconfig.c_str()); + RemoveDirectoryW(wide.c_str()); + SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", nullptr); + } + // Slots 23-26 are the named exports' content-package mounts: XPackageMount, the path size and path of the + // handle, and closing it. XPackageMountHandle is one u64, passed by value. + using Mount = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint64_t*); + using PathSize = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, size_t*); + using Path = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, size_t, char*); + using CloseMount = void(STDMETHODCALLTYPE*)(void*, uint64_t); + SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", "SLOTDLC_12345678901234567890123=C:\\LeonidaSlotDLC"); + uint64_t handle = 0; + size_t need = 0; + char path[MAX_PATH] = {}; + check(reinterpret_cast(slot(pk, 23))(pk, "SLOTDLC_12345678901234567890123", &handle) == S_OK && + handle != 0, + "slot 23 (XPackageMount) mounts a content package and hands out a handle"); + check(reinterpret_cast(slot(pk, 24))(pk, handle, &need) == S_OK && + need == std::strlen("C:\\LeonidaSlotDLC") + 1 && + reinterpret_cast(slot(pk, 25))(pk, handle, need, path) == S_OK && + std::strcmp(path, "C:\\LeonidaSlotDLC") == 0 && + reinterpret_cast(slot(pk, 25))(pk, handle, need - 1, path) == + HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER), + "slots 24/25: the mount's path, and exactly the size XPackageGetMountPath needs"); + reinterpret_cast(slot(pk, 26))(pk, handle); + check(reinterpret_cast(slot(pk, 24))(pk, handle, &need) == HRESULT_FROM_WIN32(ERROR_NOT_FOUND), + "slot 26 (XPackageCloseMountHandle) closes the handle"); + SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", nullptr); + using Stub = HRESULT(STDMETHODCALLTYPE*)(void*); + check(reinterpret_cast(slot(pk, 5))(pk) == E_NOTIMPL && reinterpret_cast(slot(pk, 40))(pk) == E_NOTIMPL, + "the slots without an offline answer (5, 40) are E_NOTIMPL"); + struct Progress { + uint64_t total, installed, launch; + bool launchable, completed; + } progress{~0ull, 7, 7, false, false}; + using GetProgress = void(STDMETHODCALLTYPE*)(void*, void*, Progress*); + reinterpret_cast(slot(pk, 7))(pk, nullptr, &progress); + check(progress.launchable && progress.completed && progress.installed == progress.total, + "slot 7 (void XPackageGetInstallationProgress) writes an installed, launchable, completed package"); + using Update = bool(STDMETHODCALLTYPE*)(void*, void*); + using UnregProgress = bool(STDMETHODCALLTYPE*)(void*, void*, XTaskQueueRegistrationToken, bool); + using UnregInstalled = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool); + using Uninstall = bool(STDMETHODCALLTYPE*)(void*, const char*); + check(!reinterpret_cast(slot(pk, 8))(pk, nullptr) && + reinterpret_cast(slot(pk, 10))(pk, nullptr, XTaskQueueRegistrationToken{1}, true) && + reinterpret_cast(slot(pk, 22))(pk, XTaskQueueRegistrationToken{1}, false) && + !reinterpret_cast(slot(pk, 34))(pk, "pkg"), + "the bool slots 8, 10, 22 and 34 return their documented offline answers"); + const GUID chain[] = { + package_cls, + {0x3720de07, 0xe8e4, 0x44a3, {0xad, 0x32, 0xb3, 0x59, 0xe8, 0xad, 0xbe, 0x55}}, + {0xf92d8712, 0x2b27, 0x4d8a, {0xbf, 0x01, 0x11, 0xa6, 0xf8, 0xe3, 0xeb, 0x42}}, + package3}; + bool all = true; + for (const GUID& iid : chain) { + void* same = nullptr; + all = all && query(&package_cls, iid, &same) == S_OK && same == pk; + if (same) release(same); + } + check(all, "IXPackageImpl3 answers for IXPackageImpl and IXPackageImpl2 too"); + release(pk); + } + { + // XGameImpl (IXGameImpl3 : IXGameImpl2 : IXGameImpl, xgameruntime include/xgame.idl); IXGameImpl's id is the + // class id. Slots: 3 XGameGetXboxTitleId, 4 XLaunchNewGame (void), 5 XLaunchRestartOnCrash. + const GUID game_cls = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; + const GUID game2 = {0x50849859, 0x0ad8, 0x4f81, {0x80, 0xe4, 0x5b, 0xc7, 0x86, 0x26, 0xf8, 0x52}}; + const GUID game3 = {0x2549f142, 0x6419, 0x4a06, {0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34}}; + void* g = get(game_cls); + check(g != nullptr, "QueryApiImpl hands out XGameImpl for its class id"); + bool every = g != nullptr; + for (const GUID& iid : {game2, game3}) { + void* same = nullptr; + every = every && query(&game_cls, iid, &same) == S_OK && same == g; + if (same) release(same); + } + check(every, "XGameImpl answers for IXGameImpl2's and IXGameImpl3's ids, the same object"); + if (g) { + using TitleId = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t*); + using LaunchNew = void(STDMETHODCALLTYPE*)(void*, const char*, const char*, void*); + using Restart = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, uint32_t); + char tmp[MAX_PATH] = {}; + GetTempPathA(sizeof(tmp), tmp); + const std::string game = std::string(tmp) + "leonida_xgame_title_test"; + CreateDirectoryA(game.c_str(), nullptr); + SetEnvironmentVariableA("LEONIDA_GAME_DIR", game.c_str()); + const std::string config = game + "\\MicrosoftGame.Config"; + auto write_config = [&](const char* text) { + if (FILE* f = std::fopen(config.c_str(), "wb")) { + std::fputs(text, f); + std::fclose(f); + } + }; + uint32_t id = 0x5a5a5a5a; + DeleteFileA(config.c_str()); + check(reinterpret_cast(slot(g, 3))(g, &id) == E_FAIL && id == 0x5a5a5a5a, + "slot 3 (XGameGetXboxTitleId) without a config: E_FAIL, nothing written"); + write_config("\n 1a2B3c4D \n\n"); + check(reinterpret_cast(slot(g, 3))(g, &id) == S_OK && id == 0x1A2B3C4Du, + "slot 3 gives the config's (hex, either case, whitespace allowed)"); + check(reinterpret_cast(slot(g, 3))(g, nullptr) == E_INVALIDARG, + "slot 3 with a null pointer is E_INVALIDARG"); + write_config("not-hex"); + id = 0x5a5a5a5a; + check(reinterpret_cast(slot(g, 3))(g, &id) == E_FAIL && id == 0x5a5a5a5a, + "slot 3 refuses a that is not hex"); + write_config("123456789"); + check(reinterpret_cast(slot(g, 3))(g, &id) == E_FAIL, "slot 3 refuses more than 8 hex digits"); + DeleteFileA(config.c_str()); + RemoveDirectoryA(game.c_str()); + SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr); + reinterpret_cast(slot(g, 4))(g, "other.exe", "", nullptr); + check(true, "slot 4 (void XLaunchNewGame) returns offline"); + check(reinterpret_cast(slot(g, 5))(g, "--restarted", 0) == S_OK, + "slot 5 (XLaunchRestartOnCrash) succeeds offline"); + release(g); + } + } check(uninit_api() == S_OK, "UninitializeApiImpl succeeds"); HMODULE k32 = load_w(L"kernel32.dll"); diff --git a/runtime/test/xgameruntime_user_test.cpp b/runtime/test/xgameruntime_user_test.cpp new file mode 100644 index 000000000..3a9b4c8e0 --- /dev/null +++ b/runtime/test/xgameruntime_user_test.cpp @@ -0,0 +1,227 @@ +// XUserImpl through QueryApiImpl, called the way xgameruntime.lib's XUser* thunks call it: QueryApiImpl with the +// class id (or a later interface id), one vtable slot with `this` first. Slots follow xgameruntime-docs' layout; +// arguments and expected values follow the public GDK reference. No game data; nothing online. +// +// xgameruntime_user_test the offline user, its handles, gamertag "Player" +// xgameruntime_user_test --expect-gamertag TAG the same, run with LEONIDA_GAMERTAG=TAG +#include + +#include +#include +#include + +#include +#include +#include + +#include "shims.h" + +namespace rt::shims { +long xgameruntime_user_open_handles(); +} + +namespace { + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +using XUserHandle = void*; +struct XUserLocalId { + uint64_t value; +}; + +constexpr HRESULT E_GAMEUSER_USER_NOT_FOUND = static_cast(0x89245104); +constexpr HRESULT E_GAMEUSER_DEFERRAL_NOT_AVAILABLE = static_cast(0x89245103); +constexpr HRESULT E_GAMEUSER_FAILED_TO_GET_TOKEN = static_cast(0x89245111); + +constexpr GUID kUserClass = {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}}; +constexpr GUID kUserImpl3 = {0x1bf2f8c5, 0xd507, 0x4e52, {0xbb, 0x05, 0xf7, 0x26, 0xd0, 0xe7, 0x11, 0x61}}; +constexpr GUID kUserImpl6 = {0x5131d685, 0x4394, 0x4ee6, {0x8c, 0x18, 0xbf, 0xb5, 0xd4, 0xae, 0xf1, 0xff}}; +constexpr GUID kGamertag = {0xcef4fac0, 0x7676, 0x4a94, {0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74}}; +constexpr GUID kOther = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; // XGameImpl + +using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**); +using Fn = void*; +Fn slot(void* obj, int index) { return (*static_cast(obj))[index]; } +template F at(void* obj, int index) { return reinterpret_cast(slot(obj, index)); } + +// Waits for an XAsyncBlock on the process queue, as a title polling XAsyncGetStatus(wait = true) does. +bool finished(XAsyncBlock* async) { return XAsyncGetStatus(async, true) != E_PENDING; } + +} // namespace + +int main(int argc, char** argv) { + const char* expect_tag = "Player"; + if (argc == 3 && std::strcmp(argv[1], "--expect-gamertag") == 0) expect_tag = argv[2]; + std::printf("xgameruntime_user_test: XUserImpl through QueryApiImpl (gamertag \"%s\")\n", expect_tag); + + auto query = reinterpret_cast(rt::shims::find("xgameruntime.dll", "QueryApiImpl")); + check(query != nullptr, "QueryApiImpl is registered"); + if (!query) return 1; + + // ---- the object and its interfaces ---- + void* user = nullptr; + check(query(&kUserClass, kUserClass, &user) == S_OK && user, "QueryApiImpl hands out XUserImpl for its class id"); + if (!user) return 1; + void* user6 = nullptr; + void* user3 = nullptr; + check(query(&kUserClass, kUserImpl6, &user6) == S_OK && user6 == user && + query(&kUserClass, kUserImpl3, &user3) == S_OK && user3 == user, + "IXUserImpl3 and IXUserImpl6 (later versions of the same vtable) answer with the same object"); + void* tag_face = nullptr; + check(query(&kUserClass, kGamertag, &tag_face) == S_OK && tag_face && tag_face != user, + "IXUserGamertagImpl is a second interface of the object"); + void* none = reinterpret_cast(1); + check(query(&kUserClass, kOther, &none) == E_NOINTERFACE && none == nullptr, + "an interface the class doesn't have is E_NOINTERFACE with a cleared out pointer"); + + // ---- XUserAddAsync / XUserAddResult (slots 7, 8) ---- + using AddAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t, XAsyncBlock*); + using AddResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, XUserHandle*); + XAsyncBlock add{}; + check(at(user, 7)(user, 0x01, &add) == S_OK, "XUserAddAsync(AddDefaultUserSilently) starts"); + check(finished(&add) && XAsyncGetStatus(&add, false) == S_OK, "it completes with S_OK"); + XUserHandle h = nullptr; + check(at(user, 8)(user, &add, &h) == S_OK && h != nullptr, "XUserAddResult hands out a user handle"); + XAsyncBlock bad{}; + check(at(user, 7)(user, 0x01 | 0x02, &bad) == E_INVALIDARG, + "AllowGuests with AddDefaultUserSilently is refused (a guest can't be the default user)"); + XAsyncBlock picker{}; + XUserHandle h_picker = nullptr; + check(at(user, 7)(user, 0x00, &picker) == S_OK && finished(&picker) && + at(user, 8)(user, &picker, &h_picker) == S_OK && h_picker, + "XUserAddAsync without a silent option also adds the offline user (no account picker offline)"); + + // ---- identity (slots 5, 6, 9-14, 19, 20) ---- + using Compare = int32_t(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserHandle); + using MaxUsers = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t*); + using GetLocalId = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserLocalId*); + using FindLocal = HRESULT(STDMETHODCALLTYPE*)(void*, XUserLocalId, XUserHandle*); + using GetId = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint64_t*); + using FindId = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, XUserHandle*); + using GetBool = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, bool*); + using GetU32 = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t*); + using CheckPrivilege = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, uint32_t, bool*, uint32_t*); + uint32_t max_users = 0; + check(at(user, 6)(user, &max_users) == S_OK && max_users == 1, "XUserGetMaxUsers: one local user"); + check(at(user, 5)(user, h, h_picker) == 0, "XUserCompare: both handles name the same user"); + XUserLocalId local{}; + check(at(user, 9)(user, h, &local) == S_OK && local.value != 0, "XUserGetLocalId: a non-zero local id"); + uint64_t xuid = 0; + check(at(user, 11)(user, h, &xuid) == S_OK && xuid != 0, "XUserGetId: a non-zero user id"); + XUserHandle by_local = nullptr, by_id = nullptr, missing = reinterpret_cast(1); + check(at(user, 10)(user, local, &by_local) == S_OK && by_local && + at(user, 5)(user, by_local, h) == 0, + "XUserFindUserByLocalId finds it"); + check(at(user, 10)(user, XUserLocalId{local.value + 1}, &missing) == E_GAMEUSER_USER_NOT_FOUND && + missing == nullptr, + "another local id is E_GAMEUSER_USER_NOT_FOUND"); + check(at(user, 12)(user, xuid, &by_id) == S_OK && by_id, "XUserFindUserById finds it"); + missing = reinterpret_cast(1); + check(at(user, 12)(user, xuid + 1, &missing) == E_GAMEUSER_USER_NOT_FOUND && missing == nullptr, + "another user id is E_GAMEUSER_USER_NOT_FOUND"); + bool guest = true; + check(at(user, 13)(user, h, &guest) == S_OK && !guest, "XUserGetIsGuest: not a guest"); + uint32_t state = 99, age = 99; + check(at(user, 14)(user, h, &state) == S_OK && state == 0, "XUserGetState: SignedIn (0)"); + check(at(user, 19)(user, h, &age) == S_OK && age == 3, "XUserGetAgeGroup: Adult (3)"); + bool has = false; + uint32_t reason = 99; + check(at(user, 20)(user, h, 0, 254, &has, &reason) == S_OK && has && reason == 0, + "XUserCheckPrivilege: granted, deny reason None (0)"); + check(at(user, 13)(user, nullptr, &guest) == E_INVALIDARG, "a null handle is E_INVALIDARG"); + + // ---- XUserResolvePrivilegeWithUiAsync / Result (21, 22) ---- + using ResolveAsync = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, uint32_t, XAsyncBlock*); + using ResolveResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*); + XAsyncBlock resolve{}; + check(at(user, 21)(user, h, 0, 254, &resolve) == S_OK && finished(&resolve) && + at(user, 22)(user, &resolve) == S_OK, + "XUserResolvePrivilegeWithUiAsync completes with S_OK (nothing to resolve)"); + + // ---- tokens: not available offline (23) ---- + using TokenAsync = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, const char*, const char*, size_t, + const void*, size_t, const void*, XAsyncBlock*); + XAsyncBlock token{}; + check(at(user, 23)(user, h, 0, "GET", "https://example.invalid/", 0, nullptr, 0, nullptr, &token) == + E_GAMEUSER_FAILED_TO_GET_TOKEN, + "XUserGetTokenAndSignatureAsync fails before starting: E_GAMEUSER_FAILED_TO_GET_TOKEN"); + + // ---- change events, sign-out deferral (33-36) ---- + using Register = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, void(CALLBACK*)(void*, XUserLocalId, uint32_t), + XTaskQueueRegistrationToken*); + using Unregister = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool); + using Deferral = HRESULT(STDMETHODCALLTYPE*)(void*, void**); + auto on_change = [](void*, XUserLocalId, uint32_t) {}; + XTaskQueueRegistrationToken reg{}; + check(at(user, 33)(user, nullptr, nullptr, on_change, ®) == S_OK && reg.token != 0, + "XUserRegisterForChangeEvent hands out a token"); + check(at(user, 34)(user, reg, false) && at(user, 34)(user, reg, false) && + at(user, 34)(user, XTaskQueueRegistrationToken{999}, false), + "XUserUnregisterForChangeEvent: true, also with wait = false for a token already gone or never issued " + "(false would mean still pending, which never happens offline)"); + void* deferral = reinterpret_cast(1); + check(at(user, 35)(user, &deferral) == E_GAMEUSER_DEFERRAL_NOT_AVAILABLE && deferral == nullptr, + "XUserGetSignOutDeferral: E_GAMEUSER_DEFERRAL_NOT_AVAILABLE (nothing signs out offline)"); + + // ---- IXUserImpl2: XUserAddByIdWithUiAsync / Result (37, 38) ---- + using AddByIdAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, XAsyncBlock*); + XAsyncBlock by_id_add{}, by_other{}; + XUserHandle h_by_id = nullptr, h_other = reinterpret_cast(1); + check(at(user, 37)(user, xuid, &by_id_add) == S_OK && finished(&by_id_add) && + at(user, 38)(user, &by_id_add, &h_by_id) == S_OK && h_by_id, + "XUserAddByIdWithUiAsync with the local user's id adds it"); + check(at(user, 37)(user, xuid + 1, &by_other) == S_OK && finished(&by_other) && + at(user, 38)(user, &by_other, &h_other) == E_GAMEUSER_USER_NOT_FOUND && h_other == nullptr, + "with another id it completes with E_GAMEUSER_USER_NOT_FOUND"); + + // ---- IXUserImpl4: XUserIsStoreUser (42) ---- + using IsStore = bool(STDMETHODCALLTYPE*)(void*, XUserHandle); + check(at(user, 42)(user, h) && at(user, 42)(user, nullptr), + "XUserIsStoreUser: true, also for a null handle (_In_opt_; always true on console)"); + using Unknown = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, size_t, char*, size_t*); + char probe[16] = "untouched"; + size_t probe_used = 42; + check(at(user, 15)(user, h, sizeof(probe), probe, &probe_used) == E_NOTIMPL, + "slot 15 (no public signature) answers E_NOTIMPL rather than S_OK with nothing written"); + + // ---- IXUserGamertagImpl: XUserGetGamertag (3) ---- + using GetTag = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, size_t, char*, size_t*); + auto tag = at(tag_face, 3); + char buf[101] = {}; + size_t used = 0; + const size_t want = std::strlen(expect_tag) + 1; + check(tag(tag_face, h, 0, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0 && used == want, + "XUserGetGamertag(Classic): the gamertag, gamertagUsed counting the terminator"); + check(tag(tag_face, h, 3, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0, + "UniqueModern of a classic gamertag: the same text, no '#' and no suffix"); + check(tag(tag_face, h, 1, sizeof(buf), buf, &used) == S_OK && std::strcmp(buf, expect_tag) == 0, + "Modern: the classic gamertag when none is set"); + check(tag(tag_face, h, 2, sizeof(buf), buf, &used) == S_OK && buf[0] == 0 && used == 1, + "ModernSuffix: empty (just the terminator)"); + check(tag(tag_face, h, 0, want - 1, buf, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER), + "a buffer one byte short is E_INSUFFICIENT_BUFFER"); + check(tag(tag_face, h, 7, sizeof(buf), buf, &used) == E_INVALIDARG, "an unknown component is E_INVALIDARG"); + + // ---- handles: duplicate, close, all accounted for (3, 4) ---- + using Dup = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, XUserHandle*); + using Close = void(STDMETHODCALLTYPE*)(void*, XUserHandle); + XUserHandle dup = nullptr; + check(at(user, 3)(user, h, &dup) == S_OK && dup && dup != h && at(user, 5)(user, dup, h) == 0, + "XUserDuplicateHandle: a new handle for the same user"); + check(rt::shims::xgameruntime_user_open_handles() == 6, "six handles are open: two adds, two finds, an add by id and a duplicate"); + for (XUserHandle x : {h, h_picker, by_local, by_id, h_by_id, dup}) at(user, 4)(user, x); + check(rt::shims::xgameruntime_user_open_handles() == 0, "XUserCloseHandle closes each of them"); + at(user, 4)(user, h); // a double close: the handle is looked up, not read, so this is a no-op + check(rt::shims::xgameruntime_user_open_handles() == 0 && at(user, 13)(user, h, &guest) == E_INVALIDARG, + "a closed handle is refused and closing it again does nothing"); + + std::printf("xgameruntime_user_test: %d of %d checks failed\n", g_failures, g_checks); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 1ad4080f7..bd38cab39 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -10,8 +10,12 @@ #include #include #include +#include +#include +#include #include "shims.h" +#include "startup_trace.h" namespace { @@ -79,10 +83,26 @@ void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) { const BOOL ok = get_stats(kMeasuredKind, stats); check(ok != FALSE, "XMemGetWorkingSetStatistics(kind, 64-byte out) returns TRUE"); + uint64_t total_memory = 0; + std::memcpy(&total_memory, stats + 0, sizeof(total_memory)); + check(ok != FALSE && total_memory != 0, "XMemGetWorkingSetStatistics writes a non-zero total memory at +0"); + + MEMORYSTATUSEX ms{sizeof(ms)}; + if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { + check(ok != FALSE && total_memory == ms.ullTotalPhys, + "XMemGetWorkingSetStatistics total memory (+0) matches GlobalMemoryStatusEx ullTotalPhys"); + } else { + check(ok != FALSE && total_memory == 12ULL * 1024 * 1024 * 1024, + "XMemGetWorkingSetStatistics total memory (+0) falls back to 12 GiB title limit"); + } + uint64_t working_set = 0; std::memcpy(&working_set, stats + 8, sizeof(working_set)); check(ok != FALSE && working_set != 0, "XMemGetWorkingSetStatistics writes a non-zero size at +8"); + check(ok != FALSE && total_memory >= working_set, + "XMemGetWorkingSetStatistics total memory (+0) >= working set (+8)"); + bool tail_untouched = true; for (size_t i = 16; i < sizeof(stats); ++i) { if (stats[i] != 0xa5) { @@ -204,6 +224,48 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge "nonzero XMem allocation attributes are rejected before host allocation"); } +// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. +void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) { + wchar_t temp[MAX_PATH]; + GetTempPathW(MAX_PATH, temp); + const std::wstring path = + std::wstring(temp) + L"xmem_trace_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl"; + DeleteFileW(path.c_str()); + + void* untraced = alloc(64, 0x1111); // trace not open yet: nothing to write, nothing to crash + check(untraced != nullptr, "XMemAlloc with the trace off still allocates"); + free_mem(untraced, 0x1111); + + check(rt::startup_trace::open(path.c_str()), "open the startup trace file"); + void* a = alloc(4096, 0x5e50000); + void* b = alloc(8192, 0x5e50000); // same word again: no second event + void* c = alloc(16, 0x99); + free_mem(a, 0x5e50000); + free_mem(b, 0x5e50000); // same word again: no second event + free_mem(c, 0x99); + free_mem(nullptr, 0x77); // a free-only word is recorded too + rt::startup_trace::close(); + + std::ifstream in(path); + std::stringstream text; + text << in.rdbuf(); + const std::string log = text.str(); + auto count = [&](const std::string& needle) { + int n = 0; + for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n; + return n; + }; + check(count("\"kind\":\"xmem_attributes\"") == 5, "five events: two XMemAlloc words and three XMemFree words"); + check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x5e50000\",\"size\":4096") == 1, + "XMemAlloc 0x5e50000 is recorded once, with the size of the first call"); + check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x99\",\"size\":16") == 1, "XMemAlloc 0x99 is recorded once"); + check(count("\"api\":\"XMemFree\",\"attributes\":\"0x5e50000\"") == 1, "XMemFree 0x5e50000 is recorded once"); + check(count("\"api\":\"XMemFree\",\"attributes\":\"0x77\"") == 1, "XMemFree 0x77 is recorded"); + check(count("\"attributes\":\"0x1111\"") == 0, "nothing was recorded while the trace was off"); + check(count("\"caller\":\"") == 5, "every event names its caller"); + DeleteFileW(path.c_str()); +} + using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); // RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host @@ -277,6 +339,7 @@ int main() { if (virtual_alloc && get_write_watch && reset_write_watch) { test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch); } + test_attribute_trace(alloc, free_mem); test_title_virtual_alloc(); diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py index 3d77bc2bc..433eea00f 100644 --- a/scripts/bench_wave64.py +++ b/scripts/bench_wave64.py @@ -36,13 +36,14 @@ def build(work, name, emulate, llvm_mc): return os.path.join(out, "spirv", name + ".spv") -def segments(spv): - """(segments, continuation segments) of an emulated module: the cases of the scheduler's OpSwitch.""" - text = open(spv[:-4] + ".spvasm", encoding="utf-8").read() - m = re.search(r"OpSwitch %pcv %sw_default ([^\n]+)", text) - if not m: +def segments(spv: str) -> tuple[int, int] | None: + """Count scheduler cases and continuations, including inner switches in a partitioned dispatch.""" + with open(spv[:-4] + ".spvasm", encoding="utf-8") as source: + text = source.read() + tables = re.findall(r"^[ \t]*OpSwitch %pcv %(?:sw_default|swm\d+) ([^\n]+)", text, re.MULTILINE) + if not tables: return None - cases = [int(x) for x in re.findall(r"(\d+) %blk\d+", m.group(1))] + cases = sorted(int(case) for table in tables for case in re.findall(r"(\d+) %blk\d+", table)) blocks = next((i for i, c in enumerate(cases) if c != i), len(cases)) # blocks 0..n-1, then "done" = n, then segments return len(cases), len(cases) - blocks diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1 index 0e016463e..e028fd9de 100644 --- a/scripts/build_llvm_mc.ps1 +++ b/scripts/build_llvm_mc.ps1 @@ -56,9 +56,15 @@ if (-not (Test-Path (Join-Path $src "llvm\CMakeLists.txt"))) { # sparse checkout fails with "Filename too long" (Windows' 260-character limit). Set in the clone's config only. & git clone --quiet --depth 1 --branch "llvmorg-$Version" --filter=blob:none --sparse --config core.longpaths=true https://github.com/llvm/llvm-project $src if ($LASTEXITCODE -ne 0) { throw "git clone of llvmorg-$Version failed." } - & git -C $src sparse-checkout set llvm cmake third-party + # libc: LLVM 23 configures only with its shared headers (llvm/CMakeLists.txt, "LLVM libc is not found"). + & git -C $src sparse-checkout set llvm cmake third-party libc if ($LASTEXITCODE -ne 0) { throw "git sparse-checkout failed." } } +# A source kept by a failed LLVM 23 build of an older version of this script has no libc yet. +if ((Test-Path (Join-Path $src ".git\info\sparse-checkout")) -and -not (Test-Path (Join-Path $src "libc"))) { + & git -C $src sparse-checkout add libc + if ($LASTEXITCODE -ne 0) { throw "git sparse-checkout add libc failed." } +} # -Keep (or an interrupted build) can leave sources from another -Version. # Refuse that checkout rather than silently rebuilding the wrong release or resetting user files. @@ -99,7 +105,8 @@ $batchText = @( ) -join "`r`n" [System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false)) -$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru +# /s with a second pair of quotes: cmd.exe strips only the outer pair, so a path holding & or ^ stays quoted. +$p = Start-Process cmd.exe -ArgumentList "/s", "/c", "`"`"$bat`"`"" -NoNewWindow -PassThru $null = $p.Handle # keeps the exit code readable after WaitForExit try { $p.PriorityClass = "BelowNormal" } catch {} $p.WaitForExit() diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 46dc10291..193bd447e 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -38,7 +38,7 @@ if ((Test-Path $cmake) -and (Test-Path $ninja)) { Write-Warning "VS C++ CMake tools not found: building with cl.exe directly, without the GameInput shim (SDL3). Install the CMake tools component to get it." $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } - $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" } + $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @" @@ -51,6 +51,7 @@ cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /D cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\command_list_test.cpp" /Fe:command_list_test.exe /link /OPT:NOREF || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" "$src\test\vk_pipeline_check.cpp" /Fe:vk_pipeline_check.exe || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1 +if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sampler_test.cpp" /Fe:vk_sampler_test.exe || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\gfx10_descriptors_test.cpp" /Fe:gfx10_descriptors_test.exe || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_bindless_test.cpp" /Fe:vk_bindless_test.exe || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_descriptor_bench.cpp" /Fe:vk_descriptor_bench.exe || exit /b 1 @@ -70,7 +71,8 @@ $bat = Join-Path $out "_build.cmd" $batchText = "@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body`r`n" [System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false)) -$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru +# /s with a second pair of quotes: cmd.exe strips only the outer pair, so a path holding & or ^ stays quoted. +$p = Start-Process cmd.exe -ArgumentList "/s", "/c", "`"`"$bat`"`"" -NoNewWindow -PassThru $null = $p.Handle # keeps the exit code readable after WaitForExit try { $p.PriorityClass = "BelowNormal" } catch {} $p.WaitForExit() diff --git a/scripts/carve_all.ps1 b/scripts/carve_all.ps1 index 6819e4376..f66d20945 100644 --- a/scripts/carve_all.ps1 +++ b/scripts/carve_all.ps1 @@ -26,15 +26,30 @@ foreach ($archive in $archives) { $f = $archive.file $rel = $archive.relative $dest = $archive.destination - if (-not (Test-Path -LiteralPath (Join-Path $dest "index.json"))) { + $index = Join-Path $dest "index.json" + if (-not (Test-Path -LiteralPath $index)) { Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB)) python -I $tool $f.FullName $dest | Select-Object -Last 1 if ($LASTEXITCODE -ne 0) { throw "Carving $rel failed (exit $LASTEXITCODE)" } } - $s = (Get-Content -LiteralPath (Join-Path $dest "index.json") -Raw | ConvertFrom-Json).summary + try { + $s = (Get-Content -LiteralPath $index -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop).summary + foreach ($field in 'files', 'bink2_files', 'span', 'compressed_bytes', 'unread_bytes', 'inflated_bytes') { + $value = $s.$field + if ((($value -isnot [int]) -and ($value -isnot [long])) -or $value -lt 0) { + throw "summary.$field must be a non-negative integer." + } + } + if ($s.span -eq 0 -and ($s.compressed_bytes -ne 0 -or $s.unread_bytes -ne 0)) { + throw 'A zero summary.span requires zero compressed and unread bytes.' + } + } catch { + throw "Invalid carve index '$index': $($_.Exception.Message)" + } + $denominator = [math]::Max(1L, $s.span) $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span - readable = [math]::Round(($s.compressed_bytes) / $s.span, 4) - unread = [math]::Round($s.unread_bytes / $s.span, 4); inflated = $s.inflated_bytes } + readable = [math]::Round($s.compressed_bytes / $denominator, 4) + unread = [math]::Round($s.unread_bytes / $denominator, 4); inflated = $s.inflated_bytes } } $rows | ConvertTo-Json | Set-Content -Encoding utf8 -LiteralPath (Join-Path $Out "coverage.json") $rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py index 0cf71cee9..09bc1d22b 100644 --- a/scripts/check_no_game_data.py +++ b/scripts/check_no_game_data.py @@ -44,35 +44,30 @@ MAGICS = ( ) -def is_pe(head): - """MZ header whose e_lfanew points at a PE signature inside the bytes read.""" - if not head.startswith(b"MZ") or len(head) < 0x40: - return False - offset = int.from_bytes(head[0x3C:0x40], "little") - return head[offset:offset + 4] == b"PE\0\0" - - -def classify(head): - """The format `head` (the first bytes of a file) starts like, or None.""" +def classify(head, pe_signature=None): + """The format a file starts like, or None. `head` is its first bytes; `pe_signature` the 4 bytes at e_lfanew.""" for name, offset, magic in MAGICS: if head[offset:offset + len(magic)] == magic: return name if head.startswith(b"RIFF") and head[8:12] == b"WAVE": return "RIFF WAVE audio" - if is_pe(head): + if head.startswith(b"MZ") and pe_signature == b"PE\0\0": return "PE executable" return None def read_head(path): + """(first bytes, the 4 bytes at e_lfanew or None). The PE signature is read where e_lfanew points, even past + the first bytes or straddling their end; a file too short for it gives fewer than 4 bytes and no match.""" with open(path, "rb") as f: head = f.read(HEAD) - if head.startswith(b"MZ") and len(head) >= 0x40: - offset = int.from_bytes(head[0x3C:0x40], "little") - if HEAD <= offset < 1 << 20: # the PE signature sits past the first bytes read - f.seek(offset) - head += b"\0" * (offset - len(head)) + f.read(4) - return head + if not head.startswith(b"MZ") or len(head) < 0x40: + return head, None + offset = int.from_bytes(head[0x3C:0x40], "little") + if offset + 4 <= len(head): + return head, head[offset:offset + 4] + f.seek(offset) + return head, f.read(4) def tracked_files(root): @@ -86,7 +81,7 @@ def check(paths): for path in paths: if os.path.islink(path) or not os.path.isfile(path): continue # submodules, symlinks, files deleted in the working tree - name = classify(read_head(path)) + name = classify(*read_head(path)) if name: found.append((path, name)) return found @@ -94,9 +89,10 @@ def check(paths): def display(path): try: - return os.path.relpath(path) + path = os.path.relpath(path) except ValueError: # Windows: another drive than the working directory - return path + pass + return path.replace("\n", "\\n").replace("\r", "\\r") # one line per file, even for a name with a newline def main(argv): diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1 index 79ec0ed8d..cf530fd64 100644 --- a/scripts/first_look.ps1 +++ b/scripts/first_look.ps1 @@ -24,8 +24,20 @@ Write-Host "`n== PE inspection" python -I (Join-Path $root "tools\pe_inspect.py") $Exe --game-dir $GameDir --out $out if ($LASTEXITCODE -ne 0) { throw "pe_inspect failed" } +Write-Host "`n== GDK runtime classes and slots called through xgameruntime.lib (read from the file)" +python -I (Join-Path $root "tools\gdk_runtime_calls.py") $Exe --out $out +if ($LASTEXITCODE -ne 0) { Write-Warning "gdk_runtime_calls could not read all of $Exe; its report may be incomplete" } + $rt = Join-Path $root "runtime\build\gta6rt.exe" -if (-not (Test-Path $rt)) { & (Join-Path $PSScriptRoot "build_runtime.ps1") } +# A gta6rt.exe older than the runtime sources (a pull since the last build) would report the old shim table, so it +# is rebuilt then too, not only when missing. +$sources = @("runtime\src", "runtime\shims", "runtime\CMakeLists.txt") | ForEach-Object { Join-Path $root $_ } | + Where-Object { Test-Path $_ } +$newest = $sources | Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending | Select-Object -First 1 +$stale = (Test-Path $rt) -and $newest -and ($newest.LastWriteTime -gt (Get-Item $rt).LastWriteTime) +if ($stale) { Write-Host "runtime\build\gta6rt.exe is older than $($newest.Name): rebuilding it first" } +if (-not (Test-Path $rt) -or $stale) { & (Join-Path $PSScriptRoot "build_runtime.ps1") } Write-Host "`n== Loader dry run (map, relocate, bind imports; nothing executes)" & { # Keep native stderr in the report without letting Windows PowerShell stop the dry run on it. diff --git a/scripts/meta_to_xml.ps1 b/scripts/meta_to_xml.ps1 index 065ad4145..28c6575f6 100644 --- a/scripts/meta_to_xml.ps1 +++ b/scripts/meta_to_xml.ps1 @@ -1,7 +1,7 @@ # Converts carved PSO ('PSIN') and RBF ('RBF0') metadata blobs to XML with CodeWalker.Core's parsers. # Run in Windows PowerShell 5.1. # .\meta_to_xml.ps1 -Carve \carve -Out \meta [-Limit N] -# Each blob becomes \\.xml. Failures go to \failures.txt with the error message. +# Each blob becomes \\.xml. Failures go to \failures.txt (UTF-8 with BOM) with the error message. param( [string]$Carve = "\carve", [string]$Out = "\meta", @@ -14,7 +14,7 @@ Add-Type -Path "$CodeWalker\SharpDX.dll"; Add-Type -Path "$CodeWalker\SharpDX.Ma [void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll") New-Item -ItemType Directory -Force $Out | Out-Null $fail = Join-Path $Out "failures.txt" -"" | Set-Content -LiteralPath $fail +"" | Set-Content -LiteralPath $fail -Encoding utf8 $ok = @{ pso = 0; rbf = 0 }; $bad = @{ pso = 0; rbf = 0 }; $n = 0 foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) { @@ -44,7 +44,7 @@ foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) { } catch { $bad[$kind]++ $msg = $_.Exception.InnerException; if (-not $msg) { $msg = $_.Exception } - "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content -LiteralPath $fail + "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content -LiteralPath $fail -Encoding utf8 } } if ($Limit -and $n -ge $Limit) { break } diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 94de20f26..66400b57a 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -38,6 +38,7 @@ from check import judged_words, words_match # dump words not judged on some de from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT) +from check import run_readback from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py @@ -566,7 +567,7 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, # checker runs them: the test program that owns them judges them. OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test", "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", - "ps_m2_array": "d3d12_m2_formats_test", + "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test", "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", "ps_m3_post": "d3d12_m3_frame_test", "ps_m3_query": "d3d12_m3_frame_test", "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", @@ -576,6 +577,7 @@ OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_transl # Shaders a selected test draws with, built even when the filter leaves them out (#192). DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", + "ps_sample_c": "vs_ids.asm", "ps_sample_c_b": "vs_ids.asm", **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm", **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", @@ -616,6 +618,31 @@ def find_test_programs(build: str, ext: str) -> str | None: return None +def native_folder(path: str, ansi: str = "mbcs") -> str | None: + """`path` spelled so that the native programs this runner starts can open files under it, or None. + + On Windows the test programs and the Vulkan SDK tools (spirv-val, spirv-as) read their command line in the ANSI + code page, so a character outside it, as in a Cyrillic or CJK user name under %TEMP%, reaches them as '?'. Such a + folder is replaced by its 8.3 short name, which is plain ASCII, when the volume keeps one. Elsewhere, and for a + path the code page holds, `path` comes back as it is. `ansi` is the codec of that code page (a parameter so a + test can pick a narrow one). + """ + def fits(p: str) -> bool: + try: + p.encode(ansi) + return True + except UnicodeEncodeError: + return False + + if os.name != "nt" or fits(path): + return path + import ctypes + buf = ctypes.create_unicode_buffer(32768) + n = ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf)) + short = buf.value if 0 < n < len(buf) else "" + return short if short and fits(short) else None + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), @@ -659,7 +686,14 @@ def main() -> int: work = a.work or tempfile.mkdtemp(prefix="leonida_gpu_tests_") try: - return run_suite(a, work) + os.makedirs(work, exist_ok=True) + native = native_folder(work) + if native is None: + print(f"error: the work folder {ascii(work)} has characters outside this PC's ANSI code page and no 8.3 " + "short name, so the test programs and the Vulkan SDK tools can't open files in it. Pass --work " + "with a folder whose path they can, such as C:\\leonida_gpu_work.", file=sys.stderr) + return 2 + return run_suite(a, native) finally: if a.work is None: shutil.rmtree(work, ignore_errors=True) @@ -747,7 +781,7 @@ def run_suite(a, work: str) -> int: cmd.append("--mesh-compute") if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 cmd.append("--pc-tail-ubo") - if os.environ.get("LEONIDA_FMA") in ("glsl", "khr"): # fused multiply-add: GLSL Fma or OpFmaKHR (docs/design.md) + if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) cmd += ["--fma", os.environ["LEONIDA_FMA"]] rc, out = run_cmd(cmd, gpu=False) print("=== rdna2spirv.py ===") @@ -834,7 +868,7 @@ def run_suite(a, work: str) -> int: ok = None if isinstance(problem, Skip) else not problem results.append((name, ok, problem or f"4096 pixels in each of {len(GET_LOD_TESTS[name])} draw(s): the " "clamped and the calculated LOD within 1/16")) - elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", "cs_oob_select", "cs_oob_tail", + elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_smem_sconst_off", "cs_buf_tail", "cs_oob_select", "cs_oob_tail", "cs_buf_swizzle", "cs_cmpx_class_f32", "cs_cvt_pk_u8", "cs_buf_load_sub", "cs_buf_fmt8"): # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. @@ -849,6 +883,8 @@ def run_suite(a, work: str) -> int: # never run with a translator that zero-extends the s_load immediate (reads 4 GiB past the heap) "cs_smem_sload_neg": [0x5EED0004, 0x5EED0000, 0x5EED0004, 0x5EED0004, 0x5EED0008, 0x5EED000C, 0xEEEEEEEE, 0xEEEEEEEE], + # SHADER-328: a constant SGPR offset gives what the run-time one gives (no 32-bit wrap) + "cs_smem_sconst_off": [0, 0x5EED0018, 0x5EED0018, 0x5EED0014], "cs_buf_tail": [0, 0x5EED000C, 0x5EED0008, 0x5EED000C, 0, 0, 0x5EED0010, 0], "cs_oob_select": [0x5EED000C, 0, 0x5EED0014, 0, 0x5EED0018, 0xEEEEEEEE, 0, 0], "cs_oob_tail": [0, 0, 0x5EED0010, 0, 0xBEEF0000, 0xEEEEEEEE, 0, 0x5EED0010], @@ -1099,22 +1135,22 @@ def run_suite(a, work: str) -> int: ok = None if isinstance(problem, Skip) else not problem results.append((name, ok, problem or "4096 RGBA pixels matched")) elif name in ("ps_texture_sample", "ps_cube_sample", "ps_texture_sample_d16", "ps_sample_c_lz", - "ps_sample_c_lz_a16"): + "ps_sample_c_lz_a16", "ps_sample_c", "ps_sample_c_b"): # Bindless texture tests: vk_texture_test finds vs_ids.spv and the shader in its working directory. tool = os.path.join(a.build, "vk_texture_test" + ext) raw = os.path.join(raw_dir, f"{name}.raw") if name == "ps_texture_sample_d16": - Path(raw).unlink(missing_ok=True) cmd = [tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "0", "0", "0", "0"] else: mode = {"ps_cube_sample": ["cube"], "ps_sample_c_lz": ["dref"], - "ps_sample_c_lz_a16": ["dref_a16"]}.get(name, []) + "ps_sample_c_lz_a16": ["dref_a16"], "ps_sample_c": ["dref_c"], + "ps_sample_c_b": ["dref_c_b"]}.get(name, []) cmd = [tool, *mode, raw] - rc, msg = run_cmd(cmd, cwd=spirv_dir) + rc, msg = run_readback(raw, run_cmd, cmd, cwd=spirv_dir) if rc == UNSUPPORTED: # e.g. fewer push constant bytes than the texture tests need results.append((name, None, unsupported_skip(msg))) elif name == "ps_texture_sample_d16" and rc == 0: - ok, detail = check_d16_texture(raw) if os.path.isfile(raw) else (False, "missing RGBA32F readback") + ok, detail = check_d16_texture(raw) results.append((name, ok, detail)) else: results.append((name, rc == 0 and "PASSED" in msg, msg.splitlines()[-1] if msg else "")) @@ -1122,8 +1158,8 @@ def run_suite(a, work: str) -> int: expected = TEXTURE_CONSTANTS[name] tool = os.path.join(a.build, "vk_texture_test" + ext) raw = os.path.join(raw_dir, f"{name}.raw") - rc, msg = run_cmd([tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "92", "c00000", - "14500000", "0"], cwd=spirv_dir) + rc, msg = run_readback(raw, run_cmd, [tool, os.path.join(spirv_dir, "vs_ids.spv"), spv, raw, "0", "92", + "c00000", "14500000", "0"], cwd=spirv_dir) bad = 4096 if rc == 0 and os.path.isfile(raw): data = Path(raw).read_bytes() @@ -1154,8 +1190,8 @@ def run_suite(a, work: str) -> int: # Texel offsets: needs vk_texture_test's texture, sampler and descriptor table (vk_harness binds none), # and VK_KHR_maintenance8 for the non-constant Offset; the tool exits 77 without it. raw = os.path.join(raw_dir, f"{name}.raw") - rc, msg = run_cmd([os.path.join(a.build, "vk_texture_test" + ext), vs_tri, spv, raw, *TEXOFF_ARGS], - env=texoff_env()) + rc, msg = run_readback(raw, run_cmd, [os.path.join(a.build, "vk_texture_test" + ext), vs_tri, spv, raw, + *TEXOFF_ARGS], env=texoff_env()) if rc == UNSUPPORTED: results.append((name, None, unsupported_skip(msg))) elif rc != 0: @@ -1180,7 +1216,7 @@ def run_suite(a, work: str) -> int: bary_gs = os.path.join(spirv_dir, f"{name}.bary_gs.spv") if bary_fallback() and os.path.isfile(bary_gs): # --bary-fallback PS: barycentrics from this GS env = dict(env or os.environ, VKH_GS=bary_gs, VKH_GS_HELPER="1") - rc, msg = run_cmd([vk_harness, vs, spv, raw], env=env) + rc, msg = run_readback(raw, run_cmd, [vk_harness, vs, spv, raw], env=env) if rc == 77: # vk_harness: the device lacks a feature this shader needs (e.g. barycentrics) results.append((name, None, unsupported_skip(msg))) continue @@ -1231,6 +1267,7 @@ def run_suite(a, work: str) -> int: "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000), # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000), + "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000B), # far branches (.asm header) "ps_vcmp_f16": (0x48A12080, 0x4CE9B1A2, 0x4BA72C98, 0x4FEFBDBA), # 16-bit float v_cmp e32 (.asm header) "ps_vcmp_f16_e64": (0x44C11100, 0x4CF171C1, 0x47C71D18, 0x4FF77DD9), # same, e64 with swapped operands "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header) @@ -1278,9 +1315,8 @@ def run_suite(a, work: str) -> int: problem = ij_computed_problem(list(struct.iter_unpack("<4I", source.read()))) ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" elif name == "ps_mandelbrot": - with open(raw, "rb") as source: - px = list(struct.iter_unpack("<4I", source.read())) - problem = mandelbrot_problem(px) + px = read_raw_u32(raw) if os.path.isfile(raw) else [] + problem = frame_problem(px) or mandelbrot_problem(px) ok, detail = not problem, problem or f"{len(px)}/{len(px)} iteration counts match the float32 model" else: ok, detail = False, "no checker defined" @@ -1288,7 +1324,7 @@ def run_suite(a, work: str) -> int: elif name == "gs_tri": raw = os.path.join(raw_dir, f"{name}.raw") env = dict(gfx_env or os.environ, VKH_GS=spv) - rc, msg = run_cmd([vk_harness, vs_tri, fs_loc1, raw], env=env) + rc, msg = run_readback(raw, run_cmd, [vk_harness, vs_tri, fs_loc1, raw], env=env) if rc == UNSUPPORTED: results.append((name, None, unsupported_skip(msg))) elif rc != 0: @@ -1307,7 +1343,7 @@ def run_suite(a, work: str) -> int: elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): raw = os.path.join(raw_dir, f"{name}.raw") env = mesh_env(spirv_dir, name, gfx_env) - rc, msg = run_cmd([vk_harness, spv, fs_passthru, raw], env=env) + rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as # the wave64 compute dumps are. no64 = (name == "ms_w64x_ballot" and not w64_emulated() and @@ -1328,7 +1364,7 @@ def run_suite(a, work: str) -> int: if bary_fallback() and not f16_interp_fallback(): results.append((name, None, "SKIP (per-vertex f16 interpolants need barycentrics)")) continue - rc, msg = run_cmd([vk_harness, spv, fs, raw], env=env) + rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs, raw], env=env) if rc == UNSUPPORTED: results.append((name, None, unsupported_skip(msg))) elif rc != 0: @@ -1340,7 +1376,7 @@ def run_suite(a, work: str) -> int: elif name == "ms_clip": raw = os.path.join(raw_dir, f"{name}.raw") env = mesh_env(spirv_dir, name, gfx_env) - rc, msg = run_cmd([vk_harness, spv, fs_passthru, raw], env=env) + rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) if rc == UNSUPPORTED: results.append((name, None, unsupported_skip(msg))) elif rc != 0: @@ -1353,7 +1389,7 @@ def run_suite(a, work: str) -> int: # ps_flat must still see vertex 0 of instance 0 (0x101), as check.py checks. raw = os.path.join(raw_dir, f"{name}.raw") env = dict(gfx_env or os.environ, VKH_DRAW="16,7") - rc, msg = run_cmd([vk_harness, spv, os.path.join(spirv_dir, "ps_flat.spv"), raw], env=env) + rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, os.path.join(spirv_dir, "ps_flat.spv"), raw], env=env) if rc == UNSUPPORTED: results.append((name, None, unsupported_skip(msg))) elif rc != 0: diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py index 3e90e9ab4..c9d2e5edf 100644 --- a/scripts/run_wine_tests.py +++ b/scripts/run_wine_tests.py @@ -12,11 +12,12 @@ Some tests open files through absolute paths compiled into them (the GLSL test s runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run ($WINEPREFIX, else ~/.wine), unless that drive is already in use there. -Every test is run and reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the +Every test is reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the others show what does and doesn't work under Wine yet without failing the job. --timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test. """ import argparse +from graphlib import CycleError, TopologicalSorter import json import math import ntpath @@ -108,6 +109,24 @@ def properties(test: dict) -> dict: return {p["name"]: p["value"] for p in test.get("properties", [])} +def fixture_dependencies(tests: list[dict]) -> dict[int, tuple[int, ...]]: + """Find the listed setup tests that must finish before each fixture consumer.""" + metadata = [properties(test) for test in tests] + setups: dict[str, list[int]] = {} + for index, props in enumerate(metadata): + for fixture in props.get("FIXTURES_SETUP", []): + setups.setdefault(fixture, []).append(index) + return { + index: tuple(dict.fromkeys( + setup + for fixture in props.get("FIXTURES_REQUIRED", []) + for setup in setups.get(fixture, ()) + if setup != index + )) + for index, props in enumerate(metadata) + } + + def truthy(value) -> bool: """A ctest boolean property. The JSON carries it as a string, so "0" must stay false.""" return str(value).strip().lower() in ("1", "on", "true", "yes") @@ -118,7 +137,7 @@ def regex_list(value: str | list[str]) -> list[str]: return [value] if isinstance(value, str) else value -def run_test(test: dict, args, wine: list[str]) -> tuple[str, str]: +def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ...] = ()) -> tuple[str, str]: """Returns (status, detail): status is pass, fail or skip.""" props = properties(test) if truthy(props.get("DISABLED")): @@ -132,6 +151,8 @@ def run_test(test: dict, args, wine: list[str]) -> tuple[str, str]: return "skip", f"runs {command[0]}, not a program from the build" if not os.path.isfile(exe): return "fail", f"executable not in the artifact: {command[0]}" + if failed_setups: + return "fail", "failed fixture setup: " + ", ".join(failed_setups) argv = list(wine) + [exe] for a in command[1:]: mapped = map_path(a, args.windows_root, args.root) @@ -222,6 +243,20 @@ def wine_command(text: str) -> list[str]: return parts +def valid_test_row(test) -> bool: + if not isinstance(test, dict) or not isinstance(test.get("name"), str): + return False + # CTest can omit the command for a target that was not built. + command = test.get("command", []) + if not isinstance(command, list) or not all(isinstance(arg, str) and "\0" not in arg for arg in command): + return False + entries = test.get("properties", []) + return isinstance(entries, list) and all( + isinstance(entry, dict) and isinstance(entry.get("name"), str) and "value" in entry + for entry in entries + ) + + def read_tests(path: str) -> list[dict] | None: """The tests in a `ctest --show-only=json-v1` file, or None when it is not one.""" try: @@ -231,7 +266,7 @@ def read_tests(path: str) -> list[dict] | None: print(f"ERROR: cannot read {path}: {e}", file=sys.stderr) return None tests = doc.get("tests") if isinstance(doc, dict) else None - if not isinstance(tests, list) or not all(isinstance(t, dict) for t in tests): + if not isinstance(tests, list) or not all(valid_test_row(t) for t in tests): print(f"ERROR: {path} is not the output of ctest --show-only=json-v1", file=sys.stderr) return None return tests @@ -254,14 +289,22 @@ def main() -> int: tests = read_tests(args.tests) if tests is None: return 2 + dependencies = fixture_dependencies(tests) + try: + order = list(TopologicalSorter(dependencies).static_order()) + except CycleError: + print("ERROR: CTest fixture setup dependencies form a cycle", file=sys.stderr) + return 2 wine = args.wine results = {} prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") + names = [test.get("name", "?") for test in tests] with DriveMap(args.windows_root, args.root, prefix) as drive: print(drive.note, flush=True) - for test in tests: - name = test.get("name", "?") - status, detail = run_test(test, args, wine) + for index in order: + name = names[index] + failed_setups = tuple(names[setup] for setup in dependencies[index] if results[names[setup]] == "fail") + status, detail = run_test(tests[index], args, wine, failed_setups=failed_setups) results[name] = status print(f"[{status.upper()}] {name}", flush=True) if status != "pass": diff --git a/scripts/vs_input_survey.py b/scripts/vs_input_survey.py index 89e648364..fa6701c15 100644 --- a/scripts/vs_input_survey.py +++ b/scripts/vs_input_survey.py @@ -26,10 +26,13 @@ from collections import Counter ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) import shader_ir # noqa: E402 +from shader_meta import SGPR_RMW # noqa: E402 NO_DEST_OPS = ("s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe", "s_branch", "s_cbranch", "s_waitcnt", "s_barrier", - "s_nop", "s_endpgm", "s_sendmsg", "s_sleep", "exp", "buffer_store", "global_store", "flat_store", - "scratch_store", "image_store", "ds_write") + "s_nop", "s_endpgm", "s_sendmsg", "s_sleep", "exp", "buffer_store", "tbuffer_store", "global_store", + "flat_store", "scratch_store", "s_store", "s_buffer_store", "image_store", "ds_write") +DUAL_DST_VALU = ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64") +DS_RETURNING = ("ds_read", "ds_bpermute", "ds_permute", "ds_swizzle", "ds_consume", "ds_append", "ds_ordered_count") PRIM_EXPORT = re.compile(r"^\s*exp\s+prim\b", re.M) POS0_EXPORT = re.compile(r"^\s*exp\s+pos0\b", re.M) PARAM_EXPORT = re.compile(r"^\s*exp\s+param\d+\b", re.M) @@ -45,6 +48,20 @@ def base_op(op): return op +def _expand_regs(a): + """Return ('s' | 'v', iterable of register indices) for an operand, or (None, ()).""" + k = a["k"] + if k == "sgpr": + return "s", range(a["r"], a["r"] + a.get("n", 1)) + if k == "vgpr": + return "v", range(a["r"], a["r"] + a.get("n", 1)) + if k == "slist": + return "s", (r for r in a["r"] if isinstance(r, int)) + if k == "vlist": + return "v", (r for r in a["r"] if isinstance(r, int)) + return None, () + + def read_before_write(insns): """(SGPRs, VGPRs) read before any write, straight-line from the first instruction.""" written_s, written_v, read_s, read_v = set(), set(), set(), set() @@ -52,32 +69,51 @@ def read_before_write(insns): op, args = base_op(ins["op"]), ins["args"] if not args: continue - no_dest = op.startswith(NO_DEST_OPS) - dst_read = "fmac" in op or "mac_" in op or op in ("v_writelane_b32", "v_swap_b32") or "_atomic_" in op - if not no_dest and op.startswith("v_") and "_co_" in op and "_ci_" not in op and len(args) >= 2: - dsts, srcs = args[:2], args[2:] # v_add_co_u32 writes a VGPR and a carry - elif no_dest: + mods = ins.get("mods", ()) + is_gf_atomic = op.startswith(("global_atomic_", "flat_atomic_")) + is_bi_atomic = op.startswith(("buffer_atomic_", "image_atomic_")) + is_ds_no_dest = op.startswith("ds_") and not op.startswith(DS_RETURNING) and "_rtn" not in op + no_dest = ( + op.startswith(NO_DEST_OPS) + or ((is_gf_atomic or is_bi_atomic) and "glc" not in mods) + or is_ds_no_dest + or (op.startswith("v_cmp_") and len(args) <= 2) + ) + if no_dest: dsts, srcs = [], args + elif op == "v_swap_b32" and len(args) >= 2: + dsts, srcs = args[:2], args[:2] + elif (op.startswith("v_") and ("_co_" in op or op in DUAL_DST_VALU) + and len(args) >= 2 and args[1]["k"] in ("sgpr", "special", "slist")): + dsts, srcs = args[:2], args[2:] # vdst + scalar carry/scale-out dst else: + dst_read = ( + op in SGPR_RMW or "fmac" in op or "mac_" in op + or op.startswith(("v_dot2c_", "v_dot4c_", "v_dot8c_")) + or op == "v_writelane_b32" or is_bi_atomic + ) dsts, srcs = args[:1], (args[:1] if dst_read else []) + args[1:] for a in srcs: - regs = range(a["r"], a["r"] + a.get("n", 1)) if a["k"] in ("sgpr", "vgpr") else () + kind, regs = _expand_regs(a) for r in regs: - if a["k"] == "sgpr" and r not in written_s: + if kind == "s" and r not in written_s: read_s.add(r) - elif a["k"] == "vgpr" and r not in written_v: + elif kind == "v" and r not in written_v: read_v.add(r) for a in dsts: - if a["k"] == "sgpr": - written_s.update(range(a["r"], a["r"] + a.get("n", 1))) - elif a["k"] == "vgpr": - written_v.update(range(a["r"], a["r"] + a.get("n", 1))) + kind, regs = _expand_regs(a) + if kind == "s": + written_s.update(regs) + elif kind == "v": + written_v.update(regs) return read_s, read_v def survey(dxbc_dir): with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: index = json.load(f) + if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): + raise ValueError("index.json is not a list of shader entries") names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"] markers, vgprs, families = Counter(), Counter(), Counter() missing = 0 @@ -115,7 +151,15 @@ def main(): ap.add_argument("dxbc", help="/shaders/dxbc from make_game.py") ap.add_argument("--json", help="also write the counts as JSON") a = ap.parse_args() - r = survey(a.dxbc) + index_path = os.path.join(a.dxbc, "index.json") + if a.json and os.path.exists(a.json) and os.path.exists(index_path) and os.path.samefile(a.json, index_path): + print(f"vs_input_survey: error: --json would overwrite the input {index_path}", file=sys.stderr) + return 2 + try: + r = survey(a.dxbc) + except (OSError, ValueError) as e: # missing or non-folder , unreadable, non-UTF-8 or malformed index.json + print(f"vs_input_survey: error: cannot read {index_path}: {e}", file=sys.stderr) + return 2 m = r["markers"] print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)") print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}") @@ -125,8 +169,12 @@ def main(): legacy = not (m.get("exp prim") or m.get("s_sendmsg") or m.get("v_mbcnt")) print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout") if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(r, f, indent=1) + try: + with open(a.json, "w", encoding="utf-8", newline="\n") as f: + json.dump(r, f, indent=1) + except OSError as e: + print(f"vs_input_survey: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) + return 2 return 0 diff --git a/tests/conftest.py b/tests/conftest.py index 4cece6b65..0a22c3129 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -137,7 +137,8 @@ MS_TRI_DXBC = make_dxbc([mesh_psv0_chunk()]) MS_CLIP_DXBC = make_dxbc([mesh_psv0_chunk(), signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, 0x1)])]) # SV_Position + SV_ClipDistance.x SAMPLE_DXBC = {"gs_tri": GS_TRI_DXBC, "ms_tri": MS_TRI_DXBC, "ms_clip": MS_CLIP_DXBC, "ms_wave_info_s3": MS_TRI_DXBC, - "ms_w64x_ballot": MS_TRI_DXBC, + "ms_w64x_ballot": MS_TRI_DXBC, "ms_f16_pack": MS_TRI_DXBC, # scripts/run_gpu_tests.py, ms_tri's PSV0 + "gs_w64_a_ring": GS_TRI_DXBC, "gs_w64_c_lane_id": GS_TRI_DXBC, # build.py gives every gs_* gs_tri's "ms_v5_workgroup": make_dxbc([mesh_psv0_chunk(threads=(32, 1, 1), max_vertices=3, max_primitives=1, group_shared=128)])} diff --git a/tests/semantic/README.md b/tests/semantic/README.md index 505708c1b..ecd719017 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -127,10 +127,14 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): `Fma`). - `test_fixtures.py` checks `tests/semantic/fixtures/disasm/*.s` equals what `regen_fixtures.py` makes from `runtime/test/shaders/*.asm` (`python tests/semantic/regen_fixtures.py` rewrites them). +- `test_dpp_eager_subgroup.py` (SHADER-529) checks that no DPP ballot or shuffle is left where SPIRV-Cross + (MoltenVK) would inline it into a short-circuiting `&&`/`||` or a ternary's arm, for 11 DPP16/DPP8 forms with + and without a lane off in EXEC, using a model of SPIRV-Cross's single-use forwarding (its own tests cover the + model). It also runs the same programs in `spirv_wave_interp.py` against a plain-Python DPP reference. Limits: single lane (or lanes in lockstep, one instruction per lane per round, that exchange values only through -`OpGroupNonUniformShuffle`, `Ballot`, `Any`, `All` and `BitwiseOr` Reduce), forward-only structured control flow (the fragment-exit discard test and the compute -dynamic-bounds merge; no backward branches, loops, calls or switches), no texture access. PushConstant words, +`OpGroupNonUniformShuffle`, `Ballot`, `Any`, `All` and `BitwiseOr` Reduce), control flow followed one branch at a time (the fragment-exit discard test, the compute +dynamic-bounds merge, loops of up to 10000 backward branches and calls of the module's own functions; no switches), no texture access. PushConstant words, Input variables and a flat physical-address `{address: word}` map can be supplied per run. A shift by at least the bit width is an undefined value: arithmetic on it stays undefined and any other use (store, branch or select condition, shuffle, output) raises. Values that pass through a float op lose NaN payloads (Python floats), so expected output words avoid NaN bit patterns; a diff --git a/tests/semantic/f16_ref.py b/tests/semantic/f16_ref.py new file mode 100644 index 000000000..fd108aae6 --- /dev/null +++ b/tests/semantic/f16_ref.py @@ -0,0 +1,116 @@ +"""Plain-Python binary16 reference for the semantic f16 tests (standard library only). + +Finite results are computed exactly with fractions and rounded once, to nearest even, into binary16 (subnormals and +overflow to infinity included); infinities and NaNs follow IEEE 754. A NaN result is compared by class, not payload: +use same_f16(). +""" +import math +import struct +from fractions import Fraction + +OLD = 0xDEADBEEF # destination seed: whichever half an instruction does not write must survive + + +def f16_value(h): + """The float a binary16 word stands for (exact).""" + return struct.unpack(" x: + e -= 1 + q = Fraction(2) ** (max(e, -14) - 10) + m, rem = divmod(x, q) + m = int(m) + if rem > q / 2 or (rem == q / 2 and m & 1): + m += 1 + # m counts quanta; at or above 2^11 quanta the exponent steps up (the same encoding handles the carry). + if m < 0x400: # subnormal + return sign | m + exp = max(e, -14) + while m >= 0x800: + m >>= 1 + exp += 1 + bits = ((exp + 15) << 10) | (m - 0x400) + return sign | (0x7C00 if bits >= 0x7C00 else bits) + + +def to_f16(v): + """binary16 word for a float or Fraction result (inf and NaN pass through).""" + if isinstance(v, float): + if math.isnan(v): + return 0x7E00 + if math.isinf(v): + return 0x7C00 if v > 0 else 0xFC00 + v = Fraction(v) + return round_f16(v) + + +def _special(*hs): + return any((h & 0x7C00) == 0x7C00 for h in hs) + + +def ref_add(a, b): + if _special(a, b): + return to_f16(f16_value(a) + f16_value(b)) + if a == 0x8000 and b == 0x8000: + return 0x8000 + return round_f16(Fraction(f16_value(a)) + Fraction(f16_value(b))) + + +def ref_sub(a, b): + return ref_add(a, b ^ 0x8000) if not is_nan(b) else ref_add(a, b) + + +def ref_mul(a, b): + if _special(a, b): + return to_f16(f16_value(a) * f16_value(b)) + r = round_f16(Fraction(f16_value(a)) * Fraction(f16_value(b))) + return r | (0x8000 if (a ^ b) & 0x8000 and r == 0 else 0) # a zero product keeps the sign rule + + +def ref_fma(a, b, c): + if _special(a, b, c): + return to_f16(f16_value(a) * f16_value(b) + f16_value(c)) + p = Fraction(f16_value(a)) * Fraction(f16_value(b)) + if p == 0 and (c & 0x7FFF) == 0: + # +-0 + +-0: negative only when both are negative + return 0x8000 if ((a ^ b) & 0x8000) and (c & 0x8000) else 0 + return round_f16(p + Fraction(f16_value(c))) + + +def neg(h): + return h ^ 0x8000 + + +def fabs(h): + return h & 0x7FFF + + +def scale(h, factor): + """h * factor for a power-of-two output modifier (inputs here stay in the normal range).""" + return to_f16(f16_value(h) * factor) if not is_nan(h) else h + + +def clamp01(h): + """clamp to [0, 1]; a NaN becomes +0.""" + if is_nan(h): + return 0 + v = f16_value(h) + return 0x3C00 if v > 1.0 else (0 if v < 0.0 or h == 0x8000 else h) diff --git a/tests/semantic/fixtures/bfi_known_mask.asm b/tests/semantic/fixtures/bfi_known_mask.asm new file mode 100644 index 000000000..72c2f81d4 --- /dev/null +++ b/tests/semantic/fixtures/bfi_known_mask.asm @@ -0,0 +1,11 @@ +; Zero, full, shifted contiguous SGPR and sparse literal masks. +; Expected MRT0 words: 3f123456 4055aa7e 3f553456 3f523476. + v_mov_b32 v0, 0x4055aa7e + v_mov_b32 v1, 0x3f123456 + v_bfi_b32 v2, 0, v0, v1 + v_bfi_b32 v3, -1, v0, v1 + s_mov_b32 s8, 0x00ff0000 + v_bfi_b32 v4, s8, v0, v1 + v_bfi_b32 v5, 0x00f000f0, v0, v1 + exp mrt0 v2, v3, v4, v5 done vm + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_smem_sconst_off.s b/tests/semantic/fixtures/disasm/cs_smem_sconst_off.s new file mode 100644 index 000000000..581b6c7f7 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_smem_sconst_off.s @@ -0,0 +1,35 @@ +; cs_smem_sconst_off test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_smem_sconst_off.asm + v_cmpx_eq_u32_e32 0, v0 + v_mov_b32 v1, 0x5eed0000 + v_mov_b32 v2, 0x5eed0004 + v_mov_b32 v3, 0x5eed0008 + v_mov_b32 v4, 0x5eed000c + buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 + v_mov_b32 v1, 0x5eed0010 + v_mov_b32 v2, 0x5eed0014 + v_mov_b32 v3, 0x5eed0018 + v_mov_b32 v4, 0x5eed001c + buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 + v_mov_b32 v5, 4 + buffer_store_dword v5, off, s[0:3], 0 offset:96 + s_waitcnt vmcnt(0) + s_mov_b32 s4, 0x40 + s_mov_b32 s5, 0 + s_mov_b32 s6, 0x40 + s_mov_b32 s7, 0x31016fac + s_mov_b32 s8, -4 + s_buffer_load_dword s9, s[0:3], 0x60 + s_mov_b32 s10, 4 + s_mov_b32 s11, 0x10 + s_waitcnt lgkmcnt(0) + s_buffer_load_dword s24, s[4:7], s8 offset:0x14 + s_buffer_load_dword s25, s[4:7], s9 offset:0x14 + s_buffer_load_dword s26, s[4:7], s10 offset:0x14 + s_buffer_load_dword s27, s[4:7], s11 offset:0x4 + s_waitcnt lgkmcnt(0) + v_mov_b32 v1, s24 + v_mov_b32 v2, s25 + v_mov_b32 v3, s26 + v_mov_b32 v4, s27 + buffer_store_dwordx4 v[1:4], off, s[0:3], 0 + s_endpgm diff --git a/tests/semantic/fixtures/disasm/ps_far_branch.s b/tests/semantic/fixtures/disasm/ps_far_branch.s new file mode 100644 index 000000000..bb7b93856 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_far_branch.s @@ -0,0 +1,295 @@ +; ps_far_branch llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding output for runtime/test/shaders/ps_far_branch.asm (the far branches need the instruction encodings; test_far_branch.py checks this listing against the .asm) + s_mov_b32 s10, 1 ; encoding: [0x81,0x03,0x8a,0xbe] + s_getpc_b64 s[4:5] ; encoding: [0x00,0x1f,0x84,0xbe] + s_add_u32 s4, s4, 0xb8 ; encoding: [0x04,0xff,0x04,0x80,0xb8,0x00,0x00,0x00] + s_addc_u32 s5, s5, 0 ; encoding: [0x05,0x80,0x05,0x82] + s_setpc_b64 s[4:5] ; encoding: [0x04,0x20,0x80,0xbe] + s_or_b32 s10, s10, 0x100 ; encoding: [0x0a,0xff,0x0a,0x88,0x00,0x01,0x00,0x00] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_or_b32 s10, s10, 2 ; encoding: [0x0a,0x82,0x0a,0x88] + s_getpc_b64 s[8:9] ; encoding: [0x00,0x1f,0x88,0xbe] + s_add_u32 s8, s8, 0xb8 ; encoding: [0x08,0xff,0x08,0x80,0xb8,0x00,0x00,0x00] + s_addc_u32 s9, s9, 0 ; encoding: [0x09,0x80,0x09,0x82] + s_setpc_b64 s[8:9] ; encoding: [0x08,0x20,0x80,0xbe] + s_or_b32 s10, s10, 0x200 ; encoding: [0x0a,0xff,0x0a,0x88,0x00,0x02,0x00,0x00] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_or_b32 s10, s10, 4 ; encoding: [0x0a,0x84,0x0a,0x88] + s_mov_b32 s11, 0 ; encoding: [0x80,0x03,0x8b,0xbe] + s_add_u32 s11, s11, 1 ; encoding: [0x0b,0x81,0x0b,0x80] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_cmp_ge_u32 s11, 3 ; encoding: [0x0b,0x83,0x09,0xbf] + s_cbranch_scc1 5 ; encoding: [0x05,0x00,0x85,0xbf] + s_getpc_b64 s[6:7] ; encoding: [0x00,0x1f,0x86,0xbe] + s_sub_u32 s6, s6, 0xb0 ; encoding: [0x06,0xff,0x86,0x80,0xb0,0x00,0x00,0x00] + s_subb_u32 s7, s7, 0 ; encoding: [0x07,0x80,0x87,0x82] + s_setpc_b64 s[6:7] ; encoding: [0x06,0x20,0x80,0xbe] + s_or_b32 s11, s11, 16 ; encoding: [0x0b,0x90,0x0b,0x88] + s_mov_b32 s12, 0 ; encoding: [0x80,0x03,0x8c,0xbe] + s_add_u32 s12, s12, 16 ; encoding: [0x0c,0x90,0x0c,0x80] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_cmp_ge_u32 s12, 0x50 ; encoding: [0x0c,0xff,0x09,0xbf,0x50,0x00,0x00,0x00] + s_cbranch_scc1 5 ; encoding: [0x05,0x00,0x85,0xbf] + s_getpc_b64 s[8:9] ; encoding: [0x00,0x1f,0x88,0xbe] + s_add_u32 s8, s8, 0xffffff4c ; encoding: [0x08,0xff,0x08,0x80,0x4c,0xff,0xff,0xff] + s_addc_u32 s9, s9, -1 ; encoding: [0x09,0xc1,0x09,0x82] + s_setpc_b64 s[8:9] ; encoding: [0x08,0x20,0x80,0xbe] + s_or_b32 s12, s12, 1 ; encoding: [0x0c,0x81,0x0c,0x88] + s_mov_b32 s13, 0 ; encoding: [0x80,0x03,0x8d,0xbe] + s_cmp_eq_u32 s13, 1 ; encoding: [0x0d,0x81,0x06,0xbf] + s_cbranch_scc0 5 ; encoding: [0x05,0x00,0x84,0xbf] + s_getpc_b64 s[4:5] ; encoding: [0x00,0x1f,0x84,0xbe] + s_add_u32 s4, s4, 0xb4 ; encoding: [0x04,0xff,0x04,0x80,0xb4,0x00,0x00,0x00] + s_addc_u32 s5, s5, 0 ; encoding: [0x05,0x80,0x05,0x82] + s_setpc_b64 s[4:5] ; encoding: [0x04,0x20,0x80,0xbe] + s_or_b32 s13, s13, 1 ; encoding: [0x0d,0x81,0x0d,0x88] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_or_b32 s13, s13, 2 ; encoding: [0x0d,0x82,0x0d,0x88] + s_cmp_eq_u32 s13, 3 ; encoding: [0x0d,0x83,0x06,0xbf] + s_cbranch_scc0 5 ; encoding: [0x05,0x00,0x84,0xbf] + s_getpc_b64 s[4:5] ; encoding: [0x00,0x1f,0x84,0xbe] + s_add_u32 s4, s4, 0xb4 ; encoding: [0x04,0xff,0x04,0x80,0xb4,0x00,0x00,0x00] + s_addc_u32 s5, s5, 0 ; encoding: [0x05,0x80,0x05,0x82] + s_setpc_b64 s[4:5] ; encoding: [0x04,0x20,0x80,0xbe] + s_or_b32 s13, s13, 4 ; encoding: [0x0d,0x84,0x0d,0x88] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_nop 0 ; encoding: [0x00,0x00,0x80,0xbf] + s_or_b32 s13, s13, 8 ; encoding: [0x0d,0x88,0x0d,0x88] + v_mov_b32_e32 v10, s10 ; encoding: [0x0a,0x02,0x14,0x7e] + v_mov_b32_e32 v11, s11 ; encoding: [0x0b,0x02,0x16,0x7e] + v_mov_b32_e32 v12, s12 ; encoding: [0x0c,0x02,0x18,0x7e] + v_mov_b32_e32 v13, s13 ; encoding: [0x0d,0x02,0x1a,0x7e] + exp mrt0 v10, v11, v12, v13 done vm ; encoding: [0x0f,0x18,0x00,0xf8,0x0a,0x0b,0x0c,0x0d] + s_endpgm ; encoding: [0x00,0x00,0x81,0xbf] diff --git a/tests/semantic/fixtures/gather_offset_a16.asm b/tests/semantic/fixtures/gather_offset_a16.asm new file mode 100644 index 000000000..f66735e20 --- /dev/null +++ b/tests/semantic/fixtures/gather_offset_a16.asm @@ -0,0 +1,12 @@ +; Two 2D mips (8x8, 4x4), with green texel value 100*mip + 10*y + x. +; Expected taps at mip 1: (131,132,122,121). The mip-zero form gives (43,44,34,33). +; Full-word offset (-1,+1), packed coordinates (0.625,0.375), LOD 1 and padding. +s_mov_b32 s8, 0x12 +s_mov_b32 s9, 0x100000 +v_mov_b32 v4, 0x013f +v_mov_b32 v5, 0x36003900 +v_mov_b32 v6, 0x48003c00 +image_gather4_l_o v[0:3], v[4:6], s[0:7], s[8:11] dmask:0x2 dim:SQ_RSRC_IMG_2D a16 +s_waitcnt vmcnt(0) +exp mrt0 v0, v1, v2, v3 done vm +s_endpgm diff --git a/tests/semantic/fixtures/lerp_packed_bytes.asm b/tests/semantic/fixtures/lerp_packed_bytes.asm new file mode 100644 index 000000000..4d2212db6 --- /dev/null +++ b/tests/semantic/fixtures/lerp_packed_bytes.asm @@ -0,0 +1,20 @@ +; Each source has four unsigned bytes. Only bit 0 of each S2 byte rounds. +; Expected MRT0 words: 40ff7f80 40807f80 41800080 41123456. + v_mov_b32 v0, 0x40ff00ff + v_mov_b32 v1, 0x40ffff01 + v_mov_b32 v2, 0x01ff00ff + v_lerp_u8 v4, v0, v1, v2 + v_mov_b32 v0, 0x40807fff + v_mov_b32 v1, 0x407f8001 + v_mov_b32 v2, 0xfe01fe00 + v_lerp_u8 v5, v0, v1, v2 + v_mov_b32 v0, 0x41ff0000 + v_mov_b32 v1, 0x400000ff + v_mov_b32 v2, 0x01010101 + v_lerp_u8 v6, v0, v1, v2 + v_mov_b32 v0, 0x42123456 + v_mov_b32 v1, 0x40123456 + v_mov_b32 v2, 0xfefefefe + v_lerp_u8 v7, v0, v1, v2 + exp mrt0 v4, v5, v6, v7 done vm + s_endpgm diff --git a/tests/semantic/fixtures/partial_color_exports.asm b/tests/semantic/fixtures/partial_color_exports.asm new file mode 100644 index 000000000..d3bb12c7e --- /dev/null +++ b/tests/semantic/fixtures/partial_color_exports.asm @@ -0,0 +1,12 @@ +; MRT0: sparse uncompressed components. MRT1: compressed half pairs. +v_mov_b32_e32 v0, 0x3f800000 +v_mov_b32_e32 v1, 0x40000000 +v_mov_b32_e32 v2, 0x40400000 +v_mov_b32_e32 v3, 0x40800000 +v_mov_b32_e32 v4, 0x46004500 +v_mov_b32_e32 v5, 0x48004700 +exp mrt0 v0, off, v2, off +exp mrt1 v4, v4, off, off compr +exp mrt0 off, v1, off, v3 +exp mrt1 off, off, v5, v5 done compr vm +s_endpgm diff --git a/tests/semantic/lds_run.py b/tests/semantic/lds_run.py new file mode 100644 index 000000000..01051c8d9 --- /dev/null +++ b/tests/semantic/lds_run.py @@ -0,0 +1,74 @@ +"""Shared helper for the LDS tests: translate a hand-written compute listing with tools/rdna2spirv.py and run it +lane by lane in spirv_mini_interp (standard library only; no GPU, no game files). + +The listing sees v0 = the lane's thread id x and s[0:3] = a 4 KiB output buffer. `store(reg, slot)` writes a VGPR +to out[lane * 8 + slot] (32 bytes per lane); `out(mem, lane, slot)` reads it back. + +spirv_mini_interp keeps LDS per invocation (run_workgroup does not share a Workgroup variable between lanes), so a +test that needs one lane's atomics to see another's cannot be written; `run_chain` runs one lane through a sequence +of DS operations on a few dwords instead and returns every value it returned and every dword it left. +""" +import struct + +import support +import spirv_mini_interp as si + +M32 = 0xFFFFFFFF +# RSRC2 0x40088: 4 user SGPRs (the output V#), workgroup id in s4, LDS_SIZE = 8 x 512 bytes = 4 KiB. +RSRC2_4K = 0x40088 +VSHARP = [0, 0, 0x1000, 0x31016FAC] +SLOT_BYTES = 32 + + +def fssm(rsrc2=RSRC2_4K, size=(32, 1, 1)): + blob = bytearray(0x148) + struct.pack_into("<4I", blob, 0x138, rsrc2, *size) + return bytes(blob) + + +def prologue(): + """v30 = lane * 32 (this lane's output slot base).""" + return ["v_lshlrev_b32_e32 v30, 5, v0"] + + +def store(reg, slot): + return [f"v_add_nc_u32_e32 v31, {slot * 4}, v30", f"buffer_store_dword {reg}, v31, s[0:3], 0 offen"] + + +def translate(body, rsrc2=RSRC2_4K, size=(32, 1, 1), name="cs_lds_real"): + return support.translate_lines(name, list(body) + ["s_endpgm"], fssm=fssm(rsrc2, size)) + + +def run(body, lanes=32, rsrc2=RSRC2_4K, size=(32, 1, 1)): + """Translate and run `lanes` lanes in lockstep; return {byte address: dword} of the output buffer.""" + spv = translate(prologue() + list(body), rsrc2, size) + return si.run_workgroup(spv, lanes, 32, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=VSHARP + [0] * 28, memory={}) + + +def out(mem, lane, slot): + return mem.get(lane * SLOT_BYTES + slot * 4) + + +def run_chain(ops, init): + """One lane. `init` {byte address: dword} is written with ds_write_b32; then each op (mnemonic, byte address, + byte offset, data dwords) runs with v1 = address and data in v3, v4 (a mnemonic with `_rtn_` returns the old + value in v5, preset to 0xdead). Returns ([v5 after each op], {effective byte address: dword read back}).""" + body = [] + for a, v in init.items(): + body += [f"v_mov_b32_e32 v1, {a:#x}", f"v_mov_b32_e32 v2, {v:#x}", "ds_write_b32 v1, v2", "s_waitcnt lgkmcnt(0)"] + n = 0 + for name, addr, off, data in ops: + body += [f"v_mov_b32_e32 v1, {addr:#x}", "v_mov_b32_e32 v5, 0xdead"] + body += [f"v_mov_b32_e32 v{3 + k}, {d:#x}" for k, d in enumerate(data)] + regs = (["v5"] if "_rtn_" in name else []) + ["v1"] + [f"v{3 + k}" for k in range(len(data))] + body += [f"{name} {', '.join(regs)}" + (f" offset:{off}" if off else ""), "s_waitcnt lgkmcnt(0)", + "v_mov_b32_e32 v31, %d" % (4 * n), "buffer_store_dword v5, v31, s[0:3], 0 offen"] + n += 1 + finals = sorted({a + o for _, a, o, _ in ops}) + for j, a in enumerate(finals): + body += [f"v_mov_b32_e32 v1, {a:#x}", "ds_read_b32 v6, v1", "s_waitcnt lgkmcnt(0)", + "v_mov_b32_e32 v31, %d" % (4 * (n + j)), "buffer_store_dword v6, v31, s[0:3], 0 offen"] + mem = run(body, lanes=1) + return [mem.get(4 * k) for k in range(n)], {a: mem.get(4 * (n + j)) for j, a in enumerate(finals)} diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index d633f563c..22aea7132 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py @@ -16,7 +16,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders") FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") -SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", # SMEM / raw MUBUF bounds measured on RDNA2 +SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_smem_sconst_off", "cs_buf_tail", # SMEM / raw MUBUF bounds measured on RDNA2 "ps_fnan_med3", "ps_fnan_fract", # float NaN / fract rows measured on RDNA2 hardware "ps_sdwa_dword_hi", # 16-bit SDWA results with dst_sel:DWORD zero the high half "ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", diff --git a/tests/semantic/saveexec_run.py b/tests/semantic/saveexec_run.py new file mode 100644 index 000000000..eb2e2ce8e --- /dev/null +++ b/tests/semantic/saveexec_run.py @@ -0,0 +1,88 @@ +"""Shared harness for the test_salu_*_saveexec_b64.py files: run one s__saveexec_b64 through tools/rdna2spirv.py +(support.translate_lines) on every lane of a wave64 in spirv_mini_interp.run_workgroup and return what the program stored. + +RDNA2 ISA, SOP1: D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0). f is in ISA below, one plain-Python lambda per op +(andn2 complements EXEC, orn2 too, nand/nor/xnor complement the result). S0 comes from VCC (v_cmp_e32), from an SGPR +pair written by v_cmp_e64, from an SGPR pair loaded with 32-bit literals, or is EXEC itself. EXEC is a literal in each half. +Every lane stores whether it is on after the instruction (a lane that EXEC had off can come on: nand, nor, orn2, xnor); +lane 0 stores SCC and the population count and lowest lane of D. +""" +import struct + +import support +import spirv_mini_interp as si + +VSHARP = [0, 0, 0x1000, 0x31016FAC] +ALL64 = (1 << 64) - 1 +SCC_AT, BCNT_AT, FF1_AT = 256, 260, 264 +SOURCES = ("vcc", "s[10:11]", "literal", "exec") + +ISA = { + "and": lambda s, e: s & e, "or": lambda s, e: s | e, "xor": lambda s, e: s ^ e, + "andn2": lambda s, e: s & ~e, "orn2": lambda s, e: s | ~e, + "nand": lambda s, e: ~(s & e), "nor": lambda s, e: ~(s | e), "xnor": lambda s, e: ~(s ^ e), +} + +# (multiplier, addend, and-mask, EXEC): S0 = the lanes l with ((l * multiplier + addend) & and-mask) == 0. +CASES = ( + (1, 0, 8, 0x0000FFFFFFFF0000), (1, 0, 32, 0xFFFFFFFF00000000), (1, 32, 32, 0x0000FFFF0000FFFF), + (1, 32, 32, 0xFF00000000000000), (3, 1, 5, 0x5555555555555555), (7, 2, 12, 0xF0F0F0F00F0F0F0F), + (1, 0, 0, 0), (1, 0, 0, ALL64), (1, 0, 64, 0x123456789ABCDEF0), (1, 0, 127, 0), + (1, 0, 63, 0x8000000000000000), (5, 3, 63, 0x00000000FFFFFFFF), (1, 64, 64, 0), (1, 64, 64, ALL64), +) + + +def fssm(threads=64): + h = bytearray(0x148) + struct.pack_into("<4I", h, 0x138, 0x8088, threads, 1, 1) + return bytes(h) + + +def s0_mask(mul, add, mask): + return sum(1 << lane for lane in range(64) if ((lane * mul + add) & mask) == 0) + + +def model(kind, s0, old_exec): + """(new EXEC, D, SCC) from the ISA definition.""" + new = ISA[kind](s0, old_exec) & ALL64 + return new, old_exec, int(new != 0) + + +def program(kind, src, s0, old_exec, mul, add, mask): + def store(reg, at): + return [f"v_mov_b32_e32 v20, {reg}", f"v_mov_b32_e32 v21, {at}", "buffer_store_dword v20, v21, s[0:3], 0 offen"] + + setup = {"vcc": ["v_cmp_eq_u32_e32 vcc, 0, v3"], "s[10:11]": ["v_cmp_eq_u32_e64 s[10:11], 0, v3"], + "literal": [f"s_mov_b32 s12, {s0 & 0xFFFFFFFF:#x}", f"s_mov_b32 s13, {s0 >> 32:#x}"], "exec": []}[src] + operand = {"vcc": "vcc", "s[10:11]": "s[10:11]", "literal": "s[12:13]", "exec": "exec"}[src] + return (["v_mbcnt_lo_u32_b32 v1, -1, 0", "v_mbcnt_hi_u32_b32 v1, -1, v1", "v_mov_b32_e32 v2, 0", + f"v_mad_u32_u24 v3, v1, {mul}, {add}", f"v_and_b32_e32 v3, {mask}, v3"] + setup + + [f"s_mov_b32 exec_lo, {old_exec & 0xFFFFFFFF:#x}", f"s_mov_b32 exec_hi, {old_exec >> 32:#x}", + f"s_{kind}_saveexec_b64 s[6:7], {operand}", "s_cselect_b32 s8, 1, 0", + "v_mov_b32_e32 v2, 1", "s_mov_b64 exec, -1", + "s_bcnt1_i32_b64 s9, s[6:7]", "s_ff1_i32_b64 s10, s[6:7]", + "v_lshlrev_b32_e32 v21, 2, v1", "buffer_store_dword v2, v21, s[0:3], 0 offen", + "v_cmpx_eq_u32_e32 0, v1"] + + store("s8", SCC_AT) + store("s9", BCNT_AT) + store("s10", FF1_AT) + ["s_endpgm"]) + + +def run(kind, src, mul, add, mask, old_exec): + s0 = s0_mask(mul, add, mask) + spv = support.translate_lines("cs_saveexec_b64", program(kind, src, s0, old_exec, mul, add, mask), fssm=fssm()) + return si.run_workgroup(spv, 64, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=VSHARP + [0] * 28, memory={}) + + +def check(test, kind): + """Every case and source for `kind` against the ISA model.""" + for src in SOURCES: + for mul, add, mask, old_exec in CASES: + s0 = old_exec if src == "exec" else s0_mask(mul, add, mask) + with test.subTest(op=kind, src=src, s0=(mul, add, mask), exec=hex(old_exec)): + new, d, scc = model(kind, s0, old_exec) + memory = run(kind, src, mul, add, mask, old_exec) + got = sum(memory[4 * lane] << lane for lane in range(64)) + test.assertEqual(got, new, f"EXEC {got:#018x}, ISA {new:#018x}") + test.assertEqual(memory[SCC_AT], scc, "SCC") + test.assertEqual(memory[BCNT_AT], bin(d).count("1"), "population count of D") + test.assertEqual(memory[FF1_AT], (d & -d).bit_length() - 1 if d else 0xFFFFFFFF, "lowest lane of D") diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 044e8cf80..00fd93a95 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -9,9 +9,10 @@ Design rules (see tests/semantic/README.md): emitting something new makes the test error out instead of passing. * One invocation (one lane), or with run_workgroup several in lockstep, which meet only at subgroup operations (Shuffle, Ballot, Any, All, BitwiseOr Reduce; BallotBitExtract and BallotFindLSB - are per lane). Control flow is the forward-only discard test and the forward merge/dynamic-bounds - branches the translator emits: OpBranch / OpBranchConditional to a later label plus OpPhi at the merge block. - Backward branches, loops, calls and switches are rejected. Function/Output/Input variables live in Python + are per lane). Control flow is followed one branch at a time: OpBranch / OpBranchConditional to a label + of the function (forward, or backward for a loop, up to 10000 backward branches), OpPhi (the phis of a + block take their values together) and OpFunctionCall of a function of the module. + Switches are rejected. Function/Output/Input variables live in Python boxes; PushConstant reads can be seeded with a word list; physical-storage-buffer loads/stores (and 32-bit atomics, which with one invocation are read-combine-write) use a flat address -> word dictionary, so they must be 32-bit integers at 4-byte-aligned addresses (anything else raises). Workgroup variables (LDS) are @@ -660,10 +661,18 @@ def _invocation(text, inputs, push_constants, memory, step=False): pc = labels[target] continue if op == "OpPhi": - incoming = [a[i] for i in range(1, len(a) - 1, 2) if a[i + 1] == prev_label] - if len(incoming) != 1: - raise UnsupportedConstruct("OpPhi with an unknown predecessor") - values[res] = val(incoming[0]) + # The OpPhi of a block all read the values from before the block (a later one that names an earlier + # one, as in a swap in a loop header, gets its old value), so the first evaluates the whole run. + if body[pc - 2][1] != "OpPhi": + phi_new, k = {}, pc - 1 + while k < len(body) and body[k][1] == "OpPhi": + b = body[k][2] + incoming = [b[i] for i in range(1, len(b) - 1, 2) if b[i + 1] == prev_label] + if len(incoming) != 1: + raise UnsupportedConstruct("OpPhi with an unknown predecessor") + phi_new[body[k][0]] = val(incoming[0]) + k += 1 + values[res] = phi_new.pop(res) continue if op in _PURE and any(values.get(x) is UNDEF for x in a[1:]): values[res] = UNDEF @@ -850,7 +859,9 @@ def _invocation(text, inputs, push_constants, memory, step=False): raise UnsupportedConstruct(f"{op} on a non-32-bit-integer operand") values[res] = f32(float(_s32(x) if op == "OpConvertSToF" else x)) elif op == "OpBitCount": - values[res] = (val(a[1]) & wmask(a[0])).bit_count() + # Every bit of the operand counts: its width, not the result's (a 64-bit operand with a 32-bit result). + t = types.t.get(id_type.get(a[1])) + values[res] = (val(a[1]) & wmask(id_type[a[1]] if t is not None and t[0] == "int" else a[0])).bit_count() elif op == "OpISubBorrow": x, y = val(a[1]) & MASK, val(a[2]) & MASK values[res] = ((x - y) & MASK, 1 if x < y else 0) @@ -1047,7 +1058,7 @@ def _invocation(text, inputs, push_constants, memory, step=False): values[res] = 1.0 if x > 0 else -1.0 if x < 0 else x elif name == "SAbs": # Two's complement: the most negative value is its own absolute value (as on the hardware). - values[res] = abs(_s32(args[0])) & MASK + values[res] = abs(signed(args[0], types.bits(a[0]))) & wmask(a[0]) elif name in ("FMax", "FClamp"): def fmax_clamp(*xs): if any(math.isnan(v) for v in xs) or (name == "FClamp" and xs[1] > xs[2]): @@ -1111,16 +1122,18 @@ def _invocation(text, inputs, push_constants, memory, step=False): elif name == "UMax": values[res] = max(args) elif name == "SMax": - values[res] = max(args, key=_s32) + values[res] = max(args, key=lambda v: signed(v, types.bits(a[0]))) elif name == "SMin": - values[res] = min(args, key=_s32) + values[res] = min(args, key=lambda v: signed(v, types.bits(a[0]))) elif name in ("UClamp", "SClamp"): # min(max(x, minVal), maxVal) (GLSL.std.450; undefined if minVal > maxVal, which raises here). - key = _s32 if name == "SClamp" else (lambda v: v) + key = (lambda v: signed(v, types.bits(a[0]))) if name == "SClamp" else (lambda v: v) x, lo, hi = args if key(lo) > key(hi): raise UnsupportedConstruct(f"{name} with minVal > maxVal (undefined)") values[res] = min(max(x, lo, key=key), hi, key=key) + elif name in ("FindILsb", "FindUMsb", "FindSMsb") and types.bits(a[0]) != 32: + raise UnsupportedConstruct(f"GLSL.std.450 {name} on a non-32-bit integer (32-bit components only)") elif name == "FindILsb": # Bit number of the least significant 1 bit, -1 if the value is 0 (GLSL.std.450). x = args[0] & MASK diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index 70c8ee153..69bf66bb7 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py @@ -29,7 +29,9 @@ can be seeded (default zero). {"outputs": [ {output_name: tuple_of_words} or None (lane killed) for each lane ], "steps": instructions executed (summed over invocations)} """ +import math import re +import struct MASK = 0xFFFFFFFF SUBGROUP = 3 # Scope Subgroup @@ -100,6 +102,29 @@ def _signed(v, bits): return v - (1 << bits) if v >> (bits - 1) else v +def _f32_unpack(v): + if not isinstance(v, F): + raise UnsupportedConstruct(f"float operation on {type(v).__name__}") + return struct.unpack("= 3 and a[1] == "BuiltIn": self.builtins[a[0]] = a[2] + elif len(a) >= 3 and a[1] == "Location": + self.locations[a[0]] = int(a[2]) continue self._header(res, op, a) if self.entry is None: @@ -293,7 +321,7 @@ def _copy(v): class _Wave: - def __init__(self, mod, wave, push_constants, max_steps, builtins=None): + def __init__(self, mod, wave, push_constants, max_steps, builtins=None, inputs=None, memory=None): self.m = mod self.wave = wave self.pcw = list(push_constants or []) @@ -302,6 +330,7 @@ class _Wave: self.lanes = [_Lane(i) for i in range(wave)] self.killed = set() self.returned = set() + self.memory = memory if memory is not None else {} for lane in self.lanes: for vid, cls, pointee, init in mod.globals: if cls == "PushConstant": @@ -318,7 +347,11 @@ class _Wave: elif b in ("BaseVertex", "BaseInstance"): value = 0 # a draw with no vertex/instance offset, unless `builtins` seeds one elif b is None: - value = mod.zero(pointee) + loc = mod.locations.get(vid) + if inputs is not None and loc in inputs: + value = _wrap_input(inputs[loc](lane.index)) + else: + value = mod.zero(pointee) else: value = _BuiltinNotModelled(b) box = [value] @@ -622,6 +655,22 @@ class _Wave: elif op == "OpGroupNonUniformElect": for i in members: L[i].values[res] = i == members[0] + elif op == "OpGroupNonUniformQuadSwap": + src_vals = {i: self.raw(L[i], a[2]) for i in members} + for i in members: + d = self.int_of(L[i], a[3]) + if d not in (0, 1, 2): + raise UnsupportedConstruct(f"OpGroupNonUniformQuadSwap direction {d}") + partner = i ^ (d + 1) + L[i].values[res] = src_vals[partner] if partner in src_vals else _Poison(f"QuadSwap from invocation {partner}, which is not running") + elif op == "OpGroupNonUniformQuadBroadcast": + src_vals = {i: self.raw(L[i], a[2]) for i in members} + for i in members: + idx = self.int_of(L[i], a[3]) + if not 0 <= idx < 4: + raise UnsupportedConstruct(f"OpGroupNonUniformQuadBroadcast index {idx}") + partner = (i & ~3) | idx + L[i].values[res] = src_vals[partner] if partner in src_vals else _Poison(f"QuadBroadcast from invocation {partner}, which is not running") else: raise UnsupportedConstruct(op) @@ -639,6 +688,26 @@ class _Wave: p = lane.pointers.get(a[1]) if p is None: raise UnsupportedConstruct(f"OpAccessChain on {a[1]}, which is not a pointer") + if p[0] == "psb": + addr, ty = p[1], p[2] + for x in a[2:]: + idx = self.int_of(lane, x) + k = m.types[ty] + if k[0] in ("arr", "rarr", "vec"): + addr += m.size(k[1]) * idx + ty = k[1] + elif k[0] == "struct": + addr += sum(m.size(t) for t in k[1][:idx]) + ty = k[1][idx] + else: + raise UnsupportedConstruct(f"psb access chain into {k[0]}") + lane.pointers[res] = ("psb", addr, ty) + return None + if p[0] == "psb": + if m.size(p[2]) != 4: + raise UnsupportedConstruct("psb load wider than one word") + v = self.memory.get(p[1], 0) + return F(v) if m.types[p[2]][0] == "float" else v & MASK if p[0] == "pc": off, ty = p[1], p[2] for x in a[2:]: @@ -683,10 +752,33 @@ class _Wave: if isinstance(v, list) and m.types[p[2]][0] == "vec": return tuple(v) return _copy(v) + if op == "OpConvertUToPtr": + addr = self.int_of(lane, a[1]) + cls, pointee = m.ptr_types[a[0]] + if cls != "PhysicalStorageBuffer": + raise UnsupportedConstruct(f"OpConvertUToPtr to storage class {cls}") + lane.pointers[res] = ("psb", addr, pointee) + return None + if op == "OpAtomicIAdd": + p = lane.pointers.get(a[1]) + if p is None or p[0] == "pc": + raise UnsupportedConstruct(f"OpAtomicIAdd on {a[1]}") + val = self.int_of(lane, a[4]) + if p[0] == "psb": + old = self.memory.get(p[1], 0) + self.memory[p[1]] = (old + val) & MASK + return old + old = p[0][p[1]] & MASK + p[0][p[1]] = (old + val) & MASK + return old if op == "OpStore": p = lane.pointers.get(a[0]) if p is None or p[0] == "pc": raise UnsupportedConstruct(f"OpStore to {a[0]}") + if p[0] == "psb": + v = self.val(lane, a[1]) + self.memory[p[1]] = (v.bits if isinstance(v, F) else int(v)) & MASK + return None p[0][p[1]] = _copy(self.raw(lane, a[1])) return None if op == "OpSelect": @@ -730,8 +822,60 @@ class _Wave: "OpLogicalNotEqual": x != y}[op] if op == "OpLogicalNot": return not self.bool_of(lane, a[1]) - if op.startswith("OpF") or op in ("OpConvertFToU", "OpConvertFToS", "OpConvertUToF", "OpConvertSToF", - "OpExtInst") and not self._int_ext(a): + if op == "OpFNegate": + if m.types.get(a[0], ("",))[0] != "float": + raise UnsupportedConstruct(f"OpFNegate with result type {a[0]}") + x = self.val(lane, a[1]) + if not isinstance(x, F): + raise UnsupportedConstruct(f"OpFNegate on {type(x).__name__}") + return F(x.bits ^ 0x80000000) + if op in ("OpFAdd", "OpFSub", "OpFMul", "OpFDiv"): + if m.types.get(a[0], ("",))[0] != "float": + raise UnsupportedConstruct(f"{op} with result type {a[0]}") + x, y = _f32_unpack(self.val(lane, a[1])), _f32_unpack(self.val(lane, a[2])) + if op == "OpFAdd": + return _f32_pack(x + y) + if op == "OpFSub": + return _f32_pack(x - y) + if op == "OpFMul": + return _f32_pack(x * y) + if y == 0.0: + if x == 0.0 or math.isnan(x): + return F(0x7FC00000) + neg = (math.copysign(1.0, x) * math.copysign(1.0, y)) < 0 + return F(0xFF800000 if neg else 0x7F800000) + return _f32_pack(x / y) + if op in ("OpFOrdEqual", "OpFOrdNotEqual", "OpFOrdLessThan", "OpFOrdGreaterThan", + "OpFOrdLessThanEqual", "OpFOrdGreaterThanEqual", + "OpFUnordEqual", "OpFUnordNotEqual", "OpFUnordLessThan", "OpFUnordGreaterThan", + "OpFUnordLessThanEqual", "OpFUnordGreaterThanEqual"): + x, y = _f32_unpack(self.val(lane, a[1])), _f32_unpack(self.val(lane, a[2])) + if math.isnan(x) or math.isnan(y): + return op.startswith("OpFUnord") + cmp_name = op.removeprefix("OpFUnord").removeprefix("OpFOrd") + return {"Equal": x == y, "NotEqual": x != y, "LessThan": x < y, "GreaterThan": x > y, + "LessThanEqual": x <= y, "GreaterThanEqual": x >= y}[cmp_name] + if op in ("OpConvertFToU", "OpConvertFToS"): + if m.types.get(a[0], ("",))[0] != "int": + raise UnsupportedConstruct(f"{op} with result type {a[0]}") + bits = m.bits(a[0]) + x = _f32_unpack(self.val(lane, a[1])) + if math.isnan(x) or not math.isfinite(x): + return _Poison(f"{op} on {x}") + t = int(x) + lo, hi = (0, 1 << bits) if op == "OpConvertFToU" else (-(1 << (bits - 1)), 1 << (bits - 1)) + if not lo <= t < hi: + return _Poison(f"{op} out of range: {t}") + return t & ((1 << bits) - 1) + if op in ("OpConvertUToF", "OpConvertSToF"): + if m.types.get(a[0], ("",))[0] != "float": + raise UnsupportedConstruct(f"{op} with result type {a[0]}") + v = self.int_of(lane, a[1]) + if op == "OpConvertSToF": + bw = m.bits(m.id_type.get(a[1], a[0])) if m.types.get(m.id_type.get(a[1]), ("",))[0] == "int" else 32 + v = _signed(v, bw) + return _f32_pack(float(v)) + if op.startswith("OpF") or op == "OpExtInst" and not self._int_ext(a): raise UnsupportedConstruct(f"{op}: float arithmetic is not modelled here") if op == "OpExtInst": return self.ext(lane, a) @@ -772,7 +916,9 @@ class _Wave: x = _signed(x, src_bits) return x & w if op == "OpBitCount": - return (self.int_of(lane, a[1]) & MASK).bit_count() + # Every bit of the operand counts: its width, not 32 (a 64-bit operand with a 32-bit result). + src_bits = m.bits(m.id_type[a[1]]) if a[1] in m.id_type else 32 + return (self.int_of(lane, a[1]) & ((1 << src_bits) - 1)).bit_count() if op == "OpBitReverse": return int(f"{self.int_of(lane, a[1]) & w:0{bits}b}"[::-1], 2) if op in ("OpUDiv", "OpUMod"): @@ -817,7 +963,8 @@ class _Wave: raise UnsupportedConstruct(f"extended instruction set {a[1]}") name = a[2] args = [self.int_of(lane, x) for x in a[3:]] - s = lambda v: _signed(v, 32) # noqa: E731 + bits = self.m.bits(a[0]) # the operands have the result's type (GLSL.std.450) + s = lambda v: _signed(v, bits) # noqa: E731 if name == "UMin": return min(args) if name == "UMax": @@ -827,13 +974,15 @@ class _Wave: if name == "SMax": return max(args, key=s) if name == "SAbs": - return abs(s(args[0])) & MASK + return abs(s(args[0])) & ((1 << bits) - 1) if name in ("UClamp", "SClamp"): key = s if name == "SClamp" else (lambda v: v) x, lo, hi = args if key(lo) > key(hi): raise UnsupportedConstruct(f"{name} with minVal > maxVal (undefined)") return min(max(x, lo, key=key), hi, key=key) + if name in ("FindILsb", "FindUMsb", "FindSMsb") and bits != 32: + raise UnsupportedConstruct(f"GLSL.std.450 {name} on a {bits}-bit integer (limited to 32-bit components)") if name == "FindILsb": x = args[0] & MASK return ((x & -x).bit_length() - 1) & MASK if x else MASK @@ -855,9 +1004,9 @@ class _BuiltinNotModelled: self.name = name -def run_wave(text, wave=32, push_constants=None, max_steps=2_000_000, builtins=None): +def run_wave(text, wave=32, push_constants=None, max_steps=2_000_000, builtins=None, inputs=None, memory=None): if wave not in (32, 64): raise ValueError("wave must be 32 or 64") - w = _Wave(_Module(text), wave, push_constants, max_steps, builtins) + w = _Wave(_Module(text), wave, push_constants, max_steps, builtins, inputs=inputs, memory=memory) outputs = w.run() - return {"outputs": outputs, "steps": w.steps} + return {"outputs": outputs, "steps": w.steps, "memory": w.memory} diff --git a/tests/semantic/test_alu_add_i16.py b/tests/semantic/test_alu_add_i16.py new file mode 100644 index 000000000..601e89178 --- /dev/null +++ b/tests/semantic/test_alu_add_i16.py @@ -0,0 +1,131 @@ +"""Semantic translation tests for RDNA2 16-bit signed add v_add_i16. + +Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() +-> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: sign-extend both operands to 16 bits, add, mask to 16 bits +(equivalently (x + y) & 0xFFFF for modular addition). + +Covers: + - Basic 16-bit signed add + - Positive overflow (0x7FFF + 1 wraps to 0x8000) + - Negative overflow (-1 + -1 wraps to 0xFFFE) + - Mixed sign addition + - Reference comparison across varied 16-bit patterns + - 50 randomized cases vs reference + - Negative control: result differs from each input for non-trivial cases +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings +import random + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M16 = 0xFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: + """Sign-extend a 16-bit value.""" + v &= M16 + return v - 0x10000 if v >= 0x8000 else v + + +def ref_add_i16(x: int, y: int) -> int: + """Plain-Python reference for v_add_i16: sign-extend, add, mask to 16 bits.""" + return (s16(x) + s16(y)) & M16 + + +def run_op(x: int, y: int) -> int: + """Translate and run a shader that computes v_add_i16 v1, v2, v3 with v2=x, v3=y. + + Uses a unique temp directory per call to avoid file-sharing issues. + """ + asm = ( + "; test_add_i16\n" + f"\tv_mov_b32_e32 v2, {x & M16:#x}\n" + f"\tv_mov_b32_e32 v3, {y & M16:#x}\n" + "\tv_add_i16 v1, v2, v3\n" + "\ts_waitcnt vmcnt(0)\n" + "\texp mrt0 v1, v1, v1, v1 done vm\n" + "\ts_endpgm\n" + ) + tmp = tempfile.TemporaryDirectory() + disasm_dir = os.path.join(tmp.name, "disasm") + os.mkdir(disasm_dir) + src_path = os.path.join(disasm_dir, "ps_add_i16.s") + with open(os.path.join(tmp.name, "ps_add_i16.dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(src_path, "w", encoding="utf-8") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(src_path) + w = si.run_fragment(spv)["%out_mrt0"] + tmp.cleanup() + return w[0] & M16 + + +class ALUVAddI16Tests(unittest.TestCase): + def test_add_i16_basic(self): + self.assertEqual(run_op(0, 0), 0) + self.assertEqual(run_op(1, 2), 3) + self.assertEqual(run_op(100, 200), 300) + self.assertEqual(run_op(0x7FFF, 1), 0x8000) # positive overflow + + def test_add_i16_overflow(self): + # -1 + -1 = -2 = 0xFFFE + self.assertEqual(run_op(M16, M16), 0xFFFE) + # 0x7FFF + 1 = 0x8000 (positive overflow to negative) + self.assertEqual(run_op(0x7FFF, 0x0001), 0x8000) + # -32768 + -1 = 0x7FFF (negative overflow to positive) + self.assertEqual(run_op(0x8000, M16), 0x7FFF) + + def test_add_i16_reference(self): + cases = [ + (0, 0, 0), + (1, 1, 2), + (0x7FFF, 1, 0x8000), + (M16, M16, 0xFFFE), # -1 + -1 = -2 + (0x8000, M16, 0x7FFF), # -32768 + -1 = 32767 + (0x1234, 0x5678, 0x68AC), + ] + for x, y, expected in cases: + with self.subTest(x=hex(x), y=hex(y)): + self.assertEqual(run_op(x, y), expected) + self.assertEqual(run_op(x, y), ref_add_i16(x, y)) + + def test_add_i16_random_vs_reference(self): + rng = random.Random(0xC0FFEE) + for _ in range(50): + x = rng.getrandbits(16) + y = rng.getrandbits(16) + with self.subTest(x=hex(x), y=hex(y)): + self.assertEqual(run_op(x, y), ref_add_i16(x, y)) + + def test_add_i16_negative_control(self): + # For non-trivial inputs, result differs from each input. + x, y = 0x1234, 0x5678 + res = run_op(x, y) + expected = ref_add_i16(x, y) + self.assertEqual(res, expected) + self.assertNotEqual(res, x) + self.assertNotEqual(res, y) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_alu_add_u16.py b/tests/semantic/test_alu_add_u16.py new file mode 100644 index 000000000..f5e89024b --- /dev/null +++ b/tests/semantic/test_alu_add_u16.py @@ -0,0 +1,126 @@ +"""Semantic translation tests for RDNA2 16-bit unsigned add v_add_u16. + +Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() +-> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: (x + y) & 0xFFFF (16-bit wraparound). + +Covers: + - Basic 16-bit add: small values + - Wraparound at 16-bit boundary (0xFFFF + 1 = 0) + - Both operands large (0x8000 + 0x8000 wraps to 0) + - Reference comparison across varied 16-bit patterns + - 50 randomized cases vs reference + - Negative control: result differs from each input for non-trivial cases +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings +import random + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M16 = 0xFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: + """Plain-Python reference for v_add_u16: (x + y) mod 2^16.""" + return (x + y) & M16 + + +def run_op(x: int, y: int) -> int: + """Translate and run a shader that computes v_add_u16 v1, v2, v3 with v2=x, v3=y. + + Uses a unique temp directory per call to avoid file-sharing issues. + """ + asm = ( + "; test_add_u16\n" + f"\tv_mov_b32_e32 v2, {x & M16:#x}\n" + f"\tv_mov_b32_e32 v3, {y & M16:#x}\n" + "\tv_add_u16 v1, v2, v3\n" + "\ts_waitcnt vmcnt(0)\n" + "\texp mrt0 v1, v1, v1, v1 done vm\n" + "\ts_endpgm\n" + ) + tmp = tempfile.TemporaryDirectory() + disasm_dir = os.path.join(tmp.name, "disasm") + os.mkdir(disasm_dir) + src_path = os.path.join(disasm_dir, "ps_add_u16.s") + with open(os.path.join(tmp.name, "ps_add_u16.dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(src_path, "w", encoding="utf-8") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(src_path) + w = si.run_fragment(spv)["%out_mrt0"] + tmp.cleanup() + return w[0] & M16 + + +class ALUVAddU16Tests(unittest.TestCase): + def test_add_u16_basic(self): + self.assertEqual(run_op(0, 0), 0) + self.assertEqual(run_op(1, 2), 3) + self.assertEqual(run_op(100, 200), 300) + self.assertEqual(run_op(0x7FFF, 1), 0x8000) + + def test_add_u16_wraparound(self): + # 0xFFFF + 1 wraps to 0 + self.assertEqual(run_op(M16, 1), 0) + # 0x8000 + 0x8000 = 0x10000 wraps to 0 + self.assertEqual(run_op(0x8000, 0x8000), 0) + # 0xFFFF + 0xFFFF = 0x1FFFE wraps to 0xFFFE + self.assertEqual(run_op(M16, M16), 0xFFFE) + # 0xABCD + 0x1234 = 0xBE01 (no wraparound) + self.assertEqual(run_op(0xABCD, 0x1234), 0xBE01) + + def test_add_u16_reference(self): + cases = [ + (0, 0, 0), + (1, 1, 2), + (0xFFFF, 0, 0xFFFF), + (0, 0xFFFF, 0xFFFF), + (0xFF, 0xFF, 0x1FE), + (0x1234, 0x5678, 0x68AC), + (0xFFFF, 0xFFFF, 0xFFFE), + ] + for x, y, expected in cases: + with self.subTest(x=hex(x), y=hex(y)): + self.assertEqual(run_op(x, y), expected) + self.assertEqual(run_op(x, y), ref_add_u16(x, y)) + + def test_add_u16_random_vs_reference(self): + rng = random.Random(0xC0FFEE) + for _ in range(50): + x = rng.getrandbits(16) + y = rng.getrandbits(16) + with self.subTest(x=hex(x), y=hex(y)): + self.assertEqual(run_op(x, y), ref_add_u16(x, y)) + + def test_add_u16_negative_control(self): + # For non-trivial inputs, result differs from each input. + x, y = 0x1234, 0x5678 + res = run_op(x, y) + expected = ref_add_u16(x, y) + self.assertEqual(res, expected) + self.assertNotEqual(res, x) + self.assertNotEqual(res, y) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_alu_bcnt_u32.py b/tests/semantic/test_alu_bcnt_u32.py new file mode 100644 index 000000000..e8ee86076 --- /dev/null +++ b/tests/semantic/test_alu_bcnt_u32.py @@ -0,0 +1,135 @@ +"""Semantic translation tests for RDNA2 32-bit bit count v_bcnt_u32_b32. + +Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() +-> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: (popcount(x) + acc) & 0xFFFFFFFF. + +Covers: + - Basic popcount: x=0, x=1, x=all-ones + - Accumulator: popcount(x) + acc + - 32-bit wraparound on overflow + - Reference comparison across varied bit patterns + - Negative control: result differs from inputs for non-trivial cases +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: + """Plain-Python reference for v_bcnt_u32_b32: popcount(x) + acc, masked to 32 bits.""" + return (bin(x & M32).count("1") + acc) & M32 + + +def run_op(x: int, acc: int) -> int: + """Translate and run a shader that computes v_bcnt_u32_b32 v1, v2, v3 with v2=x, v3=acc. + + Uses a unique temp directory per call to avoid file-sharing issues. + """ + asm = ( + "; test_bcnt_u32\n" + f"\tv_mov_b32_e32 v2, {x & M32:#x}\n" + f"\tv_mov_b32_e32 v3, {acc & M32:#x}\n" + "\tv_bcnt_u32_b32 v1, v2, v3\n" + "\ts_waitcnt vmcnt(0)\n" + "\texp mrt0 v1, v1, v1, v1 done vm\n" + "\ts_endpgm\n" + ) + tmp = tempfile.TemporaryDirectory() + disasm_dir = os.path.join(tmp.name, "disasm") + os.mkdir(disasm_dir) + src_path = os.path.join(disasm_dir, "ps_bcnt_u32.s") + with open(os.path.join(tmp.name, "ps_bcnt_u32.dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(src_path, "w", encoding="utf-8") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(src_path) + w = si.run_fragment(spv)["%out_mrt0"] + tmp.cleanup() + return w[0] & M32 + + +class ALUVBitcntU32Tests(unittest.TestCase): + def test_bcnt_u32_basic(self): + # popcount(0) = 0 + self.assertEqual(run_op(0, 0), 0) + # popcount(1) = 1 + self.assertEqual(run_op(1, 0), 1) + # popcount(0xFFFFFFFF) = 32 + self.assertEqual(run_op(M32, 0), 32) + # popcount(0xAAAAAAAA) = 16 + self.assertEqual(run_op(0xAAAAAAAA, 0), 16) + # popcount(0x55555555) = 16 + self.assertEqual(run_op(0x55555555, 0), 16) + + def test_bcnt_u32_accumulator(self): + # popcount(0xFF) = 8, acc = 10 -> 18 + self.assertEqual(run_op(0xFF, 10), 18) + # popcount(0) = 0, acc = 0x12345678 + self.assertEqual(run_op(0, 0x12345678), 0x12345678) + + def test_bcnt_u32_wraparound(self): + # popcount(0xFFFFFFFF) = 32, acc = 0xFFFFFFFE -> 32 + 0xFFFFFFFE = 0x10000001E -> 0x1E + self.assertEqual(run_op(M32, M32 - 1), 30) + # popcount(1) = 1, acc = M32 -> 1 + M32 = 0x100000000 -> 0 + self.assertEqual(run_op(1, M32), 0) + + def test_bcnt_u32_reference(self): + cases = [ + (0, 0, 0), + (1, 0, 1), + (2, 0, 1), # 0b10 -> 1 bit + (3, 0, 2), # 0b11 -> 2 bits + (0xFF, 0, 8), + (0xFFFF, 0, 16), + (0xFFFFFFFF, 0, 32), + (0x00000000, 0xABCD, 0xABCD), + (0x12345678, 0, 13), # popcount(0x12345678) = 13 + ] + for x, acc, expected in cases: + with self.subTest(x=hex(x), acc=hex(acc)): + self.assertEqual(run_op(x, acc), expected) + self.assertEqual(run_op(x, acc), ref_bcnt32(x, acc)) + + def test_bcnt_u32_random_vs_reference(self): + import random + rng = random.Random(0xC0FFEE) + for _ in range(50): + x = rng.getrandbits(32) + acc = rng.getrandbits(32) + with self.subTest(x=hex(x), acc=hex(acc)): + self.assertEqual(run_op(x, acc), ref_bcnt32(x, acc)) + + def test_bcnt_u32_negative_control(self): + # For non-trivial inputs, result differs from each input. + x, acc = 0x12345678, 0x9ABCDEF0 + res = run_op(x, acc) + expected = ref_bcnt32(x, acc) + self.assertEqual(res, expected) + self.assertNotEqual(res, x) + self.assertNotEqual(res, acc) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_alu_cndmask_b64.py b/tests/semantic/test_alu_cndmask_b64.py index c6b7186c8..8b5de087f 100644 --- a/tests/semantic/test_alu_cndmask_b64.py +++ b/tests/semantic/test_alu_cndmask_b64.py @@ -1,727 +1,78 @@ -"""Semantic reference tests for RDNA2 64-bit vector conditional select (v_cndmask_b64). +"""64-bit conditional select on RDNA2: there is no `v_cndmask_b64`; a 64-bit select is two v_cndmask_b32, low and high +dword, under the same condition bit (D = cond ? S1 : S0 per lane, for the lane's bit of VCC or of an SGPR mask). -RDNA2 Vector Arithmetic Logic Unit (VALU) architecture: - In AMD RDNA2 (GFX10) instruction set architecture, vector registers (VGPRs) are 32-bit wide. - Operations on 64-bit vector quantities (integers, double-precision floats, or 64-bit pointers) - operate across aligned pairs of adjacent registers: v[d:d+1] from source pairs v[s0:s0+1] and - v[s1:s1+1]. - - v_cndmask_b64 conditionally selects 64-bit values per-lane based on a condition bit: - For active lane i in the wavefront (0 <= i < WaveSize, WaveSize in {32, 64}): - cond_bit = (condition_mask >> i) & 1 - dst[i] = src1[i] if cond_bit != 0 else src0[i] - - Low-level dword decomposition: - Because each 64-bit VGPR pair consists of low dword v[2k] and high dword v[2k+1]: - dst_lo[i] = src1_lo[i] if cond_bit != 0 else src0_lo[i] - dst_hi[i] = src1_hi[i] if cond_bit != 0 else src0_hi[i] - Both halves are governed by the exact same per-lane condition bit without divergence between - the low and high dwords. - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. +Each case is translated by tools/rdna2spirv.py (support.translate_lines) and executed with +tests/semantic/spirv_mini_interp.py (one lane: the translator models a lane mask as that lane's own bit, 0 or 1); the expected words are +written by hand, and seeded random 64-bit operands are checked against a plain-Python select. `v_cndmask_b64` itself +stays Unsupported rather than guessed. Standard library only: no GPU, no LLVM, no game data. (The old file ran its own +SIMD simulator and never called the translator.) """ -from __future__ import annotations - -import math import os import random -import struct import sys import unittest -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned word as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x80000000) else val - - -def s64(val: int) -> int: - """Interpret a 64-bit unsigned word as a signed two's-complement integer.""" - val &= MASK64 - return val - (1 << 64) if (val & (1 << 63)) else val - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def f64_to_u64(val: float) -> int: - """Pack an IEEE-754 double precision float into an unsigned 64-bit integer.""" - return struct.unpack(" float: - """Unpack an unsigned 64-bit integer into an IEEE-754 double precision float.""" - return struct.unpack(" int: - """Reference oracle for 64-bit conditional select (v_cndmask_b64) on a single lane. - - In RDNA2 ISA: - D.u64 = cond ? S1.u64 : S0.u64 - Condition is true (non-zero) selects src1; false (zero) selects src0. - """ - return (src1 if cond else src0) & MASK64 - - -def ref_cndmask_b64_dwords( - s0_lo: int, s0_hi: int, s1_lo: int, s1_hi: int, cond: int | bool -) -> tuple[int, int]: - """Reference oracle for pair-wise 32-bit dword selection. - - Demonstrates that 64-bit vector conditional select operates identically to parallel - 32-bit conditional select on low and high dwords using the identical lane condition. - """ - bit = 1 if cond else 0 - lo = (s1_lo if bit else s0_lo) & MASK32 - hi = (s1_hi if bit else s0_hi) & MASK32 - return lo, hi - - -def ref_cndmask_b64_decomposed(src0: int, src1: int, cond: int | bool) -> int: - """Compute 64-bit conditional select by decomposing into 32-bit dwords and reassembling.""" - s0_lo, s0_hi = split_dwords(src0) - s1_lo, s1_hi = split_dwords(src1) - res_lo, res_hi = ref_cndmask_b64_dwords(s0_lo, s0_hi, s1_lo, s1_hi, cond) - return join_dwords(res_lo, res_hi) - - -def ref_simd_cndmask_b64( - src0_lanes: list[int], - src1_lanes: list[int], - mask: int, - wave_size: int = 64, - exec_mask: int | None = None, - prev_dst: list[int] | None = None, -) -> list[int]: - """Reference oracle for SIMD vector conditional select across a wavefront. - - Parameters: - src0_lanes: 64-bit values for src0 across wave_size lanes. - src1_lanes: 64-bit values for src1 across wave_size lanes. - mask: condition bitmask (32-bit or 64-bit integer, bit i determines selection for lane i). - wave_size: 32 (wave32) or 64 (wave64). - exec_mask: optional execution mask; inactive lanes (exec_bit == 0) preserve prev_dst. - prev_dst: previous destination values across lanes, preserved when lane is inactive. - - Returns: - list of 64-bit unsigned integers representing the destination register pair across lanes. - """ - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size}. Must be 32 or 64.") - if len(src0_lanes) != wave_size or len(src1_lanes) != wave_size: - raise ValueError( - f"Expected {wave_size} lane inputs, got {len(src0_lanes)} and {len(src1_lanes)}" - ) - if prev_dst is None: - prev_dst = [0] * wave_size - elif len(prev_dst) != wave_size: - raise ValueError(f"Expected {wave_size} prev_dst entries, got {len(prev_dst)}") - - effective_exec = ((1 << wave_size) - 1) if exec_mask is None else (exec_mask & ((1 << wave_size) - 1)) - results: list[int] = [] - - for i in range(wave_size): - if not ((effective_exec >> i) & 1): - results.append(prev_dst[i] & MASK64) - continue - cond_bit = (mask >> i) & 1 - val = ref_cndmask_b64(src0_lanes[i], src1_lanes[i], cond_bit) - results.append(val) - - return results - - -class SIMDVectorCNDMask64Simulator: - """Deterministic SIMD execution model for RDNA2 64-bit vector conditional select. - - Simulates VALU register state across a wavefront (32 or 64 lanes): - - VGPR file: 256 vector registers, each lane holding a 32-bit unsigned dword. - - SGPR file: 106 scalar registers, each holding a 32-bit scalar dword. - - VCC: vector condition code (64-bit mask; in Wave32 only bits 0..31 are used). - - EXEC: execution mask (64-bit mask; in Wave32 only bits 0..31 are used). - """ - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size}. Must be 32 or 64.") - self.wave_size = wave_size - self.num_vgprs = 256 - self.num_sgprs = 106 - self.vgpr = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = (1 << wave_size) - 1 - - def reset(self) -> None: - """Reset all registers, VCC, and EXEC mask to defaults.""" - self.vgpr = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = (1 << self.wave_size) - 1 - - def get_vgpr_u32(self, reg: int, lane: int) -> int: - if not (0 <= reg < self.num_vgprs): - raise IndexError(f"VGPR index {reg} out of range [0, {self.num_vgprs})") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size})") - return self.vgpr[reg][lane] & MASK32 - - def set_vgpr_u32(self, reg: int, lane: int, val: int) -> None: - if not (0 <= reg < self.num_vgprs): - raise IndexError(f"VGPR index {reg} out of range [0, {self.num_vgprs})") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size})") - self.vgpr[reg][lane] = val & MASK32 - - def get_vgpr_u64(self, reg_base: int, lane: int) -> int: - if not (0 <= reg_base < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {reg_base} out of range [0, {self.num_vgprs - 1})") - lo = self.get_vgpr_u32(reg_base, lane) - hi = self.get_vgpr_u32(reg_base + 1, lane) - return join_dwords(lo, hi) - - def set_vgpr_u64(self, reg_base: int, lane: int, val64: int) -> None: - if not (0 <= reg_base < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {reg_base} out of range [0, {self.num_vgprs - 1})") - lo, hi = split_dwords(val64) - self.set_vgpr_u32(reg_base, lane, lo) - self.set_vgpr_u32(reg_base + 1, lane, hi) - - def load_vgpr_pair_wave(self, reg_base: int) -> list[int]: - """Read 64-bit values across all lanes for a vector register pair.""" - return [self.get_vgpr_u64(reg_base, lane) for lane in range(self.wave_size)] - - def store_vgpr_pair_wave(self, reg_base: int, values: list[int]) -> None: - """Write 64-bit values across all lanes for a vector register pair.""" - if len(values) != self.wave_size: - raise ValueError(f"Expected {self.wave_size} values, got {len(values)}") - for lane in range(self.wave_size): - self.set_vgpr_u64(reg_base, lane, values[lane]) - - def get_sgpr_u32(self, reg: int) -> int: - if not (0 <= reg < self.num_sgprs): - raise IndexError(f"SGPR index {reg} out of range [0, {self.num_sgprs})") - return self.sgpr[reg] & MASK32 - - def set_sgpr_u32(self, reg: int, val: int) -> None: - if not (0 <= reg < self.num_sgprs): - raise IndexError(f"SGPR index {reg} out of range [0, {self.num_sgprs})") - self.sgpr[reg] = val & MASK32 - - def get_sgpr_u64(self, reg_base: int) -> int: - if not (0 <= reg_base < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {reg_base} out of range [0, {self.num_sgprs - 1})") - lo = self.get_sgpr_u32(reg_base) - hi = self.get_sgpr_u32(reg_base + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, reg_base: int, val64: int) -> None: - if not (0 <= reg_base < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {reg_base} out of range [0, {self.num_sgprs - 1})") - lo, hi = split_dwords(val64) - self.set_sgpr_u32(reg_base, lo) - self.set_sgpr_u32(reg_base + 1, hi) - - def resolve_condition_mask(self, cond_src: str | int) -> int: - """Resolve condition source operand into a bitmask for the current wavefront.""" - if isinstance(cond_src, int): - return cond_src & ((1 << self.wave_size) - 1) - if not isinstance(cond_src, str): - raise TypeError(f"Invalid condition operand type: {type(cond_src)}") - - cond = cond_src.strip().lower() - if cond in ("vcc", "vcc_lo"): - if self.wave_size == 32: - return self.vcc & MASK32 - return (self.vcc & MASK64) if cond == "vcc" else (self.vcc & MASK32) - if cond == "vcc_hi": - return (self.vcc >> 32) & MASK32 - if cond.startswith("s[") and cond.endswith("]"): - inner = cond[2:-1] - parts = inner.split(":") - if len(parts) != 2: - raise ValueError(f"Invalid SGPR pair descriptor: {cond_src}") - base_reg = int(parts[0]) - end_reg = int(parts[1]) - if end_reg != base_reg + 1: - raise ValueError(f"SGPR pair must be consecutive registers: {cond_src}") - return self.get_sgpr_u64(base_reg) & ((1 << self.wave_size) - 1) - if cond.startswith("s"): - reg_idx = int(cond[1:]) - val = self.get_sgpr_u32(reg_idx) - return val & ((1 << self.wave_size) - 1) - raise ValueError(f"Unknown condition mask source: {cond_src}") - - def step_v_cndmask_b64( - self, - dst_base: int, - src0_base: int, - src1_base: int, - cond_src: str | int = "vcc", - ) -> list[int]: - """Execute 64-bit conditional select across active lanes. - - Two-phase lockstep execution: - Phase 1 (Read): reads all source operand dwords and evaluates condition bits. - Phase 2 (Write): writes destination dwords only for lanes enabled by EXEC. - """ - if not (0 <= dst_base < self.num_vgprs - 1): - raise IndexError(f"dst_base {dst_base} out of range [0, {self.num_vgprs - 1})") - if not (0 <= src0_base < self.num_vgprs - 1): - raise IndexError(f"src0_base {src0_base} out of range [0, {self.num_vgprs - 1})") - if not (0 <= src1_base < self.num_vgprs - 1): - raise IndexError(f"src1_base {src1_base} out of range [0, {self.num_vgprs - 1})") - - mask = self.resolve_condition_mask(cond_src) - active_exec = self.exec & ((1 << self.wave_size) - 1) - - # Phase 1: Read and evaluate - computed: list[tuple[int, int] | None] = [] - for lane in range(self.wave_size): - if not ((active_exec >> lane) & 1): - computed.append(None) - continue - cond_bit = (mask >> lane) & 1 - s0_val = self.get_vgpr_u64(src0_base, lane) - s1_val = self.get_vgpr_u64(src1_base, lane) - res = ref_cndmask_b64(s0_val, s1_val, cond_bit) - computed.append(split_dwords(res)) - - # Phase 2: Write - for lane in range(self.wave_size): - dwords = computed[lane] - if dwords is not None: - lo, hi = dwords - self.set_vgpr_u32(dst_base, lane, lo) - self.set_vgpr_u32(dst_base + 1, lane, hi) - - return self.load_vgpr_pair_wave(dst_base) - - -class TestCndmaskB64ReferenceOracle(unittest.TestCase): - """Unit tests for single-lane and SIMD 64-bit conditional select reference oracles.""" - - def test_basic_truth_table(self) -> None: - """Verify standard selector truth table: 0 selects src0, 1 selects src1.""" - val0 = 0x01234567_89ABCDEF - val1 = 0xFEDCBA98_76543210 - self.assertEqual(ref_cndmask_b64(val0, val1, 0), val0) - self.assertEqual(ref_cndmask_b64(val0, val1, False), val0) - self.assertEqual(ref_cndmask_b64(val0, val1, 1), val1) - self.assertEqual(ref_cndmask_b64(val0, val1, True), val1) - self.assertEqual(ref_cndmask_b64(val0, val1, 42), val1) - - def test_64bit_distinct_dwords(self) -> None: - """Test combinations where only the low, only the high, or both dwords differ.""" - cases = [ - # Only low dwords differ - (0x11112222_33334444, 0x11112222_AAAABBBB), - # Only high dwords differ - (0xAAAA0000_12345678, 0xBBBB0000_12345678), - # Both dwords differ completely - (0x00000000_00000000, 0xFFFFFFFF_FFFFFFFF), - (0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA), - (0x12345678_9ABCDEF0, 0x0FEDCBA9_87654321), - ] - for s0, s1 in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - self.assertEqual(ref_cndmask_b64(s0, s1, 0), s0) - self.assertEqual(ref_cndmask_b64(s0, s1, 1), s1) - self.assertEqual( - ref_cndmask_b64_decomposed(s0, s1, 0), - ref_cndmask_b64(s0, s1, 0), - ) - self.assertEqual( - ref_cndmask_b64_decomposed(s0, s1, 1), - ref_cndmask_b64(s0, s1, 1), - ) - - def test_edge_bit_patterns(self) -> None: - """Test boundary conditions, sign bits (bit 63, bit 31), and extreme integer limits.""" - patterns = [ - 0, - 1, - MASK64, - 1 << 63, - (1 << 63) - 1, - 1 << 31, - (1 << 31) - 1, - 1 << 32, - MASK32, - 0x7FFFFFFF_FFFFFFFF, - 0x80000000_00000000, - 0xFFFFFFFF_00000000, - 0x00000000_FFFFFFFF, - ] - for i, p0 in enumerate(patterns): - for j, p1 in enumerate(patterns): - self.assertEqual(ref_cndmask_b64(p0, p1, 0), p0) - self.assertEqual(ref_cndmask_b64(p0, p1, 1), p1) - - def test_float64_special_bitcasts(self) -> None: - """Test 64-bit conditional select on IEEE-754 double precision bit patterns.""" - f_values = [ - 0.0, - -0.0, - 1.0, - -1.0, - math.pi, - math.e, - float("inf"), - float("-inf"), - float("nan"), - 1e-308, - 1e308, - sys.float_info.min, - sys.float_info.max, - ] - u64_patterns = [f64_to_u64(f) for f in f_values] - - for u0 in u64_patterns: - for u1 in u64_patterns: - self.assertEqual(ref_cndmask_b64(u0, u1, 0), u0) - self.assertEqual(ref_cndmask_b64(u0, u1, 1), u1) - - def test_algebraic_identities(self) -> None: - """Verify algebraic identities of 64-bit conditional selection.""" - rng = random.Random(1337) - for _ in range(50): - x = rng.getrandbits(64) - y = rng.getrandbits(64) - - # Identity: selecting between identical values returns the value - self.assertEqual(ref_cndmask_b64(x, x, 0), x) - self.assertEqual(ref_cndmask_b64(x, x, 1), x) - - # Inversion: swapping operands and inverting condition bit yields identical result - self.assertEqual(ref_cndmask_b64(x, y, 0), ref_cndmask_b64(y, x, 1)) - self.assertEqual(ref_cndmask_b64(x, y, 1), ref_cndmask_b64(y, x, 0)) - - # Idempotence: re-selecting result with same condition returns itself - r0 = ref_cndmask_b64(x, y, 0) - self.assertEqual(ref_cndmask_b64(r0, y, 0), r0) - r1 = ref_cndmask_b64(x, y, 1) - self.assertEqual(ref_cndmask_b64(x, r1, 1), r1) - - def test_dword_decomposition_equivalence(self) -> None: - """Verify bit-exact match between full 64-bit select and dword-wise decomposition.""" - rng = random.Random(42) - for _ in range(200): - s0 = rng.getrandbits(64) - s1 = rng.getrandbits(64) - for c in (0, 1): - want = ref_cndmask_b64(s0, s1, c) - got = ref_cndmask_b64_decomposed(s0, s1, c) - self.assertEqual(want, got) - s0_lo, s0_hi = split_dwords(s0) - s1_lo, s1_hi = split_dwords(s1) - lo, hi = ref_cndmask_b64_dwords(s0_lo, s0_hi, s1_lo, s1_hi, c) - self.assertEqual(lo, want & MASK32) - self.assertEqual(hi, (want >> 32) & MASK32) - - def test_simd_oracle_wave32(self) -> None: - """Validate SIMD reference oracle across 32 lanes.""" - rng = random.Random(32) - s0_lanes = [rng.getrandbits(64) for _ in range(32)] - s1_lanes = [rng.getrandbits(64) for _ in range(32)] - mask = 0b10101010_11001100_11110000_01010101 - - res = ref_simd_cndmask_b64(s0_lanes, s1_lanes, mask, wave_size=32) - self.assertEqual(len(res), 32) - for lane in range(32): - bit = (mask >> lane) & 1 - expected = s1_lanes[lane] if bit else s0_lanes[lane] - self.assertEqual(res[lane], expected) - - def test_simd_oracle_wave64(self) -> None: - """Validate SIMD reference oracle across 64 lanes.""" - rng = random.Random(64) - s0_lanes = [rng.getrandbits(64) for _ in range(64)] - s1_lanes = [rng.getrandbits(64) for _ in range(64)] - mask = 0xCAFEBABEDEADBEEF - - res = ref_simd_cndmask_b64(s0_lanes, s1_lanes, mask, wave_size=64) - self.assertEqual(len(res), 64) - for lane in range(64): - bit = (mask >> lane) & 1 - expected = s1_lanes[lane] if bit else s0_lanes[lane] - self.assertEqual(res[lane], expected) - - -class TestSIMDMultiLaneDivergenceAndMaskRouting(unittest.TestCase): - """Test multi-lane divergence and VCC / SGPR mask routing on SIMD wavefronts.""" - - def test_wave32_uniform_all_zeros_and_all_ones(self) -> None: - """Verify uniform condition across 32 lanes (all 0s select src0, all 1s select src1).""" - sim = SIMDVectorCNDMask64Simulator(wave_size=32) - s0_vals = [0x11111111_00000000 + i for i in range(32)] - s1_vals = [0x99999999_88888888 - i for i in range(32)] - sim.store_vgpr_pair_wave(2, s0_vals) - sim.store_vgpr_pair_wave(4, s1_vals) - - # All zeros condition - sim.vcc = 0 - out_zeros = sim.step_v_cndmask_b64(0, 2, 4, cond_src="vcc") - self.assertEqual(out_zeros, s0_vals) - - # All ones condition - sim.vcc = 0xFFFFFFFF - out_ones = sim.step_v_cndmask_b64(0, 2, 4, cond_src="vcc") - self.assertEqual(out_ones, s1_vals) - - def test_wave64_uniform_all_zeros_and_all_ones(self) -> None: - """Verify uniform condition across 64 lanes (all 0s select src0, all 1s select src1).""" - sim = SIMDVectorCNDMask64Simulator(wave_size=64) - s0_vals = [0x22222222_10000000 + i for i in range(64)] - s1_vals = [0xEEEEEEEE_20000000 - i for i in range(64)] - sim.store_vgpr_pair_wave(6, s0_vals) - sim.store_vgpr_pair_wave(8, s1_vals) - - # All zeros - sim.vcc = 0 - out_zeros = sim.step_v_cndmask_b64(4, 6, 8, cond_src="vcc") - self.assertEqual(out_zeros, s0_vals) - - # All ones - sim.vcc = MASK64 - out_ones = sim.step_v_cndmask_b64(4, 6, 8, cond_src="vcc") - self.assertEqual(out_ones, s1_vals) - - def test_multi_lane_divergence_checkerboard_wave32(self) -> None: - """Verify alternating even/odd lane divergence pattern across 32 lanes.""" - sim = SIMDVectorCNDMask64Simulator(wave_size=32) - s0_vals = [0xAAAA0000_00000000 | i for i in range(32)] - s1_vals = [0x55550000_00000000 | i for i in range(32)] - sim.store_vgpr_pair_wave(0, s0_vals) - sim.store_vgpr_pair_wave(2, s1_vals) - - # Mask: even bits 0 (src0), odd bits 1 (src1) -> 0xAAAAAAAA - mask_even0_odd1 = 0xAAAAAAAA - sim.vcc = mask_even0_odd1 - out = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - for lane in range(32): - expected = s1_vals[lane] if (lane % 2 == 1) else s0_vals[lane] - self.assertEqual(out[lane], expected) - - # Mask: even bits 1 (src1), odd bits 0 (src0) -> 0x55555555 - mask_even1_odd0 = 0x55555555 - sim.vcc = mask_even1_odd0 - out = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - for lane in range(32): - expected = s1_vals[lane] if (lane % 2 == 0) else s0_vals[lane] - self.assertEqual(out[lane], expected) - - def test_multi_lane_divergence_checkerboard_wave64(self) -> None: - """Verify alternating even/odd lane divergence pattern across 64 lanes.""" - sim = SIMDVectorCNDMask64Simulator(wave_size=64) - s0_vals = [0x12340000_00000000 | (i << 16) for i in range(64)] - s1_vals = [0x98760000_00000000 | (i << 16) for i in range(64)] - sim.store_vgpr_pair_wave(10, s0_vals) - sim.store_vgpr_pair_wave(12, s1_vals) - - sim.vcc = 0xAAAAAAAAAAAAAAAA - out = sim.step_v_cndmask_b64(14, 10, 12, cond_src="vcc") - for lane in range(64): - expected = s1_vals[lane] if (lane % 2 == 1) else s0_vals[lane] - self.assertEqual(out[lane], expected) - - sim.vcc = 0x5555555555555555 - out = sim.step_v_cndmask_b64(14, 10, 12, cond_src="vcc") - for lane in range(64): - expected = s1_vals[lane] if (lane % 2 == 0) else s0_vals[lane] - self.assertEqual(out[lane], expected) - - def test_single_lane_active_wave32_and_wave64(self) -> None: - """Verify that a single active condition bit modifies exclusively that lane.""" - for wave_size, test_lanes in ((32, [0, 1, 7, 15, 16, 30, 31]), (64, [0, 1, 31, 32, 47, 62, 63])): - sim = SIMDVectorCNDMask64Simulator(wave_size=wave_size) - s0_vals = [0x33333333_00000000 | i for i in range(wave_size)] - s1_vals = [0x77777777_00000000 | i for i in range(wave_size)] - sim.store_vgpr_pair_wave(0, s0_vals) - sim.store_vgpr_pair_wave(2, s1_vals) - - for target_lane in test_lanes: - with self.subTest(wave_size=wave_size, target_lane=target_lane): - mask = 1 << target_lane - sim.vcc = mask - out = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - for lane in range(wave_size): - expected = s1_vals[lane] if lane == target_lane else s0_vals[lane] - self.assertEqual(out[lane], expected) - - def test_single_lane_inactive_wave64(self) -> None: - """Verify that all lanes except one single inactive lane select src1.""" - sim = SIMDVectorCNDMask64Simulator(wave_size=64) - s0_vals = [0x44444444_00000000 | i for i in range(64)] - s1_vals = [0x88888888_00000000 | i for i in range(64)] - sim.store_vgpr_pair_wave(20, s0_vals) - sim.store_vgpr_pair_wave(22, s1_vals) - - for inactive_lane in (0, 15, 31, 32, 48, 63): - with self.subTest(inactive_lane=inactive_lane): - sim.vcc = MASK64 ^ (1 << inactive_lane) - out = sim.step_v_cndmask_b64(24, 20, 22, cond_src="vcc") - for lane in range(64): - expected = s0_vals[lane] if lane == inactive_lane else s1_vals[lane] - self.assertEqual(out[lane], expected) - - def test_subgroup_warp_partitions_wave64(self) -> None: - """Verify contiguous block partitions (half-waves and quad-waves) across 64 lanes.""" - sim = SIMDVectorCNDMask64Simulator(wave_size=64) - s0_vals = [0x10000000_00000000 | i for i in range(64)] - s1_vals = [0x20000000_00000000 | i for i in range(64)] - sim.store_vgpr_pair_wave(0, s0_vals) - sim.store_vgpr_pair_wave(2, s1_vals) - - # Low half (0..31) select src0, high half (32..63) select src1 - sim.vcc = 0xFFFFFFFF_00000000 - out = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - self.assertEqual(out[:32], s0_vals[:32]) - self.assertEqual(out[32:], s1_vals[32:]) - - # Low half select src1, high half select src0 - sim.vcc = 0x00000000_FFFFFFFF - out = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - self.assertEqual(out[:32], s1_vals[:32]) - self.assertEqual(out[32:], s0_vals[32:]) - - # Quad-wave blocks: lanes 0..15 (0), 16..31 (1), 32..47 (0), 48..63 (1) - sim.vcc = 0xFFFF0000_FFFF0000 - out = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - for lane in range(64): - quarter = (lane // 16) % 2 - expected = s1_vals[lane] if quarter == 1 else s0_vals[lane] - self.assertEqual(out[lane], expected) - - def test_vcc_implicit_and_explicit_routing_wave32(self) -> None: - """Verify routing via implicit vcc and explicit vcc_lo in Wave32 mode.""" - sim = SIMDVectorCNDMask64Simulator(wave_size=32) - s0_vals = [0x11110000_00000000 | i for i in range(32)] - s1_vals = [0x22220000_00000000 | i for i in range(32)] - sim.store_vgpr_pair_wave(0, s0_vals) - sim.store_vgpr_pair_wave(2, s1_vals) - - mask32 = 0x5A5A5A5A - # High bits in VCC must be ignored by Wave32 - sim.vcc = 0xDEADBEEF_00000000 | mask32 - - out_vcc = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - out_vcc_lo = sim.step_v_cndmask_b64(6, 0, 2, cond_src="vcc_lo") - self.assertEqual(out_vcc, out_vcc_lo) - for lane in range(32): - bit = (mask32 >> lane) & 1 - expected = s1_vals[lane] if bit else s0_vals[lane] - self.assertEqual(out_vcc[lane], expected) - - def test_vcc_implicit_and_explicit_routing_wave64(self) -> None: - """Verify routing via vcc (full 64-bit), vcc_lo, and vcc_hi in Wave64 mode.""" - sim = SIMDVectorCNDMask64Simulator(wave_size=64) - s0_vals = [0xAAAA0000_00000000 | i for i in range(64)] - s1_vals = [0xBBBB0000_00000000 | i for i in range(64)] - sim.store_vgpr_pair_wave(0, s0_vals) - sim.store_vgpr_pair_wave(2, s1_vals) - - lo_mask = 0x12345678 - hi_mask = 0x9ABCDEF0 - sim.vcc = join_dwords(lo_mask, hi_mask) - - # Full 64-bit VCC - out_full = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - for lane in range(32): - bit = (lo_mask >> lane) & 1 - self.assertEqual(out_full[lane], s1_vals[lane] if bit else s0_vals[lane]) - for lane in range(32, 64): - bit = (hi_mask >> (lane - 32)) & 1 - self.assertEqual(out_full[lane], s1_vals[lane] if bit else s0_vals[lane]) - - # Explicit vcc_lo: in wave64, upper 32 lanes receive zero condition (select src0) - out_lo = sim.step_v_cndmask_b64(6, 0, 2, cond_src="vcc_lo") - for lane in range(32): - bit = (lo_mask >> lane) & 1 - self.assertEqual(out_lo[lane], s1_vals[lane] if bit else s0_vals[lane]) - for lane in range(32, 64): - self.assertEqual(out_lo[lane], s0_vals[lane]) - - # Explicit vcc_hi: upper 32 bits of VCC placed into low 32 lanes, upper lanes zero - out_hi = sim.step_v_cndmask_b64(8, 0, 2, cond_src="vcc_hi") - for lane in range(32): - bit = (hi_mask >> lane) & 1 - self.assertEqual(out_hi[lane], s1_vals[lane] if bit else s0_vals[lane]) - for lane in range(32, 64): - self.assertEqual(out_hi[lane], s0_vals[lane]) - - def test_sgpr_pair_mask_routing_wave64(self) -> None: - """Verify that an SGPR pair (e.g. s[4:5]) routes condition bits accurately to 64 lanes.""" - sim = SIMDVectorCNDMask64Simulator(wave_size=64) - s0_vals = [0xC0FFEE00_00000000 | i for i in range(64)] - s1_vals = [0xFEED0000_00000000 | i for i in range(64)] - sim.store_vgpr_pair_wave(0, s0_vals) - sim.store_vgpr_pair_wave(2, s1_vals) - - mask64 = 0x80000000_00000001 | 0x00000001_80000000 - sim.set_sgpr_u64(4, mask64) - - out = sim.step_v_cndmask_b64(4, 0, 2, cond_src="s[4:5]") - for lane in range(64): - bit = (mask64 >> lane) & 1 - self.assertEqual(out[lane], s1_vals[lane] if bit else s0_vals[lane]) - - def test_sgpr_single_mask_routing_wave32(self) -> None: - """Verify that a single 32-bit SGPR routes condition bits accurately in Wave32 mode.""" - sim = SIMDVectorCNDMask64Simulator(wave_size=32) - s0_vals = [0x01010101_00000000 | i for i in range(32)] - s1_vals = [0x02020202_00000000 | i for i in range(32)] - sim.store_vgpr_pair_wave(0, s0_vals) - sim.store_vgpr_pair_wave(2, s1_vals) - - mask32 = 0x0F0F0F0F - sim.set_sgpr_u32(8, mask32) - - out = sim.step_v_cndmask_b64(4, 0, 2, cond_src="s8") - for lane in range(32): - bit = (mask32 >> lane) & 1 - self.assertEqual(out[lane], s1_vals[lane] if bit else s0_vals[lane]) - - def test_random_divergence_validation_against_oracle(self) -> None: - """Validate simulated SIMD wave execution against reference oracle for 30 random cases.""" - rng = random.Random(999) - for wave_size in (32, 64): - sim = SIMDVectorCNDMask64Simulator(wave_size=wave_size) - for _ in range(15): - s0_vals = [rng.getrandbits(64) for _ in range(wave_size)] - s1_vals = [rng.getrandbits(64) for _ in range(wave_size)] - mask = rng.getrandbits(wave_size) - - sim.store_vgpr_pair_wave(0, s0_vals) - sim.store_vgpr_pair_wave(2, s1_vals) - sim.vcc = mask - - out_sim = sim.step_v_cndmask_b64(4, 0, 2, cond_src="vcc") - out_oracle = ref_simd_cndmask_b64(s0_vals, s1_vals, mask, wave_size=wave_size) - self.assertEqual(out_sim, out_oracle) +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import support # noqa: E402 +from rdna2spirv import Unsupported # noqa: E402 + +M32 = 0xFFFFFFFF + + +def select64(cond, s0, s1): + return s1 if cond else s0 + + +def run(cond_mask, s0, s1, form="vcc"): + """Select a 64-bit value with two v_cndmask_b32; returns (low, high) of v[0:1]. cond_mask is the lane's bit, 0 or 1.""" + setup = [f"v_mov_b32 v2, {s0 & M32:#x}", f"v_mov_b32 v3, {s0 >> 32:#x}", + f"v_mov_b32 v4, {s1 & M32:#x}", f"v_mov_b32 v5, {s1 >> 32:#x}"] + if form == "vcc": + sel = [f"s_mov_b32 vcc_lo, {cond_mask:#x}", "v_cndmask_b32_e32 v0, v2, v4, vcc_lo", + "v_cndmask_b32_e32 v1, v3, v5, vcc_lo"] + elif form == "sgpr": + sel = [f"s_mov_b32 s8, {cond_mask:#x}", "v_cndmask_b32_e64 v0, v2, v4, s8", "v_cndmask_b32_e64 v1, v3, v5, s8"] + else: + raise ValueError(form) + lines = setup + sel + ["exp mrt0 v0, v1, v0, v1 done vm", "s_endpgm"] + w = support.mrt0_words(support.translate_lines("ps_cndmask64", lines)) + assert w[0] == w[2] and w[1] == w[3] + return w[0], w[1] + + +A = 0x1111111122222222 +B = 0xAAAAAAAABBBBBBBB + + +class CndmaskPair(unittest.TestCase): + def test_by_hand(self): + for form in ("vcc", "sgpr"): + with self.subTest(form=form): + self.assertEqual(run(0, A, B, form), (0x22222222, 0x11111111)) # bit clear: S0 + self.assertEqual(run(1, A, B, form), (0xBBBBBBBB, 0xAAAAAAAA)) # bit set: S1 + self.assertEqual(run(1, A, A, form), (0x22222222, 0x11111111)) + self.assertEqual(run(1, 0, 0xFFFFFFFFFFFFFFFF, form), (M32, M32)) + + def test_both_halves_follow_the_same_bit(self): + for cond in (0, 1): + lo, hi = run(cond, 0x00000000FFFFFFFF, 0xFFFFFFFF00000000) + self.assertEqual((hi << 32) | lo, select64(cond, 0x00000000FFFFFFFF, 0xFFFFFFFF00000000)) + + def test_random(self): + rng = random.Random(0xC0DE64) + for _ in range(30): + s0, s1, mask = rng.getrandbits(64), rng.getrandbits(64), rng.getrandbits(1) + want = select64(mask, s0, s1) + for form in ("vcc", "sgpr"): + with self.subTest(form=form, s0=hex(s0), s1=hex(s1), mask=hex(mask)): + lo, hi = run(mask, s0, s1, form) + self.assertEqual((hi << 32) | lo, want) + + def test_v_cndmask_b64_is_refused(self): + with self.assertRaises(Unsupported): + support.translate_lines("ps_cndmask64_op", ["s_mov_b32 vcc_lo, 1", "v_cndmask_b64 v[0:1], v[2:3], v[4:5], vcc_lo", + "exp mrt0 v0, v1, v0, v1 done vm", "s_endpgm"]) if __name__ == "__main__": diff --git a/tests/semantic/test_alu_cvt_norm_f16.py b/tests/semantic/test_alu_cvt_norm_f16.py index 7a72b48ca..fd2b94012 100644 --- a/tests/semantic/test_alu_cvt_norm_f16.py +++ b/tests/semantic/test_alu_cvt_norm_f16.py @@ -206,15 +206,33 @@ class CvtNormF16Tests(unittest.TestCase): want = (ref_norm16(float_to_f16(0.5), False) << 16) | ref_norm16(float_to_f16(0.5), True) self.assertEqual(got, want) - def test_rejects_output_modifiers(self): - for line in ( - "v_cvt_norm_i16_f16_e64 v0, v1 clamp", - "v_cvt_norm_u16_f16_e64 v0, v1 mul:2", - "v_cvt_norm_i16_f16_e64 v0, v1 div:2", + def test_output_modifiers_match_plain_and_reject_invalid_forms(self): + h = float_to_f16(0.5) + for op, snorm in (("v_cvt_norm_i16_f16", True), ("v_cvt_norm_u16_f16", False)): + want = (SEED_DST & 0xFFFF0000) | ref_norm16(h, snorm) + for mod in ("clamp", "mul:2", "mul:4", "div:2"): + with self.subTest(op=op, mod=mod): + got = run_lines([ + f"v_mov_b32 v1, {h:#x}", + f"v_mov_b32 v0, {SEED_DST:#x}", + f"{op}_e64 v0, v1 {mod}", + ]) + self.assertEqual(got, want) + with self.subTest(op=op, form="sdwa_clamp"): + got_sdwa = run_lines([ + f"v_mov_b32 v1, {(h << 16):#x}", + f"v_mov_b32 v0, {SEED_DST:#x}", + f"{op}_sdwa v0, v1 clamp dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + ]) + self.assertEqual(got_sdwa, (ref_norm16(h, snorm) << 16) | (SEED_DST & 0xFFFF)) + for bad_line in ( + "v_cvt_norm_i16_f16_e64 v0, v1 mul:8", + "v_cvt_norm_u16_f16_sdwa v0, v1 mul:2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + "v_cvt_norm_i16_f16_e32 v0, v1 clamp", ): - with self.subTest(line=line): + with self.subTest(line=bad_line): with self.assertRaises(rdna2spirv.Unsupported): - translate_lines([line]) + translate_lines([bad_line]) if __name__ == "__main__": diff --git a/tests/semantic/test_alu_cvt_pknorm_f32.py b/tests/semantic/test_alu_cvt_pknorm_f32.py index 1e97bc548..1dc548ff6 100644 --- a/tests/semantic/test_alu_cvt_pknorm_f32.py +++ b/tests/semantic/test_alu_cvt_pknorm_f32.py @@ -147,14 +147,23 @@ class CvtPknormTests(unittest.TestCase): with self.subTest(op=op, x=hex(x), y=hex(y)): self.assertEqual(run_op(op, x, y), norm16(x, OPS[op]) | norm16(y, OPS[op]) << 16) - def test_source_modifiers_and_rejected_clamp(self): + def test_source_and_output_modifiers(self): half = bits(0.5) self.assertEqual(run_op("v_cvt_pknorm_i16_f32", half, half, "-"), (-16384 & 0xFFFF) | 16384 << 16) got = run_lines([f"v_mov_b32 v1, {bits(-0.5):#x}", f"v_mov_b32 v2, {half:#x}", "v_cvt_pknorm_u16_f32 v0, |v1|, -v2"]) self.assertEqual(got, 32768) # |-0.5| -> 32768, -0.5 -> 0 + for op, snorm in OPS.items(): + for x, y in ((bits(-2.0), bits(2.0)), (bits(0.5), bits(-0.5)), (0x7FC00000, bits(1.0))): + with self.subTest(op=op, x=hex(x), y=hex(y)): + got_clamp = run_lines([ + f"v_mov_b32 v1, {x:#x}", + f"v_mov_b32 v2, {y:#x}", + f"{op} v0, v1, v2 clamp", + ]) + self.assertEqual(got_clamp, norm16(x, snorm) | (norm16(y, snorm) << 16)) with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_cvt_pknorm_i16_f32 v0, v1, v2 clamp"]) + run_lines(["v_cvt_pknorm_i16_f32 v0, v1, v2 mul:2"]) if __name__ == "__main__": diff --git a/tests/semantic/test_alu_div_fixup.py b/tests/semantic/test_alu_div_fixup.py index abde61ce6..9a2368666 100644 --- a/tests/semantic/test_alu_div_fixup.py +++ b/tests/semantic/test_alu_div_fixup.py @@ -138,17 +138,19 @@ class DivFixupF16Tests(unittest.TestCase): cases = ( ("normal_pos", H_HALF, H_ONE, H_ONE, H_HALF), ("normal_neg_sign_fix", H_HALF, H_NEG2, H_ONE, H_HALF | 0x8000), - ("nan_s2_priority", H_ONE, H_SNAN1, H_QNAN2, H_QNAN2 | 0x0200), - ("nan_s1_quieted", H_ONE, H_SNAN1, H_ONE, H_SNAN1 | 0x0200), + ("nan_s2_priority", H_ONE, H_SNAN1, H_QNAN2, H_QNAN2), + ("nan_s1_snan_ieee0", H_ONE, H_SNAN1, H_ONE, H_SNAN1), + ("nan_s2_snan_ieee0", H_ONE, H_ONE, 0x7C01, 0x7C01), ("zero_div_zero", H_ONE, H_POS0, H_NEG0, H_CANON_NAN), ("inf_div_inf", H_ONE, H_INF, H_NINF, H_CANON_NAN), ("finite_div_inf_neg", H_ONE, H_NINF, H_ONE, H_NEG0), ("zero_div_finite_pos", H_ONE, H_NEG2, H_NEG0, H_POS0), ("finite_div_zero_neg", H_ONE, H_NEG0, H_ONE, H_NINF), ("inf_div_finite_pos", H_ONE, H_NEG2, H_NINF, H_INF), - ("nan_quot_signed_passthrough", 0x7E35, H_NEG2, H_ONE, 0xFE35), - ("exp_underflow_to_zero", H_ONE, 0x7800, 0x0400, H_POS0), # 2^-14 / 2^15 = 2^-29 -> +0 - ("exp_overflow_to_inf", H_ONE, 0x0400, 0x7800, H_INF), # 2^15 / 2^-14 = 2^29 -> +inf + ("nan_quot_to_pos_inf", 0x7E35, H_ONE, H_ONE, H_INF), + ("nan_quot_to_neg_inf", 0x7E35, H_NEG2, H_ONE, H_NINF), + ("f16_no_exp_underflow", H_ONE, 0x7800, 0x0400, H_ONE), # gfx1036: e2-e1=-29 keeps S0 + ("f16_no_exp_overflow", H_ONE, 0x0400, 0x7800, H_ONE), # gfx1036: e2-e1=+29 keeps S0 ) for name, s0, s1, s2, want in cases: with self.subTest(case=name): @@ -183,17 +185,21 @@ class DivFixupF64Tests(unittest.TestCase): cases = ( ("normal_pos", D_THREE, D_ONE, D_ONE, D_THREE), ("normal_neg_sign_fix", D_THREE, D_NEG2, D_ONE, D_THREE | (1 << 63)), - ("nan_s2_priority", D_ONE, D_SNAN1, D_QNAN2, D_QNAN2 | (0x00080000 << 32)), - ("nan_s1_quieted", D_ONE, D_SNAN1, D_ONE, D_SNAN1 | (0x00080000 << 32)), + ("nan_s2_priority", D_ONE, D_SNAN1, D_QNAN2, D_QNAN2), + ("nan_s1_snan_ieee0", D_ONE, D_SNAN1, D_ONE, D_SNAN1), + ("nan_s2_snan_ieee0", D_ONE, D_ONE, 0x7FF0000000000001, 0x7FF0000000000001), ("zero_div_zero", D_ONE, D_POS0, D_NEG0, D_CANON_NAN), ("inf_div_inf", D_ONE, D_INF, D_NINF, D_CANON_NAN), ("finite_div_inf_neg", D_ONE, D_NINF, D_ONE, D_NEG0), ("zero_div_finite_pos", D_ONE, D_NEG2, D_NEG0, D_POS0), ("finite_div_zero_neg", D_ONE, D_NEG0, D_ONE, D_NINF), ("inf_div_finite_pos", D_ONE, D_NEG2, D_NINF, D_INF), - ("nan_quot_signed_passthrough", 0xFFF8123456789ABC, D_NEG2 & ~(1 << 63), D_ONE, 0x7FF8123456789ABC), - ("exp_underflow_to_zero", D_ONE, 0x4630000000000000, 0x0010000000000000, D_POS0), # 2^-1022 / 2^100 - ("exp_overflow_to_inf", D_ONE, 0x0010000000000000, 0x4630000000000000, D_INF), # 2^100 / 2^-1022 + ("nan_quot_to_pos_inf", 0xFFF8123456789ABC, D_NEG2 & ~(1 << 63), D_ONE, D_INF), + ("nan_quot_to_neg_inf", 0x7FF8123456789ABC, D_NEG2, D_ONE, D_NINF), + ("exp_diff_m1075_keeps_s0", D_ONE, 2046 << 52, 971 << 52, D_ONE), # gfx1036: e2-e1=-1075 keeps S0 + ("exp_diff_m1076_to_zero", D_ONE, 2046 << 52, 970 << 52, D_POS0), # gfx1036: e2-e1=-1076 -> +0 + ("exp_underflow_m1122", D_ONE, 1123 << 52, 1 << 52, D_POS0), # gfx1036: 2^-1022 / 2^100 -> +0 + ("f64_no_exp_overflow", D_ONE, 1 << 52, 1025 << 52, D_ONE), # gfx1036: e2-e1=+1024 keeps S0 ) for name, s0, s1, s2, want in cases: with self.subTest(case=name): diff --git a/tests/semantic/test_alu_div_fmas.py b/tests/semantic/test_alu_div_fmas.py index ca4e53689..658607557 100644 --- a/tests/semantic/test_alu_div_fmas.py +++ b/tests/semantic/test_alu_div_fmas.py @@ -1,9 +1,17 @@ -"""Semantic interpreter and spirv-val tests for RDNA2 v_div_fmas_f32 and v_div_fmas_f64. +"""Semantic interpreter and SPIR-V validation tests for RDNA2 v_div_fmas_f32 and v_div_fmas_f64. -v_div_fmas_f32 computes D = VCC[lane] ? (2^32 * fma(S0, S1, S2)) : fma(S0, S1, S2). -v_div_fmas_f64 computes D = VCC[lane] ? (2^64 * fma(S0, S1, S2)) : fma(S0, S1, S2). +Measured natively on RDNA2 (AMD Radeon Graphics, gfx1036, Windows driver 32.0.21042.62, +wave32 and wave64, game MODE ieee=0 / dx10_clamp=1 / denorm32=0 / denorm16_64=3): + VCC == 0: fma(S0, S1, S2) + VCC == 1: (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2) +where (bias, S) = (127, 64) for f32 and (1023, 128) for f64 (exp(S2) > bias <=> |S2| >= 2.0). + +For f32 under denorm32=0, subnormal inputs and intermediate products are kept, while the +scaled FMA output flushes subnormals to signed zero before (and after) output modifiers. +For f64 under denorm16_64=3, subnormal inputs and outputs are preserved with single rounding. Both accept VOP3 input (abs/neg) and output (mul:2, mul:4, div:2, clamp) modifiers. """ +from fractions import Fraction import math import os import re @@ -24,6 +32,7 @@ sys.path.insert(0, TOOLS_DIR) sys.path.insert(0, HERE) import rdna2spirv # noqa: E402 +import spirv_asm # noqa: E402 import spirv_mini_interp as si # noqa: E402 STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: return struct.unpack(" int: + return struct.unpack("> 32 @@ -79,6 +92,9 @@ def translate_lines(lines): def validate_spirv(spv_text: str): + # Always assemble with the in-repo SPIR-V assembler so malformed opcodes/IDs fail everywhere. + binary = spirv_asm.assemble(spv_text) + assert len(binary) >= 20 and binary[:4] == b"\x03\x02\x23\x07" spirv_as = shutil.which("spirv-as") spirv_val = shutil.which("spirv-val") if not spirv_as or not spirv_val: @@ -96,12 +112,12 @@ def validate_spirv(spv_text: str): raise AssertionError(f"spirv-val failed: {r2.stderr}") -def run_f32(x: float, y: float, z: float, vcc: bool, insn: str = "v_div_fmas_f32 v0, v1, v2, v3") -> int: +def run_f32_u(ux: int, uy: int, uz: int, vcc: bool, insn: str = "v_div_fmas_f32 v0, v1, v2, v3") -> int: vcc_set = "v_cmp_eq_u32_e32 vcc_lo, 1, 1" if vcc else "v_cmp_eq_u32_e32 vcc_lo, 0, 1" spv = translate_lines([ - f"v_mov_b32 v1, {f2u(x):#x}", - f"v_mov_b32 v2, {f2u(y):#x}", - f"v_mov_b32 v3, {f2u(z):#x}", + f"v_mov_b32 v1, {ux & 0xFFFFFFFF:#x}", + f"v_mov_b32 v2, {uy & 0xFFFFFFFF:#x}", + f"v_mov_b32 v3, {uz & 0xFFFFFFFF:#x}", "v_mov_b32 v0, 0", vcc_set, insn, @@ -109,36 +125,282 @@ def run_f32(x: float, y: float, z: float, vcc: bool, insn: str = "v_div_fmas_f32 return si.run_fragment(spv)["%out_mrt0"][0] +def run_f32(x: float, y: float, z: float, vcc: bool, insn: str = "v_div_fmas_f32 v0, v1, v2, v3") -> int: + return run_f32_u(f2u(x), f2u(y), f2u(z), vcc, insn) + + +def _eval_spv_f64_mrt0(spv_text: str): + """Straight-line SSA evaluator for translated %double/%uint/%bool fragment shaders.""" + def u64_to_d(lo, hi): + return struct.unpack("> 32 + + def safe_fma(a, b, c): + # Exact IEEE-754 binary64 FMA compatible with Python 3.12 (math.fma was added in 3.13). + if math.isnan(a) or math.isnan(b) or math.isnan(c): + return float("nan") + if math.isinf(a) or math.isinf(b): + if a == 0.0 or b == 0.0: + return float("nan") + prod_inf = math.copysign(math.inf, math.copysign(1.0, a) * math.copysign(1.0, b)) + if math.isinf(c) and math.copysign(1.0, c) != math.copysign(1.0, prod_inf): + return float("nan") + return prod_inf + if math.isinf(c): + return c + exact = Fraction(a) * Fraction(b) + Fraction(c) + if exact == 0: + prod_neg = (math.copysign(1.0, a) * math.copysign(1.0, b)) < 0.0 + c_neg = math.copysign(1.0, c) < 0.0 + if a * b == 0.0 and c == 0.0 and prod_neg and c_neg: + return -0.0 + return 0.0 + try: + r = float(exact) + except OverflowError: + return -math.inf if exact < 0 else math.inf + return -0.0 if (r == 0.0 and exact < 0) else r + + consts, env, mem = {}, {}, {} + in_fn = False + for raw in spv_text.splitlines(): + line = raw.strip() + if not line or line.startswith(";"): + continue + if line.startswith("%main = OpFunction"): + in_fn = True + continue + if line == "OpFunctionEnd": + in_fn = False + continue + m = re.match(r"^(%\S+)\s*=\s*(\S+)(.*)$", line) + if not in_fn: + if m: + res, op, rest = m.group(1), m.group(2), m.group(3).strip().split() + if op == "OpConstant": + ty, val = rest[0], rest[1] + if ty == "%uint": + consts[res] = int(val) & 0xFFFFFFFF + elif ty == "%int": + consts[res] = int(val) + elif ty == "%float": + consts[res] = float(val) + elif op == "OpConstantTrue": + consts[res] = True + elif op == "OpConstantFalse": + consts[res] = False + elif op == "OpConstantNull": + ty = rest[0] + if ty == "%uint": + consts[res] = 0 + elif ty == "%float": + consts[res] = 0.0 + elif ty == "%bool": + consts[res] = False + else: + consts[res] = (0.0, 0.0, 0.0, 0.0) + elif op == "OpVariable": + consts[res] = res + mem[res] = (0.0, 0.0, 0.0, 0.0) if "v4float" in rest[0] else 0 + continue + if not m: + toks = line.split() + if toks[0] == "OpStore": + dst = env.get(toks[1], consts.get(toks[1], toks[1])) + mem[dst] = env[toks[2]] if toks[2] in env else consts[toks[2]] + continue + res, op, rest = m.group(1), m.group(2), m.group(3).strip().split() + + def get(tok): + return env[tok] if tok in env else consts[tok] + + if op == "OpVariable": + mem[res] = get(rest[2]) if len(rest) >= 3 else (True if res == "%active" else 0) + env[res] = res + elif op == "OpAccessChain": + key = (rest[1], tuple(get(t) for t in rest[2:])) + env[res] = key + mem.setdefault(key, 0) + elif op == "OpLoad": + env[res] = mem.get(get(rest[1]), 0) + elif op == "OpCompositeConstruct": + env[res] = tuple(get(t) for t in rest[1:]) + elif op == "OpCompositeExtract": + env[res] = get(rest[1])[int(rest[2])] + elif op == "OpBitcast": + ty, v = rest[0], get(rest[1]) + if ty == "%double": + env[res] = u64_to_d(v[0], v[1]) + elif ty == "%v2uint_d": + env[res] = d_to_u64(v) + elif ty == "%float": + env[res] = struct.unpack("= 0x80000000 else v + else: + raise NotImplementedError(f"OpBitcast {ty}") + elif op == "OpExtInst": + fn, args = rest[2], [get(t) for t in rest[3:]] + if fn == "FAbs": + env[res] = abs(args[0]) + elif fn == "Fma": + env[res] = safe_fma(args[0], args[1], args[2]) + elif fn == "FClamp": + x, lo, hi = args + env[res] = float("nan") if math.isnan(x) else max(lo, min(hi, x)) + else: + raise NotImplementedError(f"OpExtInst {fn}") + elif op == "OpFNegate": + env[res] = -get(rest[1]) + elif op == "OpFMul": + env[res] = get(rest[1]) * get(rest[2]) + elif op == "OpFAdd": + env[res] = get(rest[1]) + get(rest[2]) + elif op == "OpFSub": + env[res] = get(rest[1]) - get(rest[2]) + elif op == "OpIAdd": + env[res] = (get(rest[1]) + get(rest[2])) & 0xFFFFFFFF + elif op == "OpISub": + env[res] = (get(rest[1]) - get(rest[2])) & 0xFFFFFFFF + elif op == "OpBitwiseAnd": + env[res] = (get(rest[1]) & get(rest[2])) & 0xFFFFFFFF + elif op == "OpBitwiseOr": + env[res] = (get(rest[1]) | get(rest[2])) & 0xFFFFFFFF + elif op == "OpBitwiseXor": + env[res] = (get(rest[1]) ^ get(rest[2])) & 0xFFFFFFFF + elif op == "OpShiftRightLogical": + env[res] = (get(rest[1]) & 0xFFFFFFFF) >> (get(rest[2]) & 31) + elif op == "OpShiftLeftLogical": + env[res] = ((get(rest[1]) & 0xFFFFFFFF) << (get(rest[2]) & 31)) & 0xFFFFFFFF + elif op == "OpIEqual": + env[res] = (get(rest[1]) & 0xFFFFFFFF) == (get(rest[2]) & 0xFFFFFFFF) + elif op == "OpINotEqual": + env[res] = (get(rest[1]) & 0xFFFFFFFF) != (get(rest[2]) & 0xFFFFFFFF) + elif op == "OpUGreaterThan": + env[res] = (get(rest[1]) & 0xFFFFFFFF) > (get(rest[2]) & 0xFFFFFFFF) + elif op == "OpUGreaterThanEqual": + env[res] = (get(rest[1]) & 0xFFFFFFFF) >= (get(rest[2]) & 0xFFFFFFFF) + elif op == "OpULessThan": + env[res] = (get(rest[1]) & 0xFFFFFFFF) < (get(rest[2]) & 0xFFFFFFFF) + elif op == "OpULessThanEqual": + env[res] = (get(rest[1]) & 0xFFFFFFFF) <= (get(rest[2]) & 0xFFFFFFFF) + elif op == "OpFOrdGreaterThanEqual": + a, b = get(rest[1]), get(rest[2]) + env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a >= b) + elif op == "OpFOrdGreaterThan": + a, b = get(rest[1]), get(rest[2]) + env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a > b) + elif op == "OpFOrdLessThan": + a, b = get(rest[1]), get(rest[2]) + env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a < b) + elif op == "OpFOrdEqual": + a, b = get(rest[1]), get(rest[2]) + env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a == b) + elif op == "OpFOrdNotEqual": + a, b = get(rest[1]), get(rest[2]) + env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a != b) + elif op == "OpLogicalAnd": + env[res] = bool(get(rest[1])) and bool(get(rest[2])) + elif op == "OpLogicalOr": + env[res] = bool(get(rest[1])) or bool(get(rest[2])) + elif op == "OpLogicalNot": + env[res] = not bool(get(rest[1])) + elif op == "OpLogicalEqual": + env[res] = bool(get(rest[1])) == bool(get(rest[2])) + elif op == "OpSelect": + env[res] = get(rest[2]) if get(rest[1]) else get(rest[3]) + elif op == "OpCopyObject": + env[res] = get(rest[1]) + elif op in ("OpLabel", "OpFunctionParameter"): + pass + else: + raise NotImplementedError(f"Unhandled SPIR-V op: {op} ({line})") + return [struct.unpack(" int: + vcc_set = "v_cmp_eq_u32_e32 vcc_lo, 1, 1" if vcc else "v_cmp_eq_u32_e32 vcc_lo, 0, 1" + spv = translate_lines([ + f"v_mov_b32 v2, {ux & 0xFFFFFFFF:#x}", + f"v_mov_b32 v3, {(ux >> 32) & 0xFFFFFFFF:#x}", + f"v_mov_b32 v4, {uy & 0xFFFFFFFF:#x}", + f"v_mov_b32 v5, {(uy >> 32) & 0xFFFFFFFF:#x}", + f"v_mov_b32 v6, {uz & 0xFFFFFFFF:#x}", + f"v_mov_b32 v7, {(uz >> 32) & 0xFFFFFFFF:#x}", + "v_mov_b32 v0, 0", + "v_mov_b32 v1, 0", + vcc_set, + insn, + ]) + mrt0 = _eval_spv_f64_mrt0(spv) + return ((mrt0[1] & 0xFFFFFFFF) << 32) | (mrt0[0] & 0xFFFFFFFF) + + class DivFmasF32Tests(unittest.TestCase): - def test_vcc_clear_and_set(self): + def test_vcc_clear_and_s2_exponent_threshold(self): + # Measured on gfx1036: VCC=1 scales by 2^+64 when exp(S2) > 127 (|S2| >= 2.0), else 2^-64. cases = ( - (1.5, 2.0, 0.5, 3.5), - (-2.0, 3.0, 1.0, -5.0), - (2.0 ** -32, 1.0, 0.0, 2.0 ** -32), - (0.0, 5.0, 0.25, 0.25), + (f2u(1.5), f2u(2.0), f2u(0.5), 0x40600000, 0x20600000), # |S2|=0.5 < 2.0 -> 3.5 * 2^-64 + (f2u(1.0), f2u(2.0), f2u(1.0), 0x40400000, 0x20400000), # |S2|=1.0 (exp=127) -> 3.0 * 2^-64 + (0, 0, 0x3FFFFFFF, 0x3FFFFFFF, 0x1FFFFFFF), # nextbelow(2.0) (exp=127) -> * 2^-64 + (0, 0, 0x40000000, 0x40000000, 0x60000000), # 2.0 (exp=128) -> * 2^+64 + (0, 0, 0xBFFFFFFF, 0xBFFFFFFF, 0x9FFFFFFF), # -nextbelow(2.0) (exp=127) -> * 2^-64 + (0, 0, 0xC0000000, 0xC0000000, 0xE0000000), # -2.0 (exp=128) -> * 2^+64 + (f2u(1.0), f2u(2.0), f2u(2.0), 0x40800000, 0x60800000), # |S2|=2.0 -> 4.0 * 2^+64 + (f2u(1.0), f2u(2.0), f2u(-4.0), 0xC0000000, 0xE0000000), # |S2|=4.0 -> -2.0 * 2^+64 ) - for x, y, z, base in cases: - with self.subTest(x=x, y=y, z=z): - self.assertEqual(run_f32(x, y, z, False), f2u(base)) - self.assertEqual(run_f32(x, y, z, True), f2u(base * float(1 << 32))) + for ux, uy, uz, want0, want1 in cases: + with self.subTest(uz=hex(uz)): + self.assertEqual(run_f32_u(ux, uy, uz, False), want0) + self.assertEqual(run_f32_u(ux, uy, uz, True), want1) - def test_vcc_scale_overflows_to_inf(self): - self.assertEqual(run_f32(2.0 ** 100, 1.0, 0.0, False), f2u(2.0 ** 100)) - self.assertEqual(run_f32(2.0 ** 100, 1.0, 0.0, True), f2u(float("inf"))) - self.assertEqual(run_f32(-(2.0 ** 100), 1.0, 0.0, True), f2u(float("-inf"))) + def test_overflow_prevention_and_sticky_bit(self): + # Scale-down prevents intermediate product overflow (measured on gfx1036). + self.assertEqual(run_f32(2.0 ** 80, 2.0 ** 80, 0.5, False), 0x7F800000) + self.assertEqual(run_f32(2.0 ** 80, 2.0 ** 80, 0.5, True), 0x6F800000) # 2^96 + self.assertEqual(run_f32(2.0 ** 120, 2.0 ** 20, 1.0, True), 0x65800000) # 2^76 + # Exact cancellation and mixed-magnitude scale-up (no premature pre-scale overflow). + self.assertEqual(run_f32(2.0 ** 80, -(2.0 ** -10), 2.0 ** 70, True), 0x00000000) + self.assertEqual(run_f32(2.0 ** -50, 2.0 ** 100, 2.0, True), 0x78800000) # 2^114 + # Scale-up overflow to +/-inf. + self.assertEqual(run_f32(2.0 ** 50, 2.0 ** 50, 2.0 ** 50, True), 0x7F800000) + self.assertEqual(run_f32(-(2.0 ** 50), 2.0 ** 50, 2.0 ** 50, True), 0xFF800000) + # Half-ULP tie breaking when z*2^-64 underflows normal range (including subnormal z). + fx = f2u(2.0 ** 120 * (1.0 + 3.0 * 2.0 ** -23)) + fy = f2u(2.0 ** 20 * 1.5) + self.assertEqual(run_f32_u(fx, fy, 0, True), 0x65C00004) + self.assertEqual(run_f32_u(fx, fy, f2u(2.0 ** -100), True), 0x65C00005) + self.assertEqual(run_f32_u(fx, fy, 0x00000010, True), 0x65C00005) + self.assertEqual(run_f32_u(fx, fy, f2u(-(2.0 ** -100)), True), 0x65C00004) - def test_tiny_intermediate_does_not_underflow_when_vcc_set(self): - # 2^-75 * 2^-75 = 2^-150 would flush to 0 if rounded before multiplying by 2^32, - # but fused scaling yields 2^-118 (0x04800000). - self.assertEqual(run_f32(2.0 ** -75, 2.0 ** -75, 0.0, False), 0) - self.assertEqual(run_f32(2.0 ** -75, 2.0 ** -75, 0.0, True), f2u(2.0 ** -118)) + def test_denormal_inputs_kept_and_output_flushed_denorm32_0(self): + # Measured on gfx1036 under game MODE (denorm32=0): subnormal inputs/intermediates are kept, + # while subnormal outputs flush to signed zero before and after omod. + self.assertEqual(run_f32_u(0x00080000, f2u(2.0 ** 80), 0, False), 0x26800000) # 2^-130 * 2^80 = 2^-50 + self.assertEqual(run_f32_u(0x00080000, f2u(1.0), 0, False), 0x00000000) # flushed output + self.assertEqual(run_f32(2.0 ** -70, 2.0 ** -70, 2.0 ** -126, False), 0x00800200) + self.assertEqual(run_f32(2.0 ** -40, 2.0 ** -40, 0.0, True), 0x00000000) # 2^-144 -> flushed + self.assertEqual(run_f32(2.0 ** -31, 2.0 ** -31, 0.0, True), 0x00800000) # 2^-126 -> min normal + # Signed zero preserved on flush/scale. + self.assertEqual(run_f32_u(0x80000000, f2u(1.0), 0x80000000, True), 0x80000000) + # Flush applies before mul:2 and after div:2. + self.assertEqual(run_f32_u(0x00400000, f2u(1.0), 0, False, "v_div_fmas_f32 v0, v1, v2, v3 mul:2"), 0) + self.assertEqual(run_f32_u(0x00800000, f2u(1.0), 0, False, "v_div_fmas_f32 v0, v1, v2, v3 div:2"), 0) def test_input_and_output_modifiers(self): - # |-2.0| * (-1.5) + 4.0 = 1.0; mul:2 -> 2.0; clamp -> 1.0 self.assertEqual(run_f32(-2.0, 1.5, 4.0, False, "v_div_fmas_f32 v0, |v1|, -v2, v3"), f2u(1.0)) self.assertEqual(run_f32(-2.0, 1.5, 4.0, False, "v_div_fmas_f32 v0, |v1|, -v2, v3 mul:2"), f2u(2.0)) self.assertEqual(run_f32(-2.0, 1.5, 4.0, False, "v_div_fmas_f32 v0, |v1|, -v2, v3 mul:2 clamp"), f2u(1.0)) - self.assertEqual(run_f32(2.0 ** -32, 1.0, 0.0, True, "v_div_fmas_f32 v0, v1, v2, v3 div:2"), f2u(0.5)) + self.assertEqual(run_f32(1.0, 2.0, 2.0, True, "v_div_fmas_f32 v0, v1, v2, v3 mul:2"), 0x61000000) + self.assertEqual(run_f32(1.0, 2.0, 2.0, True, "v_div_fmas_f32 v0, v1, v2, v3 div:2"), 0x60000000) + self.assertEqual(run_f32(2.0 ** 64, 1.0, 2.0, True, "v_div_fmas_f32 v0, v1, v2, v3 div:2"), 0x7F800000) def test_spirv_val(self): spv = translate_lines([ @@ -153,14 +415,62 @@ class DivFmasF32Tests(unittest.TestCase): class DivFmasF64Tests(unittest.TestCase): + def test_vcc_clear_and_s2_exponent_threshold(self): + # Measured on gfx1036 (wave32 and wave64): VCC=1 scales by 2^+128 when exp(S2) > 1023, else 2^-128. + cases = ( + (d2u(1.0), d2u(2.0), d2u(1.0), 0x4008000000000000, 0x3808000000000000), + (0, 0, 0x3FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF, 0x37FFFFFFFFFFFFFF), + (0, 0, 0x4000000000000000, 0x4000000000000000, 0x4800000000000000), + (0, 0, 0xBFFFFFFFFFFFFFFF, 0xBFFFFFFFFFFFFFFF, 0xB7FFFFFFFFFFFFFF), + (0, 0, 0xC000000000000000, 0xC000000000000000, 0xC800000000000000), + (d2u(1.0), d2u(2.0), d2u(2.0), 0x4010000000000000, 0x4810000000000000), + ) + for ux, uy, uz, want0, want1 in cases: + with self.subTest(uz=hex(uz)): + self.assertEqual(run_f64_u(ux, uy, uz, False), want0) + self.assertEqual(run_f64_u(ux, uy, uz, True), want1) + + def test_overflow_prevention_sticky_and_subnormal_single_rounding(self): + # All expected 64-bit words measured natively on gfx1036. + self.assertEqual(run_f64_u(d2u(2.0 ** 530), d2u(2.0 ** 530), d2u(0.5), False), 0x7FF0000000000000) + self.assertEqual(run_f64_u(d2u(2.0 ** 530), d2u(2.0 ** 530), d2u(0.5), True), 0x7A30000000000000) + self.assertEqual(run_f64_u(d2u(2.0 ** 1000), d2u(2.0 ** 100), d2u(1.0), True), 0x7CB0000000000000) + self.assertEqual(run_f64_u(d2u(2.0 ** 600), d2u(-(2.0 ** 350)), d2u(2.0 ** 950), True), 0x0000000000000000) + self.assertEqual(run_f64_u(d2u(2.0 ** -500), d2u(2.0 ** 900), d2u(2.0), True), 0x60F0000000000000) + # Single-rounded subnormal half-ULP ties (double rounding gives 0x...0000 and 0x...0002 instead of 0x...0001). + x1 = d2u(2.0 ** -450) + y1 = d2u(2.0 ** -450 * (1.0 + 2.0 ** -47)) + y2 = d2u(2.0 ** -450 * (1.0 + 2.0 ** -46 + 2.0 ** -47)) + self.assertEqual(run_f64_u(x1, y1, d2u(2.0 ** -953), True), 0x0000400000000001) + self.assertEqual(run_f64_u(x1, y1, 0, True), 0x0000400000000000) + self.assertEqual(run_f64_u(x1, y2, d2u(-(2.0 ** -953)), True), 0x0000400000000001) + self.assertEqual(run_f64_u(x1, y2, 0, True), 0x0000400000000002) + # Half-of-min-subnormal boundary (2^-947 * 2^-128 = 2^-1075) and tiny product sticky bit. + self.assertEqual(run_f64_u(d2u(2.0 ** -473), d2u(2.0 ** -474), d2u(2.0 ** -1074), True), 0x0000000000000001) + self.assertEqual(run_f64_u(d2u(2.0 ** -473), d2u(2.0 ** -474), d2u(-(2.0 ** -1074)), True), 0x0000000000000000) + self.assertEqual(run_f64_u(d2u(2.0 ** -600), d2u(2.0 ** -600), d2u(2.0 ** -947), True), 0x0000000000000001) + self.assertEqual(run_f64_u(d2u(-(2.0 ** -600)), d2u(2.0 ** -600), d2u(2.0 ** -947), True), 0x0000000000000000) + # k=52 boundary (2^-895 * (1 + 2^-52) * 2^-128 = 2^-1023 + 2^-1075). + xa = d2u(2.0 ** -447) + ya = d2u(2.0 ** -448 * (1.0 + 2.0 ** -52)) + self.assertEqual(run_f64_u(xa, ya, d2u(2.0 ** -1000), True), 0x0008000000000001) + self.assertEqual(run_f64_u(xa, ya, d2u(-(2.0 ** -1000)), True), 0x0008000000000000) + # big_prod sticky bit in f64. + bx = d2u(2.0 ** 900 * (1.0 + 3.0 * 2.0 ** -52)) + by = d2u(2.0 ** 150 * 1.5) + self.assertEqual(run_f64_u(bx, by, 0, True), 0x7998000000000004) + self.assertEqual(run_f64_u(bx, by, d2u(2.0 ** -950), True), 0x7998000000000005) + self.assertEqual(run_f64_u(bx, by, d2u(-(2.0 ** -950)), True), 0x7998000000000004) + def test_f64_lowering_modifiers_and_validation(self): - scale_lo, scale_hi = dwords(float(1 << 64)) - for mods, want_mul, want_clamp in ( - ("", False, False), - ("mul:2", True, False), - ("div:2", True, False), - ("clamp", False, True), - ("mul:4 clamp", True, True), + up_lo, up_hi = dwords(2.0 ** 128) + dn_lo, dn_hi = dwords(2.0 ** -128) + for mods, want_clamp in ( + ("", False), + ("mul:2", False), + ("div:2", False), + ("clamp", True), + ("mul:4 clamp", True), ): with self.subTest(mods=mods): spv = translate_lines([ @@ -172,15 +482,14 @@ class DivFmasF64Tests(unittest.TestCase): f"v_div_fmas_f64 v[0:1], |v[2:3]|, -s[4:5], 0.5 {mods}".rstrip(), ]) self.assertIn("OpCapability Float64", spv) + self.assertNotIn("OpCapability Int64", spv) self.assertRegex(spv, r"OpExtInst %double %glsl Fma %\w+ %\w+ %\w+") self.assertRegex(spv, r"OpExtInst %double %glsl FAbs %\w+") self.assertRegex(spv, r"OpFNegate %double %\w+") - self.assertIn(f"OpConstant %uint {scale_hi}", spv) - self.assertIn(f"OpConstant %uint {scale_lo}", spv) - self.assertRegex(spv, r"OpSelect %double %\w+ %\w+ %\w+") - fmul_count = len(re.findall(r"OpFMul %double", spv)) - # 3 pre-scale multiplies (2^32, 2^32, 2^64) + 1 post-scale multiply (2^64) + optional omod - self.assertEqual(fmul_count, 5 if want_mul else 4) + self.assertIn(f"OpConstant %uint {up_hi}", spv) + self.assertIn(f"OpConstant %uint {up_lo}", spv) + self.assertIn(f"OpConstant %uint {dn_hi}", spv) + self.assertIn(f"OpConstant %uint {dn_lo}", spv) if want_clamp: self.assertIn("FClamp", spv) else: diff --git a/tests/semantic/test_alu_dot2_f16.py b/tests/semantic/test_alu_dot2_f16.py deleted file mode 100644 index ca462845f..000000000 --- a/tests/semantic/test_alu_dot2_f16.py +++ /dev/null @@ -1,1116 +0,0 @@ -"""Semantic reference oracle and interpreter tests for RDNA2 packed half-precision dot products: - - v_dot2_f16_f16: D.f16 = S0.f16[0] * S1.f16[0] + S0.f16[1] * S1.f16[1] - - v_dot2acc_f16_f16: D.f16 = S0.f16[0] * S1.f16[0] + S0.f16[1] * S1.f16[1] + S2.f16 - -AMD RDNA2 VALU Instruction Set Architecture (GFX10): - The v_dot2_f16_f16 instruction computes the dot product of two packed pairs of IEEE-754 - binary16 (half-precision) floating-point numbers from 32-bit vector registers S0 and S1. - S0 contains two 16-bit half-precision floats: S0.x (bits [15:0]) and S0.y (bits [31:16]). - S1 contains two 16-bit half-precision floats: S1.x (bits [15:0]) and S1.y (bits [31:16]). - The accumulating variant v_dot2acc_f16_f16 (or v_dot2c_f16_f16) adds an accumulator S2 - into the scalar 16-bit result. - -Modifiers: - - clamp: Saturates the floating-point result to [0.0, 1.0]. Negative values and -0.0 clamp to - +0.0, values > 1.0 clamp to 1.0. - - op_sel / op_sel_hi: Selects which 16-bit half-word of each source is read for the low/high - product terms. - - neg_lo / neg_hi: Negates the chosen half-words prior to multiplication. - -Standard library only: Python 3.9+ compatible, zero game data, zero proprietary assets. -""" -from __future__ import annotations - -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -# Bit masks -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -# Canonical IEEE-754 binary16 encodings -H_POS_ZERO = 0x0000 # +0.0 -H_NEG_ZERO = 0x8000 # -0.0 -H_SUB_MIN = 0x0001 # +2^-24 (~5.96046e-8, smallest positive subnormal) -H_NEG_SUB_MIN = 0x8001 # -2^-24 -H_SUB_MAX = 0x03FF # +1023 * 2^-24 (~6.09756e-5, largest subnormal) -H_NEG_SUB_MAX = 0x83FF # -1023 * 2^-24 -H_NORM_MIN = 0x0400 # +2^-14 (~6.10352e-5, smallest positive normal) -H_NEG_NORM_MIN = 0x8400 # -2^-14 -H_ONE = 0x3C00 # +1.0 -H_NEG_ONE = 0xBC00 # -1.0 -H_HALF = 0x3800 # +0.5 -H_NEG_HALF = 0xB800 # -0.5 -H_TWO = 0x4000 # +2.0 -H_THREE = 0x4200 # +3.0 -H_FOUR = 0x4400 # +4.0 -H_NORM_MAX = 0x7BFF # +65504.0 (largest finite f16) -H_NEG_NORM_MAX = 0xFBFF # -65504.0 -H_POS_INF = 0x7C00 # +Infinity -H_NEG_INF = 0xFC00 # -Infinity -H_QNAN = 0x7E00 # Quiet NaN -H_SNAN = 0x7D00 # Signaling NaN - - -def f16_bits_to_float(bits: int) -> float: - """Convert a 16-bit unsigned integer to an IEEE-754 Python float.""" - bits &= MASK16 - return struct.unpack(" int: - """Convert an IEEE-754 Python float to a 16-bit unsigned integer.""" - if math.isnan(val): - sign = 0x8000 if math.copysign(1.0, val) < 0 else 0x0000 - return sign | H_QNAN - if math.isinf(val): - return H_POS_INF if val > 0 else H_NEG_INF - # Overflow boundary in IEEE-754 binary16: 65520.0 rounds to infinity - if val >= 65520.0: - return H_POS_INF - if val <= -65520.0: - return H_NEG_INF - return struct.unpack(" int: - """Pack two 16-bit halfwords into a 32-bit dword.""" - return (lo & MASK16) | ((hi & MASK16) << 16) - - -def unpack_f16x2(dword: int) -> tuple[int, int]: - """Unpack a 32-bit dword into two 16-bit halfwords (lo, hi).""" - dword &= MASK32 - return dword & MASK16, (dword >> 16) & MASK16 - - -def clamp_f16(val: float) -> float: - """Apply RDNA VALU float clamp modifier saturating to [0.0, 1.0].""" - if math.isnan(val): - return 0.0 - if val < 0.0 or math.isinf(val) and val < 0: - return 0.0 - if val > 1.0 or math.isinf(val) and val > 0: - return 1.0 - return val - - -def ref_dot2_f16( - s0: int, - s1: int, - clamp: bool = False, - op_sel: tuple[int, int] = (0, 0), - op_sel_hi: tuple[int, int] = (1, 1), - neg_lo: tuple[int, int] = (0, 0), - neg_hi: tuple[int, int] = (0, 0), -) -> int: - """Pure-Python reference oracle for RDNA2 v_dot2_f16_f16. - - Formula: D = S0.x * S1.x + S0.y * S1.y - """ - s0_halves = unpack_f16x2(s0) - s1_halves = unpack_f16x2(s1) - - # First product term (low half-word selection by default) - h0_x = s0_halves[op_sel[0] & 1] - h1_x = s1_halves[op_sel[1] & 1] - f0_x = f16_bits_to_float(h0_x) - f1_x = f16_bits_to_float(h1_x) - if neg_lo[0]: - f0_x = -f0_x - if neg_lo[1]: - f1_x = -f1_x - - # Second product term (high half-word selection by default) - h0_y = s0_halves[op_sel_hi[0] & 1] - h1_y = s1_halves[op_sel_hi[1] & 1] - f0_y = f16_bits_to_float(h0_y) - f1_y = f16_bits_to_float(h1_y) - if neg_hi[0]: - f0_y = -f0_y - if neg_hi[1]: - f1_y = -f1_y - - p0 = f0_x * f1_x - p1 = f0_y * f1_y - dot = p0 + p1 - - if clamp: - dot = clamp_f16(dot) - - return float_to_f16_bits(dot) - - -def ref_dot2acc_f16( - s0: int, - s1: int, - s2_acc: int = 0, - clamp: bool = False, - op_sel: tuple[int, int, int] = (0, 0, 0), - op_sel_hi: tuple[int, int, int] = (1, 1, 1), - neg_lo: tuple[int, int, int] = (0, 0, 0), - neg_hi: tuple[int, int, int] = (0, 0, 0), -) -> int: - """Pure-Python reference oracle for RDNA2 v_dot2acc_f16_f16. - - Formula: D = S0.x * S1.x + S0.y * S1.y + S2 - """ - s0_halves = unpack_f16x2(s0) - s1_halves = unpack_f16x2(s1) - - h0_x = s0_halves[op_sel[0] & 1] - h1_x = s1_halves[op_sel[1] & 1] - f0_x = f16_bits_to_float(h0_x) - f1_x = f16_bits_to_float(h1_x) - if neg_lo[0]: - f0_x = -f0_x - if neg_lo[1]: - f1_x = -f1_x - - h0_y = s0_halves[op_sel_hi[0] & 1] - h1_y = s1_halves[op_sel_hi[1] & 1] - f0_y = f16_bits_to_float(h0_y) - f1_y = f16_bits_to_float(h1_y) - if neg_hi[0]: - f0_y = -f0_y - if neg_hi[1]: - f1_y = -f1_y - - p0 = f0_x * f1_x - p1 = f0_y * f1_y - - # S2 accumulator - s2_bits = s2_acc & MASK16 - f2 = f16_bits_to_float(s2_bits) - if len(neg_lo) > 2 and neg_lo[2]: - f2 = -f2 - - dot = p0 + p1 + f2 - - if clamp: - dot = clamp_f16(dot) - - return float_to_f16_bits(dot) - - -class TestDot2F16ReferenceOracle(unittest.TestCase): - """Exhaustive validation of reference mathematical semantics for v_dot2_f16_f16.""" - - def test_float_conversion_roundtrip(self): - """Sanity check f16 <-> float conversions for representative constants.""" - cases = [ - (H_POS_ZERO, 0.0), - (H_NEG_ZERO, -0.0), - (H_ONE, 1.0), - (H_NEG_ONE, -1.0), - (H_HALF, 0.5), - (H_TWO, 2.0), - (H_NORM_MAX, 65504.0), - (H_NEG_NORM_MAX, -65504.0), - (H_POS_INF, float("inf")), - (H_NEG_INF, float("-inf")), - ] - for bits, val in cases: - with self.subTest(bits=hex(bits), val=val): - converted = f16_bits_to_float(bits) - if math.isinf(val): - self.assertTrue(math.isinf(converted)) - self.assertEqual(math.copysign(1.0, converted), math.copysign(1.0, val)) - else: - self.assertEqual(converted, val) - self.assertEqual(math.copysign(1.0, converted), math.copysign(1.0, val)) - re_bits = float_to_f16_bits(converted) - self.assertEqual(re_bits, bits) - - def test_basic_normal_dot_products(self): - """Standard normal vectors dot product calculation.""" - # [1.0, 2.0] . [3.0, 4.0] = 1*3 + 2*4 = 11.0 - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - res = ref_dot2_f16(s0, s1) - self.assertEqual(f16_bits_to_float(res), 11.0) - - # [0.5, 0.5] . [0.5, 0.5] = 0.25 + 0.25 = 0.5 - s0 = pack_f16x2(H_HALF, H_HALF) - s1 = pack_f16x2(H_HALF, H_HALF) - res = ref_dot2_f16(s0, s1) - self.assertEqual(res, H_HALF) - - def test_orthogonal_vectors(self): - """Dot product of orthogonal vectors yields zero.""" - # [1.0, 0.0] . [0.0, 1.0] = 0.0 - s0 = pack_f16x2(H_ONE, H_POS_ZERO) - s1 = pack_f16x2(H_POS_ZERO, H_ONE) - res = ref_dot2_f16(s0, s1) - self.assertEqual(res, H_POS_ZERO) - - # [2.0, -1.0] . [1.0, 2.0] = 2.0 - 2.0 = 0.0 - s0 = pack_f16x2(H_TWO, H_NEG_ONE) - s1 = pack_f16x2(H_ONE, H_TWO) - res = ref_dot2_f16(s0, s1) - self.assertEqual(res, H_POS_ZERO) - - def test_signed_zeros(self): - """Signed zero multiplication and addition semantics.""" - # [+0.0, +0.0] . [+0.0, +0.0] = +0.0 - s0 = pack_f16x2(H_POS_ZERO, H_POS_ZERO) - s1 = pack_f16x2(H_POS_ZERO, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1), H_POS_ZERO) - - # [-0.0, -0.0] . [+1.0, +1.0] = -0.0 + -0.0 = -0.0 - s0 = pack_f16x2(H_NEG_ZERO, H_NEG_ZERO) - s1 = pack_f16x2(H_ONE, H_ONE) - self.assertEqual(ref_dot2_f16(s0, s1), H_NEG_ZERO) - - # [+0.0, -0.0] . [+1.0, +1.0] = +0.0 + -0.0 = +0.0 - s0 = pack_f16x2(H_POS_ZERO, H_NEG_ZERO) - s1 = pack_f16x2(H_ONE, H_ONE) - self.assertEqual(ref_dot2_f16(s0, s1), H_POS_ZERO) - - def test_subnormal_operands(self): - """Gradual underflow and subnormal operand handling.""" - # Subnormal min * 1.0 + 0 = Subnormal min - s0 = pack_f16x2(H_SUB_MIN, H_POS_ZERO) - s1 = pack_f16x2(H_ONE, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1), H_SUB_MIN) - - # Two subnormals summed - s0 = pack_f16x2(H_SUB_MIN, H_SUB_MIN) - s1 = pack_f16x2(H_ONE, H_ONE) - # 2^-24 + 2^-24 = 2 * 2^-24 = 2^-23 (0x0002) - self.assertEqual(ref_dot2_f16(s0, s1), 0x0002) - - def test_infinities(self): - """Infinity arithmetic and indeterminate form NaN generation.""" - # [+inf, 0] . [1.0, 0] = +inf - s0 = pack_f16x2(H_POS_INF, H_POS_ZERO) - s1 = pack_f16x2(H_ONE, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1), H_POS_INF) - - # [-inf, 0] . [1.0, 0] = -inf - s0 = pack_f16x2(H_NEG_INF, H_POS_ZERO) - s1 = pack_f16x2(H_ONE, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1), H_NEG_INF) - - # [+inf, -inf] . [1.0, 1.0] = +inf + -inf = NaN - s0 = pack_f16x2(H_POS_INF, H_NEG_INF) - s1 = pack_f16x2(H_ONE, H_ONE) - self.assertTrue(math.isnan(f16_bits_to_float(ref_dot2_f16(s0, s1)))) - - # [0.0, 0.0] . [+inf, 0.0] = 0 * inf = NaN - s0 = pack_f16x2(H_POS_ZERO, H_POS_ZERO) - s1 = pack_f16x2(H_POS_INF, H_POS_ZERO) - self.assertTrue(math.isnan(f16_bits_to_float(ref_dot2_f16(s0, s1)))) - - def test_nan_propagation(self): - """Quiet and signaling NaNs propagate to NaN result.""" - for nan_enc in (H_QNAN, H_SNAN): - s0 = pack_f16x2(nan_enc, H_ONE) - s1 = pack_f16x2(H_ONE, H_ONE) - res = ref_dot2_f16(s0, s1) - self.assertTrue(math.isnan(f16_bits_to_float(res))) - - s0 = pack_f16x2(H_ONE, nan_enc) - s1 = pack_f16x2(H_ONE, H_ONE) - res = ref_dot2_f16(s0, s1) - self.assertTrue(math.isnan(f16_bits_to_float(res))) - - def test_overflow_to_infinity(self): - """Values exceeding maximum finite f16 overflow to infinity.""" - # 65504 * 2 + 0 = 131008 -> +inf - s0 = pack_f16x2(H_NORM_MAX, H_POS_ZERO) - s1 = pack_f16x2(H_TWO, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1), H_POS_INF) - - # -65504 * 2 + 0 = -131008 -> -inf - s0 = pack_f16x2(H_NEG_NORM_MAX, H_POS_ZERO) - s1 = pack_f16x2(H_TWO, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1), H_NEG_INF) - - def test_clamp_modifier(self): - """Clamp saturates results to [0.0, 1.0].""" - # Negative result clamps to +0.0 - s0 = pack_f16x2(H_NEG_ONE, H_POS_ZERO) - s1 = pack_f16x2(H_TWO, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1, clamp=True), H_POS_ZERO) - - # Result > 1.0 clamps to 1.0 - s0 = pack_f16x2(H_TWO, H_TWO) - s1 = pack_f16x2(H_TWO, H_TWO) - self.assertEqual(ref_dot2_f16(s0, s1, clamp=True), H_ONE) - - # Result in [0.0, 1.0] stays intact - s0 = pack_f16x2(H_HALF, H_POS_ZERO) - s1 = pack_f16x2(H_ONE, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1, clamp=True), H_HALF) - - # +inf clamps to 1.0, -inf clamps to 0.0 - s0 = pack_f16x2(H_POS_INF, H_POS_ZERO) - s1 = pack_f16x2(H_ONE, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1, clamp=True), H_ONE) - - s0 = pack_f16x2(H_NEG_INF, H_POS_ZERO) - s1 = pack_f16x2(H_ONE, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1, clamp=True), H_POS_ZERO) - - def test_source_modifiers(self): - """op_sel and negation modifiers correctly permute and invert inputs.""" - # Swap x and y halves using op_sel - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - # Default: 1*3 + 2*4 = 11 - self.assertEqual(f16_bits_to_float(ref_dot2_f16(s0, s1)), 11.0) - # Swapped S1 halves: op_sel=(0, 1), op_sel_hi=(1, 0) -> 1*4 + 2*3 = 10 - res = ref_dot2_f16(s0, s1, op_sel=(0, 1), op_sel_hi=(1, 0)) - self.assertEqual(f16_bits_to_float(res), 10.0) - - # Negate first product term - res_neg = ref_dot2_f16(s0, s1, neg_lo=(1, 0)) - # -1*3 + 2*4 = 5.0 - self.assertEqual(f16_bits_to_float(res_neg), 5.0) - - def test_accumulating_variant(self): - """v_dot2acc_f16_f16 adds the third source accumulator S2.""" - # 1*3 + 2*4 + 10 = 21.0 - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - s2 = float_to_f16_bits(10.0) - res = ref_dot2acc_f16(s0, s1, s2) - self.assertEqual(f16_bits_to_float(res), 21.0) - - -class SimdWavefront: - """RDNA2 SIMD Wavefront state holding VGPRs, SGPRs, and execution masks.""" - - def __init__(self, wave_size: int = 64, initial_exec: int = 0xFFFFFFFFFFFFFFFF) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size: {wave_size}") - self.wave_size = wave_size - self.vgpr: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - self.sgpr: list[int] = [0] * 106 - self.mask_all = (1 << wave_size) - 1 - self.exec_mask: int = initial_exec & self.mask_all - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & self.mask_all - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def set_vgpr(self, lane: int, reg: int, val: int) -> None: - self.vgpr[lane][reg & 0xFF] = val & MASK32 - - def get_vgpr(self, lane: int, reg: int) -> int: - return self.vgpr[lane][reg & 0xFF] - - def set_sgpr(self, reg: int, val: int) -> None: - if not (0 <= reg < 106): - raise IndexError(f"SGPR index {reg} out of range") - self.sgpr[reg] = val & MASK32 - - def get_sgpr(self, reg: int) -> int: - if not (0 <= reg < 106): - raise IndexError(f"SGPR index {reg} out of range") - return self.sgpr[reg] - - -class Dot2Interpreter: - """Instruction interpreter for RDNA2 packed half-precision dot products. - - Handles v_mov_b32, s_mov_b32, s_mov_b64 exec, v_dot2_f16_f16, and v_dot2acc_f16_f16. - Respects SIMD lane execution masks, register aliasing, and source/destination modifiers. - """ - - def __init__(self, wave_size: int = 64) -> None: - self.wave = SimdWavefront(wave_size=wave_size) - - def parse_reg(self, token: str) -> tuple[str, int]: - token = token.strip().lower() - if token.startswith("v") and token[1:].isdigit(): - return "vgpr", int(token[1:]) - if token.startswith("s") and token[1:].isdigit(): - return "sgpr", int(token[1:]) - raise ValueError(f"Unrecognized register name: {token}") - - def parse_imm(self, token: str) -> int: - token = token.strip() - if token.startswith("0x") or token.startswith("-0x"): - return int(token, 16) & MASK32 - try: - return int(token) & MASK32 - except ValueError: - f_val = float(token) - return float_to_f16_bits(f_val) - - def parse_imm64(self, token: str) -> int: - token = token.strip() - if token.startswith("0x") or token.startswith("-0x"): - return int(token, 16) & MASK64 - return int(token) & MASK64 - - def read_operand(self, token: str, lane: int) -> int: - token = token.strip() - if token.startswith("v") and token[1:].isdigit(): - return self.wave.get_vgpr(lane, int(token[1:])) - if token.startswith("s") and token[1:].isdigit(): - return self.wave.get_sgpr(int(token[1:])) - return self.parse_imm(token) - - def execute_line(self, line: str) -> None: - line = line.split(";")[0].strip() - if not line: - return - parts = line.split(None, 1) - mnemonic = parts[0].lower() - rest = parts[1] if len(parts) > 1 else "" - - modifiers = re.findall( - r"(?:op_sel(?:_hi)?:\[[0-9, ]+\]|neg_(?:lo|hi):\[[0-9, ]+\]|clamp)", - rest, - re.IGNORECASE, - ) - remainder = re.sub( - r"(?:op_sel(?:_hi)?:\[[0-9, ]+\]|neg_(?:lo|hi):\[[0-9, ]+\]|clamp)", - "", - rest, - flags=re.IGNORECASE, - ) - tokens = [t.strip() for t in remainder.split(",") if t.strip()] - - clamp = any(m.lower() == "clamp" for m in modifiers) - op_sel = (0, 0, 0) - op_sel_hi = (1, 1, 1) - neg_lo = (0, 0, 0) - neg_hi = (0, 0, 0) - - for m in modifiers: - m_low = m.lower() - if m_low.startswith("op_sel:[") and m_low.endswith("]"): - bits = [int(b.strip()) for b in m_low[8:-1].split(",") if b.strip()] - op_sel = tuple(bits + [0] * (3 - len(bits))) - elif m_low.startswith("op_sel_hi:[") and m_low.endswith("]"): - bits = [int(b.strip()) for b in m_low[11:-1].split(",") if b.strip()] - op_sel_hi = tuple(bits + [1] * (3 - len(bits))) - - if mnemonic == "v_mov_b32": - dst_reg = int(tokens[0][1:]) - for lane in range(self.wave.wave_size): - if self.wave.is_lane_active(lane): - val = self.read_operand(tokens[1], lane) - self.wave.set_vgpr(lane, dst_reg, val) - elif mnemonic == "s_mov_b32": - dst_reg = int(tokens[0][1:]) - val = self.read_operand(tokens[1], 0) - self.wave.set_sgpr(dst_reg, val) - elif mnemonic == "s_mov_b64" and tokens[0].lower() == "exec": - mask = self.parse_imm64(tokens[1]) - self.wave.set_exec(mask) - elif mnemonic in ("v_dot2_f16_f16", "v_dot2_f16_f16_e64"): - dst_reg = int(tokens[0][1:]) - s0_tok = tokens[1] - s1_tok = tokens[2] - for lane in range(self.wave.wave_size): - if self.wave.is_lane_active(lane): - s0_val = self.read_operand(s0_tok, lane) - s1_val = self.read_operand(s1_tok, lane) - res = ref_dot2_f16( - s0_val, - s1_val, - clamp=clamp, - op_sel=op_sel[:2], - op_sel_hi=op_sel_hi[:2], - neg_lo=neg_lo[:2], - neg_hi=neg_hi[:2], - ) - self.wave.set_vgpr(lane, dst_reg, res) - elif mnemonic in ("v_dot2acc_f16_f16", "v_dot2c_f16_f16", "v_dot2acc_f16_f16_e64"): - dst_reg = int(tokens[0][1:]) - s0_tok = tokens[1] - s1_tok = tokens[2] - has_s2 = len(tokens) >= 4 - s2_tok = tokens[3] if has_s2 else None - for lane in range(self.wave.wave_size): - if self.wave.is_lane_active(lane): - s0_val = self.read_operand(s0_tok, lane) - s1_val = self.read_operand(s1_tok, lane) - s2_val = self.read_operand(s2_tok, lane) if has_s2 else self.wave.get_vgpr(lane, dst_reg) - res = ref_dot2acc_f16( - s0_val, - s1_val, - s2_acc=s2_val, - clamp=clamp, - op_sel=op_sel, - op_sel_hi=op_sel_hi, - neg_lo=neg_lo, - neg_hi=neg_hi, - ) - self.wave.set_vgpr(lane, dst_reg, res) - else: - raise NotImplementedError(f"Interpreter opcode not implemented: {mnemonic}") - - def execute_program(self, lines: list[str]) -> None: - for line in lines: - self.execute_line(line) - - -class TestDot2AccInterpreter(unittest.TestCase): - """Semantic interpreter tests for v_dot2_f16_f16 and accumulating v_dot2acc_f16_f16.""" - - def test_v_dot2_interpreter_execution(self): - interp = Dot2Interpreter(wave_size=64) - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - interp.execute_program([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - "v_dot2_f16_f16 v0, v1, v2", - ]) - for lane in range(64): - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 11.0) - - def test_v_dot2acc_explicit_s2_vgpr(self): - interp = Dot2Interpreter(wave_size=64) - s0 = pack_f16x2(H_ONE, H_HALF) - s1 = pack_f16x2(H_FOUR, H_TWO) - s2 = float_to_f16_bits(5.0) - interp.execute_program([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {s2:#x}", - "v_dot2acc_f16_f16 v0, v1, v2, v3", - ]) - # 1*4 + 0.5*2 + 5.0 = 4 + 1 + 5 = 10.0 - for lane in range(64): - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 10.0) - - def test_v_dot2acc_explicit_s2_sgpr(self): - interp = Dot2Interpreter(wave_size=64) - s0 = pack_f16x2(H_ONE, H_ONE) - s1 = pack_f16x2(H_TWO, H_TWO) - s2 = float_to_f16_bits(1.5) - interp.execute_program([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"s_mov_b32 s4, {s2:#x}", - "v_dot2acc_f16_f16 v0, v1, v2, s4", - ]) - # 1*2 + 1*2 + 1.5 = 5.5 - for lane in range(64): - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 5.5) - - def test_v_dot2acc_implicit_in_place_accumulator(self): - interp = Dot2Interpreter(wave_size=64) - s0 = pack_f16x2(H_HALF, H_HALF) - s1 = pack_f16x2(H_TWO, H_TWO) - init_acc = float_to_f16_bits(7.0) - interp.execute_program([ - f"v_mov_b32 v0, {init_acc:#x}", - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - "v_dot2acc_f16_f16 v0, v1, v2", - ]) - # 0.5*2 + 0.5*2 + 7.0 = 2.0 + 7.0 = 9.0 - for lane in range(64): - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 9.0) - - def test_v_dot2acc_chained_accumulation(self): - interp = Dot2Interpreter(wave_size=64) - # Vector 1: [1.0, 1.0] . [1.0, 1.0] = 2.0 - # Vector 2: [2.0, 2.0] . [1.0, 1.0] = 4.0 -> total 6.0 - # Vector 3: [0.5, 0.5] . [2.0, 2.0] = 2.0 -> total 8.0 - v1 = pack_f16x2(H_ONE, H_ONE) - v2 = pack_f16x2(H_TWO, H_TWO) - v3 = pack_f16x2(H_HALF, H_HALF) - interp.execute_program([ - "v_mov_b32 v0, 0", - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - f"v_mov_b32 v3, {v3:#x}", - "v_dot2acc_f16_f16 v0, v1, v1", - "v_dot2acc_f16_f16 v0, v2, v1", - "v_dot2acc_f16_f16 v0, v3, v2", - ]) - for lane in range(64): - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 8.0) - - def test_v_dot2acc_clamp_modifier(self): - interp = Dot2Interpreter(wave_size=64) - s0 = pack_f16x2(H_ONE, H_ONE) - s1 = pack_f16x2(H_ONE, H_ONE) - s2 = float_to_f16_bits(5.0) - # 1*1 + 1*1 + 5 = 7.0 clamped -> 1.0 - interp.execute_program([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {s2:#x}", - "v_dot2acc_f16_f16 v0, v1, v2, v3 clamp", - ]) - for lane in range(64): - self.assertEqual(interp.wave.get_vgpr(lane, 0), H_ONE) - - # Clamping negative sum to 0.0 - s0_neg = pack_f16x2(H_NEG_ONE, H_NEG_ONE) - interp.execute_program([ - f"v_mov_b32 v1, {s0_neg:#x}", - f"v_mov_b32 v2, {s1:#x}", - "v_mov_b32 v3, 0", - "v_dot2acc_f16_f16 v0, v1, v2, v3 clamp", - ]) - # -1*1 + -1*1 + 0 = -2.0 clamped -> 0.0 - for lane in range(64): - self.assertEqual(interp.wave.get_vgpr(lane, 0), H_POS_ZERO) - - def test_v_dot2acc_op_sel_reordering(self): - interp = Dot2Interpreter(wave_size=64) - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - # op_sel:[1, 0] op_sel_hi:[0, 1] - # Low term: S0.y * S1.x = 2 * 3 = 6 - # High term: S0.x * S1.y = 1 * 4 = 4 - # Total = 10.0 - interp.execute_program([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - "v_mov_b32 v3, 0", - "v_dot2acc_f16_f16 v0, v1, v2, v3 op_sel:[1,0] op_sel_hi:[0,1]", - ]) - for lane in range(64): - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 10.0) - - -class TestWavefrontSimdExecution(unittest.TestCase): - """Multi-lane SIMD wavefront execution tests for v_dot2acc_f16_f16.""" - - def test_full_wavefront_uniform_execution(self): - interp = Dot2Interpreter(wave_size=64) - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_HALF, H_HALF) - s2 = float_to_f16_bits(2.5) - # 1*0.5 + 2*0.5 + 2.5 = 0.5 + 1.0 + 2.5 = 4.0 - interp.execute_program([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {s2:#x}", - "v_dot2acc_f16_f16 v0, v1, v2, v3", - ]) - for lane in range(64): - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 4.0) - - def test_full_wavefront_divergent_operands(self): - interp = Dot2Interpreter(wave_size=64) - # Seed per-lane differing values - for lane in range(64): - f_x = float(lane % 8) - f_y = float(lane // 8) - h_x = float_to_f16_bits(f_x) - h_y = float_to_f16_bits(f_y) - interp.wave.set_vgpr(lane, 1, pack_f16x2(h_x, h_y)) - interp.wave.set_vgpr(lane, 2, pack_f16x2(H_ONE, H_TWO)) - interp.wave.set_vgpr(lane, 3, float_to_f16_bits(1.0)) - - interp.execute_line("v_dot2acc_f16_f16 v0, v1, v2, v3") - - for lane in range(64): - f_x = float(lane % 8) - f_y = float(lane // 8) - expected = f_x * 1.0 + f_y * 2.0 + 1.0 - actual = f16_bits_to_float(interp.wave.get_vgpr(lane, 0)) - self.assertEqual(actual, expected, f"Mismatch at lane {lane}") - - def test_wavefront_active_vs_inactive_exec_mask(self): - interp = Dot2Interpreter(wave_size=64) - # Sentinel in v0 - for lane in range(64): - interp.wave.set_vgpr(lane, 0, 0xDEADBEEF) - interp.wave.set_vgpr(lane, 1, pack_f16x2(H_ONE, H_ONE)) - interp.wave.set_vgpr(lane, 2, pack_f16x2(H_ONE, H_ONE)) - interp.wave.set_vgpr(lane, 3, H_POS_ZERO) - - # Alternating mask: even lanes active (bit 0, 2, 4...), odd lanes inactive - mask = 0x5555555555555555 - interp.execute_line(f"s_mov_b64 exec, {mask:#x}") - interp.execute_line("v_dot2acc_f16_f16 v0, v1, v2, v3") - - for lane in range(64): - if lane % 2 == 0: - # Active: 1*1 + 1*1 + 0 = 2.0 - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 2.0) - else: - # Inactive: must preserve 0xDEADBEEF untouched! - self.assertEqual(interp.wave.get_vgpr(lane, 0), 0xDEADBEEF) - - def test_wavefront_all_lanes_inactive(self): - interp = Dot2Interpreter(wave_size=64) - for lane in range(64): - interp.wave.set_vgpr(lane, 0, 0x12345678) - interp.wave.set_vgpr(lane, 1, pack_f16x2(H_ONE, H_ONE)) - interp.wave.set_vgpr(lane, 2, pack_f16x2(H_ONE, H_ONE)) - - interp.execute_line("s_mov_b64 exec, 0") - interp.execute_line("v_dot2_f16_f16 v0, v1, v2") - - for lane in range(64): - self.assertEqual(interp.wave.get_vgpr(lane, 0), 0x12345678) - - def test_wavefront_single_lane_active(self): - interp = Dot2Interpreter(wave_size=64) - for lane in range(64): - interp.wave.set_vgpr(lane, 0, 0xCAFEBABE) - interp.wave.set_vgpr(lane, 1, pack_f16x2(H_TWO, H_TWO)) - interp.wave.set_vgpr(lane, 2, pack_f16x2(H_HALF, H_HALF)) - - # Only lane 42 active: 1 << 42 - interp.execute_line(f"s_mov_b64 exec, {1 << 42:#x}") - interp.execute_line("v_dot2_f16_f16 v0, v1, v2") - - for lane in range(64): - if lane == 42: - # 2*0.5 + 2*0.5 = 2.0 - self.assertEqual(f16_bits_to_float(interp.wave.get_vgpr(lane, 0)), 2.0) - else: - self.assertEqual(interp.wave.get_vgpr(lane, 0), 0xCAFEBABE) - - def test_wavefront_wave32_and_wave64_divergence(self): - # Wave32 test - w32 = Dot2Interpreter(wave_size=32) - s0 = pack_f16x2(H_ONE, H_ONE) - s1 = pack_f16x2(H_THREE, H_THREE) - w32.execute_program([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - "v_dot2_f16_f16 v0, v1, v2", - ]) - for lane in range(32): - self.assertEqual(f16_bits_to_float(w32.wave.get_vgpr(lane, 0)), 6.0) - - # Wave64 lower vs upper halves - w64 = Dot2Interpreter(wave_size=64) - for lane in range(64): - w64.wave.set_vgpr(lane, 0, 0) - w64.wave.set_vgpr(lane, 1, pack_f16x2(H_ONE, H_ONE)) - w64.wave.set_vgpr(lane, 2, pack_f16x2(H_TWO, H_TWO)) - w64.wave.set_vgpr(lane, 3, float_to_f16_bits(float(lane))) - - # Lower half executes: 0x00000000FFFFFFFF - w64.execute_line("s_mov_b64 exec, 0x00000000FFFFFFFF") - w64.execute_line("v_dot2acc_f16_f16 v0, v1, v2, v3") - - for lane in range(64): - if lane < 32: - expected = 1.0 * 2.0 + 1.0 * 2.0 + float(lane) - self.assertEqual(f16_bits_to_float(w64.wave.get_vgpr(lane, 0)), expected) - else: - self.assertEqual(w64.wave.get_vgpr(lane, 0), 0) - - def test_wavefront_mixed_edge_cases_across_lanes(self): - interp = Dot2Interpreter(wave_size=64) - test_lanes = [ - (0, pack_f16x2(H_POS_ZERO, H_POS_ZERO), pack_f16x2(H_POS_ZERO, H_POS_ZERO), H_POS_ZERO, H_POS_ZERO), - (1, pack_f16x2(H_SUB_MIN, H_POS_ZERO), pack_f16x2(H_ONE, H_POS_ZERO), H_POS_ZERO, H_SUB_MIN), - (2, pack_f16x2(H_POS_INF, H_POS_ZERO), pack_f16x2(H_ONE, H_POS_ZERO), H_POS_ZERO, H_POS_INF), - (3, pack_f16x2(H_QNAN, H_POS_ZERO), pack_f16x2(H_ONE, H_POS_ZERO), H_POS_ZERO, H_QNAN), - (4, pack_f16x2(H_NORM_MAX, H_POS_ZERO), pack_f16x2(H_TWO, H_POS_ZERO), H_POS_ZERO, H_POS_INF), - (5, pack_f16x2(H_NEG_ONE, H_NEG_ONE), pack_f16x2(H_ONE, H_ONE), H_POS_ZERO, float_to_f16_bits(-2.0)), - ] - for lane, s0, s1, s2, _ in test_lanes: - interp.wave.set_vgpr(lane, 1, s0) - interp.wave.set_vgpr(lane, 2, s1) - interp.wave.set_vgpr(lane, 3, s2) - - interp.execute_line("v_dot2acc_f16_f16 v0, v1, v2, v3") - - for lane, s0, s1, s2, exp in test_lanes: - actual = interp.wave.get_vgpr(lane, 0) - if exp == H_QNAN: - self.assertTrue(math.isnan(f16_bits_to_float(actual))) - else: - self.assertEqual(actual, exp, f"Edge case mismatch at lane {lane}") - - -def build_spirv_dot2( - s0: int, - s1: int, - s2_acc: int | None = None, - clamp: bool = False, - op_sel: tuple[int, int] = (0, 0), - op_sel_hi: tuple[int, int] = (1, 1), -) -> str: - """Generate synthetic SPIR-V assembly lowering for a packed f16 dot product.""" - lines = [ - "OpCapability Shader", - '%glsl = OpExtInstImport "GLSL.std.450"', - "OpMemoryModel Logical GLSL450", - 'OpEntryPoint Fragment %main "main" %out_mrt0', - "OpExecutionMode %main OriginUpperLeft", - "OpDecorate %out_mrt0 Location 0", - "%void = OpTypeVoid", - "%fn = OpTypeFunction %void", - "%uint = OpTypeInt 32 0", - "%float = OpTypeFloat 32", - "%v4float = OpTypeVector %float 4", - "%v2float = OpTypeVector %float 2", - "%_ptr_Output_v4 = OpTypePointer Output %v4float", - "%out_mrt0 = OpVariable %_ptr_Output_v4 Output", - f"%c_s0 = OpConstant %uint {s0 & MASK32}", - f"%c_s1 = OpConstant %uint {s1 & MASK32}", - "%f0 = OpConstant %float 0", - "%f1 = OpConstant %float 1", - ] - if s2_acc is not None: - lines.append(f"%c_s2 = OpConstant %uint {s2_acc & MASK32}") - lines.extend([ - "%main = OpFunction %void None %fn", - "%entry = OpLabel", - "%u0 = OpExtInst %v2float %glsl UnpackHalf2x16 %c_s0", - "%u1 = OpExtInst %v2float %glsl UnpackHalf2x16 %c_s1", - f"%x0 = OpCompositeExtract %float %u0 {op_sel[0] & 1}", - f"%y0 = OpCompositeExtract %float %u0 {op_sel_hi[0] & 1}", - f"%x1 = OpCompositeExtract %float %u1 {op_sel[1] & 1}", - f"%y1 = OpCompositeExtract %float %u1 {op_sel_hi[1] & 1}", - "%p0 = OpFMul %float %x0 %x1", - "%p1 = OpFMul %float %y0 %y1", - "%dot = OpFAdd %float %p0 %p1", - ]) - cur_val = "%dot" - if s2_acc is not None: - lines.extend([ - "%u2 = OpExtInst %v2float %glsl UnpackHalf2x16 %c_s2", - "%acc = OpCompositeExtract %float %u2 0", - "%dot_acc = OpFAdd %float %dot %acc", - ]) - cur_val = "%dot_acc" - if clamp: - lines.append(f"%clamped = OpExtInst %float %glsl FClamp {cur_val} %f0 %f1") - cur_val = "%clamped" - lines.extend([ - f"%res_vec = OpCompositeConstruct %v2float {cur_val} %f0", - "%pack = OpExtInst %uint %glsl PackHalf2x16 %res_vec", - "%flt = OpBitcast %float %pack", - "%mrt = OpCompositeConstruct %v4float %flt %flt %flt %flt", - "OpStore %out_mrt0 %mrt", - "OpReturn", - "OpFunctionEnd", - ]) - return "\n".join(lines) - - -class TestDot2SpirvTranslationAndExecution(unittest.TestCase): - """SPIR-V translation and execution tests for v_dot2_f16_f16 and v_dot2acc_f16_f16.""" - - def test_translator_unsupported_rejection(self): - """Translating v_dot2 instructions via rdna2spirv raises Unsupported as documented in docs/fssm_crosscheck.md.""" - lines = [ - "v_mov_b32 v1, 0x3c003c00", - "v_mov_b32 v2, 0x40004000", - "v_dot2_f16_f16 v0, v1, v2", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as cm: - support.translate_lines("ps_dot2_unsupported", lines) - self.assertIn("v_dot2_f16_f16", str(cm.exception)) - - def test_translator_accumulating_unsupported_rejection(self): - """Translating v_dot2acc instructions via rdna2spirv raises Unsupported.""" - lines = [ - "v_mov_b32 v1, 0x3c003c00", - "v_mov_b32 v2, 0x40004000", - "v_mov_b32 v3, 0", - "v_dot2acc_f16_f16 v0, v1, v2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as cm: - support.translate_lines("ps_dot2acc_unsupported", lines) - self.assertIn("v_dot2acc_f16_f16", str(cm.exception)) - - def test_spirv_mini_interp_basic_dot2(self): - """Execute lowered SPIR-V in spirv_mini_interp and assert equivalence with reference oracle.""" - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - spv = build_spirv_dot2(s0, s1) - out = si.run_fragment(spv)["%out_mrt0"] - expected = ref_dot2_f16(s0, s1) - self.assertEqual(out[0] & MASK16, expected & MASK16) - - def test_spirv_mini_interp_accumulating(self): - """Execute accumulating dot product lowered to SPIR-V in spirv_mini_interp.""" - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - s2 = float_to_f16_bits(5.0) - spv = build_spirv_dot2(s0, s1, s2_acc=s2) - out = si.run_fragment(spv)["%out_mrt0"] - expected = ref_dot2acc_f16(s0, s1, s2) - self.assertEqual(out[0] & MASK16, expected & MASK16) - - def test_spirv_mini_interp_clamped(self): - """Execute clamped dot product lowered to SPIR-V in spirv_mini_interp.""" - s0 = pack_f16x2(H_TWO, H_TWO) - s1 = pack_f16x2(H_TWO, H_TWO) - spv = build_spirv_dot2(s0, s1, clamp=True) - out = si.run_fragment(spv)["%out_mrt0"] - expected = ref_dot2_f16(s0, s1, clamp=True) - self.assertEqual(out[0] & MASK16, expected & MASK16) - - def test_spirv_mini_interp_op_sel_halves(self): - """Execute op_sel swapped halves lowered to SPIR-V in spirv_mini_interp.""" - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - spv = build_spirv_dot2(s0, s1, op_sel=(1, 0), op_sel_hi=(0, 1)) - out = si.run_fragment(spv)["%out_mrt0"] - expected = ref_dot2_f16(s0, s1, op_sel=(1, 0), op_sel_hi=(0, 1)) - self.assertEqual(out[0] & MASK16, expected & MASK16) - - -class TestClampAndOverflowEdgeCases(unittest.TestCase): - """Rigorous boundary and edge case coverage: subnormals, signed zeros, clamp, and +/- infinity.""" - - def test_large_normal_multiplication_overflow(self): - """Product of two large normals exceeding 65504 overflows to positive infinity.""" - s0 = pack_f16x2(H_NORM_MAX, H_POS_ZERO) - s1 = pack_f16x2(H_TWO, H_POS_ZERO) - res = ref_dot2_f16(s0, s1) - self.assertEqual(res, H_POS_INF) - - def test_negative_overflow_to_negative_infinity(self): - """Product of large positive and negative normal overflows to negative infinity.""" - s0 = pack_f16x2(H_NEG_NORM_MAX, H_POS_ZERO) - s1 = pack_f16x2(H_TWO, H_POS_ZERO) - res = ref_dot2_f16(s0, s1) - self.assertEqual(res, H_NEG_INF) - - def test_overflow_with_clamp_modifier(self): - """Overflowed positive value (+inf) clamps to 1.0; negative (-inf) clamps to 0.0.""" - s0 = pack_f16x2(H_NORM_MAX, H_POS_ZERO) - s1 = pack_f16x2(H_TWO, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1, clamp=True), H_ONE) - - s0_neg = pack_f16x2(H_NEG_NORM_MAX, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0_neg, s1, clamp=True), H_POS_ZERO) - - def test_subnormal_precision_and_gradual_underflow(self): - """Subnormal precision is preserved when multiplying subnormal with 1.0.""" - s0 = pack_f16x2(H_SUB_MAX, H_POS_ZERO) - s1 = pack_f16x2(H_ONE, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0, s1), H_SUB_MAX) - - s0_min = pack_f16x2(H_NEG_SUB_MIN, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0_min, s1), H_NEG_SUB_MIN) - - def test_signed_zero_multiplication_and_addition(self): - """Signed zero preservation adhering to IEEE-754 binary16 arithmetic.""" - # (-0.0) * (+1.0) + (-0.0) * (+1.0) = -0.0 - s0 = pack_f16x2(H_NEG_ZERO, H_NEG_ZERO) - s1 = pack_f16x2(H_ONE, H_ONE) - self.assertEqual(ref_dot2_f16(s0, s1), H_NEG_ZERO) - - # (+0.0) + (+0.0) = +0.0 - s0_pos = pack_f16x2(H_POS_ZERO, H_POS_ZERO) - self.assertEqual(ref_dot2_f16(s0_pos, s1), H_POS_ZERO) - - def test_infinity_subtraction_produces_nan(self): - """(+inf) + (-inf) indeterminate sum produces quiet NaN.""" - s0 = pack_f16x2(H_POS_INF, H_NEG_INF) - s1 = pack_f16x2(H_ONE, H_ONE) - res = ref_dot2_f16(s0, s1) - self.assertTrue(math.isnan(f16_bits_to_float(res))) - - def test_nan_payload_propagation_with_accumulator(self): - """Accumulator NaN forces final result to NaN regardless of dot terms.""" - s0 = pack_f16x2(H_ONE, H_ONE) - s1 = pack_f16x2(H_ONE, H_ONE) - res = ref_dot2acc_f16(s0, s1, s2_acc=H_QNAN) - self.assertTrue(math.isnan(f16_bits_to_float(res))) - - -class TestNegativeControls(unittest.TestCase): - """Textual sabotage controls proving test sensitivity to algorithmic and translation defects.""" - - def test_control_fmul_sabotaged_to_fadd(self): - """Sabotaging OpFMul to OpFAdd produces a divergence that the reference oracle detects.""" - s0 = pack_f16x2(H_ONE, H_TWO) - s1 = pack_f16x2(H_THREE, H_FOUR) - # True: 1*3 + 2*4 = 11.0 - # Sabotaged: (1+3) + (2+4) = 10.0 - expected = ref_dot2_f16(s0, s1) - good_spv = build_spirv_dot2(s0, s1) - self.assertIn("OpFMul", good_spv) - bad_spv = good_spv.replace("OpFMul", "OpFAdd") - bad_out = si.run_fragment(bad_spv)["%out_mrt0"][0] & MASK16 - self.assertNotEqual(bad_out, expected & MASK16) - - def test_control_fadd_sabotaged_to_fsub(self): - """Sabotaging OpFAdd to OpFSub produces a difference detected by the oracle.""" - s0 = pack_f16x2(H_THREE, H_TWO) - s1 = pack_f16x2(H_TWO, H_ONE) - # True: 3*2 + 2*1 = 8.0 - # Sabotaged: 3*2 - 2*1 = 4.0 - expected = ref_dot2_f16(s0, s1) - good_spv = build_spirv_dot2(s0, s1) - self.assertIn("OpFAdd", good_spv) - bad_spv = good_spv.replace("%dot = OpFAdd %float %p0 %p1", "%dot = OpFSub %float %p0 %p1") - bad_out = si.run_fragment(bad_spv)["%out_mrt0"][0] & MASK16 - self.assertNotEqual(bad_out, expected & MASK16) - - def test_control_clamp_removal_detected(self): - """Omitting FClamp on saturated inputs results in unmasked overflow detected by the oracle.""" - s0 = pack_f16x2(H_TWO, H_TWO) - s1 = pack_f16x2(H_TWO, H_TWO) - # True clamped: 8.0 clamped -> 1.0 - expected = ref_dot2_f16(s0, s1, clamp=True) - good_spv = build_spirv_dot2(s0, s1, clamp=True) - self.assertIn("FClamp", good_spv) - bad_spv = good_spv.replace("%clamped %f0", "%dot %f0") - bad_out = si.run_fragment(bad_spv)["%out_mrt0"][0] & MASK16 - self.assertNotEqual(bad_out, expected & MASK16) - - def test_control_accumulator_omission_detected(self): - """Dropping the accumulator addition in v_dot2acc_f16_f16 is caught by the test oracle.""" - s0 = pack_f16x2(H_ONE, H_ONE) - s1 = pack_f16x2(H_ONE, H_ONE) - s2 = float_to_f16_bits(5.0) - # True: 1*1 + 1*1 + 5 = 7.0 - expected = ref_dot2acc_f16(s0, s1, s2) - good_spv = build_spirv_dot2(s0, s1, s2_acc=s2) - self.assertIn("%dot_acc", good_spv) - bad_spv = good_spv.replace("%dot_acc %f0", "%dot %f0") - bad_out = si.run_fragment(bad_spv)["%out_mrt0"][0] & MASK16 - self.assertNotEqual(bad_out, expected & MASK16) - - def test_control_op_sel_extraction_sabotaged(self): - """Extracting the wrong half-word from unpacked vector is caught by the oracle.""" - s0 = pack_f16x2(H_ONE, H_FOUR) - s1 = pack_f16x2(H_TWO, H_THREE) - # With default op_sel=(0, 0), op_sel_hi=(1, 1): 1*2 + 4*3 = 14.0 - expected = ref_dot2_f16(s0, s1) - good_spv = build_spirv_dot2(s0, s1) - self.assertIn("%x0 = OpCompositeExtract %float %u0 0", good_spv) - bad_spv = good_spv.replace("%x0 = OpCompositeExtract %float %u0 0", "%x0 = OpCompositeExtract %float %u0 1") - bad_out = si.run_fragment(bad_spv)["%out_mrt0"][0] & MASK16 - self.assertNotEqual(bad_out, expected & MASK16) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_dot2_f16_unsupported.py b/tests/semantic/test_alu_dot2_f16_unsupported.py new file mode 100644 index 000000000..9bce02ea7 --- /dev/null +++ b/tests/semantic/test_alu_dot2_f16_unsupported.py @@ -0,0 +1,75 @@ +"""`v_dot2_f16_f16` and `v_dot2acc_f16_f16` are refused, not translated. + +Scope, measured with llvm-mc (AOMP 16.0-45 / LLVM 17.0.0git, `-arch=amdgcn`, four-operand +VOP3P form): + + | instruction | gfx1100 | gfx1030 | gfx1013 | + |---------------------|--------------------|---------------------------|---------------------------| + | `v_dot2_f16_f16` | encodes | not supported on this GPU | not supported on this GPU | + | `v_dot2acc_f16_f16` | invalid instruction| invalid instruction | invalid instruction | + | `v_dot2c_f16_f16` | invalid instruction| invalid instruction | invalid instruction | + +The packed half-precision dot product therefore exists on GFX11 only: it is not part of the +GFX10/RDNA2 VALU this project translates, and the accumulating spellings do not assemble at +all. The translator has to refuse them rather than invent a lowering, and that refusal is +what this file pins. `docs/design.md` carries no row for them; the packed-integer dot +products (`v_dot2_i32_i16`, `v_dot2c_i32_i16`, ...) are different instructions with their own +rows. + +This file replaces `tests/semantic/test_alu_dot2_f16.py`, which built its own SPIR-V with its +own reference oracle and executed that in `spirv_mini_interp`: no line of it went through +`rdna2spirv`, so nothing in it could fail when the translator changed (TEST-603), and its +docstring attributed the instruction to the RDNA2/GFX10 ISA. The sibling +`tests/semantic/test_alu_dot2acc_f16.py` is the same class and is removed by #3098. + +Standard library only, no game data, no GPU. +""" + +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +for path in (ROOT, TOOLS_DIR, HERE): + if path not in sys.path: + sys.path.insert(0, path) + +import rdna2spirv # noqa: E402 +import support # noqa: E402 + +DOT2 = [ + "v_mov_b32 v1, 0x3c003c00", + "v_mov_b32 v2, 0x40004000", + "v_dot2_f16_f16 v0, v1, v2", + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", +] + +DOT2ACC = [ + "v_mov_b32 v1, 0x3c003c00", + "v_mov_b32 v2, 0x40004000", + "v_mov_b32 v3, 0", + "v_dot2acc_f16_f16 v0, v1, v2, v3", + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", +] + + +class Dot2Unsupported(unittest.TestCase): + def assert_refused(self, name, lines, instruction): + with self.assertRaises(rdna2spirv.Unsupported) as caught: + support.translate_lines(name, lines) + self.assertIn(instruction, str(caught.exception)) + + def test_the_packed_half_dot_product_is_refused(self): + self.assert_refused("ps_dot2_unsupported", DOT2, "v_dot2_f16_f16") + + def test_the_accumulating_spelling_is_refused(self): + self.assert_refused("ps_dot2acc_unsupported", DOT2ACC, "v_dot2acc_f16_f16") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_alu_dot4acc_u8.py b/tests/semantic/test_alu_dot4acc_u8.py deleted file mode 100644 index a546d42aa..000000000 --- a/tests/semantic/test_alu_dot4acc_u8.py +++ /dev/null @@ -1,1030 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 8-bit unsigned integer dot product with accumulation. - -Instruction: - v_dot4acc_u32_u8 (VALU VOP3 / VOP3P) - -Semantics: - D = sum(S0[i] * S1[i] for i in 0..3) + S2 (modulo 2^32) - -Each 32-bit dword S0 and S1 contains four packed unsigned 8-bit integers: - Byte 0: bits [7:0] - Byte 1: bits [15:8] - Byte 2: bits [23:16] - Byte 3: bits [31:24] - -Each byte pair product S0[i] * S1[i] produces an unsigned integer in [0, 65025]. -The sum of the four products yields an unsigned integer in [0, 260100] (0x3F804). -Adding accumulator S2 yields the final 32-bit value. Arithmetic wraps strictly modulo 2^32 -unless clamped to 0xFFFFFFFF. - -Zero game data, standard library Python only, Python 3.9+ compatible. -""" - -import contextlib -import os -import random -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK8 = 0xFF -MAX_BYTE_VAL = 255 -MAX_BYTE_PRODUCT = 255 * 255 # 65025 -MAX_DOT4_SUM = 4 * MAX_BYTE_PRODUCT # 260100 (0x3F804) -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple[int, int, int, int]: - """Unpack a 32-bit dword into four unsigned 8-bit integers (byte0..byte3).""" - dword &= MASK32 - return ( - dword & MASK8, - (dword >> 8) & MASK8, - (dword >> 16) & MASK8, - (dword >> 24) & MASK8, - ) - - -def pack_u8(b0: int, b1: int, b2: int, b3: int) -> int: - """Pack four 8-bit unsigned integers into a 32-bit dword.""" - return ( - (b0 & MASK8) - | ((b1 & MASK8) << 8) - | ((b2 & MASK8) << 16) - | ((b3 & MASK8) << 24) - ) & MASK32 - - -def ref_dot4_u32_u8_sum(s0: int, s1: int) -> int: - """Calculate the unaccumulated 4-lane 8-bit unsigned integer dot product sum.""" - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - return sum(x * y for x, y in zip(b0, b1)) - - -def ref_dot4acc_u32_u8(s0: int, s1: int, s2: int = 0) -> int: - """Reference oracle for RDNA2 v_dot4acc_u32_u8: - - D = (sum_{i=0}^3 (s0[i] * s1[i]) + s2) mod 2^32 - """ - prod_sum = ref_dot4_u32_u8_sum(s0, s1) - return ((s2 & MASK32) + prod_sum) & MASK32 - - -def ref_dot4acc_clamped_u32_u8(s0: int, s1: int, s2: int = 0) -> int: - """Reference oracle with unsigned clamping/saturation at 0xFFFFFFFF.""" - prod_sum = ref_dot4_u32_u8_sum(s0, s1) - total = (s2 & MASK32) + prod_sum - return min(total, MASK32) - - -def ref_dot4_i32_i8(s0: int, s1: int, s2: int = 0) -> int: - """Signed 8-bit dot product reference oracle (v_dot4_i32_i8). - - Used for divergence tests to confirm unsigned behavior differs from signed. - """ - def s8(x: int) -> int: - return x - 256 if (x & 0x80) else x - - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - prod_sum = sum(s8(x) * s8(y) for x, y in zip(b0, b1)) - return ((s2 & MASK32) + prod_sum) & MASK32 - - -def build_spirv_dot4acc_fragment(s0: int, s1: int, acc: int = 0, clamp: bool = False) -> str: - """Synthesize valid SPIR-V assembly computing unsigned dot4acc via OpBitFieldUExtract/OpIMul/OpIAdd.""" - s0 &= MASK32 - s1 &= MASK32 - acc &= MASK32 - clamp_code = "" - res_var = "%t3" - if clamp: - # Detect overflow past 32-bit: if total in 64-bit > 0xFFFFFFFF or if t3 < acc and prod_sum > 0 - clamp_code = """ -%total64 = OpIAdd %ulong %acc64 %prod_sum64 -%is_overflow = OpUGreaterThan %bool %total64 %c_max32_in64 -%clamped_res = OpSelect %uint %is_overflow %c_max32 %t3 -""" - res_var = "%clamped_res" - - return f"""OpCapability Shader -OpCapability Int64 -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out_mrt0 -OpExecutionMode %main OriginUpperLeft -OpDecorate %out_mrt0 Location 0 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%bool = OpTypeBool -%uint = OpTypeInt 32 0 -%ulong = OpTypeInt 64 0 -%v4uint = OpTypeVector %uint 4 -%pout = OpTypePointer Output %v4uint -%out_mrt0 = OpVariable %pout Output - -%c_s0 = OpConstant %uint {s0} -%c_s1 = OpConstant %uint {s1} -%c_acc = OpConstant %uint {acc} -%c0 = OpConstant %uint 0 -%c8 = OpConstant %uint 8 -%c16 = OpConstant %uint 16 -%c24 = OpConstant %uint 24 -%c_max32 = OpConstant %uint 4294967295 -%c_max32_in64 = OpConstant %ulong 4294967295 - -%main = OpFunction %void None %fn -%entry = OpLabel -%x0 = OpBitFieldUExtract %uint %c_s0 %c0 %c8 -%y0 = OpBitFieldUExtract %uint %c_s1 %c0 %c8 -%p0 = OpIMul %uint %x0 %y0 -%t0 = OpIAdd %uint %c_acc %p0 - -%x1 = OpBitFieldUExtract %uint %c_s0 %c8 %c8 -%y1 = OpBitFieldUExtract %uint %c_s1 %c8 %c8 -%p1 = OpIMul %uint %x1 %y1 -%t1 = OpIAdd %uint %t0 %p1 - -%x2 = OpBitFieldUExtract %uint %c_s0 %c16 %c8 -%y2 = OpBitFieldUExtract %uint %c_s1 %c16 %c8 -%p2 = OpIMul %uint %x2 %y2 -%t2 = OpIAdd %uint %t1 %p2 - -%x3 = OpBitFieldUExtract %uint %c_s0 %c24 %c8 -%y3 = OpBitFieldUExtract %uint %c_s1 %c24 %c8 -%p3 = OpIMul %uint %x3 %y3 -%t3 = OpIAdd %uint %t2 %p3 - -%p0_1 = OpIAdd %uint %p0 %p1 -%p2_3 = OpIAdd %uint %p2 %p3 -%prod_sum32 = OpIAdd %uint %p0_1 %p2_3 -%prod_sum64 = OpUConvert %ulong %prod_sum32 -%acc64 = OpUConvert %ulong %c_acc -{clamp_code} -%out_vec = OpCompositeConstruct %v4uint {res_var} {res_var} {res_var} {res_var} -OpStore %out_mrt0 %out_vec -OpReturn -OpFunctionEnd -""" - - -@contextlib.contextmanager -def patch_rdna2spirv_dot4acc_u8(): - """Context manager to temporarily hook rdna2spirv instruction generator with v_dot4acc_u32_u8.""" - orig_insn = rdna2spirv.Gen._insn - orig_rbw = rdna2spirv.read_before_write_vgprs - orig_rrw = rdna2spirv.reg_reads_writes - - def patched_insn(self, ins): - op = ins.get("op", "") - if op == "v_dot4acc_u32_u8": - mods = ins.get("mods", set()) - if "clamp" in mods or any(m.startswith("op_sel") for m in mods): - raise rdna2spirv.Unsupported(op + (" clamp" if "clamp" in mods else " op_sel")) - a = ins["args"] - x, y = self.src_u(a[1]), self.src_u(a[2]) - acc = self.src_u(a[3]) if len(a) > 3 else self.cu(0) - for i in range(4): - xb, yb, prod, total = (self.tmp() for _ in range(4)) - self.emit(f"{xb} = OpBitFieldUExtract %uint {x} {self.cu(8 * i)} {self.cu(8)}") - self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(8 * i)} {self.cu(8)}") - self.emit(f"{prod} = OpIMul %uint {xb} {yb}") - self.emit(f"{total} = OpIAdd %uint {acc} {prod}") - acc = total - self.dst(a[0], acc) - return - return orig_insn(self, ins) - - rdna2spirv.Gen._insn = patched_insn - try: - yield - finally: - rdna2spirv.Gen._insn = orig_insn - rdna2spirv.read_before_write_vgprs = orig_rbw - rdna2spirv.reg_reads_writes = orig_rrw - - -class WavefrontDot4accInterpreter: - """Simulates an RDNA2 SIMD wavefront executing VALU/SALU dot-product accumulation instructions. - - Models: - - Wave32 (32 lanes) and Wave64 (64 lanes). - - Per-lane VGPR file: vgprs[reg][lane]. - - Uniform SGPR file: sgprs[reg]. - - EXEC mask: 32-bit or 64-bit integer mask. - - Instructions: v_mov_b32, v_mov_b32_e32, s_mov_b32, v_dot4acc_u32_u8 (with optional clamp). - """ - - def __init__(self, wave_size: int = 32): - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size {wave_size}; must be 32 or 64") - self.wave_size = wave_size - self.vgprs = [[0] * wave_size for _ in range(256)] - self.sgprs = [0] * 106 - self.exec_mask = (1 << wave_size) - 1 - - def set_vgpr(self, reg: int, lane: int, val: int) -> None: - self.vgprs[reg][lane] = val & MASK32 - - def get_vgpr(self, reg: int, lane: int) -> int: - return self.vgprs[reg][lane] & MASK32 - - def set_sgpr(self, reg: int, val: int) -> None: - self.sgprs[reg] = val & MASK32 - - def get_sgpr(self, reg: int) -> int: - return self.sgprs[reg] & MASK32 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def parse_operand(self, token: str, lane: int) -> int: - token = token.strip().rstrip(",") - lower = token.lower() - if lower.startswith("v") and lower[1:].isdigit(): - idx = int(lower[1:]) - if 0 <= idx < 256: - return self.vgprs[idx][lane] & MASK32 - raise IndexError(f"VGPR index out of range: {token}") - if lower.startswith("s") and lower[1:].isdigit(): - idx = int(lower[1:]) - if 0 <= idx < 106: - return self.sgprs[idx] & MASK32 - raise IndexError(f"SGPR index out of range: {token}") - if lower.startswith("0x") or lower.startswith("-0x"): - return int(token, 16) & MASK32 - return int(token) & MASK32 - - def execute_line(self, line: str) -> None: - line = line.split(";", 1)[0].split("//", 1)[0].strip() - if not line: - return - parts = line.split(None, 1) - opcode = parts[0].lower() - args_str = parts[1] if len(parts) > 1 else "" - - # Check for clamp modifier - clamp = False - raw_tokens = [t.strip() for t in args_str.split(",") if t.strip()] - if raw_tokens and "clamp" in raw_tokens[-1].lower(): - clamp = True - last = raw_tokens[-1].lower().replace("clamp", "").strip() - if last: - raw_tokens[-1] = last - else: - raw_tokens.pop() - - tokens = raw_tokens - - if opcode == "s_mov_b32": - dst = tokens[0].lower() - if not (dst.startswith("s") and dst[1:].isdigit()): - raise ValueError(f"s_mov_b32 dst must be SGPR, got {tokens[0]}") - s_idx = int(dst[1:]) - val = self.parse_operand(tokens[1], 0) - self.sgprs[s_idx] = val - - elif opcode in ("v_mov_b32", "v_mov_b32_e32"): - dst = tokens[0].lower() - if not (dst.startswith("v") and dst[1:].isdigit()): - raise ValueError(f"v_mov_b32 dst must be VGPR, got {tokens[0]}") - v_idx = int(dst[1:]) - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - val = self.parse_operand(tokens[1], lane) - self.vgprs[v_idx][lane] = val - - elif opcode == "v_dot4acc_u32_u8": - dst = tokens[0].lower() - if not (dst.startswith("v") and dst[1:].isdigit()): - raise ValueError(f"v_dot4acc_u32_u8 dst must be VGPR, got {tokens[0]}") - v_idx = int(dst[1:]) - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.parse_operand(tokens[1], lane) - s1 = self.parse_operand(tokens[2], lane) - s2 = self.parse_operand(tokens[3], lane) if len(tokens) > 3 else 0 - if clamp: - self.vgprs[v_idx][lane] = ref_dot4acc_clamped_u32_u8(s0, s1, s2) - else: - self.vgprs[v_idx][lane] = ref_dot4acc_u32_u8(s0, s1, s2) - - elif opcode == "s_endpgm": - return - else: - raise NotImplementedError(f"Unsupported opcode: {opcode}") - - def execute_program(self, program: str | list[str]) -> None: - lines = program if isinstance(program, list) else program.strip().splitlines() - for line in lines: - self.execute_line(line) - - -class ReferenceOracleTests(unittest.TestCase): - """Verifies reference oracle against hand-calculated test vectors and algebraic invariants.""" - - def test_unpack_pack_u8_roundtrip(self) -> None: - """Verifies byte unpacking and packing round-trip across distinct word patterns.""" - patterns = [ - 0x00000000, - 0xFFFFFFFF, - 0x12345678, - 0xA55AA55A, - 0x01020304, - 0x80808080, - 0x7F8001FE, - 0xDEADBEEF, - ] - for val in patterns: - with self.subTest(val=hex(val)): - b0, b1, b2, b3 = unpack_u8(val) - repacked = pack_u8(b0, b1, b2, b3) - self.assertEqual(repacked, val) - - def test_known_test_vectors(self) -> None: - """Verifies reference oracle reproduces all hand-calculated vectors.""" - for s0, s1, s2, expected in KNOWN_VECTORS: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - got = ref_dot4acc_u32_u8(s0, s1, s2) - self.assertEqual(got, expected, f"{s0:#x} . {s1:#x} + {s2:#x}") - - def test_commutativity_of_multipliers(self) -> None: - """Multipliers are commutative: S0 . S1 + S2 == S1 . S0 + S2.""" - test_pairs = [ - (0x01020304, 0x05060708), - (0xFFFFFFFF, 0x12345678), - (0x80808080, 0x7F7F7F7F), - (0xA1B2C3D4, 0x1E2D3C4B), - (0x00FF00FF, 0xFF00FF00), - (0xDEADBEEF, 0xCAFEBABE), - ] - for s0, s1 in test_pairs: - for s2 in (0, 100, 0x12345678, 0xFFFFFFFF): - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual( - ref_dot4acc_u32_u8(s0, s1, s2), - ref_dot4acc_u32_u8(s1, s0, s2), - ) - - def test_zero_multipliers_preserve_accumulator(self) -> None: - """Zero multiplier on either operand preserves accumulator exactly.""" - vectors = [0x01020304, 0xFFFFFFFF, 0x80808080, 0x12345678, 0xCAFEBABE] - for v in vectors: - for acc in (0, 1, 0x7FFFFFFF, 0xFFFFFFFF, 0x10000000): - with self.subTest(v=hex(v), acc=hex(acc)): - self.assertEqual(ref_dot4acc_u32_u8(0, v, acc), acc & MASK32) - self.assertEqual(ref_dot4acc_u32_u8(v, 0, acc), acc & MASK32) - - def test_identity_multiplier_sums_bytes(self) -> None: - """Dot product with broadcast 0x01010101 computes the sum of the four unsigned bytes.""" - test_words = [ - (0x01020304, 1 + 2 + 3 + 4), - (0xFFFFFFFF, 255 * 4), - (0x10203040, 0x10 + 0x20 + 0x30 + 0x40), - (0x000000FF, 255), - (0x0000FF00, 255), - (0x00FF0000, 255), - (0xFF000000, 255), - (0x80808080, 128 * 4), - ] - for word, expected_sum in test_words: - with self.subTest(word=hex(word)): - self.assertEqual(ref_dot4acc_u32_u8(word, 0x01010101, 0), expected_sum) - self.assertEqual(ref_dot4acc_u32_u8(0x01010101, word, 0), expected_sum) - - def test_max_single_step_sum(self) -> None: - """Verifies maximum product sum per step is exactly 4 * (255 * 255) = 260100.""" - self.assertEqual(MAX_DOT4_SUM, 260100) - self.assertEqual(MAX_DOT4_SUM, 0x3F804) - got = ref_dot4_u32_u8_sum(0xFFFFFFFF, 0xFFFFFFFF) - self.assertEqual(got, 260100) - - def test_byte_lane_isolation(self) -> None: - """Each of the 4 byte lanes computes independently without cross-lane bit bleed.""" - for byte_idx in range(4): - for val_a in (1, 15, 128, 255): - for val_b in (1, 10, 100, 255): - s0 = val_a << (8 * byte_idx) - s1 = val_b << (8 * byte_idx) - expected = val_a * val_b - with self.subTest(lane=byte_idx, a=val_a, b=val_b): - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, 0), expected) - - def test_accumulator_linearity(self) -> None: - """ref_dot4acc_u32_u8(s0, s1, s2) == (ref_dot4acc_u32_u8(s0, s1, 0) + s2) mod 2^32.""" - s0, s1 = 0x11223344, 0x55667788 - base_dot = ref_dot4acc_u32_u8(s0, s1, 0) - for addend in (0, 1, 0x1000, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE): - with self.subTest(addend=hex(addend)): - want = (base_dot + addend) & MASK32 - got = ref_dot4acc_u32_u8(s0, s1, addend) - self.assertEqual(got, want) - - def test_unsigned_vs_signed_fundamental_divergence(self) -> None: - """Unsigned dot product behaves fundamentally differently from signed dot product.""" - divergent_pairs = [ - (0x000000FF, 0x00000001, 0), # 255 * 1 = 255 vs -1 * 1 = -1 - (0x000000FF, 0x000000FF, 0), # 255 * 255 = 65025 vs (-1)*(-1) = 1 - (0xFFFFFFFF, 0x01010101, 0), # 4 * 255 = 1020 vs 4 * (-1) = -4 - (0x80808080, 0x7F7F7F7F, 0), # 4 * (128*127) = 65024 vs 4 * (-128*127) = -65024 - (0xFFFFFFFF, 0xFFFFFFFF, 0), # 4 * 65025 = 260100 vs 4 * 1 = 4 - ] - for s0, s1, s2 in divergent_pairs: - with self.subTest(s0=hex(s0), s1=hex(s1)): - u_res = ref_dot4acc_u32_u8(s0, s1, s2) - s_res = ref_dot4_i32_i8(s0, s1, s2) - self.assertNotEqual(u_res, s_res) - - def test_pseudorandom_fuzz_invariants(self) -> None: - """Deterministic fuzzing over 128 pseudo-random word triples checking invariants.""" - rng = random.Random(0x444F5441) # ASCII 'DOTA' - for _ in range(128): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - s2 = rng.getrandbits(32) - - # Commutativity - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, s2), ref_dot4acc_u32_u8(s1, s0, s2)) - - # Manual byte arithmetic verification - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - manual_sum = ((s2 & MASK32) + b0[0]*b1[0] + b0[1]*b1[1] + b0[2]*b1[2] + b0[3]*b1[3]) & MASK32 - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, s2), manual_sum) - - # Single-step dot4 sum bounded by MAX_DOT4_SUM - prod_sum = ref_dot4_u32_u8_sum(s0, s1) - self.assertGreaterEqual(prod_sum, 0) - self.assertLessEqual(prod_sum, MAX_DOT4_SUM) - - -class AccumulatorWrappingAndClampingTests(unittest.TestCase): - """Verifies modulo 2^32 wrapping, clamping saturation, and chaining sequences.""" - - def test_exact_overflow_boundary_wraps_to_zero(self) -> None: - """When S2 + sum equals 2^32 exactly, result wraps to 0 without saturation.""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - prod_sum = ref_dot4_u32_u8_sum(s0, s1) - self.assertEqual(prod_sum, 260100) - - acc_exact = (MASK32 - prod_sum + 1) & MASK32 - res = ref_dot4acc_u32_u8(s0, s1, acc_exact) - self.assertEqual(res, 0) - - def test_wrap_around_with_remainder(self) -> None: - """Accumulator 0xFFFFFFFF + 260100 wraps modulo 2^32 to 260099.""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - res = ref_dot4acc_u32_u8(s0, s1, MASK32) - self.assertEqual(res, 260099) - - def test_wrap_around_plus_one(self) -> None: - """Accumulator 1 past exact boundary wraps to 1.""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - prod_sum = 260100 - acc = (MASK32 - prod_sum + 2) & MASK32 - res = ref_dot4acc_u32_u8(s0, s1, acc) - self.assertEqual(res, 1) - - def test_clamping_saturates_at_max_uint32(self) -> None: - """With clamp modifier, any sum exceeding 0xFFFFFFFF saturates to 0xFFFFFFFF.""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - self.assertEqual(ref_dot4acc_clamped_u32_u8(s0, s1, MASK32), MASK32) - self.assertEqual(ref_dot4acc_clamped_u32_u8(s0, s1, MASK32 - 100), MASK32) - - def test_clamping_below_threshold_is_exact(self) -> None: - """With clamp modifier, sums not exceeding 0xFFFFFFFF equal the unclamped sum.""" - s0 = 0x01020304 - s1 = 0x05060708 - acc = 0x10000000 - unclamped = ref_dot4acc_u32_u8(s0, s1, acc) - clamped = ref_dot4acc_clamped_u32_u8(s0, s1, acc) - self.assertEqual(clamped, unclamped) - self.assertEqual(clamped, 0x10000000 + 70) - - def test_accumulator_chaining_long_sequence(self) -> None: - """Chaining 64 consecutive dot product steps computes exact multi-step reduction.""" - current_acc = 0x00000100 - expected_total = current_acc - for step in range(64): - s0 = ((step + 1) * 0x01010101) & MASK32 - s1 = 0x02020202 - step_sum = ref_dot4_u32_u8_sum(s0, s1) - expected_total = (expected_total + step_sum) & MASK32 - current_acc = ref_dot4acc_u32_u8(s0, s1, current_acc) - self.assertEqual(current_acc, expected_total) - - def test_spirv_mini_interp_modulo_wrapping(self) -> None: - """SPIR-V fragment shader in spirv_mini_interp exhibits exact modulo 2^32 wrapping.""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - acc_exact = (MASK32 - MAX_DOT4_SUM + 1) & MASK32 - spv = build_spirv_dot4acc_fragment(s0, s1, acc_exact, clamp=False) - res = si.run_fragment(spv) - self.assertEqual(list(res["%out_mrt0"]), [0] * 4) - - acc_wrap1 = (acc_exact + 1) & MASK32 - spv_wrap1 = build_spirv_dot4acc_fragment(s0, s1, acc_wrap1, clamp=False) - res_wrap1 = si.run_fragment(spv_wrap1) - self.assertEqual(list(res_wrap1["%out_mrt0"]), [1] * 4) - - def test_spirv_mini_interp_clamping_saturation(self) -> None: - """SPIR-V fragment shader with clamping saturates to 0xFFFFFFFF on overflow in mini_interp.""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - spv_clamped = build_spirv_dot4acc_fragment(s0, s1, MASK32, clamp=True) - res_clamped = si.run_fragment(spv_clamped) - self.assertEqual(list(res_clamped["%out_mrt0"]), [MASK32] * 4) - - def test_translated_shader_execution_with_patch(self) -> None: - """Pixel shaders translated via rdna2spirv execute correctly in mini_interp.""" - with patch_rdna2spirv_dot4acc_u8(): - for s0, s1, acc, expected in KNOWN_VECTORS[:8]: - with self.subTest(s0=hex(s0), s1=hex(s1), acc=hex(acc)): - lines = [ - f"v_mov_b32_e32 v1, 0x{s0:08x}", - f"v_mov_b32_e32 v2, 0x{s1:08x}", - f"v_mov_b32_e32 v3, 0x{acc:08x}", - "v_dot4acc_u32_u8 v8, v1, v2, v3", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_dot4acc_test", lines) - self.assertEqual(support.mrt0_words(spv), [expected] * 4) - - -class WavefrontSimdExecutionTests(unittest.TestCase): - """Verifies SIMD multi-lane wavefront execution and accumulation under EXEC masks.""" - - def test_wave32_uniform_execution(self) -> None: - """32-lane SIMD execution under full EXEC mask with divergent per-lane data.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - for lane in range(32): - s0 = ((lane + 1) * 0x01020304) & MASK32 - s1 = 0x05060708 - acc = lane * 10 - interp.set_vgpr(1, lane, s0) - interp.set_vgpr(2, lane, s1) - interp.set_vgpr(3, lane, acc) - - interp.execute_line("v_dot4acc_u32_u8 v0, v1, v2, v3") - - for lane in range(32): - s0 = ((lane + 1) * 0x01020304) & MASK32 - s1 = 0x05060708 - acc = lane * 10 - expected = ref_dot4acc_u32_u8(s0, s1, acc) - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_wave64_uniform_execution(self) -> None: - """64-lane SIMD execution covering the entire Wave64 execution space.""" - interp = WavefrontDot4accInterpreter(wave_size=64) - for lane in range(64): - s0 = (0x01010101 * (lane + 1)) & MASK32 - s1 = 0x02020202 - interp.set_vgpr(1, lane, s0) - interp.set_vgpr(2, lane, s1) - interp.set_vgpr(3, lane, 0x1000) - - interp.execute_line("v_dot4acc_u32_u8 v8, v1, v2, v3") - - for lane in range(64): - s0 = (0x01010101 * (lane + 1)) & MASK32 - s1 = 0x02020202 - expected = ref_dot4acc_u32_u8(s0, s1, 0x1000) - self.assertEqual(interp.get_vgpr(8, lane), expected) - - def test_simd_exec_mask_inactive_lanes_preserved(self) -> None: - """Inactive lanes under partial EXEC mask must strictly preserve destination registers.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - sentinel = 0xDEADBEEF - - for lane in range(32): - interp.set_vgpr(5, lane, sentinel) - interp.set_vgpr(1, lane, 0x01020304) - interp.set_vgpr(2, lane, 0x05060708) - interp.set_vgpr(3, lane, 100) - - # Only low 16 lanes active - interp.set_exec(0x0000FFFF) - interp.execute_line("v_dot4acc_u32_u8 v5, v1, v2, v3") - - for lane in range(32): - if lane < 16: - self.assertEqual(interp.get_vgpr(5, lane), 170) - else: - self.assertEqual(interp.get_vgpr(5, lane), sentinel) - - def test_simd_alternating_even_odd_divergence(self) -> None: - """Divergent execution between alternating even and odd lanes.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - for lane in range(32): - interp.set_vgpr(10, lane, 0) - interp.set_vgpr(1, lane, 0x01010101) - interp.set_vgpr(2, lane, 0x0A0A0A0A) - interp.set_vgpr(3, lane, 0x02020202) - interp.set_vgpr(4, lane, 0x14141414) - - # Even lanes active - interp.set_exec(0x55555555) - interp.execute_line("v_dot4acc_u32_u8 v10, v1, v2, 0") - - # Odd lanes active - interp.set_exec(0xAAAAAAAA) - interp.execute_line("v_dot4acc_u32_u8 v10, v3, v4, 0") - - for lane in range(32): - expected = 40 if (lane % 2 == 0) else 160 - self.assertEqual(interp.get_vgpr(10, lane), expected) - - def test_simd_single_lane_active(self) -> None: - """Only a single lane active (lane 27), ensuring zero collateral writes.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - for lane in range(32): - interp.set_vgpr(7, lane, 0xBAADF00D) - interp.set_vgpr(1, lane, 0x01020304) - interp.set_vgpr(2, lane, 0x05060708) - - target_lane = 27 - interp.set_exec(1 << target_lane) - interp.execute_line("v_dot4acc_u32_u8 v7, v1, v2, 0") - - for lane in range(32): - if lane == target_lane: - self.assertEqual(interp.get_vgpr(7, lane), 70) - else: - self.assertEqual(interp.get_vgpr(7, lane), 0xBAADF00D) - - def test_simd_uniform_scalar_broadcast(self) -> None: - """SGPR sources broadcast uniform values across all lanes.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - interp.set_sgpr(4, 0x05060708) - interp.set_sgpr(5, 5000) - - for lane in range(32): - interp.set_vgpr(1, lane, 0x01020304) - - interp.execute_line("v_dot4acc_u32_u8 v0, v1, s4, s5") - - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), 5070) - - def test_simd_accumulator_chain_loop(self) -> None: - """Simulate a vector reduction accumulating dot products across loop iterations.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - running_totals = [0] * 32 - steps = [ - (0x01010101, 0x02020202), # 4 * 2 = 8 - (0x03030303, 0x04040404), # 4 * 12 = 48 - (0x05050505, 0x06060606), # 4 * 30 = 120 - (0x07070707, 0x08080808), # 4 * 56 = 224 - ] - for s0, s1 in steps: - for lane in range(32): - interp.set_vgpr(1, lane, s0) - interp.set_vgpr(2, lane, s1) - running_totals[lane] = (running_totals[lane] + ref_dot4_u32_u8_sum(s0, s1)) & MASK32 - interp.execute_line("v_dot4acc_u32_u8 v0, v1, v2, v0") - - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), running_totals[lane]) - self.assertEqual(interp.get_vgpr(0, lane), 8 + 48 + 120 + 224) - - def test_simd_clamping_under_divergent_lanes(self) -> None: - """Clamping modifier saturates overflowing lanes while preserving non-overflowing lanes.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - for lane in range(32): - if lane % 2 == 0: - # Overflowing lane - interp.set_vgpr(1, lane, 0xFFFFFFFF) - interp.set_vgpr(2, lane, 0xFFFFFFFF) - interp.set_vgpr(3, lane, MASK32) - else: - # Non-overflowing lane - interp.set_vgpr(1, lane, 0x01020304) - interp.set_vgpr(2, lane, 0x05060708) - interp.set_vgpr(3, lane, 100) - - interp.execute_line("v_dot4acc_u32_u8 v0, v1, v2, v3 clamp") - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(interp.get_vgpr(0, lane), MASK32) - else: - self.assertEqual(interp.get_vgpr(0, lane), 170) - - -class EdgeCaseBytePatternsTests(unittest.TestCase): - """Verifies edge-case byte patterns, walking bits, alternating patterns, and sensitivity.""" - - def test_walking_ones_patterns(self) -> None: - """Walking 1-bit across all 8 bit positions in each of the 4 bytes.""" - for byte_idx in range(4): - for bit in range(8): - val = (1 << bit) << (8 * byte_idx) - multiplier = 1 << (8 * byte_idx) - expected = 1 << bit - self.assertEqual(ref_dot4acc_u32_u8(val, multiplier, 0), expected) - - def test_alternating_chessboards(self) -> None: - """Alternating bit patterns across bytes (0xAA55AA55, 0x55AA55AA, 0x00FF00FF, 0xFF00FF00).""" - pat_a = 0xAA55AA55 - pat_b = 0x55AA55AA - # 0x55 = 85, 0xAA = 170. 85 * 170 = 14450. 4 * 14450 = 57800. - self.assertEqual(ref_dot4acc_u32_u8(pat_a, pat_b, 0), 57800) - self.assertEqual(ref_dot4acc_u32_u8(pat_a, pat_b, 1000), 58800) - - # 0x00FF00FF dot 0xFF00FF00: byte products are 0*255 + 255*0 + 0*255 + 255*0 = 0 - self.assertEqual(ref_dot4acc_u32_u8(0x00FF00FF, 0xFF00FF00, 0x12345678), 0x12345678) - - # 0x0F0F0F0F dot 0xF0F0F0F0: 15 * 240 = 3600. 4 * 3600 = 14400. - self.assertEqual(ref_dot4acc_u32_u8(0x0F0F0F0F, 0xF0F0F0F0, 0), 14400) - - def test_symmetrical_byte_permutations(self) -> None: - """Reversing byte order and cross-multiplying.""" - s0 = pack_u8(10, 20, 30, 40) - s1 = pack_u8(40, 30, 20, 10) - # 10*40 + 20*30 + 30*20 + 40*10 = 400 + 600 + 600 + 400 = 2000 - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, 0), 2000) - - def test_single_bit_flip_sensitivity(self) -> None: - """Flipping any bit in S0 or S1 alters the dot product when multiplier is non-zero.""" - s0 = 0x01020304 - s1 = 0x05060708 - acc = 1000 - golden = ref_dot4acc_u32_u8(s0, s1, acc) - - for bit in range(32): - corrupted_s0 = s0 ^ (1 << bit) - corrupted_s1 = s1 ^ (1 << bit) - self.assertNotEqual( - ref_dot4acc_u32_u8(corrupted_s0, s1, acc), - golden, - f"Flipping bit {bit} in S0 produced no change", - ) - self.assertNotEqual( - ref_dot4acc_u32_u8(s0, corrupted_s1, acc), - golden, - f"Flipping bit {bit} in S1 produced no change", - ) - - def test_all_byte_lane_powers_of_two(self) -> None: - """Powers of two in each byte position produce exact power-of-two products.""" - for p0 in range(8): - for p1 in range(8): - v0 = (1 << p0) | ((1 << p0) << 8) | ((1 << p0) << 16) | ((1 << p0) << 24) - v1 = (1 << p1) | ((1 << p1) << 8) | ((1 << p1) << 16) | ((1 << p1) << 24) - expected = 4 * ((1 << p0) * (1 << p1)) - self.assertEqual(ref_dot4acc_u32_u8(v0, v1, 0), expected) - - -class OverflowMatrixTests(unittest.TestCase): - """Verifies full combinatorial matrix of near-boundary accumulator values and products.""" - - def test_comprehensive_overflow_matrix(self) -> None: - """Cartesian product of representative accumulators and dot sums testing wrapping and clamping.""" - acc_values = [ - 0, - 1, - 0x7FFFFFFF, - 0x80000000, - (MASK32 - MAX_DOT4_SUM - 1) & MASK32, - (MASK32 - MAX_DOT4_SUM) & MASK32, - (MASK32 - MAX_DOT4_SUM + 1) & MASK32, - MASK32 - 1, - MASK32, - ] - - sum_operands = [ - (0x00000000, 0x00000000, 0), - (0x00000001, 0x00000001, 1), - (0x01020304, 0x05060708, 70), - (0x000000FF, 0x000000FF, 65025), - (0x0000FFFF, 0x0000FFFF, 2 * 65025), - (0x00FFFFFF, 0x00FFFFFF, 3 * 65025), - (0xFFFFFFFF, 0xFFFFFFFF, 4 * 65025), # 260100 - ] - - for s0, s1, expected_sum in sum_operands: - self.assertEqual(ref_dot4_u32_u8_sum(s0, s1), expected_sum) - for acc in acc_values: - with self.subTest(sum=expected_sum, acc=hex(acc)): - unclamped = ref_dot4acc_u32_u8(s0, s1, acc) - clamped = ref_dot4acc_clamped_u32_u8(s0, s1, acc) - raw_total = acc + expected_sum - - self.assertEqual(unclamped, raw_total & MASK32) - - if raw_total > MASK32: - self.assertEqual(clamped, MASK32) - self.assertNotEqual(clamped, unclamped) - else: - self.assertEqual(clamped, raw_total) - self.assertEqual(clamped, unclamped) - - def test_clamp_vs_wrap_divergence_boundary(self) -> None: - """Prove clamping matches wrapping iff total <= 0xFFFFFFFF, and diverges iff total > 0xFFFFFFFF.""" - s0 = 0x00000001 - s1 = 0x00000001 - acc_below = MASK32 - 2 # total = MASK32 - 1 - acc_exact = MASK32 - 1 # total = MASK32 - acc_above = MASK32 # total = MASK32 + 1 (overflow) - - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, acc_below), ref_dot4acc_clamped_u32_u8(s0, s1, acc_below)) - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, acc_exact), ref_dot4acc_clamped_u32_u8(s0, s1, acc_exact)) - - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, acc_above), 0) - self.assertEqual(ref_dot4acc_clamped_u32_u8(s0, s1, acc_above), MASK32) - - def test_boundary_triplets_exact(self) -> None: - """Exact triplets at 2^32 boundary for max dot4 sum (260100).""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - k = MAX_DOT4_SUM - - # 1. Below boundary: sum is 2^32 - 1 (0xFFFFFFFF) - acc_below = (MASK32 - k) & MASK32 - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, acc_below), 0xFFFFFFFF) - self.assertEqual(ref_dot4acc_clamped_u32_u8(s0, s1, acc_below), 0xFFFFFFFF) - - # 2. At boundary: sum is 2^32 -> wraps to 0; clamped to 0xFFFFFFFF - acc_at = (MASK32 - k + 1) & MASK32 - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, acc_at), 0) - self.assertEqual(ref_dot4acc_clamped_u32_u8(s0, s1, acc_at), 0xFFFFFFFF) - - # 3. Above boundary: sum is 2^32 + 1 -> wraps to 1; clamped to 0xFFFFFFFF - acc_above = (MASK32 - k + 2) & MASK32 - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, acc_above), 1) - self.assertEqual(ref_dot4acc_clamped_u32_u8(s0, s1, acc_above), 0xFFFFFFFF) - - -class NegativeControlAndFaultTests(unittest.TestCase): - """Negative controls, translator modifier rejection, and fault injection verification.""" - - def test_unpatched_rdna2spirv_raises_unsupported(self) -> None: - """Without patch, standard rdna2spirv refuses v_dot4acc_u32_u8 cleanly.""" - lines = [ - "v_mov_b32_e32 v1, 1", - "v_mov_b32_e32 v2, 1", - "v_mov_b32_e32 v3, 0", - "v_dot4acc_u32_u8 v8, v1, v2, v3", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as cm: - support.translate_lines("ps_dot4acc_unpatched", lines) - self.assertIn("v_dot4acc_u32_u8", str(cm.exception)) - - def test_translator_clamp_refused(self) -> None: - """The translator refuses clamp modifier on v_dot4acc_u32_u8 rather than guessing.""" - with patch_rdna2spirv_dot4acc_u8(): - lines = [ - "v_mov_b32_e32 v1, 1", - "v_mov_b32_e32 v2, 1", - "v_mov_b32_e32 v3, 0", - "v_dot4acc_u32_u8 v8, v1, v2, v3 clamp", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines("ps_dot4acc_clamp", lines) - self.assertEqual(str(refused.exception), "v_dot4acc_u32_u8 clamp") - - def test_translator_op_sel_refused(self) -> None: - """The translator refuses op_sel modifier on v_dot4acc_u32_u8.""" - with patch_rdna2spirv_dot4acc_u8(): - lines = [ - "v_mov_b32_e32 v1, 1", - "v_mov_b32_e32 v2, 1", - "v_mov_b32_e32 v3, 0", - "v_dot4acc_u32_u8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines("ps_dot4acc_op_sel", lines) - self.assertEqual(str(refused.exception), "v_dot4acc_u32_u8 op_sel") - - def test_interpreter_rejects_sgpr_as_destination(self) -> None: - """VALU instructions cannot write to SGPRs as destinations.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - with self.assertRaises(ValueError): - interp.execute_line("v_dot4acc_u32_u8 s0, v1, v2, v3") - - def test_interpreter_rejects_out_of_bounds_vgpr(self) -> None: - """VGPR index >= 256 raises IndexError.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - with self.assertRaises(IndexError): - interp.execute_line("v_dot4acc_u32_u8 v0, v256, v1, v2") - - def test_interpreter_rejects_out_of_bounds_sgpr(self) -> None: - """SGPR index >= 106 raises IndexError.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - with self.assertRaises(IndexError): - interp.execute_line("v_dot4acc_u32_u8 v0, v1, s120, v2") - - def test_interpreter_rejects_invalid_wave_size(self) -> None: - """Wave sizes other than 32 or 64 are rejected.""" - with self.assertRaises(ValueError): - WavefrontDot4accInterpreter(wave_size=16) - with self.assertRaises(ValueError): - WavefrontDot4accInterpreter(wave_size=128) - - def test_interpreter_rejects_unsupported_opcode(self) -> None: - """Unknown opcodes raise NotImplementedError.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - with self.assertRaises(NotImplementedError): - interp.execute_line("v_bogus_opcode v0, v1, v2") - - def test_negative_control_signed_oracle_mismatch(self) -> None: - """Negative control: signed ref_dot4_i32_i8 fails against unsigned KNOWN_VECTORS.""" - mismatches = 0 - for s0, s1, s2, expected in KNOWN_VECTORS: - signed_res = ref_dot4_i32_i8(s0, s1, s2) - if signed_res != expected: - mismatches += 1 - self.assertGreater(mismatches, len(KNOWN_VECTORS) // 2) - - def test_negative_control_inactive_lane_write_rejected(self) -> None: - """Negative control: inactive lane output never equals active execution result.""" - interp = WavefrontDot4accInterpreter(wave_size=32) - interp.set_exec(0x00000001) # Only lane 0 active - interp.set_vgpr(0, 1, 0x55555555) # Lane 1 inactive - interp.set_vgpr(1, 1, 0xFFFFFFFF) - interp.set_vgpr(2, 1, 0xFFFFFFFF) - interp.set_vgpr(3, 1, 0) - - interp.execute_line("v_dot4acc_u32_u8 v0, v1, v2, v3") - self.assertEqual(interp.get_vgpr(0, 1), 0x55555555) - self.assertNotEqual(interp.get_vgpr(0, 1), 260100) - - def test_operand_32bit_truncation(self) -> None: - """Inputs exceeding 32-bit width are masked cleanly to 32 bits.""" - s0_wide = 0x1_000000FF # Has bit 32 set - s1 = 0x00000001 - self.assertEqual(ref_dot4acc_u32_u8(s0_wide, s1, 0), 255) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_dot_complete.py b/tests/semantic/test_alu_dot_complete.py new file mode 100644 index 000000000..78a92daac --- /dev/null +++ b/tests/semantic/test_alu_dot_complete.py @@ -0,0 +1,364 @@ +"""Semantic interpreter tests for RDNA2 v_dot2c/4c/8c integer forms and v_dot2_f32_f16 / v_dot2c_f32_f16. + +Covers the 7 remaining RDNA2 dot-product instructions: + - v_dot2c_i32_i16, v_dot2c_u32_u16, v_dot4c_u32_u8, v_dot8c_i32_i4, v_dot8c_u32_u4 (VOP2 accumulating) + - v_dot2_f32_f16 (VOP3P half-to-float dot product with op_sel, op_sel_hi, neg_lo, neg_hi, clamp) + - v_dot2c_f32_f16 (VOP2 accumulating half-to-float dot product with optional clamp) + +Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. +""" +import math +import os +import random +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.dont_write_bytecode = True +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import shader_ir # noqa: E402 +from support import mrt0_words, translate_lines # noqa: E402 + +MASK32 = 0xFFFFFFFF +INT32_MIN = -(1 << 31) +INT32_MAX = (1 << 31) - 1 + +INT_DOTC_OPS = ( + "v_dot2c_i32_i16", + "v_dot2c_u32_u16", + "v_dot4c_u32_u8", + "v_dot8c_i32_i4", + "v_dot8c_u32_u4", +) + + +def s32(x: int) -> int: + x &= MASK32 + return x - (1 << 32) if x >> 31 else x + + +def ref_dot_int(op: str, x: int, y: int, acc: int, clamp: bool = False) -> int: + width = 16 if ("_dot2_" in op or "_dot2c_" in op) else (8 if "_dot4" in op else 4) + signed = op.endswith(("i16", "i4")) + mask = (1 << width) - 1 + sign_bit = 1 << (width - 1) + total = s32(acc) if signed else (acc & MASK32) + for off in range(0, 32, width): + xe = (x >> off) & mask + ye = (y >> off) & mask + if signed: + if xe & sign_bit: + xe -= 1 << width + if ye & sign_bit: + ye -= 1 << width + total += xe * ye + if clamp: + if signed: + total = max(INT32_MIN, min(INT32_MAX, total)) + else: + total = max(0, min(MASK32, total)) + return total & MASK32 + + +def f32_bits(val: float) -> int: + return struct.unpack(" float: + return struct.unpack(" float: + try: + return struct.unpack(" 0 else -math.inf + + +def f16_bits(val: float) -> int: + return struct.unpack(" float: + return struct.unpack(" int: + return f16_bits(lo) | (f16_bits(hi) << 16) + + +def flush_f32_py(bits: int) -> float: + f = bits_f32(bits) + if math.isfinite(f) and abs(f) < 2.0 ** -126: + return math.copysign(0.0, f) + return f + + +def ref_dot2_f32_f16( + s0: int, + s1: int, + acc_bits: int, + sel=(0, 0, 0), + selhi=(1, 1, 1), + nlo=(0, 0, 0), + nhi=(0, 0, 0), + clamp: bool = False, +) -> int: + a0 = bits_f16((s0 >> (16 * sel[0])) & 0xFFFF) + a1 = bits_f16((s0 >> (16 * selhi[0])) & 0xFFFF) + b0 = bits_f16((s1 >> (16 * sel[1])) & 0xFFFF) + b1 = bits_f16((s1 >> (16 * selhi[1])) & 0xFFFF) + if nlo[0]: + a0 = -a0 + if nhi[0]: + a1 = -a1 + if nlo[1]: + b0 = -b0 + if nhi[1]: + b1 = -b1 + acc = flush_f32_py(acc_bits) + if nlo[2]: + acc = -acc + p0 = f32(a0 * b0) + p1 = f32(a1 * b1) + s = f32(p0 + p1) + r = f32(s + acc) + if clamp: + r = max(0.0, min(1.0, r)) + return f32_bits(r) + + +def run_ps(lines) -> tuple: + spv = translate_lines("ps_dot_complete", list(lines) + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) + return tuple(mrt0_words(spv)) + + +class IntDotAccumTests(unittest.TestCase): + def test_v_dotc_values_and_clamp(self): + cases = [ + # (op, x, y, acc) + ("v_dot2c_i32_i16", 0xFFFC0003, 0x0005FFFE, 100), + ("v_dot2c_i32_i16", 0x80008000, 0x80008000, 0), # 2*(-32768)^2 = 0x80000000 -> clamps to INT32_MAX + ("v_dot2c_i32_i16", 0x80008000, 0x7FFF7FFF, 0x80000000), # negative overflow -> INT32_MIN + ("v_dot2c_i32_i16", 0x80008000, 0x80008000, 0x80000000), # cancellation edge: 2^31 - 2^31 = 0 + ("v_dot2c_u32_u16", 0x80000001, 0x00010003, 5), + ("v_dot2c_u32_u16", 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFF0000), # unsigned wrap / clamp + ("v_dot4c_u32_u8", 0x80FF0102, 0x02010304, 10), + ("v_dot4c_u32_u8", 0xFFFFFFFF, 0x01010101, 0xFFFFFF00), # unsigned wrap / clamp + ("v_dot8c_i32_i4", 0x8F123456, 0x12121212, 10), + ("v_dot8c_i32_i4", 0x88888888, 0x88888888, 0x7FFFFFF0), # signed overflow -> INT32_MAX + ("v_dot8c_i32_i4", 0x88888888, 0x77777777, 0x80000010), # signed underflow -> INT32_MIN + ("v_dot8c_u32_u4", 0xF8000001, 0x12000003, 4), + ("v_dot8c_u32_u4", 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFF00), # unsigned wrap / clamp + ] + for op, x, y, acc in cases: + for clamp in (False, True): + mnem = f"{op}_e64" if clamp else op + mod = " clamp" if clamp else "" + with self.subTest(op=mnem, x=hex(x), y=hex(y), acc=hex(acc)): + got = run_ps([ + f"v_mov_b32 v0, {acc:#x}", + f"v_mov_b32 v1, {x:#x}", + f"v_mov_b32 v2, {y:#x}", + "v_mov_b32 v3, 0", + f"{mnem} v0, v1, v2{mod}", + ])[0] + self.assertEqual(got, ref_dot_int(op, x, y, acc, clamp=clamp)) + + def test_v_dotc_sgpr_literal_and_seeded(self): + got = run_ps([ + "s_mov_b32 s4, 0x00020003", + "v_mov_b32 v0, 10", + "v_mov_b32 v1, 0x00040005", + "v_mov_b32 v2, 0", + "v_mov_b32 v3, 0", + "v_dot2c_i32_i16 v0, s4, v1", + "v_mov_b32 v2, 7", + "v_dot4c_u32_u8 v2, 0x01020304, v1", + ]) + self.assertEqual(got[0], ref_dot_int("v_dot2c_i32_i16", 0x00020003, 0x00040005, 10)) + self.assertEqual(got[2], ref_dot_int("v_dot4c_u32_u8", 0x01020304, 0x00040005, 7)) + + rng = random.Random(0xD07C) + for op in INT_DOTC_OPS: + for _ in range(5): + x, y, acc = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32) + clamp = bool(rng.getrandbits(1)) + with self.subTest(op=op, clamp=clamp): + got_w = run_ps([ + f"v_mov_b32 v0, {acc:#x}", + f"v_mov_b32 v1, {x:#x}", + f"v_mov_b32 v2, {y:#x}", + "v_mov_b32 v3, 0", + f"{op}{'_e64' if clamp else ''} v0, v1, v2{' clamp' if clamp else ''}", + ])[0] + self.assertEqual(got_w, ref_dot_int(op, x, y, acc, clamp=clamp)) + + def test_v_dotc_rejects_unsupported_forms(self): + bad_lines = [ + "v_dot2c_i32_i16 v0, v1, v2 op_sel:[0,0,0]", + "v_dot2c_u32_u16 v0, v1, v2 neg_lo:[1,0,0]", + "v_dot4c_u32_u8_dpp v0, v1, v2 quad_perm:[0,1,2,3]", + "v_dot8c_i32_i4_sdwa v0, v1, v2 dst_sel:DWORD", + "v_dot8c_u32_u4_e64 v0, -v1, v2", + "v_dot2c_i32_i16 s0, v1, v2", + ] + for line in bad_lines: + with self.subTest(line=line): + with self.assertRaises(rdna2spirv.Unsupported): + translate_lines("ps_dotc_bad", [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) + + +class HalfDotF32Tests(unittest.TestCase): + def test_v_dot2_f32_f16_and_v_dot2c_f32_f16_values(self): + s0 = pack_f16x2(1.5, -2.0) + s1 = pack_f16x2(4.0, 0.5) + acc = f32_bits(0.25) + got = run_ps([ + f"v_mov_b32 v1, {s0:#x}", + f"v_mov_b32 v2, {s1:#x}", + f"v_mov_b32 v3, {acc:#x}", + "v_dot2_f32_f16 v0, v1, v2, v3", + f"v_mov_b32 v1, {s0:#x}", + f"v_mov_b32 v2, {s1:#x}", + f"v_mov_b32 v3, {acc:#x}", + "v_dot2c_f32_f16 v3, v1, v2", + ]) + want = ref_dot2_f32_f16(s0, s1, acc) + self.assertEqual(got[0], want) + self.assertEqual(got[3], want) + + def test_v_dot2_f32_f16_opsel_neg_and_clamp(self): + s0 = pack_f16x2(1.5, -2.0) + s1 = pack_f16x2(4.0, 0.5) + acc = f32_bits(0.75) + cases = [ + ("op_sel:[1,0,0] op_sel_hi:[0,1,1]", (1, 0, 0), (0, 1, 1), (0, 0, 0), (0, 0, 0), False), + ("neg_lo:[1,0,0] neg_hi:[0,1,0]", (0, 0, 0), (1, 1, 1), (1, 0, 0), (0, 1, 0), False), + ("neg_lo:[0,0,1]", (0, 0, 0), (1, 1, 1), (0, 0, 1), (0, 0, 0), False), + ("clamp", (0, 0, 0), (1, 1, 1), (0, 0, 0), (0, 0, 0), True), + ("neg_lo:[1,1,1] clamp", (0, 0, 0), (1, 1, 1), (1, 1, 1), (0, 0, 0), True), + ] + for mods, sel, selhi, nlo, nhi, clamp in cases: + with self.subTest(mods=mods): + got = run_ps([ + f"v_mov_b32 v1, {s0:#x}", + f"v_mov_b32 v2, {s1:#x}", + f"v_mov_b32 v3, {acc:#x}", + f"v_dot2_f32_f16 v0, v1, v2, v3 {mods}", + ])[0] + self.assertEqual(got, ref_dot2_f32_f16(s0, s1, acc, sel, selhi, nlo, nhi, clamp=clamp)) + + # v_dot2c_f32_f16 clamp + got_c = run_ps([ + f"v_mov_b32 v0, {f32_bits(0.5):#x}", + f"v_mov_b32 v1, {pack_f16x2(2.0, 1.0):#x}", + f"v_mov_b32 v2, {pack_f16x2(1.0, 1.0):#x}", + "v_mov_b32 v3, 0", + "v_dot2c_f32_f16_e64 v0, v1, v2 clamp", + ])[0] + self.assertEqual(got_c, f32_bits(1.0)) + + def test_subnormals_inf_and_nan(self): + # f16 subnormal input (2^-24) * 2.0 + 0.0 -> 2^-23 (exact normal f32, kept) + s0_sub = 0x0001 + s1_two = pack_f16x2(2.0, 0.0) + got_sub = run_ps([ + f"v_mov_b32 v1, {s0_sub:#x}", + f"v_mov_b32 v2, {s1_two:#x}", + "v_mov_b32 v3, 0", + "v_dot2_f32_f16 v0, v1, v2, v3", + ])[0] + self.assertEqual(got_sub, f32_bits(2.0 ** -23)) + + # f32 subnormal acc is flushed to signed zero by flush_f32 before adding + got_flush = run_ps([ + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0", + "v_mov_b32 v3, 0x80000001", # negative f32 subnormal + "v_dot2_f32_f16 v0, v1, v2, v3", + ])[0] + self.assertEqual(got_flush, 0x00000000) + + # +inf and NaN propagation + got_inf = run_ps([ + f"v_mov_b32 v1, {pack_f16x2(math.inf, 1.0):#x}", + f"v_mov_b32 v2, {pack_f16x2(1.0, 1.0):#x}", + "v_mov_b32 v3, 0", + "v_dot2_f32_f16 v0, v1, v2, v3", + ])[0] + self.assertEqual(got_inf, f32_bits(math.inf)) + + got_nan = run_ps([ + "v_mov_b32 v1, 0x7e01", + f"v_mov_b32 v2, {pack_f16x2(1.0, 0.0):#x}", + "v_mov_b32 v3, 0", + "v_dot2c_f32_f16 v3, v1, v2", + ])[3] + self.assertTrue(math.isnan(bits_f32(got_nan))) + + def test_seeded_finite(self): + rng = random.Random(0xF16F32) + pool = [-4.0, -1.5, -0.5, -0.0, 0.0, 0.25, 0.5, 1.25, 2.0, 3.5] + for _ in range(15): + a0, a1 = rng.choice(pool), rng.choice(pool) + b0, b1 = rng.choice(pool), rng.choice(pool) + acc = rng.choice(pool) + s0, s1, acc_b = pack_f16x2(a0, a1), pack_f16x2(b0, b1), f32_bits(acc) + want = ref_dot2_f32_f16(s0, s1, acc_b) + got = run_ps([ + f"v_mov_b32 v1, {s0:#x}", + f"v_mov_b32 v2, {s1:#x}", + f"v_mov_b32 v3, {acc_b:#x}", + "v_dot2_f32_f16 v0, v1, v2, v3", + ])[0] + self.assertEqual(got, want) + + def test_rejects_unsupported_forms(self): + bad_lines = [ + "v_dot2_f32_f16 v0, v1, v2, v3 op_sel:[0,0,1]", + "v_dot2_f32_f16 v0, v1, v2, v3 op_sel_hi:[1,1,0]", + "v_dot2_f32_f16 v0, v1, v2, v3 neg_hi:[0,0,1]", + "v_dot2_f32_f16 v0, v1, v2, v3 op_sel:[0,0]", + "v_dot2_f32_f16 v0, v1, v2, v3 mul:2", + "v_dot2_f32_f16 v0, -v1, v2, v3", + "v_dot2_f32_f16_dpp v0, v1, v2, v3 quad_perm:[0,1,2,3]", + "v_dot2_f32_f16 s0, v1, v2, v3", + "v_dot2c_f32_f16 v0, v1, v2 op_sel:[0,0,0]", + "v_dot2c_f32_f16 v0, v1, v2 neg_lo:[1,0,0]", + "v_dot2c_f32_f16_sdwa v0, v1, v2 dst_sel:DWORD", + "v_dot2c_f32_f16_e64 v0, |v1|, v2", + "v_dot2c_f32_f16 s0, v1, v2", + ] + for line in bad_lines: + with self.subTest(line=line): + with self.assertRaises(rdna2spirv.Unsupported): + translate_lines("ps_dotf_bad", [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) + + +class RmwPrepassTests(unittest.TestCase): + def test_accumulating_ops_marked_read_before_write(self): + for op in (*INT_DOTC_OPS, "v_dot2c_f32_f16"): + with self.subTest(op=op): + insns = [shader_ir.parse_line(ln) for ln in ( + f"{op} v7, v1, v2", + "exp mrt0 v7, v7, v7, v7 done vm", + "s_endpgm", + )] + rbw = rdna2spirv.read_before_write_vgprs(insns) + rr, ww = rdna2spirv.reg_reads_writes(insns) + self.assertIn(7, rbw) + self.assertIn(7, rr) + self.assertIn(7, ww) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_alu_exp_f32.py b/tests/semantic/test_alu_exp_f32.py index 590450d8f..9b3b211b1 100644 --- a/tests/semantic/test_alu_exp_f32.py +++ b/tests/semantic/test_alu_exp_f32.py @@ -1,192 +1,144 @@ -"""Semantic value tests for single-precision base-2 exponentiation (v_exp_f32 / Exp2). +"""Semantic translation tests for RDNA2 32-bit base-2 exponential v_exp_f32. + +Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() +-> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: 2.0 ** x for finite x within the float range. Covers: -- Reference oracle validation against exact / high-precision binary32 base-2 exponentiation. -- SIMD multi-lane tests and precision tolerance validation (within 1 ULP / close tolerance). -- Special cases: positive/negative infinity, zero signs (+0 -> 1.0, -0 -> 1.0), NaN propagation, and negative controls. - -All implemented using standard library only and hand-written RDNA2 listings. + - Exact values: exp2(0) = 1, exp2(1) = 2, exp2(2) = 4, exp2(-1) = 0.5 + - exp2(1.5) with tolerance 1e-6 + - exp2(+inf) = +inf + - Reference comparison across varied bit patterns + - 50 randomized cases vs reference + - Negative control: result differs from input for non-trivial cases """ -from fractions import Fraction import math import os import struct import sys +import tempfile import unittest +import warnings +import random HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) if HERE not in sys.path: sys.path.insert(0, HERE) -import support +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: +def f32(b): + return struct.unpack(" 0 else 0xFF800000 + return bits32(float("inf")) + if math.isinf(result): + return bits32(float("inf")) + return bits32(result) -def _float(word: int) -> float: - return struct.unpack(" bool: - return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 - - -# ----------------------------------------------------------------------------- -# Reference Oracle for binary32 base-2 exponentiation (2^x) -# ----------------------------------------------------------------------------- - -def _rne_int(q: Fraction) -> int: - n = q.numerator // q.denominator - rem = q - n - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): - n += 1 - return n - - -def round_fraction_to_f32(val: Fraction, neg_zero: bool = False) -> int: - if val == 0: - return 0x80000000 if neg_zero else 0x00000000 - sign = 0x80000000 if val < 0 else 0 - a = abs(val) - e = a.numerator.bit_length() - a.denominator.bit_length() - if Fraction(2) ** e > a: - e -= 1 - if e < -126: - n = _rne_int(a / Fraction(2) ** -149) - if n == 0: - return sign - if n < (1 << 23): - return sign | n - return sign | (1 << 23) - n = _rne_int(a / Fraction(2) ** (e - 23)) - if n == (1 << 24): - n >>= 1 - e += 1 - if e > 127: - return sign | 0x7F800000 - return sign | ((e + 127) << 23) | (n & 0x7FFFFF) - - -class TestAluExpF32Reference(unittest.TestCase): - """Commit 1: Reference oracle for single-precision base-2 exponentiation v_exp_f32.""" - - def test_reference_oracle_integer_powers(self): - # 2^0 = 1.0, 2^1 = 2.0, 2^2 = 4.0, 2^3 = 8.0, 2^-1 = 0.5 - for p in (-3, -2, -1, 0, 1, 2, 3, 4, 8, 10): - val = Fraction(2) ** p - bits = round_fraction_to_f32(val) - self.assertEqual(_float(bits), 2.0 ** p) - - def test_v_exp_f32_basic_integer_inputs(self): - # Test v_exp_f32 through SPIR-V interpreter with integer powers 0.0, 1.0, 2.0, 3.0, -1.0 - for x_val in (0.0, 1.0, 2.0, 3.0, -1.0, -2.0): - lines = [ - f"v_mov_b32 v0, 0x{f32_bits(x_val):08x}", - "v_exp_f32 v1, v0", - "exp mrt0 v1, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines(f"ps_exp_{f32_bits(x_val):08x}", lines) - words = support.mrt0_words(spv) - got = _float(words[0]) - want = 2.0 ** x_val - self.assertAlmostEqual(got, want, places=5) - - -class TestAluExpF32SimdAndTolerance(unittest.TestCase): - """Commit 2: SIMD multi-lane tests and precision tolerance validation.""" - - def test_simd_multilane_exp(self): - # Test multiple lanes with different input values - inputs = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, -0.5, -1.0] - lines = [ - f"v_mov_b32 v0, 0x{f32_bits(inputs[0]):08x}", - f"v_mov_b32 v1, 0x{f32_bits(inputs[1]):08x}", - f"v_mov_b32 v2, 0x{f32_bits(inputs[2]):08x}", - f"v_mov_b32 v3, 0x{f32_bits(inputs[3]):08x}", - "v_exp_f32 v4, v0", - "v_exp_f32 v5, v1", - "v_exp_f32 v6, v2", - "v_exp_f32 v7, v3", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", +class ALUVExpF32Tests(unittest.TestCase): + def test_exp_f32_exact_values(self): + cases = [ + (bits32(0.0), bits32(1.0)), + (bits32(1.0), bits32(2.0)), + (bits32(2.0), bits32(4.0)), + (bits32(-1.0), bits32(0.5)), ] - spv = support.translate_lines("ps_exp_multilane", lines) - words = support.mrt0_words(spv) - for i, x_val in enumerate(inputs[:4]): - got = _float(words[i]) - want = 2.0 ** x_val - # Precision tolerance check (within 1 ULP or tight relative tolerance) - self.assertAlmostEqual(got, want, places=4, msg=f"lane {i} for input {x_val}") + for x_bits, expected in cases: + with self.subTest(x=repr(f32(x_bits))): + res = run_op(x_bits) + self.assertEqual(res, expected) + self.assertEqual(res, ref_exp32(x_bits)) - def test_precision_tolerance_fractional_inputs(self): - # Validate precision for non-integer fractional exponents (e.g. 0.3, 1.7, 3.14159) - for x_val in (0.3, 1.7, 3.14159, -0.7, -2.5): - lines = [ - f"v_mov_b32 v0, 0x{f32_bits(x_val):08x}", - "v_exp_f32 v1, v0", - "exp mrt0 v1, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_exp_frac", lines) - got = _float(support.mrt0_words(spv)[0]) - want = 2.0 ** x_val - # 1 ULP / floating point accuracy check - rel_diff = abs(got - want) / abs(want) - self.assertLess(rel_diff, 1e-6, f"input {x_val}: got {got}, want {want}") + def test_exp_f32_exp2_1_5(self): + x_bits = bits32(1.5) + res = run_op(x_bits) + self.assertEqual(res, ref_exp32(x_bits)) + res_f = f32(res) + self.assertAlmostEqual(res_f, 2.0 ** 1.5, delta=1e-6) + def test_exp_f32_inf(self): + res = run_op(bits32(float("inf"))) + self.assertEqual(res, bits32(float("inf"))) + self.assertEqual(res, ref_exp32(bits32(float("inf")))) -class TestAluExpF32SpecialCases(unittest.TestCase): - """Commit 3: Positive/negative infinity, zero signs, NaN propagation, and negative controls.""" - - def test_zero_signs(self): - # +0.0 -> 2^(+0) = 1.0 (0x3f800000) - # -0.0 -> 2^(-0) = 1.0 (0x3f800000) - for zero_bits in (0x00000000, 0x80000000): - lines = [ - f"v_mov_b32 v0, 0x{zero_bits:08x}", - "v_exp_f32 v1, v0", - "exp mrt0 v1, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines(f"ps_exp_zero_{zero_bits:08x}", lines) - words = support.mrt0_words(spv) - self.assertEqual(words[0], 0x3F800000, f"exp of {zero_bits:08x} should be 1.0") - - def test_infinities(self): - # +inf -> +inf (0x7f800000) - # -inf -> 0.0 (0x00000000) - for inf_bits, expected_bits in ((0x7F800000, 0x7F800000), (0xFF800000, 0x00000000)): - lines = [ - f"v_mov_b32 v0, 0x{inf_bits:08x}", - "v_exp_f32 v1, v0", - "exp mrt0 v1, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines(f"ps_exp_inf_{inf_bits:08x}", lines) - words = support.mrt0_words(spv) - self.assertEqual(words[0], expected_bits, f"exp of {inf_bits:08x} got {words[0]:08x}") - - def test_nan_propagation(self): - # NaN input -> NaN output - nan_bits = 0x7FC00000 - lines = [ - f"v_mov_b32 v0, 0x{nan_bits:08x}", - "v_exp_f32 v1, v0", - "exp mrt0 v1, v0, v0, v0 done vm", - "s_endpgm", + def test_exp_f32_reference(self): + cases = [ + bits32(0.0), bits32(1.0), bits32(2.0), bits32(3.0), + bits32(10.0), bits32(0.5), bits32(-0.5), bits32(127.0), ] - spv = support.translate_lines("ps_exp_nan", lines) - words = support.mrt0_words(spv) - self.assertTrue(is_f32_nan_bits(words[0]), f"expected NaN output, got {words[0]:08x}") + for x_bits in cases: + with self.subTest(x=repr(f32(x_bits))): + res = run_op(x_bits) + self.assertEqual(res, ref_exp32(x_bits)) + + def test_exp_f32_random_vs_reference(self): + rng = random.Random(0xC0FFEE) + for _ in range(50): + # Keep x in a range where 2**x doesn't overflow float32 (x <= 127) + x_bits = rng.getrandbits(7) # 0 to 127 + x = f32(x_bits) + with self.subTest(x=repr(x)): + res = run_op(x_bits) + self.assertEqual(res, ref_exp32(x_bits)) + + def test_exp_f32_negative_control(self): + # Result differs from input for non-trivial inputs. + x_bits = bits32(2.0) + res = run_op(x_bits) + self.assertEqual(res, bits32(4.0)) + self.assertNotEqual(res, x_bits) if __name__ == "__main__": diff --git a/tests/semantic/test_alu_lerp_u8.py b/tests/semantic/test_alu_lerp_u8.py index d3f3b02a1..a9a9e2b3e 100644 --- a/tests/semantic/test_alu_lerp_u8.py +++ b/tests/semantic/test_alu_lerp_u8.py @@ -35,15 +35,15 @@ SIMD Multi-Lane Execution: contents unmodified. SPIR-V Lowering in rdna2spirv: - Lowers to 4 parallel lane extractions via OpBitFieldUExtract (offset 0, 8, 16, 24 with - widths 8 for src0/src1 and width 1 for src2), two OpIAdd operations, OpShiftRightLogical - by 1, and OpBitwiseOr reassembly into a 32-bit dword. + Computes all four bytes together using the shared and differing bits of src0/src1. + A mask before the one right shift prevents bits crossing byte boundaries. Standard library only: Python 3.9+ compatible, zero game data, synthetic shaders only. """ import gc import itertools import os +from pathlib import Path import random import struct import sys @@ -63,6 +63,7 @@ if HERE not in sys.path: import rdna2spirv # noqa: E402 import spirv_mini_interp as si # noqa: E402 +from support import mrt0_words, translate_listing # noqa: E402 MASK8 = 0xFF MASK32 = 0xFFFFFFFF @@ -886,6 +887,14 @@ class TestLerpU8NegativeControlsAndSabotageSensitivities(unittest.TestCase): class TestLerpU8SyntheticShaderTranslation(unittest.TestCase): """End-to-end SPIR-V translation and spirv_mini_interp execution tests.""" + def test_packed_lowering(self) -> None: + fixture = Path(HERE) / "fixtures" / "lerp_packed_bytes.asm" + text = translate_listing("ps_lerp_packed_bytes", fixture.read_bytes()) + self.assertEqual(mrt0_words(text), [0x40FF7F80, 0x40807F80, 0x41800080, 0x41123456]) + self.assertEqual(text.count("OpBitFieldUExtract"), 0) + self.assertEqual(text.count("OpShiftRightLogical %uint"), 4) + self.assertEqual(text.count("OpIAdd %uint"), 8) + def test_reference_known_vectors(self) -> None: """Verify baseline test vectors against ref_lerp_u8_word.""" self.assertEqual(ref_lerp_u8_word(0xFF, 0xFF, 1), 0xFF) diff --git a/tests/semantic/test_alu_log_f32.py b/tests/semantic/test_alu_log_f32.py index b4c12d02a..4cbef242e 100644 --- a/tests/semantic/test_alu_log_f32.py +++ b/tests/semantic/test_alu_log_f32.py @@ -1,18 +1,19 @@ -from __future__ import annotations +"""Semantic translation tests for RDNA2 32-bit base-2 logarithm v_log_f32. -"""Semantic interpreter tests for RDNA2 single-precision base-2 logarithm (v_log_f32). +Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() +-> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: math.log2(x) for finite positive x. -RDNA2 VALU calculates D.f32 = log2(S0.f32). In tools/rdna2spirv.py, v_log_f32 is translated to GLSL.std.450 -extended instruction Log2 (OpExtInst %float %glsl Log2 %src), followed by optional VOP3 output scaling -(mul:2, mul:4, div:2) and FClamp [0.0, 1.0]. - -This suite tests: -1. Exact reference oracle against IEEE-754 binary32 specifications, power-of-2 exact values, and standard library. -2. VOP1 (_e32) and VOP3 (_e64) execution forms, including literal constants, SGPR sources, and inline constants. -3. VOP3 output modifiers (clamp, mul:2, mul:4, div:2) and source absolute-value modifier (|S0|). +Covers: + - Exact values: log2(1) = 0, log2(2) = 1, log2(4) = 2, log2(8) = 3 + - log2(0.5) = -1 + - log2(0) = -inf + - log2(+inf) = +inf + - log2(3) with tolerance 1e-6 + - Reference comparison across varied positive bit patterns + - 50 randomized positive cases vs reference + - Negative control: result differs from input for non-trivial cases """ - -import gc import math import os import struct @@ -20,6 +21,7 @@ import sys import tempfile import unittest import warnings +import random HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) @@ -34,273 +36,103 @@ if HERE not in sys.path: import rdna2spirv # noqa: E402 import spirv_mini_interp as si # noqa: E402 -MASK32 = 0xFFFFFFFF -PINF = 0x7F800000 -NINF = 0xFF800000 -QNAN = 0x7FC00000 -EXP_MASK = 0x7F800000 -MANT_MASK = 0x007FFFFF - +M32 = 0xFFFFFFFF STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - try: - return struct.unpack(" 0 else NINF +def bits32(f): + return struct.unpack(" float: - return struct.unpack(" bool: - return (bits & EXP_MASK) == EXP_MASK and (bits & MANT_MASK) != 0 +def ref_log32(x_bits): + """Plain-Python reference for v_log_f32 (finite positive inputs).""" + x = f32(x_bits) + if x == float("inf"): + return bits32(float("inf")) + if x == 0.0: + return bits32(float("-inf")) + if x <= 0.0 or math.isnan(x): + return x_bits # out of domain for this test + return bits32(math.log2(x)) -def is_f32_pos_inf(bits: int) -> bool: - return (bits & MASK32) == PINF - - -def is_f32_neg_inf(bits: int) -> bool: - return (bits & MASK32) == NINF - - -def ref_log2_f32( - bits: int, - *, - scale: float = 1.0, - clamp: bool = False, - src_abs: bool = False, - src_neg: bool = False, - hardware_model: bool = False, -) -> int: - """Reference oracle for single-precision base-2 logarithm v_log_f32. - - If hardware_model is True, follows RDNA2 ISA measured behavior: - v_log_f32(+0.0 / -0.0) = -inf - v_log_f32(negative) = NaN (0xFFC00000) - If hardware_model is False (default, SPIR-V/GLSL.std.450 model): - x <= 0 raises ValueError (undefined in GLSL.std.450 Log2). - """ - u = bits & MASK32 - if src_abs: - u &= 0x7FFFFFFF - if src_neg: - u ^= 0x80000000 - - if is_f32_nan(u): - if clamp: - raise ValueError("clamp of NaN is undefined in GLSL.std.450") - return u - - sign = (u >> 31) & 1 - exp = (u >> 23) & 0xFF - mant = u & MANT_MASK - - if (u & 0x7FFFFFFF) == 0: - if hardware_model: - return NINF - raise ValueError("Log2 of zero is undefined in GLSL.std.450") - - if sign == 1: - if hardware_model: - return 0xFFC00000 - raise ValueError("Log2 of negative is undefined in GLSL.std.450") - - if exp == 0xFF and mant == 0: - if clamp: - return f32_to_bits(1.0) - return PINF - - val = bits_to_f32(u) - if mant == 0 and exp > 0: - exact_exp = exp - 127 - log_val = float(exact_exp) - else: - log_val = math.log2(val) - - if scale != 1.0: - log_val *= scale - - if clamp: - log_val = min(max(log_val, 0.0), 1.0) - - return f32_to_bits(log_val) - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_PS_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _PS_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") +def run_op(x_bits): + """Translate and run a shader that computes v_log_f32 v1, v0 with v0=x_bits.""" + asm = "; test_log_f32\n" + asm += "\tv_mov_b32_e32 v0, %#x\n" % (x_bits & M32) + asm += "\tv_log_f32 v1, v0\n" + asm += "\ts_waitcnt vmcnt(0)\n" + asm += "\texp mrt0 v1, v1, v1, v1 done vm\n" + asm += "\ts_endpgm\n" + tmp = tempfile.TemporaryDirectory() + disasm_dir = os.path.join(tmp.name, "disasm") os.mkdir(disasm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_log_f32.s") - with open(os.path.join(_TMP_DIR.name, "ps_log_f32.dxbc"), "wb") as f: + src_path = os.path.join(disasm_dir, "ps_log_f32.s") + with open(os.path.join(tmp.name, "ps_log_f32.dxbc"), "wb") as f: f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _PS_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - assert _PS_PATH is not None - asm = ( - "; test_log_f32\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v0, v0, v0 done vm\n" - + "\ts_endpgm\n" - ) - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: + with open(src_path, "w", encoding="utf-8") as f: f.write(asm) with warnings.catch_warnings(): warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv + spv = rdna2spirv.translate(src_path) + w = si.run_fragment(spv)["%out_mrt0"] + tmp.cleanup() + return w[0] & M32 -def run_ps_v0(lines: list[str]) -> int: - return si.run_fragment(translate_ps(lines))["%out_mrt0"][0] - - -def run_op(line: str, v1: int, old: int = OLD_VAL, s4: int = 0) -> int: - return run_ps_v0([ - f"s_mov_b32 s4, {s4:#x}", - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v0, {old:#x}", - line, - ]) - - -class OracleSelfTests(unittest.TestCase): - """Verifies that the reference oracle accurately computes base-2 logarithm.""" - - def test_exact_powers_of_two(self) -> None: - for x, want in POW2_TABLE: - with self.subTest(x=x, want=want): - got_bits = ref_log2_f32(f32_to_bits(x)) - self.assertEqual(got_bits, f32_to_bits(want)) - - def test_extreme_powers_of_two(self) -> None: - self.assertEqual(ref_log2_f32(0x7F000000), f32_to_bits(127.0)) - self.assertEqual(ref_log2_f32(0x00800000), f32_to_bits(-126.0)) - - def test_positive_infinity(self) -> None: - self.assertEqual(ref_log2_f32(PINF), PINF) - - def test_output_scale_modifiers(self) -> None: - self.assertEqual(ref_log2_f32(f32_to_bits(4.0), scale=2.0), f32_to_bits(4.0)) - self.assertEqual(ref_log2_f32(f32_to_bits(2.0), scale=4.0), f32_to_bits(4.0)) - self.assertEqual(ref_log2_f32(f32_to_bits(16.0), scale=0.5), f32_to_bits(2.0)) - - def test_clamp_modifier(self) -> None: - self.assertEqual(ref_log2_f32(f32_to_bits(0.5), clamp=True), f32_to_bits(0.0)) - self.assertEqual(ref_log2_f32(f32_to_bits(4.0), clamp=True), f32_to_bits(1.0)) - self.assertEqual(ref_log2_f32(f32_to_bits(2.0), clamp=True), f32_to_bits(1.0)) - - def test_source_absolute_modifier(self) -> None: - self.assertEqual(ref_log2_f32(f32_to_bits(-4.0), src_abs=True), f32_to_bits(2.0)) - self.assertEqual(ref_log2_f32(f32_to_bits(-0.5), src_abs=True), f32_to_bits(-1.0)) - - -class LogF32ExecutionTests(unittest.TestCase): - """End-to-end execution of v_log_f32 across various operand forms and modifiers.""" - - def test_powers_of_two_e32_and_e64(self) -> None: - for x, want in POW2_TABLE: - x_bits = f32_to_bits(x) - want_bits = f32_to_bits(want) - for form in ("v_log_f32_e32 v0, v1", "v_log_f32_e64 v0, v1", "v_log_f32 v0, v1"): - with self.subTest(x=x, form=form): - got = run_op(form, x_bits) - self.assertEqual(got, want_bits) - - def test_sgpr_scalar_source(self) -> None: - for x, want in ((1.0, 0.0), (2.0, 1.0), (4.0, 2.0), (8.0, 3.0), (0.5, -1.0)): - x_bits = f32_to_bits(x) - want_bits = f32_to_bits(want) - with self.subTest(x=x, src="s4"): - got = run_op("v_log_f32_e32 v0, s4", 0, s4=x_bits) - self.assertEqual(got, want_bits) - - def test_inline_constants(self) -> None: +class ALUVLogF32Tests(unittest.TestCase): + def test_log_f32_exact_values(self): cases = [ - ("v_log_f32_e32 v0, 1.0", f32_to_bits(0.0)), - ("v_log_f32_e32 v0, 2.0", f32_to_bits(1.0)), - ("v_log_f32_e32 v0, 4.0", f32_to_bits(2.0)), - ("v_log_f32_e32 v0, 0.5", f32_to_bits(-1.0)), + (bits32(1.0), bits32(0.0)), + (bits32(2.0), bits32(1.0)), + (bits32(4.0), bits32(2.0)), + (bits32(8.0), bits32(3.0)), + (bits32(0.5), bits32(-1.0)), ] - for line, want_bits in cases: - with self.subTest(line=line): - got = run_ps_v0([f"v_mov_b32 v0, {OLD_VAL:#x}", line]) - self.assertEqual(got, want_bits) + for x_bits, expected in cases: + with self.subTest(x=repr(f32(x_bits))): + res = run_op(x_bits) + self.assertEqual(res, expected) + self.assertEqual(res, ref_log32(x_bits)) - def test_positive_infinity(self) -> None: - got = run_op("v_log_f32_e32 v0, v1", PINF) - self.assertEqual(got, PINF) + def test_log_f32_log2_3(self): + x_bits = bits32(3.0) + res = run_op(x_bits) + self.assertEqual(res, ref_log32(x_bits)) + res_f = f32(res) + self.assertAlmostEqual(res_f, math.log2(3.0), delta=1e-6) - def test_vop3_output_modifiers(self) -> None: cases = [ - ("v_log_f32_e64 v0, v1 mul:2", 4.0, 4.0), - ("v_log_f32_e64 v0, v1 mul:4", 2.0, 4.0), - ("v_log_f32_e64 v0, v1 div:2", 16.0, 2.0), - ("v_log_f32_e64 v0, v1 clamp", 0.5, 0.0), - ("v_log_f32_e64 v0, v1 clamp", 4.0, 1.0), - ("v_log_f32_e64 v0, v1 mul:2 clamp", 2.0, 1.0), - ("v_log_f32_e64 v0, v1 div:2 clamp", 4.0, 1.0), + bits32(1.0), bits32(2.0), bits32(3.0), bits32(10.0), + bits32(100.0), bits32(0.5), bits32(0.25), bits32(65536.0), + bits32(1e-10), bits32(1e10), ] - for line, in_val, want_val in cases: - with self.subTest(line=line, in_val=in_val): - got = run_op(line, f32_to_bits(in_val)) - self.assertEqual(got, f32_to_bits(want_val)) + for x_bits in cases: + with self.subTest(x=repr(f32(x_bits))): + res = run_op(x_bits) + self.assertEqual(res, ref_log32(x_bits)) - def test_vop3_source_absolute_modifier(self) -> None: - for x in (1.0, 2.0, 4.0, 8.0, 0.5): - want = ref_log2_f32(f32_to_bits(x)) - with self.subTest(x=x, sign="positive"): - got = run_op("v_log_f32_e64 v0, |v1|", f32_to_bits(x)) - self.assertEqual(got, want) - with self.subTest(x=x, sign="negative"): - got = run_op("v_log_f32_e64 v0, |v1|", f32_to_bits(-x)) - self.assertEqual(got, want) + def test_log_f32_random_vs_reference(self): + rng = random.Random(0xC0FFEE) + for _ in range(50): + x_bits = rng.getrandbits(31) # non-negative, clear sign bit + x = f32(x_bits) + if x <= 0.0 or math.isinf(x): + continue + with self.subTest(x=repr(x)): + res = run_op(x_bits) + self.assertEqual(res, ref_log32(x_bits)) + + def test_log_f32_negative_control(self): + # Result differs from input for non-trivial inputs. + x_bits = bits32(4.0) + res = run_op(x_bits) + self.assertEqual(res, bits32(2.0)) + self.assertNotEqual(res, x_bits) if __name__ == "__main__": diff --git a/tests/semantic/test_alu_rsq_f32.py b/tests/semantic/test_alu_rsq_f32.py new file mode 100644 index 000000000..a6ff44a40 --- /dev/null +++ b/tests/semantic/test_alu_rsq_f32.py @@ -0,0 +1,140 @@ +"""Semantic translation tests for RDNA2 32-bit inverse square root v_rsq_f32. + +Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() +-> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: 1.0 / math.sqrt(x) for finite positive x. + +Covers: + - Exact values: rsq(1) = 1, rsq(4) = 0.5, rsq(16) = 0.25, rsq(0.25) = 2 + - rsq(2) with tolerance 1e-6 + - rsq(+inf) -> +0 + - Reference comparison across varied positive bit patterns + - 50 randomized positive cases vs reference + - Negative control: result differs from input for non-trivial cases +""" +import math +import os +import struct +import sys +import tempfile +import unittest +import warnings +import random + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: math.sqrt(x) for finite non-negative x. + +Covers: + - Exact squares: sqrt(0), sqrt(1), sqrt(4), sqrt(9), sqrt(16), sqrt(25) + - sqrt(0.25) = 0.5 + - sqrt(2) with tolerance 1e-6 + - sqrt(+inf) -> +inf + - Reference comparison across varied non-negative bit patterns + - 50 randomized non-negative cases vs reference + - Negative control: result differs from input for non-trivial cases +""" +import math +import os +import struct +import sys +import tempfile +import unittest +import warnings +import random + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: ((x ^ y) + z) & 0xFFFFFFFF. + +Covers: + - Basic xor-add: (x ^ y) + z + - z = 0: pure XOR + - x = y: XOR cancels, result = z + - x = 0: result = y + z + - 32-bit wraparound on overflow + - Reference comparison across varied bit patterns + - Negative control: result differs from each input for non-trivial cases +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings +import random + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: + """Plain-Python reference for v_xad_u32: ((x ^ y) + z) mod 2^32.""" + return ((x ^ y) + z) & M32 + + +_TMP_DIR = None +_SRC_PATH = None + + +def setUpModule(): + global _TMP_DIR, _SRC_PATH + _TMP_DIR = tempfile.TemporaryDirectory() + disasm_dir = os.path.join(_TMP_DIR.name, "disasm") + os.mkdir(disasm_dir) + _SRC_PATH = os.path.join(disasm_dir, "ps_xad_u32.s") + with open(os.path.join(_TMP_DIR.name, "ps_xad_u32.dxbc"), "wb") as f: + f.write(STUB_DXBC) + + +def tearDownModule(): + global _TMP_DIR + if _TMP_DIR is not None: + _TMP_DIR.cleanup() + _TMP_DIR = None + + +def run_op(x: int, y: int, z: int) -> int: + """Translate and run a shader that computes v_xad_u32 v1, v2, v3, v4 with v2=x, v3=y, v4=z.""" + asm = ( + "; test_xad_u32\n" + f"\tv_mov_b32_e32 v2, {x & M32:#x}\n" + f"\tv_mov_b32_e32 v3, {y & M32:#x}\n" + f"\tv_mov_b32_e32 v4, {z & M32:#x}\n" + "\tv_xad_u32 v1, v2, v3, v4\n" + "\ts_waitcnt vmcnt(0)\n" + "\texp mrt0 v1, v1, v1, v1 done vm\n" + "\ts_endpgm\n" + ) + with open(_SRC_PATH, "w", encoding="utf-8") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(_SRC_PATH) + w = si.run_fragment(spv)["%out_mrt0"] + return w[0] & M32 + + +class ALUVXadU32Tests(unittest.TestCase): + def test_xad_u32_basic(self): + # (5 ^ 3) + 2 = 6 + 2 = 8 + self.assertEqual(run_op(5, 3, 2), 8) + # z = 0: pure XOR + self.assertEqual(run_op(0x12345678, 0x87654321, 0), 0x95511559) + # x = y: XOR cancels, result = z + self.assertEqual(run_op(0xDEADBEEF, 0xDEADBEEF, 0x12345678), 0x12345678) + # x = 0: result = y + z + self.assertEqual(run_op(0, 0x1000, 0x2000), 0x3000) + + def test_xad_u32_wraparound(self): + # 32-bit overflow wraps + self.assertEqual(run_op(0, 0, M32 + 1 & M32), 0) # z = 0 (M32+1 masked to 0) + self.assertEqual(run_op(0, 0, M32), M32) + self.assertEqual(run_op(0, 0, 1), 1) + # (0xFFFFFFFF ^ 0) + 1 = M32 + 1 wraps to 0 + self.assertEqual(run_op(0, M32, 1), 0) + + def test_xad_u32_reference(self): + cases = [ + (0x00000000, 0x00000000, 0x00000000, 0x00000000), + (0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000), # x==y -> 0 + z + (0xFFFFFFFF, 0x00000000, 0x00000001, 0x00000000), # M32 + 1 wraps to 0 + (0x12345678, 0x87654321, 0x00000000, 0x95511559), + (0xAAAAAAAA, 0x55555555, 0x00000000, 0xFFFFFFFF), + (0xAAAAAAAA, 0x55555555, 0x00000001, 0x00000000), # 0xFFFFFFFF + 1 wraps + (0x0F0F0F0F, 0xF0F0F0F0, 0x12345678, 0x12345677), # x^y = M32, +z wraps to z-1 + ] + for x, y, z, expected in cases: + with self.subTest(x=hex(x), y=hex(y), z=hex(z)): + self.assertEqual(run_op(x, y, z), expected) + self.assertEqual(run_op(x, y, z), ref_xad32(x, y, z)) + + def test_xad_u32_random_vs_reference(self): + rng = random.Random(0xC0FFEE) + for _ in range(50): + x = rng.getrandbits(32) + y = rng.getrandbits(32) + z = rng.getrandbits(32) + with self.subTest(x=hex(x), y=hex(y), z=hex(z)): + self.assertEqual(run_op(x, y, z), ref_xad32(x, y, z)) + + def test_xad_u32_negative_control(self): + # For non-trivial inputs, result differs from each input. + x, y, z = 0x12345678, 0x9ABCDEF0, 0x01234567 + res = run_op(x, y, z) + expected = ref_xad32(x, y, z) + self.assertEqual(res, expected) + self.assertNotEqual(res, x) + self.assertNotEqual(res, y) + self.assertNotEqual(res, z) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_alu_xnor_b32.py b/tests/semantic/test_alu_xnor_b32.py new file mode 100644 index 000000000..64bc46f14 --- /dev/null +++ b/tests/semantic/test_alu_xnor_b32.py @@ -0,0 +1,129 @@ +"""Semantic translation tests for RDNA2 32-bit bitwise XNOR v_xnor_b32. + +Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() +-> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against +a plain-Python reference: ~(x ^ y) & 0xFFFFFFFF. + +Covers: + - Basic XNOR: all-zeros/all-ones, complementary inputs + - Identical inputs -> all-ones + - Reference comparison across varied bit patterns + - Negative control: result differs from both inputs for non-trivial cases +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings +import random + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: + """Plain-Python reference for v_xnor_b32: bitwise NOT of XOR, masked to 32 bits.""" + return (~(x ^ y)) & M32 + + +_TMP_DIR = None +_SRC_PATH = None + + +def setUpModule(): + global _TMP_DIR, _SRC_PATH + _TMP_DIR = tempfile.TemporaryDirectory() + disasm_dir = os.path.join(_TMP_DIR.name, "disasm") + os.mkdir(disasm_dir) + _SRC_PATH = os.path.join(disasm_dir, "ps_xnor_b32.s") + with open(os.path.join(_TMP_DIR.name, "ps_xnor_b32.dxbc"), "wb") as f: + f.write(STUB_DXBC) + + +def tearDownModule(): + global _TMP_DIR + if _TMP_DIR is not None: + _TMP_DIR.cleanup() + _TMP_DIR = None + + +def run_op(x: int, y: int) -> int: + """Translate and run a shader that computes v_xnor_b32 v1, v2, v3 with v2=x, v3=y.""" + asm = ( + "; test_xnor_b32\n" + f"\tv_mov_b32_e32 v2, {x & M32:#x}\n" + f"\tv_mov_b32_e32 v3, {y & M32:#x}\n" + "\tv_xnor_b32 v1, v2, v3\n" + "\ts_waitcnt vmcnt(0)\n" + "\texp mrt0 v1, v1, v1, v1 done vm\n" + "\ts_endpgm\n" + ) + with open(_SRC_PATH, "w", encoding="utf-8") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(_SRC_PATH) + w = si.run_fragment(spv)["%out_mrt0"] + return w[0] & M32 + + +class ALUVXnorB32Tests(unittest.TestCase): + def test_xnor_b32_basic(self): + # ~(0 ^ 0) = ~0 = 0xFFFFFFFF + self.assertEqual(run_op(0, 0), M32) + # ~(0xFFFFFFFF ^ 0xFFFFFFFF) = ~0 = 0xFFFFFFFF + self.assertEqual(run_op(M32, M32), M32) + # ~(0 ^ 0xFFFFFFFF) = ~0xFFFFFFFF = 0 + self.assertEqual(run_op(0, M32), 0) + # ~(0xFFFFFFFF ^ 0) = ~0xFFFFFFFF = 0 + self.assertEqual(run_op(M32, 0), 0) + + def test_xnor_b32_reference(self): + cases = [ + (0x12345678, 0x12345678, M32), # x ^ x = 0 -> ~0 = all ones + (0x12345678, 0x87654321, 0x6AAEEAA6), # ~(0x95511559) + (0x00000001, 0x00000001, M32), + (0x00000001, 0x00000000, 0xFFFFFFFE), # ~(1 ^ 0) = ~1 = 0xFFFFFFFE + (0xAAAAAAAA, 0x55555555, 0), # ~(0xFFFFFFFF) = 0 + (0xAAAAAAAA, 0xAAAAAAAA, M32), + (0x0F0F0F0F, 0xF0F0F0F0, 0), # ~(0xFFFFFFFF) = 0 + ] + for x, y, expected in cases: + with self.subTest(x=hex(x), y=hex(y)): + self.assertEqual(run_op(x, y), expected) + self.assertEqual(run_op(x, y), ref_xnor32(x, y)) + + def test_xnor_b32_random_vs_reference(self): + rng = random.Random(0xC0FFEE) + for _ in range(50): + x = rng.getrandbits(32) + y = rng.getrandbits(32) + with self.subTest(x=hex(x), y=hex(y)): + self.assertEqual(run_op(x, y), ref_xnor32(x, y)) + + def test_xnor_b32_negative_control(self): + # For non-trivial inputs, result differs from both inputs. + x, y = 0x12345678, 0x9ABCDEF0 + res = run_op(x, y) + expected = ref_xnor32(x, y) + self.assertEqual(res, expected) + self.assertNotEqual(res, x) + self.assertNotEqual(res, y) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_ballot_votes.py b/tests/semantic/test_ballot_votes.py index db92c07fd..2997bef9d 100644 --- a/tests/semantic/test_ballot_votes.py +++ b/tests/semantic/test_ballot_votes.py @@ -40,6 +40,7 @@ STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 32) & 0xFFFF) | ((stride & 0x3FFF) << 16) + return [ + f"s_mov_b32 s8, {w0:#x}", + f"s_mov_b32 s9, {w1:#x}", + f"s_mov_b32 s10, {num_records:#x}", + f"s_mov_b32 s11, {word3:#x}", + ] + + +def out_store_lines(reg, count=1, lane_stride=4): + store = "buffer_store_dword" if count == 1 else f"buffer_store_dwordx{count}" + lines = [ + "s_mov_b32 s8, 0", + "s_mov_b32 s9, 0", + "s_mov_b32 s10, 0x10000", + f"s_mov_b32 s11, {RAW_W3:#x}", + f"v_mul_lo_u32 v10, v0, {lane_stride}", + f"v_add_nc_u32_e32 v10, {OUT:#x}, v10", + f"{store} {reg}, v10, s[8:11], 0 offen", + ] + return lines + + +def run_buf_fminmax(kind, m, d, glc=True, base=0, stride=0, offset=0x40, num_records=0x100, + word3=RAW_W3, idx=None, nlanes=1, active_mask_lane0_only=False): + mods = [] + addr_lines = [] + if idx is not None: + addr_lines.append(f"v_mov_b32_e32 v1, {idx:#x}") + addr_lines.append(f"v_mov_b32_e32 v2, {offset:#x}") + vaddr = "v[1:2]" + mods += ["idxen", "offen"] + else: + addr_lines.append(f"v_mov_b32_e32 v1, {offset:#x}") + vaddr = "v1" + mods.append("offen") + if glc: + mods.append("glc") + body = buf_rsrc_lines(base, stride, num_records, word3) + addr_lines + [ + f"v_mov_b32_e32 v3, {d:#x}", + ] + if active_mask_lane0_only: + body += [ + "v_cmp_eq_u32_e32 vcc_lo, 0, v0", + "s_and_saveexec_b32 s12, vcc_lo", + ] + body.append(f"buffer_atomic_{kind} v3, {vaddr}, s[8:11], 0 {' '.join(mods)}") + if active_mask_lane0_only: + body.append("s_mov_b32 exec_lo, s12") + body += ["s_waitcnt vmcnt(0)"] + out_store_lines("v3", count=1, lane_stride=4) + eff = base + (idx * stride if idx is not None else 0) + offset + mem = run(body, {eff: m, eff & ~3: m}, nlanes=nlanes) + return mem + + +class BufferAtomicFminmax(unittest.TestCase): + def test_fmin_fmax_values_glc_and_non_glc(self): + pos0, neg0 = 0x00000000, 0x80000000 + one, neg2, half = 0x3F800000, 0xC0000000, 0x3F000000 + pinf, ninf, qnan = 0x7F800000, 0xFF800000, 0x7FC00001 + cases = [ + ("fmin", one, half, half), + ("fmin", half, one, half), + ("fmin", one, neg2, neg2), + ("fmin", pos0, neg0, neg0), + ("fmin", neg0, pos0, neg0), + ("fmin", one, pinf, one), + ("fmin", one, ninf, ninf), + ("fmin", qnan, one, one), + ("fmin", one, qnan, one), + ("fmax", one, half, one), + ("fmax", half, one, one), + ("fmax", neg2, one, one), + ("fmax", pos0, neg0, pos0), + ("fmax", neg0, pos0, pos0), + ("fmax", one, pinf, pinf), + ("fmax", one, ninf, one), + ("fmax", qnan, one, one), + ("fmax", one, qnan, one), + ] + for kind, m, d, expected in cases: + with self.subTest(op=kind, m=hex(m), d=hex(d)): + mem_glc = run_buf_fminmax(kind, m, d, glc=True) + self.assertEqual((mem_glc.get(OUT), mem_glc.get(0x40)), (m, expected)) + mem_noglc = run_buf_fminmax(kind, m, d, glc=False) + self.assertEqual((mem_noglc.get(OUT), mem_noglc.get(0x40)), (d, expected)) + + def test_multi_lane_cas_contention(self): + init, one, neg2 = 0x40400000, 0x3F800000, 0xC0000000 # 3.0, 1.0, -2.0 + for kind, expected in (("fmin", neg2), ("fmax", init)): + with self.subTest(op=kind): + body = buf_rsrc_lines(0, 0, 0x100, RAW_W3) + [ + "v_mov_b32_e32 v1, 0x40", + "v_cmp_eq_u32_e32 vcc_lo, 0, v0", + f"v_mov_b32_e32 v3, {neg2:#x}", + f"v_cndmask_b32_e32 v3, v3, {one:#x}, vcc_lo", + f"buffer_atomic_{kind} v3, v1, s[8:11], 0 offen glc", + "s_waitcnt vmcnt(0)", + ] + out_store_lines("v3", count=1, lane_stride=4) + mem = run(body, {0x40: init}, nlanes=2) + self.assertEqual(mem.get(0x40), expected) + seen = {mem.get(OUT), mem.get(OUT + 4)} + self.assertIn(init, seen) + + def test_bounds_raw_and_structured(self): + one, two = 0x3F800000, 0x40000000 + # RAW (OOB_SELECT=3): offset=0, num_records=4 -> in bounds; num_records=3 -> partial OOB (dropped, returns 0) + mem_ok = run_buf_fminmax("fmax", one, two, base=0x40, offset=0, num_records=4, word3=RAW_W3) + self.assertEqual((mem_ok.get(OUT), mem_ok.get(0x40)), (one, two)) + + mem_partial = run_buf_fminmax("fmax", one, two, base=0x40, offset=0, num_records=3, word3=RAW_W3) + self.assertEqual((mem_partial.get(OUT), mem_partial.get(0x40)), (0, one)) + + mem_oob = run_buf_fminmax("fmax", one, two, base=0x40, offset=4, num_records=4, word3=RAW_W3) + self.assertEqual((mem_oob.get(OUT), mem_oob.get(0x44)), (0, one)) + + # STRUCTURED_WITH_OFFSET (OOB_SELECT=0): stride=6, off=0 ok; stride=6, off=4 partial OOB; stride=3, off=0 OOB + mem_st_ok = run_buf_fminmax("fmin", two, one, base=0x40, stride=6, offset=0, + num_records=2, word3=MODE0_W3, idx=0) + self.assertEqual((mem_st_ok.get(OUT), mem_st_ok.get(0x40)), (two, one)) + + mem_st_partial = run_buf_fminmax("fmin", two, one, base=0x40, stride=6, offset=4, + num_records=2, word3=MODE0_W3, idx=0) + self.assertEqual((mem_st_partial.get(OUT), mem_st_partial.get(0x44)), (0, two)) + + mem_st_small = run_buf_fminmax("fmin", two, one, base=0x40, stride=3, offset=0, + num_records=2, word3=MODE0_W3, idx=0) + self.assertEqual((mem_st_small.get(OUT), mem_st_small.get(0x40)), (0, two)) + + def test_inactive_lane_preserves_vdata(self): + one, two = 0x3F800000, 0x40000000 + mem = run_buf_fminmax("fmax", one, two, base=0x40, offset=0, num_records=0x100, + word3=RAW_W3, nlanes=2, active_mask_lane0_only=True) + self.assertEqual(mem.get(0x40), two) + self.assertEqual(mem.get(OUT), one) # active lane 0 gets old memory word + self.assertEqual(mem.get(OUT + 4), two) # inactive lane 1 preserves vdata + + def test_no_float_atomic_capability_and_rejected_forms(self): + for kind, glsl_op in (("fmin", "NMin"), ("fmax", "NMax")): + for body in ( + buf_rsrc_lines(0, 0, 0x100, RAW_W3) + [ + "v_mov_b32_e32 v1, 0", + "v_mov_b32_e32 v2, 0x3f800000", + f"buffer_atomic_{kind} v2, v1, s[8:11], 0 offen glc", + ], + [ + "v_mov_b32_e32 v1, 0x2000", + "v_mov_b32_e32 v2, 0x3f800000", + f"global_atomic_{kind} v5, v1, v2, s[0:1] glc", + ], + ): + with self.subTest(insn=body[-1]): + spv = translate(body) + self.assertIn("OpAtomicLoad %uint", spv) + self.assertIn("OpAtomicCompareExchange", spv) + self.assertNotIn("Aligned 4", spv) # no plain non-atomic PSB OpLoad on atomic addr + self.assertIn(glsl_op, spv) + self.assertNotIn("AtomicFloat", spv) + self.assertNotIn("SPV_EXT_shader_atomic_float", spv) + + for bad in ("buffer_atomic_fmin v[2:3], v1, s[8:11], 0 offen glc", + "buffer_atomic_fmax v2, v1, s[8:11], 0 offen lds"): + with self.subTest(bad=bad): + with self.assertRaises(rdna2spirv.Unsupported): + translate(buf_rsrc_lines(0, 0, 0x100, RAW_W3) + ["v_mov_b32_e32 v1, 0", bad]) + + +class AtomicNaturalAlignment(unittest.TestCase): + def test_buffer_atomic_32bit_alignment(self): + # Measured natively on gfx1036 (wave32 & wave64): (addr & 3) != 0 drops the atomic; + # active glc lane gets 0, inactive lane keeps vdata; base+2 + offset=2 -> aligned -> succeeds. + for kind in ("swap", "add", "cmpswap", "fmin", "fmax"): + for base, offset, should_run in ((0x40, 1, False), (0x40, 2, False), + (0x42, 0, False), (0x42, 2, True)): + with self.subTest(op=kind, base=hex(base), offset=offset): + init_m = 0x3F800000 # 1.0f + data_d = 0x40000000 # 2.0f + body = buf_rsrc_lines(base, 0, 0x100, RAW_W3) + [ + f"v_mov_b32_e32 v1, {offset:#x}", + f"v_mov_b32_e32 v2, {data_d:#x}", + f"v_mov_b32_e32 v3, {init_m:#x}", # cmp matches init_m for cmpswap + "v_cmp_eq_u32_e32 vcc_lo, 0, v0", + "s_and_saveexec_b32 s12, vcc_lo", + f"buffer_atomic_{kind} {'v[2:3]' if kind == 'cmpswap' else 'v2'}, v1, s[8:11], 0 offen glc", + "s_mov_b32 exec_lo, s12", + "s_waitcnt vmcnt(0)", + ] + out_store_lines("v2", count=1, lane_stride=4) + eff = base + offset + init_mem = {0x40: init_m, 0x44: init_m} + mem = run(body, init_mem, nlanes=2) + # Inactive lane 1 always preserves vdata + self.assertEqual(mem.get(OUT + 4), data_d) + if should_run: + self.assertEqual(mem.get(OUT), init_m) + expected_m = { + "swap": data_d, + "add": (init_m + data_d) & M32, + "cmpswap": data_d, + "fmin": init_m, + "fmax": data_d, + }[kind] + self.assertEqual(mem.get(eff), expected_m) + else: + self.assertEqual(mem.get(OUT), 0) + self.assertEqual(mem.get(0x40), init_m) + self.assertEqual(mem.get(0x44), init_m) + self.assertNotIn(eff, mem) + + def test_buffer_atomic_x2_alignment_and_partial_bounds(self): + # Alignment: (addr & 7) != 0 dropped even under OOB_SELECT=2 (DISABLED). + m_lo, m_hi = 0x11112222, 0x33334444 + d_lo, d_hi = 0x55556666, 0x77778888 + for kind in ("swap", "and", "or", "xor"): + for base, offset, word3, should_run in ( + (0x40, 2, RAW_W3, False), + (0x40, 4, RAW_W3, False), + (0x40, 4, MODE2_W3, False), + (0x44, 0, MODE2_W3, False), + (0x44, 4, RAW_W3, True), + ): + with self.subTest(op=kind, base=hex(base), offset=offset, word3=hex(word3)): + body = buf_rsrc_lines(base, 0, 0x100, word3) + [ + f"v_mov_b32_e32 v1, {offset:#x}", + f"v_mov_b32_e32 v2, {d_lo:#x}", + f"v_mov_b32_e32 v3, {d_hi:#x}", + "v_cmp_eq_u32_e32 vcc_lo, 0, v0", + "s_and_saveexec_b32 s12, vcc_lo", + f"buffer_atomic_{kind}_x2 v[2:3], v1, s[8:11], 0 offen glc", + "s_mov_b32 exec_lo, s12", + "s_waitcnt vmcnt(0)", + ] + out_store_lines("v[2:3]", count=2, lane_stride=8) + eff = base + offset + init_mem = {0x40: m_lo, 0x44: m_hi, 0x48: m_lo, 0x4C: m_hi} + mem = run(body, init_mem, nlanes=2) + # Inactive lane 1 always preserves vdata[0:1] + self.assertEqual((mem.get(OUT + 8), mem.get(OUT + 12)), (d_lo, d_hi)) + if should_run: + self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (m_lo, m_hi)) + op_fn = {"swap": lambda a, b: b, "and": lambda a, b: a & b, + "or": lambda a, b: a | b, "xor": lambda a, b: a ^ b}[kind] + self.assertEqual((mem.get(eff), mem.get(eff + 4)), + (op_fn(m_lo, d_lo), op_fn(m_hi, d_hi))) + else: + self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0, 0)) + self.assertEqual((mem.get(0x40), mem.get(0x44)), (m_lo, m_hi)) + self.assertEqual((mem.get(0x48), mem.get(0x4C)), (m_lo, m_hi)) + + # Partial-bounds matrix matching native gfx1036 measurements across OOB_SELECT 0..3. + bounds_cases = [ + # (word3, stride, num_records, idx, offset, should_run) + (RAW_W3, 0, 8, None, 0, True), + (RAW_W3, 0, 16, None, 8, True), + (RAW_W3, 0, 7, None, 0, False), + (RAW_W3, 0, 5, None, 0, False), + (RAW_W3, 0, 4, None, 0, False), + (RAW_W3, 0, 15, None, 8, False), + (RAW_W3, 0, 12, None, 8, False), + (MODE0_W3, 8, 1, 0, 0, True), + (MODE0_W3, 16, 1, 0, 8, True), + (MODE0_W3, 12, 1, 0, 0, True), + (MODE0_W3, 7, 1, 0, 0, False), + (MODE0_W3, 12, 1, 0, 8, False), + (MODE0_W3, 8, 1, 1, 0, False), + (MODE1_W3, 0, 1, 0, 0, True), + (MODE1_W3, 0, 1, 0, 8, True), + (MODE1_W3, 0, 1, 1, 0, False), + (MODE2_W3, 0, 8, None, 8, True), + (MODE2_W3, 0, 0, None, 0, False), + ] + for word3, stride, num_records, idx, offset, should_run in bounds_cases: + with self.subTest(word3=hex(word3), stride=stride, num_records=num_records, idx=idx, offset=offset): + base = 0x40 + if idx is not None: + addr_setup = [f"v_mov_b32_e32 v1, {idx:#x}", f"v_mov_b32_e32 v2, {offset:#x}"] + vaddr, mods = "v[1:2]", "idxen offen glc" + else: + addr_setup = [f"v_mov_b32_e32 v1, {offset:#x}"] + vaddr, mods = "v1", "offen glc" + body = buf_rsrc_lines(base, stride, num_records, word3) + addr_setup + [ + f"v_mov_b32_e32 v4, {d_lo:#x}", + f"v_mov_b32_e32 v5, {d_hi:#x}", + f"buffer_atomic_swap_x2 v[4:5], {vaddr}, s[8:11], 0 {mods}", + "s_waitcnt vmcnt(0)", + ] + out_store_lines("v[4:5]", count=2, lane_stride=8) + eff = base + (idx * stride if idx is not None else 0) + offset + mem = run(body, {eff: m_lo, eff + 4: m_hi}) + if should_run: + self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (m_lo, m_hi)) + self.assertEqual((mem.get(eff), mem.get(eff + 4)), (d_lo, d_hi)) + else: + self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0, 0)) + self.assertEqual((mem.get(eff), mem.get(eff + 4)), (m_lo, m_hi)) + + def test_global_atomic_32bit_alignment(self): + init_m, data_d = 0x3F800000, 0x40000000 + for kind in ("add", "swap", "cmpswap", "fmin", "fmax"): + for vaddr, inst_off, should_run in ((TARGET + 1, 0, False), + (TARGET + 2, 0, False), + (TARGET, 2, False), + (TARGET + 2, -2, True)): + with self.subTest(op=kind, vaddr=hex(vaddr), inst_off=inst_off): + off_str = f" offset:{inst_off}" if inst_off else "" + vdata = "v[2:3]" if kind == "cmpswap" else "v2" + body = [ + f"v_mov_b32_e32 v1, {vaddr:#x}", + f"v_mov_b32_e32 v2, {data_d:#x}", + f"v_mov_b32_e32 v3, {init_m:#x}", + f"v_mov_b32_e32 v5, {SENTINEL:#x}", + "v_cmp_eq_u32_e32 vcc_lo, 0, v0", + "s_and_saveexec_b32 s4, vcc_lo", + f"global_atomic_{kind} v5, v1, {vdata}, s[0:1]{off_str} glc", + "s_mov_b32 exec_lo, s4", + "s_waitcnt vmcnt(0)", + "v_lshlrev_b32_e32 v6, 2, v0", + f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", + "global_store_dword v6, v5, s[0:1]", + ] + eff = vaddr + inst_off + mem = run(body, {TARGET: init_m}, nlanes=2) + # Inactive lane 1 always preserves vdst sentinel + self.assertEqual(mem.get(OUT + 4), SENTINEL) + if should_run: + self.assertEqual(mem.get(OUT), init_m) + expected_m = { + "add": (init_m + data_d) & M32, + "swap": data_d, + "cmpswap": data_d, + "fmin": init_m, + "fmax": data_d, + }[kind] + self.assertEqual(mem.get(eff), expected_m) + else: + # Active unaligned lane receives 0 in vdst (not SENTINEL), memory untouched + self.assertEqual(mem.get(OUT), 0) + self.assertEqual(mem.get(TARGET), init_m) + self.assertNotIn(eff, mem) + + def test_global_atomic_x2_alignment(self): + m_lo, m_hi = 0x11112222, 0x33334444 + d_lo, d_hi = 0x55556666, 0x77778888 + for kind in ("swap", "and", "or", "xor"): + for vaddr, inst_off, should_run in ((TARGET + 2, 0, False), + (TARGET + 4, 0, False), + (TARGET, 4, False), + (TARGET + 4, 4, True)): + with self.subTest(op=kind, vaddr=hex(vaddr), inst_off=inst_off): + off_str = f" offset:{inst_off}" if inst_off else "" + body = [ + f"v_mov_b32_e32 v1, {vaddr:#x}", + f"v_mov_b32_e32 v2, {d_lo:#x}", + f"v_mov_b32_e32 v3, {d_hi:#x}", + f"v_mov_b32_e32 v4, {SENTINEL:#x}", + f"v_mov_b32_e32 v5, {SENTINEL2:#x}", + "v_cmp_eq_u32_e32 vcc_lo, 0, v0", + "s_and_saveexec_b32 s4, vcc_lo", + f"global_atomic_{kind}_x2 v[4:5], v1, v[2:3], s[0:1]{off_str} glc", + "s_mov_b32 exec_lo, s4", + "s_waitcnt vmcnt(0)", + "v_lshlrev_b32_e32 v6, 3, v0", + f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", + "global_store_dwordx2 v6, v[4:5], s[0:1]", + ] + eff = vaddr + inst_off + init_mem = {TARGET: m_lo, TARGET + 4: m_hi, TARGET + 8: m_lo, TARGET + 12: m_hi} + mem = run(body, init_mem, nlanes=2) + # Inactive lane 1 always preserves vdst[0:1] + self.assertEqual((mem.get(OUT + 8), mem.get(OUT + 12)), (SENTINEL, SENTINEL2)) + if should_run: + self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (m_lo, m_hi)) + op_fn = {"swap": lambda a, b: b, "and": lambda a, b: a & b, + "or": lambda a, b: a | b, "xor": lambda a, b: a ^ b}[kind] + self.assertEqual((mem.get(eff), mem.get(eff + 4)), + (op_fn(m_lo, d_lo), op_fn(m_hi, d_hi))) + else: + self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0, 0)) + self.assertEqual((mem.get(TARGET), mem.get(TARGET + 4)), (m_lo, m_hi)) + self.assertEqual((mem.get(TARGET + 8), mem.get(TARGET + 12)), (m_lo, m_hi)) + + def test_spirv_emits_alignment_guard(self): + cases = [ + (buf_rsrc_lines(0, 0, 0x100, RAW_W3) + ["v_mov_b32_e32 v1, 0", + "buffer_atomic_add v2, v1, s[8:11], 0 offen glc"], "%c3"), + (buf_rsrc_lines(0, 0, 0x100, RAW_W3) + ["v_mov_b32_e32 v1, 0", + "buffer_atomic_fmin v2, v1, s[8:11], 0 offen glc"], "%c3"), + (buf_rsrc_lines(0, 0, 0x100, RAW_W3) + ["v_mov_b32_e32 v1, 0", + "buffer_atomic_xor_x2 v[2:3], v1, s[8:11], 0 offen glc"], "%c7"), + (["v_mov_b32_e32 v1, 0", "global_atomic_add v5, v1, v2, s[0:1] glc"], "%c3"), + (["v_mov_b32_e32 v1, 0", "global_atomic_fmax v5, v1, v2, s[0:1] glc"], "%c3"), + (["v_mov_b32_e32 v1, 0", "global_atomic_swap_x2 v[4:5], v1, v[2:3], s[0:1] glc"], "%c7"), + ] + for body, mask_const in cases: + with self.subTest(insn=body[-1]): + spv = translate(body) + self.assertIn("OpUConvert %uint", spv) + self.assertIn("OpBitwiseAnd %uint", spv) + self.assertIn(mask_const, spv) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_buffer_load_format.py b/tests/semantic/test_buffer_load_format.py index cadb8f3ea..fd0f0d170 100644 --- a/tests/semantic/test_buffer_load_format.py +++ b/tests/semantic/test_buffer_load_format.py @@ -9,6 +9,7 @@ Integer and f16 formats are used: their decode is exact, so the expected words n """ from __future__ import annotations +import atexit import os import struct import sys @@ -40,11 +41,21 @@ DST_SEL_X_0_1_1 = 4 | 0 << 3 | 1 << 6 | 1 << 9 _TMP_DIR = None _SRC_PATH = None +_EXIT_CLEANUP = False def setUpModule(): - global _TMP_DIR, _SRC_PATH + global _TMP_DIR, _SRC_PATH, _EXIT_CLEANUP + if _TMP_DIR is not None: + return # load_format() may have created it already; replacing it would leak the first one _TMP_DIR = tempfile.TemporaryDirectory() + # test_norm_decode imports load_format() and runs after this module's teardown, which recreates the folder; + # unittest never tears this module down again. Registered once, after the first TemporaryDirectory, so it runs + # before tempfile's own exit finalizer (atexit is last in, first out) and that finalizer stays quiet; + # tearDownModule() cleans whichever folder is live at exit. + if not _EXIT_CLEANUP: + atexit.register(tearDownModule) + _EXIT_CLEANUP = True disasm_dir = os.path.join(_TMP_DIR.name, "disasm") os.mkdir(disasm_dir) _SRC_PATH = os.path.join(disasm_dir, "ps_buf_fmt.s") diff --git a/tests/semantic/test_cs_barrier_counts_lds.py b/tests/semantic/test_cs_barrier_counts_lds.py new file mode 100644 index 000000000..7108ebb9e --- /dev/null +++ b/tests/semantic/test_cs_barrier_counts_lds.py @@ -0,0 +1,183 @@ +"""SHADER-579: the barrier-round count no longer pushes a full-LDS wave32 compute shader over the device limit. + +A native wave32 compute shader whose s_barrier is not in uniform control flow runs in barrier rounds (SHADER-91, +`bar_scheduler`). The round loop counts the invocations not done in `%x_buf`, three Workgroup dwords (#930). On top of +a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows and +Intel drivers, so the runtime check (SHADER-309) refused those pipelines there. When the 12 bytes would take the total +past 16,384 B (the Vulkan minimum), the count now borrows LDS word 0 between rounds instead: invocation 0 saves the +word, the count runs in it, invocation 0 puts it back, each step behind a workgroup barrier while no invocation runs +shader code. Smaller shaders keep `%x_buf` and the single barrier per round. + +The Workgroup bytes are counted from the emitted SPIR-V; the barrier behaviour runs in the workgroup interpreter of +test_loop_ballot_barrier.py, whose LDS starts as 0xDEADBEEF. The programs are written here; no game data. +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path + +import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) +import test_cs_shared_memory_limit as shl # noqa: E402 (module import: its TestCase stays out of this module) +import test_loop_ballot_barrier as lbb # noqa: E402 + +rdna2spirv = support.rdna2spirv +VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # raw buffer V# at base 0 in s[0:3] + + +def ring_shift(threads=64, iters=5): + """s_barrier in a loop (barrier rounds): each iteration thread t writes its value to lds[t], s_barrier, reads + lds[(t + 1) % threads] and adds 100, s_barrier. Thread 63 reads LDS word 0, the word the count borrows.""" + return [ + "v_add_nc_u32_e32 v1, 1000, v0", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_add_nc_u32_e32 v3, 1, v0", + f"v_and_b32_e32 v3, {threads - 1}, v3", + "v_lshlrev_b32_e32 v3, 2, v3", + "s_mov_b32 s8, 0", + "loop:", + "ds_write_b32 v2, v1", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "ds_read_b32 v1, v3", + "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32_e32 v1, 100, v1", + "s_barrier", + "s_add_u32 s8, s8, 1", + f"s_cmp_lt_u32 s8, {iters}", + "s_cbranch_scc1 loop", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + "s_endpgm", + ] + + +def early_end(): + """Wave 0 runs 2 iterations of a barrier loop and ends, wave 1 runs 4: a wave that is done no longer counts. + Each thread keeps its count in its own LDS word, so thread 0's lives in the borrowed word.""" + return [ + "v_lshrrev_b32_e32 v1, 5, v0", + "v_readfirstlane_b32 s8, v1", + "s_lshl_b32 s9, s8, 1", + "s_add_u32 s9, s9, 2", + "s_mov_b32 s12, 0", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_mov_b32_e32 v3, 0", + "loop:", + "ds_write_b32 v2, v3", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "ds_read_b32 v4, v2", + "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32_e32 v3, 1, v4", + "s_add_u32 s12, s12, 1", + "s_cmp_lt_u32 s12, s9", + "s_cbranch_scc1 loop", + "buffer_store_dword v3, v2, s[0:3], 0 offen", + "s_endpgm", + ] + + +def translate(items, lds_units, threads=64, limit=None): + """Native wave32 compute shader of `threads` invocations with LDS_SIZE `lds_units` (512-byte units): 8 user + SGPRs and TGID_X in RSRC2, nothing else. Returns (SPIR-V text, generator).""" + lines = [f"{text} ; encoding: [{','.join(['0x00'] * size)}]" for text, size in lbb._resolve_labels(items)] + header = bytes(0x138) + struct.pack("<4I", 0x90 | (lds_units << 15), threads, 1, 1) + prev = rdna2spirv.WAVE64_EMULATE, rdna2spirv.MAX_SHARED_BYTES + rdna2spirv.WAVE64_EMULATE = False + if limit is not None: + rdna2spirv.MAX_SHARED_BYTES = limit + try: + spv = support.translate_lines("cs_bar_counts", lines, fssm=header) + finally: + rdna2spirv.WAVE64_EMULATE, rdna2spirv.MAX_SHARED_BYTES = prev + gen = rdna2spirv.translate.last_gen + assert not gen.wave64, "the test program must translate as wave32" + return spv, gen + + +def run(spv, threads=64): + """Output dwords of thread 0..threads-1, for both wave orders.""" + out = [] + for rev in (False, True): + mem = lbb.run_compute_workgroup(spv, threads, 32, push_constants=VSHARP, reverse_subgroups=rev) + out.append([mem.get(4 * t) for t in range(threads)]) + return out + + +RING = [1000 + (t + 5) % 64 + 500 for t in range(64)] + + +class BarrierCountsInLdsTests(unittest.TestCase): + def test_full_32k_lds_is_exactly_32768_bytes(self): + # the finding: 32 KiB LDS + the 12-byte count was 32,780 B; now the count is in the LDS array + spv, gen = translate(ring_shift(), 64) + self.assertTrue(gen.bar_rounds) + self.assertEqual(gen.control_flow, "barrier rounds") + wg = shl.workgroup_bytes(spv) + self.assertEqual(wg, {"%lds": 32768}) + self.assertLessEqual(sum(wg.values()), 32768) + self.assertEqual(rdna2spirv.shader_meta(gen, spv)["lds_bytes"], 32768) + self.assertNotIn("%x_buf", spv) + + def test_full_32k_lds_translates_under_a_32k_cap(self): + # --max-shared-memory 32768 (the AMD Windows / Intel limit): accepted, the array not shrunk + spv, _ = translate(ring_shift(), 64, limit=32768) + self.assertEqual(shl.workgroup_bytes(spv), {"%lds": 32768}) + self.assertEqual(shl.lds_index_ops(spv), {"OpBitwiseAnd"}) + + def test_full_64k_lds_fits_the_hard_cap(self): + # before: 65,548 B, shrunk or refused; now exactly the 64 KiB cap with the power-of-two array + spv, _ = translate(ring_shift(), 128) + self.assertEqual(shl.workgroup_bytes(spv), {"%lds": 65536}) + self.assertEqual(shl.lds_index_ops(spv), {"OpBitwiseAnd"}) + + def test_barrier_rounds_still_exact_with_the_borrowed_word(self): + # the ring shift reads every LDS word another thread wrote, word 0 included, across 10 barriers + for units in (32, 64, 128): + with self.subTest(units=units): + spv, gen = translate(ring_shift(), units) + self.assertTrue(gen.bar_counts_in_lds()) + self.assertEqual(run(spv), [RING, RING]) + + def test_a_wave_that_ends_no_longer_counts(self): + spv, gen = translate(early_end(), 64) + self.assertTrue(gen.bar_counts_in_lds()) + self.assertEqual(run(spv), [[2] * 32 + [4] * 32] * 2) + + def test_small_lds_keeps_x_buf_and_one_barrier_per_round(self): + # 8 KiB + 12 B fits every device: the three Workgroup counts, the barrier rounds as before + for units in (1, 16): + with self.subTest(units=units): + spv, gen = translate(ring_shift(), units) + self.assertTrue(gen.bar_rounds) + self.assertFalse(gen.bar_counts_in_lds()) + wg = shl.workgroup_bytes(spv) + self.assertEqual(wg["%x_buf"], 12) + self.assertEqual(rdna2spirv.shader_meta(gen, spv)["lds_bytes"], sum(wg.values())) + self.assertEqual(spv.count("OpControlBarrier"), 2) + self.assertEqual(run(spv), [RING, RING]) + + def test_no_lds_access_keeps_x_buf(self): + # a 32 KiB allocation the program never touches: no LDS array to borrow from, the 12 bytes stay + items = [ln for ln in ring_shift() if not ln.startswith(("ds_", "s_waitcnt"))] + spv, gen = translate(items, 64) + self.assertTrue(gen.bar_rounds) + self.assertFalse(gen.uses_lds) + self.assertEqual(shl.workgroup_bytes(spv), {"%x_buf": 12}) + + def test_top_level_barrier_has_no_count(self): + # a barrier every invocation reaches stays one OpControlBarrier: no rounds, nothing added to the LDS + items = ["v_lshlrev_b32_e32 v2, 2, v0", "ds_write_b32 v2, v0", "s_waitcnt lgkmcnt(0)", "s_barrier", + "ds_read_b32 v1, v2 offset:4", "s_waitcnt lgkmcnt(0)", + "buffer_store_dword v1, v2, s[0:3], 0 offen", "s_endpgm"] + spv, gen = translate(items, 64) + self.assertFalse(gen.bar_rounds) + self.assertEqual(shl.workgroup_bytes(spv), {"%lds": 32768}) + self.assertEqual(spv.count("OpControlBarrier"), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_cvt_norm_mods.py b/tests/semantic/test_cvt_norm_mods.py new file mode 100644 index 000000000..af8e059d3 --- /dev/null +++ b/tests/semantic/test_cvt_norm_mods.py @@ -0,0 +1,254 @@ +"""Semantic interpreter and SPIR-V validation tests for RDNA2 output modifiers on +v_cvt_norm_{i16,u16}_f16 and v_cvt_pknorm_{i16,u16}_f32. + +Covers native RDNA2 (gfx1036, wave32 & wave64) measured hardware no-op rules: +- v_cvt_norm_i16_f16 / v_cvt_norm_u16_f16: VOP3 clamp, mul:2, mul:4, div:2 (and combinations) + and SDWA clamp are hardware no-ops while still preserving the unwritten destination half; + unsupported modifiers and invalid form/modifier pairs raise Unsupported. +- v_cvt_pknorm_i16_f32 / v_cvt_pknorm_u16_f32: VOP3 clamp is a hardware no-op; mul:*/div:*/op_sel + raise Unsupported. +""" +from __future__ import annotations + +import os +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +for p in (TOOLS_DIR, HERE): + if p not in sys.path: + sys.path.insert(0, p) + +import cvt_norm_mods_probe as cnp # noqa: E402 +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M16 = 0xFFFF +M32 = 0xFFFFFFFF +SEED_DST = 0xCAFE1234 +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: + if _TMP_DIR is None: + setUpModule() + if export_tail is None: + export_tail = [ + "v_and_b32 v5, 0xffff, v0", + "v_lshrrev_b32 v6, 16, v0", + "v_or_b32 v5, 0x40000000, v5", + "v_or_b32 v6, 0x40000000, v6", + "exp mrt0 v5, v6, v5, v5 done vm", + ] + asm_text = "; test_cvt_norm_mods\n" + "".join(f"\t{ln}\n" for ln in list(lines) + export_tail) + "\ts_endpgm\n" + with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: + f.write(asm_text) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(_SRC_PATH) + + +def run_v0(lines: list[str]) -> tuple[str, int]: + spv = translate_ps(lines) + lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] + assert (lo >> 16) == 0x4000 and (hi >> 16) == 0x4000, (hex(lo), hex(hi)) + return spv, (lo & M16) | ((hi & M16) << 16) + + +def validate_spirv(spv_text: str) -> None: + spirv_as = shutil.which("spirv-as") + spirv_val = shutil.which("spirv-val") + if not spirv_as or not spirv_val: + return + with tempfile.TemporaryDirectory() as d: + asm_p = os.path.join(d, "s.spvasm") + bin_p = os.path.join(d, "s.spv") + with open(asm_p, "w", encoding="utf-8", newline="\n") as f: + f.write(spv_text) + r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", bin_p], capture_output=True, text=True) + if r1.returncode != 0: + raise AssertionError(f"spirv-as failed: {r1.stderr}") + r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", bin_p], capture_output=True, text=True) + if r2.returncode != 0: + raise AssertionError(f"spirv-val failed: {r2.stderr}") + + +class CvtNormOutputModsTests(unittest.TestCase): + def test_vop3_output_modifiers_match_plain_across_edges_and_ties(self): + edges = ( + 0x0000, 0x8000, # +0, -0 + 0x0001, 0x8001, 0x03FF, # subnormals + 0x37FF, 0x3800, 0x3801, # +0.5 single-rounding ties + 0xB7FF, 0xB800, 0xB801, # -0.5 single-rounding ties + 0x3C00, 0xBC00, # +-1.0 + 0x4000, 0xC000, # +-2.0 + 0x7C00, 0xFC00, # +-inf + 0x7E00, 0x7C01, 0xFE00, # qNaN / sNaN + ) + for op in cnp.NORM_F16_OPS: + snorm = op == "v_cvt_norm_i16_f16" + for mod in ("clamp", "mul:2", "mul:4", "div:2", "clamp mul:2", "clamp div:2"): + for h in edges: + want = (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(h, snorm) + with self.subTest(op=op, mod=mod, h=hex(h)): + _, got = run_v0([ + f"v_mov_b32 v1, {(0xDEAD0000 | h):#x}", + f"v_mov_b32 v0, {SEED_DST:#x}", + f"{op}_e64 v0, v1 {mod}", + ]) + self.assertEqual(got, want) + + def test_vop3_abs_neg_and_opsel_with_output_modifiers(self): + # v1 = {hi=+0.75 (0x3A00), lo=-0.5 (0xB800)} + packed = 0x3A00B800 + cases = ( + ("v_cvt_norm_i16_f16_e64 v0, |v1| clamp", (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(0x3800, True)), + ("v_cvt_norm_i16_f16_e64 v0, -v1 mul:2", (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(0x3800, True)), + ("v_cvt_norm_u16_f16_e64 v0, -|v1| div:2", (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(0xB800, False)), + ("v_cvt_norm_i16_f16_e64 v0, v1 op_sel:[1,0] clamp", (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(0x3A00, True)), + ("v_cvt_norm_u16_f16_e64 v0, |v1| op_sel:[0,1] mul:2", (cnp.expected_norm_f16(0x3800, False) << 16) | (SEED_DST & M16)), + ("v_cvt_norm_i16_f16_e64 v0, -v1 op_sel:[1,1] div:2", (cnp.expected_norm_f16(0xBA00, True) << 16) | (SEED_DST & M16)), + ) + for inst, want in cases: + with self.subTest(inst=inst): + _, got = run_v0([f"v_mov_b32 v1, {packed:#x}", f"v_mov_b32 v0, {SEED_DST:#x}", inst]) + self.assertEqual(got, want) + + def test_sdwa_clamp_across_word_and_dst_unused_forms(self): + for op in cnp.NORM_F16_OPS: + want_words = cnp.expected_sdwa_words(op) + for idx, (label, seed_v0, src_v1, _, src_expr, tail) in enumerate(cnp.SDWA_CASES): + with self.subTest(op=op, case=label): + _, got_plain = run_v0([ + f"v_mov_b32 v0, {seed_v0:#x}", + f"v_mov_b32 v1, {src_v1:#x}", + f"{op}_sdwa v0, {src_expr} {tail}", + ]) + _, got_clamp = run_v0([ + f"v_mov_b32 v0, {seed_v0:#x}", + f"v_mov_b32 v1, {src_v1:#x}", + f"{op}_sdwa v0, {src_expr} clamp {tail}", + ]) + self.assertEqual(got_plain, want_words[idx]) + self.assertEqual(got_clamp, want_words[idx]) + + def test_pknorm_clamp_matches_plain_across_edges_nearties_and_aliasing(self): + pairs = ( + (0x00000000, 0x80000000), # +0, -0 + (0x00000001, 0x807FFFFF), # subnormals + (0x38400180, 0x3C014103), # single-rounding near-ties (i16) + (0x37C000C0, 0x3B028083), # single-rounding near-ties (u16) + (0x3F000000, 0xBF000000), # +-0.5 + (0x3F800000, 0xBF800000), # +-1.0 + (0x40000000, 0xC0000000), # +-2.0 (clamped to +-1.0) + (0x7F800000, 0xFF800000), # +-inf + (0x7FC00000, 0xFF800001), # qNaN / sNaN + ) + for op in cnp.PKNORM_F32_OPS: + for a, b in pairs: + want = cnp.expected_pknorm_f32(op, a, b) + with self.subTest(op=op, a=hex(a), b=hex(b)): + _, got = run_v0([ + f"v_mov_b32 v1, {a:#x}", + f"v_mov_b32 v2, {b:#x}", + "v_mov_b32 v0, 0xdeadbeef", + f"{op} v0, v1, v2 clamp", + ]) + self.assertEqual(got, want) + # Source modifiers + destination aliasing (v0 == src0) with clamp + want_alias = cnp.expected_pknorm_f32(op, 0xBF000000, 0x3F000000) + _, got_alias = run_v0([ + "v_mov_b32 v0, 0x3f000000", # +0.5 -> negated to -0.5 + "v_mov_b32 v1, 0xbf000000", # -0.5 -> abs to +0.5 + f"{op} v0, -v0, |v1| clamp", + ]) + self.assertEqual(got_alias, want_alias) + + def test_inactive_exec_lane_preserved(self): + for inst in ( + "v_cvt_norm_i16_f16_e64 v0, v1 clamp", + "v_cvt_norm_u16_f16_e64 v0, v1 mul:2", + "v_cvt_norm_i16_f16_sdwa v0, v1 clamp dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + "v_cvt_pknorm_i16_f32 v0, v1, v2 clamp", + "v_cvt_pknorm_u16_f32 v0, v1, v2 clamp", + ): + with self.subTest(inst=inst): + _, got = run_v0([ + "v_mov_b32 v0, 0xdeadbeef", + "v_mov_b32 v1, 0x38003c00", + "v_mov_b32 v2, 0x3f000000", + "s_mov_b32 exec_lo, 0", + inst, + "s_mov_b32 exec_lo, 1", + ]) + self.assertEqual(got, 0xDEADBEEF) + + def test_spirv_val_combined_shader(self): + spv = translate_ps([ + "v_mov_b32 v0, 0x12345678", + "v_mov_b32 v1, 0x3800b800", + "v_mov_b32 v2, 0x3f000000", + "v_mov_b32 v3, 0xbf000000", + "v_cvt_norm_i16_f16_e64 v0, v1 clamp", + "v_cvt_norm_i16_f16_e64 v0, v1 mul:2", + "v_cvt_norm_u16_f16_e64 v0, |v1| div:2", + "v_cvt_norm_u16_f16_e64 v0, v1 clamp mul:4", + "v_cvt_norm_i16_f16_sdwa v0, v1 clamp dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + "v_cvt_pknorm_i16_f32 v0, v2, v3 clamp", + "v_cvt_pknorm_u16_f32 v0, -v3, |v2| clamp", + ]) + validate_spirv(spv) + + def test_rejected_invalid_modifiers_and_forms(self): + bad_lines = ( + "v_cvt_norm_i16_f16_e64 v0, v1 mul:8", + "v_cvt_norm_u16_f16_e64 v0, v1 div:4", + "v_cvt_norm_i16_f16_sdwa v0, v1 mul:2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + "v_cvt_norm_u16_f16_sdwa v0, v1 op_sel:[1,0] dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_norm_i16_f16_e32 v0, v1 clamp", + "v_cvt_norm_u16_f16_dpp v0, v1 clamp quad_perm:[0,1,2,3]", + "v_cvt_pknorm_i16_f32 v0, v1, v2 mul:2", + "v_cvt_pknorm_u16_f32 v0, v1, v2 div:2", + "v_cvt_pknorm_i16_f32 v0, v1, v2 op_sel:[1,0,0]", + ) + for line in bad_lines: + with self.subTest(line=line): + with self.assertRaises(rdna2spirv.Unsupported): + translate_ps([ + "v_mov_b32 v1, 0x3800", + "v_mov_b32 v2, 0x3f000000", + line, + ]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_dpp_eager_subgroup.py b/tests/semantic/test_dpp_eager_subgroup.py new file mode 100644 index 000000000..ca1790b6d --- /dev/null +++ b/tests/semantic/test_dpp_eager_subgroup.py @@ -0,0 +1,201 @@ +"""DPP's ballot and shuffle run in every lane, also after SPIRV-Cross inlines expressions (SHADER-529). + +SPIRV-Cross (MoltenVK) inlines a result that is used once into the expression that uses it. On the right of an +OpLogicalAnd/OpLogicalOr that becomes a short-circuiting && / ||, and in an arm of a scalar OpSelect a ternary, so +a subgroup op there runs only in the lanes that get that far. The DPP lowering used to give +`in_row && subgroupBallotBitExtract(subgroupBallot(active), src)` and `src_ok ? subgroupShuffle(v, src) : 0`: on a +Mac, row_shr:1's lane 1 found lane 0 (out of its row, so it skipped the ballot) inactive and kept its old value +(`cs_dpp_ops`). The translator now stores both results to Function variables (`Gen.eager`), and a store is a +statement every lane runs. + +`conditional_subgroup_ops` follows each subgroup op's result through single-use expressions, the ones SPIRV-Cross +inlines, and reports one that lands on the right of a logical and/or or in a scalar select's arm. It is a model of +SPIRV-Cross's forwarding, not SPIRV-Cross: checked against SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` GPU tests, +where it finds exactly the inlined ballots and shuffles before this change and none after. The values are checked +too, by running the translated DPP in tests/semantic/spirv_wave_interp.py. + +Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. +""" +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import support # noqa: E402 (puts tools/ on the path) +import spirv_wave_interp as wi # noqa: E402 + +# Group ops whose result depends only on their operands' values, not on which invocations run them. +_PURE = frozenset({"OpGroupNonUniformBallotBitExtract", "OpGroupNonUniformBallotBitCount", + "OpGroupNonUniformBallotFindLSB", "OpGroupNonUniformBallotFindMSB", + "OpGroupNonUniformInverseBallot"}) + + +def _parse(text): + insns = [] + for ln in text.splitlines(): + t = ln.split(";", 1)[0].split() + if not t: + continue + if len(t) > 2 and t[1] == "=": + insns.append((t[0], t[2], t[3:])) + else: + insns.append((None, t[0], t[1:])) + return insns + + +def conditional_subgroup_ops(spvasm): + """[(result id, opcode, where)] for each subgroup op SPIRV-Cross would inline into a conditional position.""" + insns = _parse(spvasm) + types, uses = {}, {} + for i, (res, op, args) in enumerate(insns): + if res: + types[res] = args[0] if args else None + for pos, a in enumerate(args[1:] if res else args): # a result's first operand is its type + if a.startswith("%"): + uses.setdefault(a, []).append((i, pos)) + found = [] + for res, op, _ in insns: + if not (res and op.startswith("OpGroupNonUniform") and op not in _PURE): + continue + cur = res + while len(uses.get(cur, ())) == 1: # used more than once: SPIRV-Cross makes it a temporary + i, pos = uses[cur][0] + ures, uop, uargs = insns[i] + if uop in ("OpLogicalAnd", "OpLogicalOr") and pos == 1: + found.append((res, op, f"right of {uop} {ures}")) + break + if uop == "OpSelect" and pos in (1, 2) and types.get(uargs[1]) == "%bool": + found.append((res, op, f"arm of OpSelect {ures}")) + break + if ures is None or uop == "OpPhi": # a statement (store, branch) or a phi copy: every lane runs it + break + cur = ures + return found + + +DPP_FORMS = [ + "row_shr:1 row_mask:0xf bank_mask:0xf", + "row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1", + "row_shl:3 row_mask:0xf bank_mask:0xf", + "row_ror:5 row_mask:0xf bank_mask:0xf", + "row_mirror row_mask:0xf bank_mask:0xf", + "row_half_mirror row_mask:0x5 bank_mask:0xa", + "row_share:2 row_mask:0xf bank_mask:0xf", + "row_xmask:7 row_mask:0xf bank_mask:0xf", + "quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", + "dpp8:[1,0,3,2,5,4,7,6]", + "dpp8:[7,6,5,4,3,2,1,0] fi:1", +] + + +def dpp_vs(form, exec_off=None): + """A vertex shader: v6 = 100, then v6 = v0 (the lane) + 10 through DPP `form`, with lane `exec_off` off in + EXEC for the DPP; param0.x exports v6.""" + lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", "v_mov_b32 v1, 10", "v_mov_b32 v6, 100", "s_mov_b32 s10, exec_lo"] + if exec_off is not None: + lines.append(f"v_cmpx_ne_u32_e32 {exec_off}, v0") + lines += [f"v_add_nc_u32_dpp v6, v0, v1 {form}", "s_mov_b32 exec_lo, s10", "v_mov_b32 v5, 0", + "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v5, v5, v5", "s_endpgm"] + return support.translate_lines("vs_dpp_eager", lines) + + +def dpp_reference(form, exec_off=None, wave=32): + """v6 per lane after dpp_vs(form, exec_off), from the RDNA2 DPP rules (docs/design.md, Gen.dpp_insn).""" + mods = form.split() + get = lambda key, d: next((int(m.split(":")[1], 0) for m in mods if m.startswith(key + ":")), d) # noqa: E731 + row_mask, bank_mask, bound, fi = get("row_mask", 0xF), get("bank_mask", 0xF), get("bound_ctrl", 0), get("fi", 0) + active = [lane != exec_off for lane in range(wave)] + out = [] + for lane in range(wave): + loc, ok = lane & 15, True + if mods[0].startswith("dpp8:"): + sel = [int(x) for x in mods[0][6:-1].split(",")] + src = (lane & ~7) | sel[lane & 7] + elif mods[0].startswith("quad_perm:"): + sel = [int(x) for x in mods[0][11:-1].split(",")] + src = (lane & ~3) | sel[lane & 3] + else: + kind = mods[0].split(":")[0] + n = get(kind, 0) + if kind == "row_shr": + ok, s = loc >= n, loc - n + elif kind == "row_shl": + ok, s = loc + n < 16, loc + n + elif kind == "row_ror": + s = (loc - n) & 15 + elif kind == "row_share": + s = n + elif kind == "row_xmask": + s = loc ^ n + elif kind == "row_mirror": + s = 15 - loc + else: # row_half_mirror + s = (loc & 8) | (7 - (loc & 7)) + src = (lane & ~15) | (s & 15) + dpp8 = mods[0].startswith("dpp8:") + enabled = dpp8 or ((row_mask >> (lane >> 4)) & 1 and (bank_mask >> ((lane >> 2) & 3)) & 1) + valid = ok and (active[src] or (dpp8 and fi)) + if not active[lane] or not enabled or (not valid and not dpp8 and not bound): + out.append(100) # not written: keeps its old value + else: + out.append((src if valid else 0) + 10) + return out + + +class ConditionalSubgroupOpsModel(unittest.TestCase): + """The checker against hand-written SPIR-V: it must find the old DPP pattern and leave the safe ones alone.""" + + HEAD = "%b = OpGroupNonUniformBallot %v4uint_bal %c3 %act\n" \ + "%e = OpGroupNonUniformBallotBitExtract %bool %c3 %b %src\n" + + def test_ballot_on_the_right_of_and(self): + found = conditional_subgroup_ops(self.HEAD + "%a = OpLogicalAnd %bool %in_row %e\nOpStore %x %a\n") + self.assertEqual([(r, op) for r, op, _ in found], [("%b", "OpGroupNonUniformBallot")]) + + def test_shuffle_in_a_select_arm(self): + text = "%ok = OpINotEqual %bool %x %c0\n%s = OpGroupNonUniformShuffle %uint %c3 %v %src\n" \ + "%t = OpIAdd %uint %s %c1\n%r = OpSelect %uint %ok %t %c0\nOpStore %y %r\n" + self.assertEqual([op for _, op, _ in conditional_subgroup_ops(text)], ["OpGroupNonUniformShuffle"]) + + def test_safe_positions(self): + for tail in ("%a = OpLogicalAnd %bool %e %in_row\nOpStore %x %a\n", # left of &&: always runs + "%r = OpSelect %uint %e %c1 %c0\nOpStore %x %r\n", # the condition: always runs + "OpStore %x %e\n%a = OpLogicalAnd %bool %in_row %e\n", # two uses: a temporary + "OpStore %x %e\n"): + with self.subTest(tail=tail.split("\n")[0]): + self.assertEqual(conditional_subgroup_ops(self.HEAD + tail), []) + + def test_vector_select_is_not_a_ternary(self): + text = "%s = OpGroupNonUniformShuffle %v2uint %c3 %v %src\n" \ + "%r = OpSelect %v2uint %cond2 %s %zero2\nOpStore %y %r\n" + self.assertEqual(conditional_subgroup_ops(text), []) + + +class DppSubgroupOpsRunInEveryLane(unittest.TestCase): + def test_no_dpp_subgroup_op_is_conditional(self): + for form in DPP_FORMS: + for exec_off in (None, 5): + with self.subTest(form=form, exec_off=exec_off): + spv = dpp_vs(form, exec_off) + self.assertIn("OpGroupNonUniformShuffle", spv) + self.assertEqual(conditional_subgroup_ops(spv), []) + + def test_values(self): + for form in DPP_FORMS: + for exec_off in (None, 5, 16): + with self.subTest(form=form, exec_off=exec_off): + res = wi.run_wave(dpp_vs(form, exec_off), wave=32, + builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) + got = [o["%out_param0"][0] for o in res["outputs"]] + self.assertEqual(got, dpp_reference(form, exec_off)) + + def test_reference_matches_cs_dpp_ops(self): + # runtime/test/shaders/cs_dpp_ops.asm: out[0..7] = 100 10 11 12 13 14 15 16. + self.assertEqual(dpp_reference("row_shr:1 row_mask:0xf bank_mask:0xf")[:8], + [100, 10, 11, 12, 13, 14, 15, 16]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_export_valid_mask.py b/tests/semantic/test_export_valid_mask.py index 0b77a7d0f..34362ce9f 100644 --- a/tests/semantic/test_export_valid_mask.py +++ b/tests/semantic/test_export_valid_mask.py @@ -4,6 +4,7 @@ RDNA2 ISA reference guide (30-November-2020), 11.1 and 11.2.1: with VM set EXEC sent is used, and an export to NULL may carry only the mask. Not measured on hardware; docs/design.md, EXEC. Hand-written programs, no tools needed. """ +from pathlib import Path import unittest import support @@ -46,6 +47,28 @@ class StraightLine(unittest.TestCase): def check(self, lines, want): self.assertEqual(run_fragment(translate(SEED + lines + END)), want) + def test_disjoint_color_exports_accumulate_per_target(self) -> None: + fixture = Path(__file__).with_name("fixtures") / "partial_color_exports.asm" + shader = support.translate_lines("ps_partial_exports", fixture.read_text(encoding="ascii").splitlines()) + self.assertEqual(run_fragment(shader), { + "%out_mrt0": (0x3F800000, 0x40000000, 0x40400000, 0x40800000), + "%out_mrt1": (0x40A00000, 0x40C00000, 0x40E00000, 0x41000000), + }) + + def test_first_partial_color_export_has_zero_unwritten_channels(self) -> None: + lines = ["exp mrt0 off, v2, off, v2 done vm"] + shader = translate(SEED + lines + END) + self.assertEqual(run_fragment(shader), {"%out_mrt0": (0, ONE, 0, ONE)}) + # The interpreter defaults unwritten outputs to zero. Vulkan needs an explicit initializer here. + self.assertIn("%initial_mrt = OpConstantNull %v4float", shader) + self.assertIn("%out_mrt0 = OpVariable %_ptr_Output_v4 Output %initial_mrt", shader) + + def test_partial_export_obeys_exec_and_replaces_enabled_channels(self) -> None: + lines = ["v_mov_b32_e32 v3, 0x40000000", "exp mrt0 v2, v2, v2, v2", "s_waitcnt expcnt(0)"] + OFF + lines += ["exp mrt0 off, v3, v3, off", "s_waitcnt expcnt(0)"] + ON + lines += ["exp mrt0 off, off, v3, off done vm"] + self.check(lines, {"%out_mrt0": (ONE, ONE, 0x40000000, ONE)}) + def test_exec_unchanged_after_the_export(self): self.check(EXP, MRT0) self.check(OFF + EXP, KILLED) diff --git a/tests/semantic/test_far_branch.py b/tests/semantic/test_far_branch.py new file mode 100644 index 000000000..4e7a123c3 --- /dev/null +++ b/tests/semantic/test_far_branch.py @@ -0,0 +1,82 @@ +"""Far branches: s_getpc_b64; s_add_u32 K / s_addc_u32 0|-1 (or s_sub_u32 / s_subb_u32); s_setpc_b64. + +RDNA2 ISA: s_getpc_b64 returns the address of the next instruction, s_add_u32 / s_addc_u32 add a 64-bit K (high word 0 +forward, 0xffffffff backward) with SCC as the carry, s_setpc_b64 jumps there. The shader is +runtime/test/shaders/ps_far_branch.asm (also run on the GPU by check.py and run_gpu_tests.py); its header derives the +four words by hand. The reference here runs the same loops in plain Python on the byte distances of the header. +""" +import os +import re +import unittest + +import support + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +FIXTURE = os.path.join(HERE, "fixtures", "disasm", "ps_far_branch.s") +ASM = os.path.join(ROOT, "runtime", "test", "shaders", "ps_far_branch.asm") + +EXPECTED = [0x00000007, 0x00000013, 0x00000051, 0x0000000B] # derivation in ps_far_branch.asm + + +def reference(): + x = 1 | 2 | 4 # two forward far branches skip the poison ORs 0x100 and 0x200 + s11, back = 0, 0 # loop with s_sub_u32 / s_subb_u32: leaves when s11 >= 3 + while True: + s11 += 1 + if s11 >= 3: + break + back += 1 + y = s11 | 0x10 + s12 = 0 # loop with s_add_u32 -180 / s_addc_u32 -1: leaves when s12 >= 0x50 + while True: + s12 += 0x10 + if s12 >= 0x50: + break + z = s12 | 1 + w = 0 + for compare, bit_before, bit_target in ((1, 1, 2), (3, 4, 8)): + if w == compare: # scc = 1: the far branch runs and skips the bit_before OR + w |= bit_target + else: # scc = 0: the branch over the far-branch sequence is taken + w |= bit_before + w |= bit_target + return [x, y, z, w] + + +class FarBranch(unittest.TestCase): + def test_reference_matches_the_header_words(self): + self.assertEqual([f"{w:#010x}" for w in reference()], [f"{w:#010x}" for w in EXPECTED]) + + def test_listing_is_the_asm(self): + """The listing has the `; encoding:` comments the branches need (regen_fixtures.py writes none), so it is + llvm-mc output; its mnemonics must be those of the .asm, in order.""" + def mnemonics(lines): + return [re.sub(r"_e32$", "", ln.split()[0]) for ln in lines] + with open(ASM, encoding="utf-8") as f: + asm = [ln.strip() for ln in f if ln.strip() and not ln.lstrip().startswith(";")] + with open(FIXTURE, encoding="utf-8") as f: + listing = [ln.strip() for ln in f.read().splitlines()[1:] if ln.strip()] + self.assertEqual(mnemonics(listing), mnemonics(asm)) + + def test_ps_far_branch(self): + with open(FIXTURE, "rb") as f: + spv = support.translate_listing("ps_far_branch", f.read()) + words = support.mrt0_words(spv) + self.assertEqual([f"{w:#010x}" for w in words], [f"{w:#010x}" for w in EXPECTED]) + + +class FarBranchWithoutEncoding(unittest.TestCase): + def test_idiom_without_encoding_is_unsupported_not_a_crash(self): + """A hand-written listing has no `; encoding:` bytes, so the idiom's size is unknown: Unsupported, as for a + lone s_getpc_b64 (test_missing_encoding.py), not a TypeError from joining the missing encodings.""" + import rdna2spirv + lines = ["s_getpc_b64 s[4:5]", "s_add_u32 s4, s4, 8", "s_addc_u32 s5, s5, 0", "s_setpc_b64 s[4:5]", + "v_mov_b32 v0, 1", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + text = "; far\n" + "".join("\t" + ln + "\n" for ln in lines) + with self.assertRaisesRegex(rdna2spirv.Unsupported, "without encoding"): + support.translate_listing("ps_far_noenc", text.encode("utf-8")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_fma_exact.py b/tests/semantic/test_fma_exact.py new file mode 100644 index 000000000..e02c78ad9 --- /dev/null +++ b/tests/semantic/test_fma_exact.py @@ -0,0 +1,205 @@ +"""--fma exact (SHADER-497): fused multiply-adds emulated from single-rounded f32 operations (Gen.fma_exact). + +RDNA2's v_fma_f32, v_fmac_f32, v_fmaak_f32, v_fmamk_f32 and v_fma_mix* round once. GLSL Fma may be split into two +roundings by a driver (Intel UHD Graphics, Xe-LP, Windows driver 101.7088: cs_fma_fused words 0, 2, 3 and 5), and a +device without VK_KHR_shader_fma can't take --fma khr. --fma exact builds the single rounding from NoContraction +FMul/FAdd/FSub: Dekker's exact product, TwoSum, a round-to-odd sum of the two error terms and one final rounding +(Boldo and Melquiond, IEEE Transactions on Computers 57(4), 2008), with power-of-two scaling that keeps every +intermediate in the normal range. The interpreter rounds every FMul/FAdd/FSub to binary32, so these tests run the +emitted instructions as a driver would, and compare each word with an exact rational reference (si.fma_f32). +""" +import math +import os +import random +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") +sys.path.insert(0, TOOLS_DIR) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +from support import mrt0_words, translate_lines # noqa: E402 + +EXIT = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] +EXACT_FMA = si.fma_f32 + + +def split_fma(x, y, z): + """GLSL Fma on a driver that rounds the product first, as the Intel UHD driver does for cs_fma_fused.""" + return si.f32(si.f32(x * y) + z) + + +def run_split(spv): + """mrt0_words with the interpreter's Fma split into two roundings, so only the emulation can be exact.""" + si.fma_f32 = split_fma + try: + return mrt0_words(spv) + finally: + si.fma_f32 = EXACT_FMA + + +def f32_of(w): + return struct.unpack("> bit & ((1 << w) - 1) + bit += w + signed = v - (1 << w) if v >> (w - 1) else v + if kind in ("f32", "u32", "i32", "uint"): + out.append(v) + elif kind == "sint": + out.append(signed & 0xFFFFFFFF) + elif kind == "f16": + # The interpreter's pinned f16 -> f32 rule (a NaN half widens to the canonical quiet NaN with its sign), + # not struct's ' max on any axis) is a miss. + +One pixel shader per case runs the instruction on a hand-built box node and exports the four child words. The ray +starts at (0, 0, -1) and runs along +z. A box contributes its entry distance only when it is well formed and the +slab interval overlaps [0, extent); empty boxes (min > max) and boxes the ray misses give 0xFFFFFFFF, in distance +order, as tools/xdxr_bvh.py `_box_test` does. + +box32 (node type 5) stores a child as six f32 at byte 16 + 24 i; box16 (type 4) stores the same six values as +f16 at byte 16 + 12 i. Both go through the same slab test in tools/rdna2spirv.py. + + python -m unittest discover -s tests/semantic -p "test_image_bvh_box.py" -v +""" +import struct +import unittest + +from support import mrt0_words, translate_lines + +INF_WORD = 0x7F800000 +MISS = 0xFFFFFFFF +NODE = 0x1040 # descriptor base 0x10 (256-byte units) = 0x1000; node id 0x08 | type -> +0x40 + + +def f2u(x): + return struct.unpack(" max -1). + boxes = [(-1, 1, 0.5, 1, -1, 2), (2, 2, 2, 3, 3, 3), (2, 2, 2, 3, 3, 3), (2, 2, 2, 3, 3, 3)] + for node_type in (4, 5): + with self.subTest(node_type=node_type): + self.assertEqual(run(node_type, CHILDREN, boxes), [MISS, MISS, MISS, MISS]) + + def test_zero_thickness_box_is_not_empty(self): + # min == max is a degenerate but well-formed box; the CPU reference keeps it (lo > hi only). + boxes = [(-1, -1, 0, 1, 1, 0), (2, 2, 2, 3, 3, 3), (2, 2, 2, 3, 3, 3), (2, 2, 2, 3, 3, 3)] + for node_type in (4, 5): + with self.subTest(node_type=node_type): + self.assertEqual(run(node_type, CHILDREN, boxes), [0x20, MISS, MISS, MISS]) + + def test_empty_box_does_not_hide_a_later_hit(self): + # child 0's box is empty; child 1's overlaps, child 2's starts right after the extent, child 3's is empty. + boxes = [(1, 1, 4, -1, -1, 5), (-1, -1, 2, 1, 1, 3), (2, 2, 2, 3, 3, 3), (0, 1, 0, 1, 0, 1)] + # The four results stay in child-slot order; a miss at slot 0 is not compacted away. + for node_type in (4, 5): + with self.subTest(node_type=node_type): + self.assertEqual(run(node_type, CHILDREN, boxes), [MISS, 0x28, MISS, MISS]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_image_bvh_box_hw.py b/tests/semantic/test_image_bvh_box_hw.py new file mode 100644 index 000000000..5cfdd56ea --- /dev/null +++ b/tests/semantic/test_image_bvh_box_hw.py @@ -0,0 +1,810 @@ +"""image_bvh_intersect_ray box nodes against words measured on native RDNA2 hardware (SHADER-650). + +Every expected value below was returned by the instruction itself on an AMD Radeon RX 6900 XT (gfx1030, AMD +driver 26.11.2, Windows), through tools/hw_oracle raw kernels that write the node into memory and trace one ray +with box sorting on (descriptor w1 bit 31, w2 = -1, w3 = 0x81000000). This file runs the same node and ray +through the translator and compares the four child words. The rule they follow is in the docs/design.md Ray +tracing row: near/far planes picked by the sign of the inverse direction, NaN skipped in the max/min of the +three, all-NaN a miss, sort key max(tnear, 0) through the network (0,2) (1,3) (0,1) (2,3) (1,2). + +241 of the 338 measured cases: the empty-box set (BOX32 and BOX16), the NaN set, the multi-NaN and +other-bound rows of the NaN grid on four rays, every measured tie order, planes on the origin, and the +cs_bvh scene root. No game data. + + python -m unittest discover -s tests/semantic -p "test_image_bvh_box_hw.py" -v +""" +import struct +import unittest + +from support import mrt0_words, translate_lines + +INF = float("inf") +NAN = float("nan") +FMAX = struct.unpack(" o.x', 'box32', 'R2', [0x40, 0x48, 0x50, 0x58], + [(-0.25, -0.25, -3.0, 0.75, 0.75, -2.75), (1.0, -1.0, -2.0, 0.25, 1.0, -1.0), (-0.25, -0.25, 1.0, 0.75, 0.75, 1.25), (-0.25, -0.25, 6.0, 0.75, 0.75, 6.25)], + [0x40, 0x50, 0x58, MISS]), + ('box32 cs_bvh scene root', 'box32', 'R0', [0x40, 0x48, 0x60, 0x68], + [(0.0, 0.0, 10.0, 1.0, 1.0, 10.0), (0.0, 0.0, 5.0, 1.0, 1.0, 5.0), (5.0, 0.0, 0.0, 6.0, 1.0, 1.0), (NAN, 0.0, 0.0, 1.0, 1.0, 1.0)], + [0x68, 0x48, 0x40, MISS]), +] + + +def f2u(x): + return struct.unpack(" 2, 3.5 -> 4. self.assertEqual(run_word("%x = OpExtInst %float %glsl RoundEven %f2p5\n%res = OpBitcast %uint %x\n"), @@ -458,6 +499,26 @@ class InterpreterTests(unittest.TestCase): with self.subTest(cond=cond): self.assertEqual(si.run_fragment(text)["%out"][0], want) + def test_phis_of_a_block_take_their_values_together(self): + # A loop header that swaps %a and %b on every back edge: each OpPhi reads the other's value from before + # the block. Three iterations from (1, 2) leave (2, 1); assigning %a first would give %b the new %a, (2, 2). + text = (HEADER.replace('"main" %out', '"main" %out %out2') + .replace("%main = OpFunction", "%out2 = OpVariable %_ptr_Output_uint Output\n" + "%c3 = OpConstant %uint 3\n%main = OpFunction") + + "OpBranch %head\n" + "%head = OpLabel\n" + "%a = OpPhi %uint %c1 %entry %b %cont\n" + "%b = OpPhi %uint %c2 %entry %a %cont\n" + "%i = OpPhi %uint %c0 %entry %inext %cont\n" + "%more = OpULessThan %bool %i %c3\n" + "OpLoopMerge %done %cont None\nOpBranchConditional %more %cont %done\n" + "%cont = OpLabel\n%inext = OpIAdd %uint %i %c1\nOpBranch %head\n" + "%done = OpLabel\nOpStore %out %a\nOpStore %out2 %b\n" + FOOTER) + out = si.run_fragment(text) + self.assertEqual((out["%out"], out["%out2"]), ((2,), (1,))) + lane0 = spirv_wave_interp.run_wave(text, wave=32)["outputs"][0] # the other interpreter agrees + self.assertEqual((lane0["%out"], lane0["%out2"]), ((2,), (1,))) + def test_function_array_access(self): self.assertEqual(run_word("%arr_v = OpVariable %_ptr_Function_arr Function %null_arr\n" "%p = OpAccessChain %_ptr_Function_uint %arr_v %c2\n" diff --git a/tests/semantic/test_interp_guards.py b/tests/semantic/test_interp_guards.py index 16bf04eaa..08da4156d 100644 --- a/tests/semantic/test_interp_guards.py +++ b/tests/semantic/test_interp_guards.py @@ -7,7 +7,8 @@ so anything else is refused instead of silently translating wrong (docs/design.m p2 reads J = v1, per op — as the hardware register or a qualifying copy: anything else, including a swapped p1(v1)/p2(v0) pair or both-v0, -> Unsupported naming the register and the role (the corpus has none: 117,001 v0 and 116,997 v1 over 26,503 shaders); -* v_interp_mov_f32 with p10/p20 -> Unsupported naming the select (all 6,926 in the corpus are p0); +* v_interp_mov_f32 with p10/p20 was refused here; it is now modelled as P1 - P0 / P2 - P0 + (test_interp_mov_delta.py; all 6,926 in the corpus are p0); * a plain v_mov_b32 copy of the op's coordinate (rooted at v0 for p1, at v1 for p2) is still accepted, including a chain of copies: its single write in the whole shader is the mov, and its source v0/v1 is itself unwritten up to the copy (a copy of an already-overwritten v0/v1 carries a computed value — @@ -62,14 +63,14 @@ class InterpPairGuards(unittest.TestCase): "s_endpgm"]) self.assertIn("v_interp_p2_f16 J source v9", str(cm.exception)) - def test_mov_vertex_select_refused(self): + def test_mov_vertex_select_translates(self): + # p10/p20 are modelled as P1 - P0 / P2 - P0 (test_interp_mov_delta.py); only an unknown select is refused. for sel in ("p10", "p20"): with self.subTest(sel=sel): - with self.assertRaises(rdna2spirv.Unsupported) as cm: - support.translate_lines("ps_m", [f"v_interp_mov_f32_e32 v2, {sel}, attr1.x", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm"]) - self.assertIn(f"v_interp_mov_f32 vertex select {sel}: only p0", str(cm.exception)) + spv = support.translate_lines("ps_m", [f"v_interp_mov_f32_e32 v2, {sel}, attr1.x", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm"]) + self.assertIn("OpDecorate %in_attr1 PerVertexKHR", spv) def test_copy_of_pair_translates_and_computes(self): for chain in (["v_mov_b32_e32 v6, v1"], # the corpus form: J read through a copy diff --git a/tests/semantic/test_interp_mov_delta.py b/tests/semantic/test_interp_mov_delta.py new file mode 100644 index 000000000..40b04bcf8 --- /dev/null +++ b/tests/semantic/test_interp_mov_delta.py @@ -0,0 +1,81 @@ +"""v_interp_mov_f32 with the p10 / p20 vertex selects: the attribute deltas P1 - P0 and P2 - P0. + +RDNA2 ISA, VINTRP: v_interp_mov_f32 returns {P10, P20, P0}[S], the three values the hardware keeps per attribute +for the p1/p2 pair (P = P0 + i * P10 + j * P20). p0 is the provoking vertex (Flat); p10 and p20 read the location +PerVertexKHR (like the *_f16 interps) and subtract vertex 0's word from vertex 1's or 2's. Hand-written programs +only; no game files. + + python -m unittest discover -s tests/semantic -p test_interp_mov_delta.py +""" +import struct +import unittest + +import support +import rdna2spirv + +BARY = (0.25, 0.25, 0.5) +VERTS0 = ((1.0, 10.0, 100.0, -1.0), (3.0, 14.0, 107.5, 2.0), (6.0, 19.0, 115.25, -4.0)) + + +def f32_bits(x): + return struct.unpack("> 2) & (lds_dwords - 1). - - Non-returning: Results are written in-place to LDS; VGPRs remain unchanged. -""" - -from dataclasses import dataclass -from enum import Enum -import sys -import unittest - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -DEFAULT_LDS_DWORDS = 16384 # 64 KiB default capacity in dwords (16384 * 4 bytes) -DEFAULT_NUM_LANES = 64 # Wave64 default width -DEFAULT_NUM_VGPRS = 256 # Standard GFX10 vector register file size -DEFAULT_NUM_SGPRS = 106 # Standard GFX10 scalar register file size - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit dword.""" - return val & MASK32 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned dword as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x80000000) else val - - -def ref_ds_add_src2_u32(val_a: int, val_b: int) -> int: - """Reference ISA calculation for ds_add_src2_u32. - - LDS[A] = (LDS[A] + LDS[B]) mod 2^32. - """ - return u32(u32(val_a) + u32(val_b)) - - -def ref_ds_sub_src2_u32(val_a: int, val_b: int) -> int: - """Reference ISA calculation for ds_sub_src2_u32. - - LDS[A] = (LDS[A] - LDS[B]) mod 2^32. - """ - return u32(u32(val_a) - u32(val_b)) - - -def calc_lds_src2_addresses( - vaddr: int, - offset0: int = 0, - offset1: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, -) -> tuple[int, int, int, int]: - """Calculate byte addresses and dword indices for address A and address B. - - Address A = (vaddr + offset0 * 4) & MASK32 - Address B = (vaddr + offset1 * 4) & MASK32 - Dword index = (addr >> 2) & (lds_dwords - 1) - - Returns: - tuple[int, int, int, int]: (byte_addr_a, byte_addr_b, dword_idx_a, dword_idx_b) - """ - byte_addr_a = u32(vaddr + (offset0 * 4)) - byte_addr_b = u32(vaddr + (offset1 * 4)) - dword_idx_a = (byte_addr_a >> 2) & (lds_dwords - 1) - dword_idx_b = (byte_addr_b >> 2) & (lds_dwords - 1) - return byte_addr_a, byte_addr_b, dword_idx_a, dword_idx_b - - -# ============================================================================== -# Symbolic AST Definitions and Typed Expressions -# ============================================================================== - -class DSOpcode(Enum): - """Supported DS src2 add/sub opcodes.""" - DS_ADD_SRC2_U32 = "ds_add_src2_u32" - DS_SUB_SRC2_U32 = "ds_sub_src2_u32" - - -class RegType(Enum): - """Register file class.""" - VGPR = "v" - SGPR = "s" - - -@dataclass(frozen=True) -class RegisterOperand: - """Symbolic register operand representation.""" - index: int - reg_type: RegType = RegType.VGPR - - def __post_init__(self) -> None: - if not (0 <= self.index < DEFAULT_NUM_VGPRS): - raise ValueError( - f"Register index out of bounds: {self.reg_type.value}{self.index} " - f"(expected 0 <= index < {DEFAULT_NUM_VGPRS})" - ) - - @property - def name(self) -> str: - return f"{self.reg_type.value}{self.index}" - - -@dataclass(frozen=True) -class LDSAddressExpression: - """Symbolic representation of LDS address with dual offset descriptors.""" - base_reg: RegisterOperand - offset0: int = 0 - offset1: int = 0 - gds: bool = False - - def __post_init__(self) -> None: - if not (0 <= self.offset0 <= 0xFF): - raise ValueError(f"offset0 out of 8-bit range: {self.offset0}") - if not (0 <= self.offset1 <= 0xFF): - raise ValueError(f"offset1 out of 8-bit range: {self.offset1}") - if self.base_reg.reg_type != RegType.VGPR: - raise TypeError("LDS base address register must be a VGPR") - - -@dataclass(frozen=True) -class DSSrc2Instruction: - """Symbolic AST node for DS src2 atomic instruction.""" - opcode: DSOpcode - addr: LDSAddressExpression - - def disasm(self) -> str: - """Format canonical assembly mnemonic and operand string.""" - parts = [self.opcode.value, self.addr.base_reg.name] - if self.addr.offset0 != 0: - parts.append(f"offset0:{self.addr.offset0}") - if self.addr.offset1 != 0: - parts.append(f"offset1:{self.addr.offset1}") - if self.addr.gds: - parts.append("gds") - return " ".join(parts) - - -# ============================================================================== -# Deterministic Scalar Interpreter & Machine State -# ============================================================================== - -class LDSMemory: - """Model of Local Data Share memory storage.""" - - def __init__(self, size_dwords: int = DEFAULT_LDS_DWORDS) -> None: - if size_dwords <= 0 or (size_dwords & (size_dwords - 1)) != 0: - raise ValueError(f"LDS size must be a positive power of two: {size_dwords}") - self.size_dwords = size_dwords - self.data = [0] * size_dwords - - def read_dword(self, index: int) -> int: - return self.data[index & (self.size_dwords - 1)] - - def write_dword(self, index: int, val: int) -> None: - self.data[index & (self.size_dwords - 1)] = u32(val) - - -class ScalarMachineState: - """Scalar architectural machine state for single-lane emulation.""" - - def __init__(self, lds_dwords: int = DEFAULT_LDS_DWORDS) -> None: - self.vgprs = [0] * DEFAULT_NUM_VGPRS - self.sgprs = [0] * DEFAULT_NUM_SGPRS - self.lds = LDSMemory(lds_dwords) - - def get_vgpr(self, index: int) -> int: - return self.vgprs[index] - - def set_vgpr(self, index: int, val: int) -> None: - self.vgprs[index] = u32(val) - - def get_lds(self, dword_idx: int) -> int: - return self.lds.read_dword(dword_idx) - - def set_lds(self, dword_idx: int, val: int) -> None: - self.lds.write_dword(dword_idx, val) - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for DS src2 add/sub.""" - - def execute(self, instr: DSSrc2Instruction, state: ScalarMachineState) -> None: - base_addr = state.get_vgpr(instr.addr.base_reg.index) - _, _, idx_a, idx_b = calc_lds_src2_addresses( - vaddr=base_addr, - offset0=instr.addr.offset0, - offset1=instr.addr.offset1, - lds_dwords=state.lds.size_dwords, - ) - - val_a = state.lds.read_dword(idx_a) - val_b = state.lds.read_dword(idx_b) - - if instr.opcode == DSOpcode.DS_ADD_SRC2_U32: - new_a = ref_ds_add_src2_u32(val_a, val_b) - elif instr.opcode == DSOpcode.DS_SUB_SRC2_U32: - new_a = ref_ds_sub_src2_u32(val_a, val_b) - else: - raise NotImplementedError(f"Unsupported opcode: {instr.opcode}") - - state.lds.write_dword(idx_a, new_a) - - -# ============================================================================== -# SIMD Multi-Lane State and Divergence Interpreter -# ============================================================================== - -class SIMDState: - """SIMD vector machine state with multi-lane VGPR files and shared LDS.""" - - def __init__( - self, - num_lanes: int = DEFAULT_NUM_LANES, - exec_mask: int = MASK64, - lds_dwords: int = DEFAULT_LDS_DWORDS, - ) -> None: - if num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {num_lanes}") - self.num_lanes = num_lanes - self.exec_mask = (exec_mask & MASK32) if num_lanes == 32 else (exec_mask & MASK64) - self.vgprs = [[0] * DEFAULT_NUM_VGPRS for _ in range(num_lanes)] - self.lds = LDSMemory(lds_dwords) - - def is_lane_active(self, lane: int) -> bool: - if 0 <= lane < self.num_lanes: - return bool((self.exec_mask >> lane) & 1) - return False - - def get_lane_vgpr(self, lane: int, reg: int) -> int: - return self.vgprs[lane][reg] - - def set_lane_vgpr(self, lane: int, reg: int, val: int) -> None: - self.vgprs[lane][reg] = u32(val) - - -class SIMDInterpreter: - """SIMD multi-lane execution interpreter handling divergence and EXEC masking.""" - - def execute(self, instr: DSSrc2Instruction, state: SIMDState) -> None: - for lane in range(state.num_lanes): - if not state.is_lane_active(lane): - continue - - base_addr = state.get_lane_vgpr(lane, instr.addr.base_reg.index) - _, _, idx_a, idx_b = calc_lds_src2_addresses( - vaddr=base_addr, - offset0=instr.addr.offset0, - offset1=instr.addr.offset1, - lds_dwords=state.lds.size_dwords, - ) - - val_a = state.lds.read_dword(idx_a) - val_b = state.lds.read_dword(idx_b) - - if instr.opcode == DSOpcode.DS_ADD_SRC2_U32: - new_a = ref_ds_add_src2_u32(val_a, val_b) - elif instr.opcode == DSOpcode.DS_SUB_SRC2_U32: - new_a = ref_ds_sub_src2_u32(val_a, val_b) - else: - raise NotImplementedError(f"Unsupported opcode: {instr.opcode}") - - state.lds.write_dword(idx_a, new_a) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Evaluation -# ============================================================================== - -@dataclass(frozen=True) -class ArithmeticStatusFlags: - """Condition codes and status flags for 32-bit addition/subtraction.""" - zero: bool - sign: bool - carry: bool - borrow: bool - overflow: bool - - -def evaluate_add_sub_status_flags( - opcode: DSOpcode, - val_a: int, - val_b: int, - result: int, -) -> ArithmeticStatusFlags: - """Evaluate condition codes, flags, and carry/borrow generation.""" - a = u32(val_a) - b = u32(val_b) - res = u32(result) - - zero = (res == 0) - sign = bool(res & 0x80000000) - carry = False - borrow = False - overflow = False - - if opcode == DSOpcode.DS_ADD_SRC2_U32: - carry = (a + b) > MASK32 - sa, sb, sres = s32(a), s32(b), s32(res) - overflow = ((sa > 0 and sb > 0 and sres < 0) or (sa < 0 and sb < 0 and sres > 0)) - elif opcode == DSOpcode.DS_SUB_SRC2_U32: - borrow = (a < b) - sa, sb, sres = s32(a), s32(b), s32(res) - overflow = ((sa > 0 and sb < 0 and sres < 0) or (sa < 0 and sb > 0 and sres > 0)) - - return ArithmeticStatusFlags( - zero=zero, - sign=sign, - carry=carry, - borrow=borrow, - overflow=overflow, - ) - - -class TestReferenceModelAndOracle(unittest.TestCase): - """Unit tests for reference mathematical oracle and architectural model.""" - - def test_add_src2_basic_addition(self) -> None: - self.assertEqual(ref_ds_add_src2_u32(0, 0), 0) - self.assertEqual(ref_ds_add_src2_u32(100, 250), 350) - self.assertEqual(ref_ds_add_src2_u32(1, 0xFFFE), 0xFFFF) - self.assertEqual(ref_ds_add_src2_u32(0x12345678, 0x10000001), 0x22345679) - - def test_add_src2_overflow_wrapping(self) -> None: - self.assertEqual(ref_ds_add_src2_u32(MASK32, 1), 0) - self.assertEqual(ref_ds_add_src2_u32(MASK32, 2), 1) - self.assertEqual(ref_ds_add_src2_u32(0x80000000, 0x80000000), 0) - self.assertEqual(ref_ds_add_src2_u32(0xFFFFFFF0, 0x20), 0x10) - - def test_sub_src2_basic_subtraction(self) -> None: - self.assertEqual(ref_ds_sub_src2_u32(0, 0), 0) - self.assertEqual(ref_ds_sub_src2_u32(500, 200), 300) - self.assertEqual(ref_ds_sub_src2_u32(100, 100), 0) - self.assertEqual(ref_ds_sub_src2_u32(0x50000000, 0x10000000), 0x40000000) - - def test_sub_src2_underflow_wrapping(self) -> None: - self.assertEqual(ref_ds_sub_src2_u32(0, 1), MASK32) - self.assertEqual(ref_ds_sub_src2_u32(0, 5), MASK32 - 4) - self.assertEqual(ref_ds_sub_src2_u32(10, 20), MASK32 - 9) - self.assertEqual(ref_ds_sub_src2_u32(0x80000000, 0x80000001), MASK32) - - def test_address_calculation_and_alignment(self) -> None: - byte_a, byte_b, idx_a, idx_b = calc_lds_src2_addresses( - vaddr=0x2000, offset0=3, offset1=7, lds_dwords=2048 - ) - self.assertEqual(byte_a, 0x200C) - self.assertEqual(byte_b, 0x201C) - self.assertEqual(idx_a, (0x200C >> 2) & 2047) - self.assertEqual(idx_b, (0x201C >> 2) & 2047) - - def test_self_referencing_aliasing(self) -> None: - self.assertEqual(ref_ds_add_src2_u32(50, 50), 100) - self.assertEqual(ref_ds_add_src2_u32(0x80000000, 0x80000000), 0) - self.assertEqual(ref_ds_sub_src2_u32(50, 50), 0) - self.assertEqual(ref_ds_sub_src2_u32(MASK32, MASK32), 0) - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_opcode_enumeration(self) -> None: - self.assertEqual(DSOpcode.DS_ADD_SRC2_U32.value, "ds_add_src2_u32") - self.assertEqual(DSOpcode.DS_SUB_SRC2_U32.value, "ds_sub_src2_u32") - - def test_register_operand_validation(self) -> None: - v0 = RegisterOperand(0, RegType.VGPR) - self.assertEqual(v0.name, "v0") - v127 = RegisterOperand(127, RegType.VGPR) - self.assertEqual(v127.name, "v127") - - with self.assertRaises(ValueError): - RegisterOperand(-1, RegType.VGPR) - with self.assertRaises(ValueError): - RegisterOperand(256, RegType.VGPR) - - def test_address_expression_validation(self) -> None: - v4 = RegisterOperand(4, RegType.VGPR) - expr = LDSAddressExpression(base_reg=v4, offset0=2, offset1=6) - self.assertEqual(expr.base_reg.name, "v4") - self.assertEqual(expr.offset0, 2) - self.assertEqual(expr.offset1, 6) - - with self.assertRaises(ValueError): - LDSAddressExpression(base_reg=v4, offset0=-1) - with self.assertRaises(ValueError): - LDSAddressExpression(base_reg=v4, offset0=256) - with self.assertRaises(ValueError): - LDSAddressExpression(base_reg=v4, offset1=300) - - s0 = RegisterOperand(0, RegType.SGPR) - with self.assertRaises(TypeError): - LDSAddressExpression(base_reg=s0) - - def test_disasm_formatting(self) -> None: - v1 = RegisterOperand(1, RegType.VGPR) - addr = LDSAddressExpression(base_reg=v1, offset0=4, offset1=8) - instr = DSSrc2Instruction(DSOpcode.DS_ADD_SRC2_U32, addr) - self.assertEqual(instr.disasm(), "ds_add_src2_u32 v1 offset0:4 offset1:8") - - addr_zero = LDSAddressExpression(base_reg=v1, offset0=0, offset1=0) - instr_sub = DSSrc2Instruction(DSOpcode.DS_SUB_SRC2_U32, addr_zero) - self.assertEqual(instr_sub.disasm(), "ds_sub_src2_u32 v1") - - def test_ast_immutability_and_equality(self) -> None: - v0 = RegisterOperand(0, RegType.VGPR) - addr1 = LDSAddressExpression(v0, offset0=1, offset1=2) - addr2 = LDSAddressExpression(v0, offset0=1, offset1=2) - instr1 = DSSrc2Instruction(DSOpcode.DS_ADD_SRC2_U32, addr1) - instr2 = DSSrc2Instruction(DSOpcode.DS_ADD_SRC2_U32, addr2) - self.assertEqual(instr1, instr2) - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for deterministic scalar instruction interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState(lds_dwords=1024) - - def test_scalar_add_src2_execution(self) -> None: - self.state.set_vgpr(0, 0x10) - self.state.set_lds(4, 75) - self.state.set_lds(5, 25) - - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - self.interp.execute(instr, self.state) - self.assertEqual(self.state.get_lds(4), 100) - self.assertEqual(self.state.get_lds(5), 25) - self.assertEqual(self.state.get_vgpr(0), 0x10) - - def test_scalar_sub_src2_execution(self) -> None: - self.state.set_vgpr(1, 0x20) - self.state.set_lds(8, 20) - self.state.set_lds(9, 30) - - v1 = RegisterOperand(1, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_SUB_SRC2_U32, - LDSAddressExpression(v1, offset0=0, offset1=1), - ) - self.interp.execute(instr, self.state) - self.assertEqual(self.state.get_lds(8), u32(-10)) - self.assertEqual(self.state.get_lds(9), 30) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.interp = SIMDInterpreter() - - def test_wave32_full_exec_independent_lanes(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFFFFFF, lds_dwords=1024) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - for lane in range(32): - state.set_lane_vgpr(lane, 0, (lane * 2) * 4) - state.lds.write_dword(lane * 2, 100) - state.lds.write_dword(lane * 2 + 1, lane) - - self.interp.execute(instr, state) - - for lane in range(32): - self.assertEqual(state.lds.read_dword(lane * 2), 100 + lane) - - def test_wave64_full_exec_independent_lanes(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=MASK64, lds_dwords=1024) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_SUB_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - for lane in range(64): - state.set_lane_vgpr(lane, 0, (lane * 2) * 4) - state.lds.write_dword(lane * 2, 200) - state.lds.write_dword(lane * 2 + 1, lane) - - self.interp.execute(instr, state) - - for lane in range(64): - self.assertEqual(state.lds.read_dword(lane * 2), 200 - lane) - - def test_sparse_exec_mask_even_lanes(self) -> None: - exec_mask = 0x5555555555555555 - state = SIMDState(num_lanes=64, exec_mask=exec_mask, lds_dwords=1024) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - for lane in range(64): - state.set_lane_vgpr(lane, 0, (lane * 2) * 4) - state.lds.write_dword(lane * 2, 10) - state.lds.write_dword(lane * 2 + 1, 5) - - self.interp.execute(instr, state) - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(state.lds.read_dword(lane * 2), 15) - else: - self.assertEqual(state.lds.read_dword(lane * 2), 10) - - def test_zero_exec_mask_no_op(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0, lds_dwords=1024) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - for lane in range(32): - state.set_lane_vgpr(lane, 0, (lane * 2) * 4) - state.lds.write_dword(lane * 2, 50) - state.lds.write_dword(lane * 2 + 1, 10) - - self.interp.execute(instr, state) - - for lane in range(32): - self.assertEqual(state.lds.read_dword(lane * 2), 50) - - def test_lane_divergence_same_address_atomic_accumulate(self) -> None: - exec_mask = 0xFF - state = SIMDState(num_lanes=32, exec_mask=exec_mask, lds_dwords=1024) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - for lane in range(32): - state.set_lane_vgpr(lane, 0, 0) - state.lds.write_dword(0, 100) - state.lds.write_dword(1, 10) - - self.interp.execute(instr, state) - self.assertEqual(state.lds.read_dword(0), 180) - - def test_lane_divergence_same_address_atomic_decrement(self) -> None: - exec_mask = 0x0F - state = SIMDState(num_lanes=32, exec_mask=exec_mask, lds_dwords=1024) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_SUB_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - for lane in range(32): - state.set_lane_vgpr(lane, 0, 0) - state.lds.write_dword(0, 50) - state.lds.write_dword(1, 5) - - self.interp.execute(instr, state) - self.assertEqual(state.lds.read_dword(0), 30) - - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_base_address_vgpr_preservation_scalar(self) -> None: - state = ScalarMachineState(lds_dwords=1024) - for reg in range(DEFAULT_NUM_VGPRS): - state.set_vgpr(reg, 0xABC00000 | reg) - - v5 = RegisterOperand(5, RegType.VGPR) - state.set_vgpr(5, 0x200) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v5, offset0=0, offset1=1), - ) - self.scalar_interp.execute(instr, state) - - self.assertEqual(state.get_vgpr(5), 0x200) - for reg in range(DEFAULT_NUM_VGPRS): - if reg != 5: - self.assertEqual(state.get_vgpr(reg), 0xABC00000 | reg) - - def test_base_address_vgpr_preservation_simd(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=MASK64, lds_dwords=1024) - for lane in range(64): - for reg in range(8): - state.set_lane_vgpr(lane, reg, (lane << 16) | reg) - - v2 = RegisterOperand(2, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_SUB_SRC2_U32, - LDSAddressExpression(v2, offset0=0, offset1=1), - ) - self.simd_interp.execute(instr, state) - - for lane in range(64): - for reg in range(8): - self.assertEqual(state.get_lane_vgpr(lane, reg), (lane << 16) | reg) - - def test_secondary_memory_operand_preservation(self) -> None: - state = ScalarMachineState(lds_dwords=1024) - state.set_vgpr(0, 0x40) - state.set_lds(16, 50) - state.set_lds(17, 30) - - v0 = RegisterOperand(0, RegType.VGPR) - for opcode in (DSOpcode.DS_ADD_SRC2_U32, DSOpcode.DS_SUB_SRC2_U32): - instr = DSSrc2Instruction(opcode, LDSAddressExpression(v0, offset0=0, offset1=1)) - self.scalar_interp.execute(instr, state) - self.assertEqual(state.get_lds(17), 30) - - def test_address_aliasing_same_cell_add(self) -> None: - state = ScalarMachineState(lds_dwords=1024) - state.set_vgpr(0, 0) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v0, offset0=3, offset1=3), - ) - - state.set_lds(3, 40) - self.scalar_interp.execute(instr, state) - self.assertEqual(state.get_lds(3), 80) - - state.set_lds(3, 0x80000000) - self.scalar_interp.execute(instr, state) - self.assertEqual(state.get_lds(3), 0) - - def test_address_aliasing_same_cell_sub(self) -> None: - state = ScalarMachineState(lds_dwords=1024) - state.set_vgpr(0, 0) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_SUB_SRC2_U32, - LDSAddressExpression(v0, offset0=2, offset1=2), - ) - - for val in (0, 1, 100, 0x7FFFFFFF, MASK32): - state.set_lds(2, val) - self.scalar_interp.execute(instr, state) - self.assertEqual(state.get_lds(2), 0) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow generation.""" - - def test_add_carry_generation(self) -> None: - flags = evaluate_add_sub_status_flags( - DSOpcode.DS_ADD_SRC2_U32, MASK32, 1, 0 - ) - self.assertTrue(flags.carry) - self.assertTrue(flags.zero) - self.assertFalse(flags.sign) - self.assertFalse(flags.borrow) - - def test_add_signed_overflow(self) -> None: - flags = evaluate_add_sub_status_flags( - DSOpcode.DS_ADD_SRC2_U32, 0x7FFFFFFF, 1, 0x80000000 - ) - self.assertTrue(flags.overflow) - self.assertTrue(flags.sign) - self.assertFalse(flags.carry) - - def test_sub_borrow_generation(self) -> None: - flags = evaluate_add_sub_status_flags( - DSOpcode.DS_SUB_SRC2_U32, 0, 1, MASK32 - ) - self.assertTrue(flags.borrow) - self.assertFalse(flags.zero) - self.assertTrue(flags.sign) - self.assertFalse(flags.carry) - - def test_sub_zero_flag(self) -> None: - flags = evaluate_add_sub_status_flags( - DSOpcode.DS_SUB_SRC2_U32, 42, 42, 0 - ) - self.assertTrue(flags.zero) - self.assertFalse(flags.borrow) - self.assertFalse(flags.sign) - - -class TestBoundaryExtremesAndBitPatterns(unittest.TestCase): - """Unit tests for boundary extremes, unsigned wraparound, and bit patterns.""" - - def test_add_modulo_wrap_extremes(self) -> None: - self.assertEqual(ref_ds_add_src2_u32(MASK32, 1), 0) - self.assertEqual(ref_ds_add_src2_u32(MASK32, MASK32), MASK32 - 1) - self.assertEqual(ref_ds_add_src2_u32(0, 0), 0) - - def test_sub_borrow_wrap_extremes(self) -> None: - self.assertEqual(ref_ds_sub_src2_u32(0, 1), MASK32) - self.assertEqual(ref_ds_sub_src2_u32(0, MASK32), 1) - self.assertEqual(ref_ds_sub_src2_u32(MASK32, MASK32), 0) - - def test_alternating_bit_patterns(self) -> None: - p1 = 0x55555555 - p2 = 0xAAAAAAAA - self.assertEqual(ref_ds_add_src2_u32(p1, p2), MASK32) - self.assertEqual(ref_ds_sub_src2_u32(MASK32, p1), p2) - self.assertEqual(ref_ds_sub_src2_u32(MASK32, p2), p1) - - def test_sign_boundary_transitions(self) -> None: - self.assertEqual(ref_ds_add_src2_u32(0x7FFFFFFF, 1), 0x80000000) - self.assertEqual(ref_ds_sub_src2_u32(0x80000000, 1), 0x7FFFFFFF) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_registers(self) -> None: - with self.assertRaises(ValueError): - RegisterOperand(-1, RegType.VGPR) - with self.assertRaises(ValueError): - RegisterOperand(256, RegType.VGPR) - - def test_syntax_rejection_offsets(self) -> None: - v0 = RegisterOperand(0, RegType.VGPR) - with self.assertRaises(ValueError): - LDSAddressExpression(v0, offset0=-1) - with self.assertRaises(ValueError): - LDSAddressExpression(v0, offset0=256) - with self.assertRaises(ValueError): - LDSAddressExpression(v0, offset1=-1) - with self.assertRaises(ValueError): - LDSAddressExpression(v0, offset1=256) - - def test_syntax_rejection_lds_capacity(self) -> None: - with self.assertRaises(ValueError): - LDSMemory(size_dwords=0) - with self.assertRaises(ValueError): - LDSMemory(size_dwords=500) - - def test_syntax_rejection_simd_lanes(self) -> None: - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - - def test_mutation_detection_reversed_sub(self) -> None: - def mutant_sub(a: int, b: int) -> int: - return u32(u32(b) - u32(a)) - - val_a, val_b = 30, 10 - correct_res = ref_ds_sub_src2_u32(val_a, val_b) - mutant_res = mutant_sub(val_a, val_b) - self.assertEqual(correct_res, 20) - self.assertEqual(mutant_res, u32(-20)) - self.assertNotEqual(correct_res, mutant_res) - - def test_mutation_detection_unmasked_add(self) -> None: - def mutant_add(a: int, b: int) -> int: - return a + b - - val_a, val_b = MASK32, 1 - correct_res = ref_ds_add_src2_u32(val_a, val_b) - mutant_res = mutant_add(val_a, val_b) - self.assertEqual(correct_res, 0) - self.assertEqual(mutant_res, 0x100000000) - self.assertNotEqual(correct_res, mutant_res) - - def test_mutation_detection_exec_leak(self) -> None: - class MutantSIMD(SIMDInterpreter): - def execute(self, instr: DSSrc2Instruction, state: SIMDState) -> None: - for lane in range(state.num_lanes): - base_addr = state.get_lane_vgpr(lane, instr.addr.base_reg.index) - _, _, idx_a, _ = calc_lds_src2_addresses( - vaddr=base_addr, - offset0=instr.addr.offset0, - offset1=instr.addr.offset1, - lds_dwords=state.lds.size_dwords, - ) - state.lds.write_dword(idx_a, 999) - - state = SIMDState(num_lanes=32, exec_mask=0, lds_dwords=1024) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - state.lds.write_dword(0, 10) - - mutant = MutantSIMD() - mutant.execute(instr, state) - self.assertEqual(state.lds.read_dword(0), 999) - - state.lds.write_dword(0, 10) - standard = SIMDInterpreter() - standard.execute(instr, state) - self.assertEqual(state.lds.read_dword(0), 10) - - def test_mutation_detection_vaddr_clobber(self) -> None: - class MutantScalar(ScalarInterpreter): - def execute(self, instr: DSSrc2Instruction, state: ScalarMachineState) -> None: - super().execute(instr, state) - state.set_vgpr(instr.addr.base_reg.index, 0xBADF00D) - - state = ScalarMachineState(lds_dwords=1024) - state.set_vgpr(0, 0x10) - v0 = RegisterOperand(0, RegType.VGPR) - instr = DSSrc2Instruction( - DSOpcode.DS_ADD_SRC2_U32, - LDSAddressExpression(v0, offset0=0, offset1=1), - ) - - mutant = MutantScalar() - mutant.execute(instr, state) - self.assertEqual(state.get_vgpr(0), 0xBADF00D) - - state.set_vgpr(0, 0x10) - standard = ScalarInterpreter() - standard.execute(instr, state) - self.assertEqual(state.get_vgpr(0), 0x10) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_atomic_add.py b/tests/semantic/test_lds_atomic_add.py index 0e623195b..a771b08de 100644 --- a/tests/semantic/test_lds_atomic_add.py +++ b/tests/semantic/test_lds_atomic_add.py @@ -1,822 +1,88 @@ -"""Semantic interpreter tests for LDS atomic addition (ds_add_u32, ds_add_rtn_u32). +"""ds_add_u32, ds_add_rtn_u32, ds_sub_u32 and ds_sub_rtn_u32 through the translator. -Standard library only; no GPU, no LLVM, no external tools, no game files. +Standard library only; no GPU, no LLVM, no game files. - python -I tests/semantic/test_lds_atomic_add.py - python -m unittest discover -s tests/semantic -v +RDNA2 ISA, "Data Share Instructions": ds_add_u32 is the atomic M = M + D (mod 2^32) on the dword at +(vaddr + offset) / 4, ds_sub_u32 is M = M - D; the _rtn_ form also returns the old M in vdst, the plain form leaves +vdst alone. The offset is added to the address in bytes. -Background & Specification Rules: - * AMD RDNA2 / GFX10 Local Data Share (LDS) Architecture: - - LDS is an on-chip software-managed scratchpad memory shared by all threads - in a workgroup (threadgroup). - - `ds_add_u32 vaddr, vdata [offset:N]`: - Atomically computes: - addr = (vaddr + byte_offset) - idx = (addr >> 2) & (lds_dwords - 1) - LDS[idx] = (LDS[idx] + vdata) & 0xFFFFFFFF - Non-returning form: the prior value at LDS[idx] is discarded. - - `ds_add_rtn_u32 vdst, vaddr, vdata [offset:N]`: - Atomically computes: - addr = (vaddr + byte_offset) - idx = (addr >> 2) & (lds_dwords - 1) - old_val = LDS[idx] - LDS[idx] = (old_val + vdata) & 0xFFFFFFFF - vdst = old_val - Returning form: writes the pre-addition value into destination VGPR vdst. - - Active lane masking: - LDS operations are vector instructions; in hardware, only active lanes - participate (inactive lanes do not modify LDS or destination VGPRs). - - Hardware wrapping & alignment: - Byte addresses are converted to dwords by shifting right by 2 (truncating - unaligned low bits). The dword index is masked with (lds_dwords - 1), - wrapping out-of-bounds addresses within the allocated power-of-two LDS slice. - - Modulo 2^32 arithmetic: - All additions wrap strictly modulo 2^32 without trapping or saturating. - * SPIR-V Representation: - - LDS is declared as an array in the Workgroup storage class: - %lds_arr = OpTypeArray %uint - %_ptr_WG_lds = OpTypePointer Workgroup %lds_arr - %_ptr_WG_uint = OpTypePointer Workgroup %uint - %lds = OpVariable %_ptr_WG_lds Workgroup - - Atomic additions map directly to OpAtomicIAdd: - %old = OpAtomicIAdd %uint %ptr %scope %semantics %val - where %scope is Workgroup (2) and %semantics is Relaxed / None (0). +Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run in +tests/semantic/spirv_mini_interp.py (one lane: that interpreter does not share LDS between lanes, see lds_run.py). +It writes a few LDS dwords, runs a sequence of these atomics on them and stores each returned value and the final +dwords. The one-operation tables are written out by hand from the formulas above; seeded random sequences are checked +against a plain-Python LDS. Until this file, the LDS tests of this name ran a self-built interpreter that checked +only the shape of the SPIR-V. """ import os -import re +import random import sys import unittest -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - -MASK = 0xFFFFFFFF - - -class UnsupportedConstruct(NotImplementedError): - """The module uses an unmodelled SPIR-V opcode, type, or storage class.""" - - -class WorkgroupBoundsError(ValueError): - """Workgroup dimension or memory bounds violation.""" - - -_IGNORED = frozenset({ - "OpCapability", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", - "OpReturn", "OpFunctionEnd", "OpName", "OpSource", "OpSelectionMerge", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -def reference_atomic_add(initial, addend): - """Reference 32-bit unsigned wrapping atomic addition.""" - return (initial + addend) & MASK - - -def reference_lds_index(base_addr, byte_offset, lds_dwords): - """Reference dword index calculation with hardware wrapping.""" - effective_byte = (base_addr + byte_offset) & MASK - dword_idx = effective_byte >> 2 - return dword_idx & (lds_dwords - 1) - - -class LdsAtomicInterp: - """Strict semantic interpreter for compute SPIR-V modules exercising LDS atomics.""" - - def __init__(self, spvasm): - self.spvasm = spvasm - self.types = {} - self.constants = {} - self.ptr_types = {} - self.var_class = {} - self.local_size = (1, 1, 1) - self.lds_var = None - self.lds_size = 0 - self.body = [] - self._parse() - - def _parse(self): - in_body = False - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"Cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - self.body.append((res, op, a, line)) - continue - if op == "OpFunction": - in_body = True - continue - if op == "OpExecutionMode" and len(a) >= 5 and a[1] == "LocalSize": - lx, ly, lz = int(a[2]), int(a[3]), int(a[4]) - if lx < 1 or ly < 1 or lz < 1 or (lx * ly * lz) > 1024: - raise WorkgroupBoundsError(f"Invalid LocalSize {lx}x{ly}x{lz}") - self.local_size = (lx, ly, lz) - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit int supported") - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeBool": - self.types[res] = ("bool",) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - size = int(self.constants[a[1]]) - self.types[res] = ("arr", a[0], size) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - self.constants[res] = int(a[1], 0) & MASK - elif op == "OpConstantTrue": - self.constants[res] = True - elif op == "OpConstantFalse": - self.constants[res] = False - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - if a[1] != cls: - raise UnsupportedConstruct("OpVariable storage class mismatch") - self.var_class[res] = cls - if cls == "Workgroup": - if self.lds_var is not None: - raise UnsupportedConstruct("Multiple Workgroup variables") - self.lds_var = res - arr_ty = self.types[pointee] - if arr_ty[0] != "arr": - raise UnsupportedConstruct("Workgroup variable must be an array") - self.lds_size = arr_ty[2] - elif cls not in ("Output", "Function"): - raise UnsupportedConstruct(f"Unsupported storage class {cls}") - else: - raise UnsupportedConstruct(f"Header opcode {op}") - - def run(self, num_invocations=None, seed_lds=None, lane_inputs=None): - """Executes the workgroup and returns (final_lds, outputs_per_lane).""" - lx, ly, lz = self.local_size - total_invocations = lx * ly * lz - count = total_invocations if num_invocations is None else min(num_invocations, total_invocations) - - lds = [0] * self.lds_size - if seed_lds: - for idx, val in seed_lds.items(): - if 0 <= idx < self.lds_size: - lds[idx] = val & MASK - - lane_outputs = [] - for lidx in range(count): - inputs = lane_inputs[lidx] if lane_inputs and lidx < len(lane_inputs) else {} - out = self._run_lane(lidx, lds, inputs) - lane_outputs.append(out) - - return list(lds), lane_outputs - - def _run_lane(self, lidx, lds, inputs): - values = dict(self.constants) - values.update(inputs) - var_box = {} - pointers = {} - outputs = [] - - if self.lds_var: - pointers[self.lds_var] = ("lds", lds, None) - - for res, cls in self.var_class.items(): - if cls == "Output": - var_box[res] = [0] - pointers[res] = ("out", var_box[res], 0) - outputs.append(res) - elif cls == "Function": - var_box[res] = [0] - pointers[res] = ("fn", var_box[res], 0) - - def val(x): - if x in values: - return values[x] - raise UnsupportedConstruct(f"Undefined identifier {x}") - - for res, op, a, _ in self.body: - if op in _IGNORED: - continue - if op == "OpBranch": - continue - if op == "OpBranchConditional": - # Branch conditional: if condition is false, skip to else/merge label - continue - if op == "OpVariable": - cls, _ = self.ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("Non-Function variable in body") - var_box[res] = [val(a[2]) if len(a) > 2 else 0] - pointers[res] = ("fn", var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if base not in pointers: - raise UnsupportedConstruct(f"OpAccessChain on non-pointer {base}") - ptag = pointers[base][0] - if ptag == "lds": - idx = val(a[2]) - if not (0 <= idx < len(lds)): - raise WorkgroupBoundsError(f"LDS access out of bounds: {idx} >= {len(lds)}") - pointers[res] = ("lds", lds, idx) - elif ptag in ("out", "fn"): - pointers[res] = pointers[base] - else: - raise UnsupportedConstruct(f"Access chain on {ptag}") - elif op == "OpLoad": - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag == "lds": - values[res] = ptr[1][ptr[2]] & MASK - elif ptag in ("out", "fn"): - values[res] = ptr[1][ptr[2]] & MASK - elif op == "OpStore": - ptr = pointers[a[0]] - v = val(a[1]) & MASK - ptag = ptr[0] - if ptag == "lds": - ptr[1][ptr[2]] = v - elif ptag in ("out", "fn"): - ptr[1][ptr[2]] = v - elif op == "OpAtomicIAdd": - # %res = OpAtomicIAdd %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicIAdd on non-LDS pointer {ptag}") - addend = val(a[4]) & MASK - old = ptr[1][ptr[2]] & MASK - ptr[1][ptr[2]] = (old + addend) & MASK - values[res] = old - elif op == "OpIAdd": - values[res] = (val(a[1]) + val(a[2])) & MASK - elif op == "OpISub": - values[res] = (val(a[1]) - val(a[2])) & MASK - elif op == "OpShiftRightLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) >> sh) & MASK - elif op == "OpShiftLeftLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) << sh) & MASK - elif op == "OpBitwiseAnd": - values[res] = val(a[1]) & val(a[2]) & MASK - elif op == "OpBitwiseOr": - values[res] = (val(a[1]) | val(a[2])) & MASK - elif op == "OpBitwiseXor": - values[res] = (val(a[1]) ^ val(a[2])) & MASK - elif op == "OpSelect": - cond = val(a[1]) - values[res] = val(a[2]) if cond else val(a[3]) - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpBitcast": - values[res] = val(a[1]) & MASK - else: - raise UnsupportedConstruct(f"Opcode {op} not modelled in body") - - return {name: var_box[name][0] & MASK for name in outputs} - - -class TestAtomicAddReferenceMath(unittest.TestCase): - """Verifies 32-bit unsigned wrapping arithmetic and edge cases for atomic additions.""" - - def test_basic_addition(self): - self.assertEqual(reference_atomic_add(10, 20), 30) - self.assertEqual(reference_atomic_add(0, 0), 0) - self.assertEqual(reference_atomic_add(100, 0), 100) - self.assertEqual(reference_atomic_add(0, 100), 100) - - def test_overflow_modulo_2_pow_32(self): - cases = [ - (0xFFFFFFFF, 1, 0), - (0xFFFFFFFF, 2, 1), - (0xFFFFFFF0, 0x10, 0), - (0xFFFFFFF0, 0x20, 0x10), - (0x80000000, 0x80000000, 0), - (0x7FFFFFFF, 1, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE), - ] - for init, addend, expected in cases: - with self.subTest(init=hex(init), addend=hex(addend)): - self.assertEqual(reference_atomic_add(init, addend), expected) - - def test_twos_complement_subtraction_via_add(self): - # Adding (2^32 - k) is equivalent to subtracting k - self.assertEqual(reference_atomic_add(10, 0xFFFFFFFF), 9) # 10 + (-1) = 9 - self.assertEqual(reference_atomic_add(5, 0xFFFFFFFB), 0) # 5 + (-5) = 0 - self.assertEqual(reference_atomic_add(0, 0xFFFFFFFF), 0xFFFFFFFF) # 0 - 1 = 0xFFFFFFFF - - def test_accumulative_series(self): - # Simulates multiple atomic increments accumulating - total = 0 - for i in range(1, 101): - total = reference_atomic_add(total, i) - self.assertEqual(total, 5050) - - -class TestLdsAddressingAndOffsets(unittest.TestCase): - """Verifies byte offset math, dword truncation, and power-of-two modulo wrapping.""" - - def test_aligned_dword_addressing(self): - lds_dwords = 256 - for dword in (0, 1, 2, 64, 127, 255): - byte_addr = dword * 4 - self.assertEqual(reference_lds_index(byte_addr, 0, lds_dwords), dword) - - def test_unaligned_byte_truncation(self): - # LDS addressing ignores the lowest 2 bits (shifts right by 2) - lds_dwords = 128 - # Any byte offset 0..3 added to aligned byte 16 maps to dword 4 - for byte_off in (0, 1, 2, 3): - self.assertEqual(reference_lds_index(16, byte_off, lds_dwords), 4) - # Unaligned byte addresses 16..19 with 0 offset all map to dword 4 - for unaligned_base in (16, 17, 18, 19): - self.assertEqual(reference_lds_index(unaligned_base, 0, lds_dwords), 4) - - def test_static_offset_addition(self): - lds_dwords = 512 - base = 32 # dword 8 - offset = 64 # +16 dwords - self.assertEqual(reference_lds_index(base, offset, lds_dwords), 24) - - def test_boundary_wrapping(self): - lds_dwords = 64 # 256 bytes - # Byte address 256 wraps to dword 0 - self.assertEqual(reference_lds_index(256, 0, lds_dwords), 0) - # Byte address 260 wraps to dword 1 - self.assertEqual(reference_lds_index(256, 4, lds_dwords), 1) - # Byte address 0xFFFFFFFC wraps to dword 63 - self.assertEqual(reference_lds_index(0xFFFFFFFC, 0, lds_dwords), 63) - - -class TestSpirvAtomicAddInterpreter(unittest.TestCase): - """Executes SPIR-V compute kernels with LDS OpAtomicIAdd operations.""" - - def test_ds_add_u32_non_returning_semantic(self): - # ds_add_u32: updates LDS[target], returns nothing to registers - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c3 = OpConstant %uint 3 -%c15 = OpConstant %uint 15 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c3 -%dummy = OpAtomicIAdd %uint %ptr %c2 %c0 %c15 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicInterp(spvasm) - final_lds, _ = interp.run(seed_lds={3: 100}) - # Initial 100 + addend 15 = 115 - self.assertEqual(final_lds[3], 115) - # Other slots stay pristine - self.assertEqual(final_lds[0], 0) - self.assertEqual(final_lds[2], 0) - self.assertEqual(final_lds[4], 0) - - def test_ds_add_rtn_u32_returning_semantic(self): - # ds_add_rtn_u32: updates LDS[target] AND returns the prior value - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c7 = OpConstant %uint 7 -%c50 = OpConstant %uint 50 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c7 -%old = OpAtomicIAdd %uint %ptr %c2 %c0 %c50 -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicInterp(spvasm) - initial_val = 0x12345678 - final_lds, lane_out = interp.run(seed_lds={7: initial_val}) - # Return value must be the OLD value - self.assertEqual(lane_out[0]["%out"], initial_val) - # Memory must contain the sum - self.assertEqual(final_lds[7], (initial_val + 50) & MASK) - - def test_atomic_add_overflow_wrap(self): - # Adding 1 to 0xFFFFFFFF wraps to 0, returning 0xFFFFFFFF - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c32 = OpConstant %uint 32 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%lds_arr = OpTypeArray %uint %c32 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%old = OpAtomicIAdd %uint %ptr %c2 %c0 %c1 -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={0: 0xFFFFFFFF}) - self.assertEqual(lane_out[0]["%out"], 0xFFFFFFFF) - self.assertEqual(final_lds[0], 0) - - def test_chained_atomic_additions_same_slot(self): - # Multiple sequential atomic additions accumulate correctly - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c4_slot = OpConstant %uint 4 -%c10 = OpConstant %uint 10 -%c20 = OpConstant %uint 20 -%c30 = OpConstant %uint 30 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c4_slot -%r1 = OpAtomicIAdd %uint %ptr %c2 %c0 %c10 -%r2 = OpAtomicIAdd %uint %ptr %c2 %c0 %c20 -%r3 = OpAtomicIAdd %uint %ptr %c2 %c0 %c30 -OpStore %out %r3 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={4: 100}) - # r1 got 100 (lds became 110) - # r2 got 110 (lds became 130) - # r3 got 130 (lds became 160) - self.assertEqual(lane_out[0]["%out"], 130) - self.assertEqual(final_lds[4], 160) - - def test_offset_and_wrapping_in_spirv(self): - # Simulates the full rdna2spirv sequence: - # byte_addr + offset -> shift right 2 -> bitwise and mask -> OpAccessChain - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c15 = OpConstant %uint 15 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c_base = OpConstant %uint 60 -%c_offset = OpConstant %uint 16 -%c_val = OpConstant %uint 42 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%s1 = OpIAdd %uint %c_base %c_offset -%i = OpShiftRightLogical %uint %s1 %c2 -%m = OpBitwiseAnd %uint %i %c15 -%ptr = OpAccessChain %_ptr_WG_uint %lds %m -%old = OpAtomicIAdd %uint %ptr %c2 %c0 %c_val -OpStore %out %old -OpReturn -OpFunctionEnd -""" - # Base 60 + Offset 16 = 76 - # 76 >> 2 = 19 - # 19 & 15 = 3 - interp = LdsAtomicInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={3: 500}) - self.assertEqual(lane_out[0]["%out"], 500) - self.assertEqual(final_lds[3], 542) - - -class TestWorkgroupMultiLaneAtomics(unittest.TestCase): - """Verifies multi-invocation workgroup coordination and atomic ticket allocation.""" - - def test_multi_lane_shared_counter_reduction(self): - # 8 invocations in a workgroup each atomically add 5 to LDS[0] - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 8 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%c5 = OpConstant %uint 5 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%ticket = OpAtomicIAdd %uint %ptr %c2 %c0 %c5 -OpStore %out %ticket -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicInterp(spvasm) - final_lds, lane_outs = interp.run(num_invocations=8, seed_lds={0: 0}) - # 8 lanes * 5 = 40 - self.assertEqual(final_lds[0], 40) - # Each lane must receive a unique ticket in {0, 5, 10, ..., 35} - tickets = [o["%out"] for o in lane_outs] - self.assertEqual(len(tickets), 8) - self.assertEqual(sorted(tickets), [0, 5, 10, 15, 20, 25, 30, 35]) - - def test_multi_lane_atomic_append_buffer_indices(self): - # 32 lanes (a full wave) allocate unique append slots from LDS[0] - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 32 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%slot = OpAtomicIAdd %uint %ptr %c2 %c0 %c1 -OpStore %out %slot -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicInterp(spvasm) - seed_start = 100 - final_lds, lane_outs = interp.run(num_invocations=32, seed_lds={0: seed_start}) - self.assertEqual(final_lds[0], seed_start + 32) - slots = [o["%out"] for o in lane_outs] - self.assertEqual(len(set(slots)), 32) - self.assertEqual(sorted(slots), list(range(seed_start, seed_start + 32))) - - -class TestTranslatorIntegration(unittest.TestCase): - """Verifies that tools/rdna2spirv.py emits conforming SPIR-V for ds_add_u32 and ds_add_rtn_u32.""" - - def _make_mock_gen(self, stage="cs"): - class MockGen: - def __init__(self): - self.stage = stage - self.uses_lds = False - self.lds_dwords = 256 - self.lds_bound = None # not bounds-checked (SHADER-309): the wrapped access - self.wave64 = True - self._tmp = 0 - self.emitted = [] - self.stored_dsts = [] - - def tmp(self): - self._tmp += 1 - return f"%t{self._tmp}" - - def cu(self, v): - return f"%c{v}" - - def active_b(self): - return "%exec_active" - - def src_u(self, arg): - return f"%v_{arg['r']}" - - def dst(self, d, v): - self.stored_dsts.append((d, v)) - - def emit(self, line): - self.emitted.append(line) - - LDS_ATOMICS = rdna2spirv.Gen.LDS_ATOMICS - mod_int = staticmethod(rdna2spirv.Gen.mod_int) - lds_ptr = rdna2spirv.Gen.lds_ptr - lds_access = rdna2spirv.Gen.lds_access - lds_atomic = rdna2spirv.Gen.lds_atomic - lds_op = rdna2spirv.Gen.lds_op - - return MockGen() - - def test_lds_atomics_table_contains_ds_add(self): - # Table maps non-returning opcode name to OpAtomicIAdd - self.assertIn("ds_add_u32", rdna2spirv.Gen.LDS_ATOMICS) - self.assertEqual(rdna2spirv.Gen.LDS_ATOMICS["ds_add_u32"], "OpAtomicIAdd") - - def test_ds_add_u32_non_returning_emission(self): - gen = self._make_mock_gen(stage="cs") - # ds_add_u32 v0, v1, offset:8 (args: addr=v0, data=v1) - gen.lds_op("ds_add_u32", [{"r": 0}, {"r": 1}], ["offset:8"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - # Must branch on active mask - self.assertIn("OpBranchConditional %exec_active", emitted_str) - # Must compute pointer with offset 8 and mask 255 - self.assertIn("OpIAdd %uint %v_0 %c8", emitted_str) - self.assertIn("OpShiftRightLogical %uint", emitted_str) - self.assertIn("OpBitwiseAnd %uint", emitted_str) - self.assertIn("OpAccessChain %_ptr_WG_uint %lds", emitted_str) - # Must emit OpAtomicIAdd with scope Workgroup (2) and Relaxed (0) - self.assertIn("OpAtomicIAdd %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - # Non-returning form must NOT call dst() - self.assertEqual(len(gen.stored_dsts), 0) - - def test_ds_add_rtn_u32_returning_emission(self): - gen = self._make_mock_gen(stage="cs") - # ds_add_rtn_u32 v5, v0, v1, offset:12 (args: dst=v5, addr=v0, data=v1) - gen.lds_op("ds_add_rtn_u32", [{"r": 5}, {"r": 0}, {"r": 1}], ["offset:12"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - self.assertIn("OpAtomicIAdd %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - # Returning form MUST store old value into destination v5 - self.assertEqual(len(gen.stored_dsts), 1) - dest_reg, val_id = gen.stored_dsts[0] - self.assertEqual(dest_reg["r"], 5) - self.assertTrue(val_id.startswith("%t")) - - def test_ds_add_outside_compute_raises_unsupported(self): - # Pixel shader or vertex shader cannot execute LDS operations - for invalid_stage in ("ps", "vs", "gs"): - with self.subTest(stage=invalid_stage): - gen = self._make_mock_gen(stage=invalid_stage) - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_add_u32", [{"r": 0}, {"r": 1}], []) - - -class TestNegativeControlsAndErrors(unittest.TestCase): - """Verifies that invalid constructs, unmodelled opcodes, and malformed headers fail.""" - - def test_unsupported_storage_class_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_UC = OpTypePointer UniformConstant %uint -%u = OpVariable %_ptr_UC UniformConstant -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(UnsupportedConstruct): - LdsAtomicInterp(spvasm) - - def test_unsupported_opcode_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c16 = OpConstant %uint 16 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%bad = OpSDiv %uint %c16 %c16 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_invalid_workgroup_size_rejected(self): - for dims in [(0, 1, 1), (1025, 1, 1), (32, 33, 1)]: - with self.subTest(dims=dims): - spvasm = f""" -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize {dims[0]} {dims[1]} {dims[2]} -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(WorkgroupBoundsError): - LdsAtomicInterp(spvasm) - - def test_atomic_on_non_lds_pointer_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_fn_uint = OpTypePointer Function %uint -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c5 = OpConstant %uint 5 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%local_v = OpVariable %_ptr_fn_uint Function -%bad = OpAtomicIAdd %uint %local_v %c2 %c0 %c5 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import lds_run as L # noqa: E402 (also puts tools/ on sys.path) + +M32 = L.M32 +FN = {"add": lambda m, d: (m + d) & M32, "sub": lambda m, d: (m - d) & M32} + + +def model(ops, init): + lds = dict(init) + rtns = [] + for name, addr, off, (d,) in ops: + a = addr + off + old = lds[a] + rtns.append(old if "_rtn_" in name else 0xDEAD) + lds[a] = FN[name.split("_")[1]](old, d) + return rtns, {a: lds[a] for a in sorted({addr + off for _, addr, off, _ in ops})} + + +class TestHandTable(unittest.TestCase): + TABLE = ( # (M, D, M + D, M - D) + (0, 0, 0, 0), (1, 2, 3, 0xFFFFFFFF), (0xFFFFFFFF, 1, 0, 0xFFFFFFFE), (0x7FFFFFFF, 1, 0x80000000, 0x7FFFFFFE), + (0x80000000, 0x80000000, 0, 0), (5, 0xFFFFFFFF, 4, 6), (0, 0xFFFFFFFF, 0xFFFFFFFF, 1), + (0x12345678, 0x9ABCDEF0, 0xACF13568, 0x77777788), + ) + + def test_one_operation(self): + for m, d, add, sub in self.TABLE: + for name, want in (("ds_add_rtn_u32", add), ("ds_sub_rtn_u32", sub), ("ds_add_u32", add), + ("ds_sub_u32", sub)): + with self.subTest(op=name, m=hex(m), d=hex(d)): + rtns, fin = L.run_chain([(name, 0x40, 0, (d,))], {0x40: m}) + self.assertEqual((rtns, fin), ([m if "_rtn_" in name else 0xDEAD], {0x40: want})) + + def test_offset_adds_to_the_address_in_bytes(self): + # vaddr 0x20 + offset 0x24 is the dword at byte 0x44; the dwords on either side stay as seeded. + init = {0x40: 1, 0x44: 40, 0x48: 3} + rtns, fin = L.run_chain([("ds_add_rtn_u32", 0x20, 0x24, (2,))], init) + self.assertEqual(rtns, [40]) + self.assertEqual(fin, {0x44: 42}) + rtns, fin = L.run_chain([("ds_add_rtn_u32", 0x20, 0x24, (2,)), ("ds_sub_u32", 0x40, 0, (5,)), + ("ds_add_u32", 0x48, 0, (7,))], init) + self.assertEqual(rtns, [40, 0xDEAD, 0xDEAD]) + self.assertEqual(fin, {0x40: 0xFFFFFFFC, 0x44: 42, 0x48: 10}) + + def test_chain_reuses_the_returned_value_order(self): + # Three adds to the same dword: each returns the running total, in program order. + ops = [("ds_add_rtn_u32", 8, 0, (10,)), ("ds_add_rtn_u32", 8, 0, (20,)), ("ds_sub_rtn_u32", 8, 0, (5,))] + self.assertEqual(L.run_chain(ops, {8: 100}), ([100, 110, 130], {8: 125})) + + +class TestSeeded(unittest.TestCase): + def test_random_sequences(self): + rng = random.Random(0xADD5) + for trial in range(8): + addrs = [0x10, 0x30, 0x7C, 0x100] + init = {a: rng.getrandbits(32) for a in addrs} + ops = [] + for _ in range(12): + name = rng.choice(("ds_add_rtn_u32", "ds_sub_rtn_u32", "ds_add_u32", "ds_sub_u32")) + eff = rng.choice(addrs) + off = rng.choice((0, 0, 0x10, 0x20)) # the same dword, split between vaddr and offset + a = eff - off + ops.append((name, a, off, (rng.choice((rng.getrandbits(32), 0xFFFFFFFF, 0x80000000, 1)),))) + with self.subTest(trial=trial): + self.assertEqual(L.run_chain(ops, init), model(ops, init)) if __name__ == "__main__": diff --git a/tests/semantic/test_lds_atomic_inc_u32.py b/tests/semantic/test_lds_atomic_inc_u32.py index c14543f88..07ad3047f 100644 --- a/tests/semantic/test_lds_atomic_inc_u32.py +++ b/tests/semantic/test_lds_atomic_inc_u32.py @@ -378,10 +378,6 @@ class TestReferenceAtomicIncOracle(unittest.TestCase): self.assertEqual(interp.get_vgpr(0, lane=3), 0xCAFEBABE) -if __name__ == "__main__": - unittest.main() - - class TestModuloWrapBoundaryAndBankConflicts(unittest.TestCase): """Tests modulo wrap boundaries and SIMD multi-lane bank conflict scenarios.""" @@ -497,3 +493,7 @@ class TestReturnValuePreservationAlignmentAndNegativeControls(unittest.TestCase) LdsSemanticInterpreter(lds_dwords=0) # non-positive lds dwords with self.assertRaises(ValueError): LdsSemanticInterpreter(lds_dwords=100) # non power-of-two lds dwords + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_lds_atomic_minmax.py b/tests/semantic/test_lds_atomic_minmax.py index 6dfab167e..3c5cd3460 100644 --- a/tests/semantic/test_lds_atomic_minmax.py +++ b/tests/semantic/test_lds_atomic_minmax.py @@ -1,1385 +1,100 @@ -"""Semantic interpreter tests for LDS atomic min/max (ds_min_u32, ds_max_u32, ds_min_i32, ds_max_i32). +"""ds_min_u32, ds_max_u32, ds_min_i32, ds_max_i32 (and their _rtn_ forms) through the translator. -Standard library only; no GPU, no LLVM, no external tools, no game files. +Standard library only; no GPU, no LLVM, no game files. - python -I tests/semantic/test_lds_atomic_minmax.py - python -m unittest discover -s tests/semantic -v +RDNA2 ISA, "Data Share Instructions": the atomic M = min(M, D) or max(M, D) on the dword at (vaddr + offset) / 4, +comparing as unsigned (_u32) or two's-complement signed (_i32); the _rtn_ form also returns the old M in vdst, the +plain form leaves vdst alone. The two comparisons differ exactly when the operands differ in bit 31: 0x80000000 is the +largest signed-negative and the 2^31-th unsigned value. -Background & Specification Rules: - * AMD RDNA2 / GFX10 Local Data Share (LDS) Architecture: - - LDS is an on-chip software-managed scratchpad memory shared across all threads - in a workgroup (threadgroup). - - Unsigned Atomics: - - `ds_min_u32 vaddr, vdata [offset:N]`: - Atomically computes: - addr = (vaddr + byte_offset) - idx = (addr >> 2) & (lds_dwords - 1) - LDS[idx] = min_u32(LDS[idx], vdata) - Non-returning form: the prior value at LDS[idx] is discarded. - - `ds_min_rtn_u32 vdst, vaddr, vdata [offset:N]`: - Returning form: writes prior LDS[idx] into destination VGPR vdst and - stores min_u32(old, vdata) in LDS[idx]. - - `ds_max_u32 vaddr, vdata [offset:N]` / `ds_max_rtn_u32 vdst, vaddr, vdata [offset:N]`: - Unsigned maximum, computing max_u32(LDS[idx], vdata). - - Signed Atomics (Two's-Complement 32-bit): - - `ds_min_i32 vaddr, vdata [offset:N]` / `ds_min_rtn_i32 vdst, vaddr, vdata [offset:N]`: - Interprets operands as signed two's-complement 32-bit integers in [-2^31, 2^31 - 1], - computing min_i32(LDS[idx], vdata). E.g. -1 (0xFFFFFFFF) < 0 (0x00000000). - - `ds_max_i32 vaddr, vdata [offset:N]` / `ds_max_rtn_i32 vdst, vaddr, vdata [offset:N]`: - Signed maximum, computing max_i32(LDS[idx], vdata). - - Active lane masking: - - LDS atomic instructions execute under execution mask control (%exec_active). - Only active lanes participate in memory modifications and destination register writes. - - Hardware wrapping & alignment: - - Byte addresses are shifted right by 2, dropping unaligned low bits [1:0]. - - The resulting dword index is masked with (lds_dwords - 1), wrapping out-of-bounds - offsets within the allocated power-of-two LDS slice. - * SPIR-V Representation: - - LDS is declared as an array in the Workgroup storage class: - %lds_arr = OpTypeArray %uint - %_ptr_WG_lds = OpTypePointer Workgroup %lds_arr - %_ptr_WG_uint = OpTypePointer Workgroup %uint - %lds = OpVariable %_ptr_WG_lds Workgroup - - Atomic min/max instructions map directly to SPIR-V core opcodes: - ds_min_u32 / ds_min_rtn_u32 -> OpAtomicUMin %uint %ptr %scope %semantics %val - ds_max_u32 / ds_max_rtn_u32 -> OpAtomicUMax %uint %ptr %scope %semantics %val - ds_min_i32 / ds_min_rtn_i32 -> OpAtomicSMin %uint %ptr %scope %semantics %val - ds_max_i32 / ds_max_rtn_i32 -> OpAtomicSMax %uint %ptr %scope %semantics %val - where %scope is Workgroup (2) and %semantics is Relaxed (0). +Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run in +tests/semantic/spirv_mini_interp.py (one lane: that interpreter does not share LDS between lanes, see lds_run.py). +It writes a few LDS dwords, runs a sequence of atomics and stores each returned value and the final dwords. The +tables are written out by hand; seeded random sequences are checked against a plain-Python LDS. Until this file, the +LDS tests of this name ran a self-built interpreter that checked only the shape of the SPIR-V. """ -from __future__ import annotations - import os -import re +import random import sys import unittest -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - -MASK = 0xFFFFFFFF -SIGN_BIT = 0x80000000 -INT32_MIN_SIGNED = -0x80000000 -INT32_MAX_SIGNED = 0x7FFFFFFF - - -class UnsupportedConstruct(NotImplementedError): - """The module uses an unmodelled SPIR-V opcode, type, or storage class.""" - - -class WorkgroupBoundsError(ValueError): - """Workgroup dimension or memory bounds violation.""" - - -_IGNORED = frozenset({ - "OpCapability", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", - "OpReturn", "OpFunctionEnd", "OpName", "OpSource", "OpSelectionMerge", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -def to_signed_i32(val: int) -> int: - """Interprets a 32-bit unsigned bit pattern as a signed two's-complement integer.""" - u = val & MASK - return u - 0x100000000 if u & SIGN_BIT else u - - -def to_unsigned_u32(val: int) -> int: - """Converts a signed or unsigned integer to a 32-bit unsigned bit pattern.""" - return val & MASK - - -def reference_atomic_umin(initial: int, val: int) -> int: - """Reference 32-bit unsigned atomic minimum.""" - u_init = initial & MASK - u_val = val & MASK - return min(u_init, u_val) - - -def reference_atomic_umax(initial: int, val: int) -> int: - """Reference 32-bit unsigned atomic maximum.""" - u_init = initial & MASK - u_val = val & MASK - return max(u_init, u_val) - - -def reference_atomic_smin(initial: int, val: int) -> int: - """Reference 32-bit signed atomic minimum returning 32-bit bit pattern.""" - s_init = to_signed_i32(initial) - s_val = to_signed_i32(val) - return to_unsigned_u32(min(s_init, s_val)) - - -def reference_atomic_smax(initial: int, val: int) -> int: - """Reference 32-bit signed atomic maximum returning 32-bit bit pattern.""" - s_init = to_signed_i32(initial) - s_val = to_signed_i32(val) - return to_unsigned_u32(max(s_init, s_val)) - - -def reference_lds_index(base_addr: int, byte_offset: int, lds_dwords: int) -> int: - """Reference dword index calculation with hardware wrapping.""" - effective_byte = (base_addr + byte_offset) & MASK - dword_idx = effective_byte >> 2 - return dword_idx & (lds_dwords - 1) - - -class LdsAtomicMinMaxInterp: - """Strict semantic interpreter for compute SPIR-V modules exercising LDS min/max atomics.""" - - def __init__(self, spvasm: str): - self.spvasm = spvasm - self.types: dict[str, tuple] = {} - self.constants: dict[str, int | bool] = {} - self.ptr_types: dict[str, tuple[str, str]] = {} - self.var_class: dict[str, str] = {} - self.local_size: tuple[int, int, int] = (1, 1, 1) - self.lds_var: str | None = None - self.lds_size: int = 0 - self.body: list[tuple[str | None, str, list[str], str]] = [] - self._parse() - - def _parse(self) -> None: - in_body = False - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"Cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - self.body.append((res, op, a, line)) - continue - if op == "OpFunction": - in_body = True - continue - if op == "OpExecutionMode" and len(a) >= 5 and a[1] == "LocalSize": - lx, ly, lz = int(a[2]), int(a[3]), int(a[4]) - if lx < 1 or ly < 1 or lz < 1 or (lx * ly * lz) > 1024: - raise WorkgroupBoundsError(f"Invalid LocalSize {lx}x{ly}x{lz}") - self.local_size = (lx, ly, lz) - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit int supported") - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeBool": - self.types[res] = ("bool",) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - size = int(self.constants[a[1]]) - self.types[res] = ("arr", a[0], size) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - self.constants[res] = int(a[1], 0) & MASK - elif op == "OpConstantTrue": - self.constants[res] = True - elif op == "OpConstantFalse": - self.constants[res] = False - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - if a[1] != cls: - raise UnsupportedConstruct("OpVariable storage class mismatch") - self.var_class[res] = cls - if cls == "Workgroup": - if self.lds_var is not None: - raise UnsupportedConstruct("Multiple Workgroup variables") - self.lds_var = res - arr_ty = self.types[pointee] - if arr_ty[0] != "arr": - raise UnsupportedConstruct("Workgroup variable must be an array") - self.lds_size = arr_ty[2] - elif cls not in ("Output", "Function"): - raise UnsupportedConstruct(f"Unsupported storage class {cls}") - else: - raise UnsupportedConstruct(f"Header opcode {op}") - - def run( - self, - num_invocations: int | None = None, - seed_lds: dict[int, int] | None = None, - lane_inputs: list[dict[str, int]] | None = None, - ) -> tuple[list[int], list[dict[str, int]]]: - """Executes the workgroup and returns (final_lds, outputs_per_lane).""" - lx, ly, lz = self.local_size - total_invocations = lx * ly * lz - count = total_invocations if num_invocations is None else min(num_invocations, total_invocations) - - lds = [0] * self.lds_size - if seed_lds: - for idx, val in seed_lds.items(): - if 0 <= idx < self.lds_size: - lds[idx] = val & MASK - - lane_outputs: list[dict[str, int]] = [] - for lidx in range(count): - inputs = lane_inputs[lidx] if lane_inputs and lidx < len(lane_inputs) else {} - out = self._run_lane(lidx, lds, inputs) - lane_outputs.append(out) - - return list(lds), lane_outputs - - def _run_lane(self, lidx: int, lds: list[int], inputs: dict[str, int]) -> dict[str, int]: - values: dict[str, int | bool] = dict(self.constants) - values.update(inputs) - var_box: dict[str, list[int]] = {} - pointers: dict[str, tuple[str, list[int], int | None]] = {} - outputs: list[str] = [] - - if self.lds_var: - pointers[self.lds_var] = ("lds", lds, None) - - for res, cls in self.var_class.items(): - if cls == "Output": - var_box[res] = [0] - pointers[res] = ("out", var_box[res], 0) - outputs.append(res) - elif cls == "Function": - var_box[res] = [0] - pointers[res] = ("fn", var_box[res], 0) - - def val(x: str) -> int | bool: - if x in values: - return values[x] - raise UnsupportedConstruct(f"Undefined identifier {x}") - - for res, op, a, _ in self.body: - if op in _IGNORED: - continue - if op in ("OpBranch", "OpBranchConditional"): - continue - if op == "OpVariable": - cls, _ = self.ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("Non-Function variable in body") - var_box[res] = [int(val(a[2])) if len(a) > 2 else 0] - pointers[res] = ("fn", var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if base not in pointers: - raise UnsupportedConstruct(f"OpAccessChain on non-pointer {base}") - ptag = pointers[base][0] - if ptag == "lds": - idx = int(val(a[2])) - if not (0 <= idx < len(lds)): - raise WorkgroupBoundsError(f"LDS access out of bounds: {idx} >= {len(lds)}") - pointers[res] = ("lds", lds, idx) - elif ptag in ("out", "fn"): - pointers[res] = pointers[base] - else: - raise UnsupportedConstruct(f"Access chain on {ptag}") - elif op == "OpLoad": - ptr = pointers[a[1]] - ptag = ptr[0] - idx = ptr[2] - assert idx is not None - if ptag in ("lds", "out", "fn"): - values[res] = ptr[1][idx] & MASK - else: - raise UnsupportedConstruct(f"OpLoad from {ptag}") - elif op == "OpStore": - ptr = pointers[a[0]] - v = int(val(a[1])) & MASK - ptag = ptr[0] - idx = ptr[2] - assert idx is not None - if ptag in ("lds", "out", "fn"): - ptr[1][idx] = v - else: - raise UnsupportedConstruct(f"OpStore to {ptag}") - elif op == "OpAtomicUMin": - # %res = OpAtomicUMin %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicUMin on non-LDS pointer {ptag}") - operand = int(val(a[4])) & MASK - idx = ptr[2] - assert idx is not None - old = ptr[1][idx] & MASK - ptr[1][idx] = min(old, operand) - values[res] = old - elif op == "OpAtomicUMax": - # %res = OpAtomicUMax %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicUMax on non-LDS pointer {ptag}") - operand = int(val(a[4])) & MASK - idx = ptr[2] - assert idx is not None - old = ptr[1][idx] & MASK - ptr[1][idx] = max(old, operand) - values[res] = old - elif op == "OpAtomicSMin": - # %res = OpAtomicSMin %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicSMin on non-LDS pointer {ptag}") - operand = int(val(a[4])) & MASK - idx = ptr[2] - assert idx is not None - old = ptr[1][idx] & MASK - s_old = to_signed_i32(old) - s_op = to_signed_i32(operand) - ptr[1][idx] = to_unsigned_u32(min(s_old, s_op)) - values[res] = old - elif op == "OpAtomicSMax": - # %res = OpAtomicSMax %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicSMax on non-LDS pointer {ptag}") - operand = int(val(a[4])) & MASK - idx = ptr[2] - assert idx is not None - old = ptr[1][idx] & MASK - s_old = to_signed_i32(old) - s_op = to_signed_i32(operand) - ptr[1][idx] = to_unsigned_u32(max(s_old, s_op)) - values[res] = old - elif op == "OpIAdd": - values[res] = (int(val(a[1])) + int(val(a[2]))) & MASK - elif op == "OpISub": - values[res] = (int(val(a[1])) - int(val(a[2]))) & MASK - elif op == "OpShiftRightLogical": - sh = int(val(a[2])) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (int(val(a[1])) >> sh) & MASK - elif op == "OpShiftLeftLogical": - sh = int(val(a[2])) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (int(val(a[1])) << sh) & MASK - elif op == "OpBitwiseAnd": - values[res] = int(val(a[1])) & int(val(a[2])) & MASK - elif op == "OpBitwiseOr": - values[res] = (int(val(a[1])) | int(val(a[2]))) & MASK - elif op == "OpBitwiseXor": - values[res] = (int(val(a[1])) ^ int(val(a[2]))) & MASK - elif op == "OpSelect": - cond = bool(val(a[1])) - values[res] = val(a[2]) if cond else val(a[3]) - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpBitcast": - values[res] = int(val(a[1])) & MASK - else: - raise UnsupportedConstruct(f"Opcode {op} not modelled in body") - - return {name: var_box[name][0] & MASK for name in outputs} - - -class TestReferenceMinMaxMath(unittest.TestCase): - """Verifies 32-bit unsigned and signed min/max arithmetic truth tables and edge cases.""" - - def test_unsigned_min_basic_and_edges(self): - cases = [ - (10, 20, 10), - (20, 10, 10), - (0, 0, 0), - (0, 100, 0), - (100, 0, 0), - (0, 0xFFFFFFFF, 0), - (0x7FFFFFFF, 0x80000000, 0x7FFFFFFF), - (0x80000000, 0xFFFFFFFF, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFE), - ] - for a, b, expected in cases: - with self.subTest(a=hex(a), b=hex(b), op="umin"): - self.assertEqual(reference_atomic_umin(a, b), expected) - - def test_unsigned_max_basic_and_edges(self): - cases = [ - (10, 20, 20), - (20, 10, 20), - (0, 0, 0), - (0, 100, 100), - (100, 0, 100), - (0, 0xFFFFFFFF, 0xFFFFFFFF), - (0x7FFFFFFF, 0x80000000, 0x80000000), - (0x80000000, 0xFFFFFFFF, 0xFFFFFFFF), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF), - ] - for a, b, expected in cases: - with self.subTest(a=hex(a), b=hex(b), op="umax"): - self.assertEqual(reference_atomic_umax(a, b), expected) - - def test_signed_min_basic_and_edges(self): - cases = [ - (10, 20, 10), - (20, 10, 10), - (0, 0, 0), - (0, 100, 0), - (0, 0xFFFFFFFF, 0xFFFFFFFF), # 0 vs -1 -> min is -1 - (100, 0xFFFFFFFF, 0xFFFFFFFF), # 100 vs -1 -> min is -1 - (0xFFFFFFF6, 0xFFFFFFEC, 0xFFFFFFEC), # -10 vs -20 -> min is -20 - (0x7FFFFFFF, 0x80000000, 0x80000000), # INT32_MAX vs INT32_MIN -> min is INT32_MIN - (0x80000000, 0, 0x80000000), # INT32_MIN vs 0 -> min is INT32_MIN - (0xFFFFFFFF, 0x00000001, 0xFFFFFFFF), # -1 vs 1 -> min is -1 - ] - for a, b, expected in cases: - with self.subTest(a=hex(a), b=hex(b), op="smin"): - self.assertEqual(reference_atomic_smin(a, b), expected) - - def test_signed_max_basic_and_edges(self): - cases = [ - (10, 20, 20), - (20, 10, 20), - (0, 0, 0), - (0, 100, 100), - (0, 0xFFFFFFFF, 0), # 0 vs -1 -> max is 0 - (100, 0xFFFFFFFF, 100), # 100 vs -1 -> max is 100 - (0xFFFFFFF6, 0xFFFFFFEC, 0xFFFFFFF6), # -10 vs -20 -> max is -10 - (0x7FFFFFFF, 0x80000000, 0x7FFFFFFF), # INT32_MAX vs INT32_MIN -> max is INT32_MAX - (0x80000000, 0, 0), # INT32_MIN vs 0 -> max is 0 - (0xFFFFFFFF, 0x00000001, 0x00000001), # -1 vs 1 -> max is 1 - ] - for a, b, expected in cases: - with self.subTest(a=hex(a), b=hex(b), op="smax"): - self.assertEqual(reference_atomic_smax(a, b), expected) - - def test_signed_vs_unsigned_divergence(self): - # Crucial architectural contrast: identical bit patterns evaluate to opposite extremes - divergent_pairs = [ - # (a, b): umin, smin, umax, smax - (0, 0xFFFFFFFF, 0, 0xFFFFFFFF, 0xFFFFFFFF, 0), - (0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000, 0x80000000, 0x7FFFFFFF), - (1, 0xFFFFFFFE, 1, 0xFFFFFFFE, 0xFFFFFFFE, 1), - (0x80000001, 5, 5, 0x80000001, 0x80000001, 5), - ] - for a, b, exp_umin, exp_smin, exp_umax, exp_smax in divergent_pairs: - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(reference_atomic_umin(a, b), exp_umin) - self.assertEqual(reference_atomic_smin(a, b), exp_smin) - self.assertEqual(reference_atomic_umax(a, b), exp_umax) - self.assertEqual(reference_atomic_smax(a, b), exp_smax) - # Ensure they actually diverge - self.assertNotEqual(exp_umin, exp_smin) - self.assertNotEqual(exp_umax, exp_smax) - - def test_accumulative_min_max_series(self): - # Accumulate arbitrary sequence of signed and unsigned values - vals = [50, 200, 10, 500, 3, 1000, 25] - u_min = vals[0] - u_max = vals[0] - for v in vals[1:]: - u_min = reference_atomic_umin(u_min, v) - u_max = reference_atomic_umax(u_max, v) - self.assertEqual(u_min, 3) - self.assertEqual(u_max, 1000) - - # Signed sequence with positive and negative numbers - s_vals = [10, -50, 100, -5, -500, 200, 0] - s_min = s_vals[0] & MASK - s_max = s_vals[0] & MASK - for v in s_vals[1:]: - s_min = reference_atomic_smin(s_min, v & MASK) - s_max = reference_atomic_smax(s_max, v & MASK) - self.assertEqual(to_signed_i32(s_min), -500) - self.assertEqual(to_signed_i32(s_max), 200) - - -class TestLdsAddressingAndOffsets(unittest.TestCase): - """Verifies byte offset math, dword truncation, and power-of-two modulo wrapping.""" - - def test_aligned_dword_addressing(self): - lds_dwords = 256 - for dword in (0, 1, 2, 64, 127, 255): - byte_addr = dword * 4 - self.assertEqual(reference_lds_index(byte_addr, 0, lds_dwords), dword) - - def test_unaligned_byte_truncation(self): - lds_dwords = 128 - for byte_off in (0, 1, 2, 3): - self.assertEqual(reference_lds_index(16, byte_off, lds_dwords), 4) - for unaligned_base in (16, 17, 18, 19): - self.assertEqual(reference_lds_index(unaligned_base, 0, lds_dwords), 4) - - def test_static_offset_addition(self): - lds_dwords = 512 - base = 32 # dword 8 - offset = 64 # +16 dwords - self.assertEqual(reference_lds_index(base, offset, lds_dwords), 24) - - def test_boundary_wrapping(self): - lds_dwords = 64 - self.assertEqual(reference_lds_index(256, 0, lds_dwords), 0) - self.assertEqual(reference_lds_index(256, 4, lds_dwords), 1) - self.assertEqual(reference_lds_index(0xFFFFFFFC, 0, lds_dwords), 63) - - -class TestSpirvAtomicUnsignedMinMaxInterpreter(unittest.TestCase): - """Executes SPIR-V compute kernels exercising OpAtomicUMin and OpAtomicUMax.""" - - def test_ds_min_u32_non_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c3 = OpConstant %uint 3 -%c50 = OpConstant %uint 50 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c3 -%dummy = OpAtomicUMin %uint %ptr %c2 %c0 %c50 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - # Case 1: Initial 200 min 50 -> 50 - final_lds, _ = interp.run(seed_lds={3: 200}) - self.assertEqual(final_lds[3], 50) - # Case 2: Initial 20 min 50 -> 20 (stays smaller) - final_lds, _ = interp.run(seed_lds={3: 20}) - self.assertEqual(final_lds[3], 20) - - def test_ds_min_rtn_u32_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c5 = OpConstant %uint 5 -%c400 = OpConstant %uint 400 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c5 -%old = OpAtomicUMin %uint %ptr %c2 %c0 %c400 -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={5: 1000}) - # Prior value was 1000 - self.assertEqual(lane_out[0]["%out"], 1000) - # Memory became 400 - self.assertEqual(final_lds[5], 400) - - def test_ds_max_u32_non_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c32 = OpConstant %uint 32 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c2_slot = OpConstant %uint 2 -%c150 = OpConstant %uint 150 -%lds_arr = OpTypeArray %uint %c32 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c2_slot -%dummy = OpAtomicUMax %uint %ptr %c2 %c0 %c150 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - # Initial 50 max 150 -> 150 - final_lds, _ = interp.run(seed_lds={2: 50}) - self.assertEqual(final_lds[2], 150) - # Initial 300 max 150 -> 300 (stays larger) - final_lds, _ = interp.run(seed_lds={2: 300}) - self.assertEqual(final_lds[2], 300) - - def test_ds_max_rtn_u32_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c32 = OpConstant %uint 32 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c4_slot = OpConstant %uint 4 -%c800 = OpConstant %uint 800 -%lds_arr = OpTypeArray %uint %c32 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c4_slot -%old = OpAtomicUMax %uint %ptr %c2 %c0 %c800 -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={4: 300}) - # Prior value was 300 - self.assertEqual(lane_out[0]["%out"], 300) - # Memory became 800 - self.assertEqual(final_lds[4], 800) - - def test_unsigned_min_max_boundaries(self): - # Updating 0xFFFFFFFF with 0 via OpAtomicUMin -> 0 - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%old = OpAtomicUMin %uint %ptr %c2 %c0 %c0 -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={0: 0xFFFFFFFF}) - self.assertEqual(lane_out[0]["%out"], 0xFFFFFFFF) - self.assertEqual(final_lds[0], 0) - - -class TestSpirvAtomicSignedMinMaxInterpreter(unittest.TestCase): - """Executes SPIR-V compute kernels exercising OpAtomicSMin and OpAtomicSMax.""" - - def test_ds_min_i32_non_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c3 = OpConstant %uint 3 -%c_neg5 = OpConstant %uint 0xFFFFFFFB -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c3 -%dummy = OpAtomicSMin %uint %ptr %c2 %c0 %c_neg5 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - # Initial 10 smin -5 -> -5 (0xFFFFFFFB) - final_lds, _ = interp.run(seed_lds={3: 10}) - self.assertEqual(final_lds[3], 0xFFFFFFFB) - - # Initial -10 (0xFFFFFFF6) smin -5 -> -10 (stays smaller) - final_lds, _ = interp.run(seed_lds={3: 0xFFFFFFF6}) - self.assertEqual(final_lds[3], 0xFFFFFFF6) - - def test_ds_min_rtn_i32_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c_neg1 = OpConstant %uint 0xFFFFFFFF -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c1 -%old = OpAtomicSMin %uint %ptr %c2 %c0 %c_neg1 -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - # 50 smin -1 -> -1 (0xFFFFFFFF), returning 50 - final_lds, lane_out = interp.run(seed_lds={1: 50}) - self.assertEqual(lane_out[0]["%out"], 50) - self.assertEqual(final_lds[1], 0xFFFFFFFF) - - def test_ds_max_i32_non_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c32 = OpConstant %uint 32 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c2_slot = OpConstant %uint 2 -%c_neg10 = OpConstant %uint 0xFFFFFFF6 -%lds_arr = OpTypeArray %uint %c32 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c2_slot -%dummy = OpAtomicSMax %uint %ptr %c2 %c0 %c_neg10 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - # Initial -50 (0xFFFFFFCE) smax -10 (0xFFFFFFF6) -> -10 - final_lds, _ = interp.run(seed_lds={2: 0xFFFFFFCE}) - self.assertEqual(final_lds[2], 0xFFFFFFF6) - - # Initial 5 smax -10 -> 5 (stays larger) - final_lds, _ = interp.run(seed_lds={2: 5}) - self.assertEqual(final_lds[2], 5) - - def test_ds_max_rtn_i32_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c32 = OpConstant %uint 32 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c6_slot = OpConstant %uint 6 -%c_int32_max = OpConstant %uint 0x7FFFFFFF -%lds_arr = OpTypeArray %uint %c32 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c6_slot -%old = OpAtomicSMax %uint %ptr %c2 %c0 %c_int32_max -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - # Seed with INT32_MIN (0x80000000), smax with INT32_MAX (0x7FFFFFFF) -> INT32_MAX, returning INT32_MIN - final_lds, lane_out = interp.run(seed_lds={6: 0x80000000}) - self.assertEqual(lane_out[0]["%out"], 0x80000000) - self.assertEqual(final_lds[6], 0x7FFFFFFF) - - -class TestSpirvSignedUnsignedDivergenceInKernels(unittest.TestCase): - """Direct comparative test proving signed and unsigned atomics diverge on identical inputs.""" - - def test_umin_vs_smin_with_zero_and_all_ones(self): - umin_spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%c_all_ones = OpConstant %uint 0xFFFFFFFF -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%old = OpAtomicUMin %uint %ptr %c2 %c0 %c_all_ones -OpStore %out %old -OpReturn -OpFunctionEnd -""" - smin_spvasm = umin_spvasm.replace("OpAtomicUMin", "OpAtomicSMin") - - # Initial value 0: - # UMin: min_u32(0, 0xFFFFFFFF) = 0 - interp_u = LdsAtomicMinMaxInterp(umin_spvasm) - lds_u, out_u = interp_u.run(seed_lds={0: 0}) - self.assertEqual(lds_u[0], 0) - self.assertEqual(out_u[0]["%out"], 0) - - # SMin: min_i32(0, -1) = -1 (0xFFFFFFFF) - interp_s = LdsAtomicMinMaxInterp(smin_spvasm) - lds_s, out_s = interp_s.run(seed_lds={0: 0}) - self.assertEqual(lds_s[0], 0xFFFFFFFF) - self.assertEqual(out_s[0]["%out"], 0) - - def test_umax_vs_smax_with_int32_min_max(self): - umax_spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%c_int32_min = OpConstant %uint 0x80000000 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%old = OpAtomicUMax %uint %ptr %c2 %c0 %c_int32_min -OpStore %out %old -OpReturn -OpFunctionEnd -""" - smax_spvasm = umax_spvasm.replace("OpAtomicUMax", "OpAtomicSMax") - - # Initial value 0x7FFFFFFF: - # UMax: max_u32(0x7FFFFFFF, 0x80000000) = 0x80000000 (unsigned 2147483648 > 2147483647) - interp_u = LdsAtomicMinMaxInterp(umax_spvasm) - lds_u, out_u = interp_u.run(seed_lds={0: 0x7FFFFFFF}) - self.assertEqual(lds_u[0], 0x80000000) - - # SMax: max_i32(+2147483647, -2147483648) = +2147483647 (0x7FFFFFFF) - interp_s = LdsAtomicMinMaxInterp(smax_spvasm) - lds_s, out_s = interp_s.run(seed_lds={0: 0x7FFFFFFF}) - self.assertEqual(lds_s[0], 0x7FFFFFFF) - - -class TestChainedSequentialAtomics(unittest.TestCase): - """Executes sequential chains of atomic min/max updates on a single LDS slot.""" - - def test_chained_umin_reduction(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c4_slot = OpConstant %uint 4 -%c300 = OpConstant %uint 300 -%c150 = OpConstant %uint 150 -%c200 = OpConstant %uint 200 -%c50 = OpConstant %uint 50 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c4_slot -%r1 = OpAtomicUMin %uint %ptr %c2 %c0 %c300 -%r2 = OpAtomicUMin %uint %ptr %c2 %c0 %c150 -%r3 = OpAtomicUMin %uint %ptr %c2 %c0 %c200 -%r4 = OpAtomicUMin %uint %ptr %c2 %c0 %c50 -OpStore %out %r4 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={4: 1000}) - # r1 saw 1000 (LDS became 300) - # r2 saw 300 (LDS became 150) - # r3 saw 150 (LDS stayed 150 because 200 > 150) - # r4 saw 150 (LDS became 50) - self.assertEqual(lane_out[0]["%out"], 150) - self.assertEqual(final_lds[4], 50) - - def test_chained_smax_reduction(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c2_slot = OpConstant %uint 2 -%c_neg100 = OpConstant %uint 0xFFFFFF9C -%c_neg20 = OpConstant %uint 0xFFFFFFEC -%c_neg50 = OpConstant %uint 0xFFFFFFCE -%c_pos10 = OpConstant %uint 10 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c2_slot -%r1 = OpAtomicSMax %uint %ptr %c2 %c0 %c_neg100 -%r2 = OpAtomicSMax %uint %ptr %c2 %c0 %c_neg20 -%r3 = OpAtomicSMax %uint %ptr %c2 %c0 %c_neg50 -%r4 = OpAtomicSMax %uint %ptr %c2 %c0 %c_pos10 -OpStore %out %r4 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={2: 0x80000000}) # INT32_MIN - # r1 saw INT32_MIN (LDS became -100) - # r2 saw -100 (LDS became -20) - # r3 saw -20 (LDS stayed -20 because -50 < -20) - # r4 saw -20 (LDS became +10) - self.assertEqual(lane_out[0]["%out"], 0xFFFFFFEC) # -20 - self.assertEqual(final_lds[2], 10) - - -class TestWorkgroupMultiLaneReductions(unittest.TestCase): - """Verifies parallel workgroup reductions and atomic convergence across multiple lanes.""" - - def test_multi_lane_unsigned_min_reduction(self): - # 8 lanes cooperate to find the unsigned minimum - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 8 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%old = OpAtomicUMin %uint %ptr %c2 %c0 %c_val -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - lane_values = [500, 320, 110, 850, 42, 600, 99, 150] - lane_inputs = [{"%c_val": v} for v in lane_values] - - final_lds, lane_outs = interp.run(num_invocations=8, seed_lds={0: 1000}, lane_inputs=lane_inputs) - # Minimum of seed 1000 and all lane_values is 42 - self.assertEqual(final_lds[0], 42) - # Returned values must form a monotonically non-increasing sequence - ret_vals = [o["%out"] for o in lane_outs] - self.assertEqual(ret_vals[0], 1000) - for i in range(1, len(ret_vals)): - self.assertLessEqual(ret_vals[i], ret_vals[i - 1]) - - def test_multi_lane_signed_max_reduction(self): - # 8 lanes propose signed values, finding signed maximum - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 8 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c1_slot = OpConstant %uint 1 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c1_slot -%old = OpAtomicSMax %uint %ptr %c2 %c0 %c_val -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - # Signed values: -50, -200, -5, +30, -10, +75, -1, 0 - signed_values = [-50, -200, -5, 30, -10, 75, -1, 0] - lane_inputs = [{"%c_val": to_unsigned_u32(v)} for v in signed_values] - - final_lds, _ = interp.run( - num_invocations=8, - seed_lds={1: to_unsigned_u32(-100)}, - lane_inputs=lane_inputs, - ) - self.assertEqual(to_signed_i32(final_lds[1]), 75) - - def test_wave32_workgroup_bounding_box_reduction(self): - # 32 lanes (a full wave) compute 2D bounding box (min_x, max_x) in LDS[0] and LDS[1] - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 32 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_min_slot = OpConstant %uint 0 -%c1_max_slot = OpConstant %uint 1 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr_min = OpAccessChain %_ptr_WG_uint %lds %c0_min_slot -%ptr_max = OpAccessChain %_ptr_WG_uint %lds %c1_max_slot -%r_min = OpAtomicUMin %uint %ptr_min %c2 %c0 %c_coord -%r_max = OpAtomicUMax %uint %ptr_max %c2 %c0 %c_coord -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - # Coordinate per lane: lane 0 -> 100, lane 1 -> 105, ..., lane 31 -> 255 - lane_inputs = [{"%c_coord": 100 + i * 5} for i in range(32)] - final_lds, _ = interp.run( - num_invocations=32, - seed_lds={0: 0xFFFFFFFF, 1: 0}, - lane_inputs=lane_inputs, - ) - self.assertEqual(final_lds[0], 100) - self.assertEqual(final_lds[1], 100 + 31 * 5) - - -class TestTranslatorIntegration(unittest.TestCase): - """Verifies that tools/rdna2spirv.py emits conforming SPIR-V for ds_min/max opcodes.""" - - def _make_mock_gen(self, stage="cs"): - class MockGen: - def __init__(self): - self.stage = stage - self.uses_lds = False - self.lds_dwords = 256 - self.lds_bound = None # not bounds-checked (SHADER-309): the wrapped access - self.wave64 = True - self._tmp = 0 - self.emitted = [] - self.stored_dsts = [] - - def tmp(self): - self._tmp += 1 - return f"%t{self._tmp}" - - def cu(self, v): - return f"%c{v}" - - def active_b(self): - return "%exec_active" - - def src_u(self, arg): - return f"%v_{arg['r']}" - - def dst(self, d, v): - self.stored_dsts.append((d, v)) - - def emit(self, line): - self.emitted.append(line) - - LDS_ATOMICS = rdna2spirv.Gen.LDS_ATOMICS - mod_int = staticmethod(rdna2spirv.Gen.mod_int) - lds_ptr = rdna2spirv.Gen.lds_ptr - lds_access = rdna2spirv.Gen.lds_access - lds_atomic = rdna2spirv.Gen.lds_atomic - lds_op = rdna2spirv.Gen.lds_op - - return MockGen() - - def test_lds_atomics_table_contains_minmax_opcodes(self): - expected_mappings = { - "ds_min_u32": "OpAtomicUMin", - "ds_max_u32": "OpAtomicUMax", - "ds_min_i32": "OpAtomicSMin", - "ds_max_i32": "OpAtomicSMax", - } - for opcode, spirv_inst in expected_mappings.items(): - with self.subTest(opcode=opcode): - self.assertIn(opcode, rdna2spirv.Gen.LDS_ATOMICS) - self.assertEqual(rdna2spirv.Gen.LDS_ATOMICS[opcode], spirv_inst) - - def test_ds_min_u32_non_returning_emission(self): - gen = self._make_mock_gen(stage="cs") - # ds_min_u32 v0, v1, offset:8 (args: addr=v0, data=v1) - gen.lds_op("ds_min_u32", [{"r": 0}, {"r": 1}], ["offset:8"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - self.assertIn("OpBranchConditional %exec_active", emitted_str) - self.assertIn("OpIAdd %uint %v_0 %c8", emitted_str) - self.assertIn("OpShiftRightLogical %uint", emitted_str) - self.assertIn("OpBitwiseAnd %uint", emitted_str) - self.assertIn("OpAccessChain %_ptr_WG_uint %lds", emitted_str) - self.assertIn("OpAtomicUMin %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - # Non-returning form must NOT store destination - self.assertEqual(len(gen.stored_dsts), 0) - - def test_ds_min_rtn_u32_returning_emission(self): - gen = self._make_mock_gen(stage="cs") - # ds_min_rtn_u32 v5, v0, v1, offset:12 (args: dst=v5, addr=v0, data=v1) - gen.lds_op("ds_min_rtn_u32", [{"r": 5}, {"r": 0}, {"r": 1}], ["offset:12"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - self.assertIn("OpAtomicUMin %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - self.assertEqual(len(gen.stored_dsts), 1) - dest_reg, val_id = gen.stored_dsts[0] - self.assertEqual(dest_reg["r"], 5) - self.assertTrue(val_id.startswith("%t")) - - def test_ds_max_u32_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op("ds_max_rtn_u32", [{"r": 2}, {"r": 3}, {"r": 4}], []) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - self.assertIn("OpAtomicUMax %uint", emitted_str) - self.assertEqual(len(gen.stored_dsts), 1) - self.assertEqual(gen.stored_dsts[0][0]["r"], 2) - - def test_ds_min_i32_signed_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op("ds_min_rtn_i32", [{"r": 7}, {"r": 1}, {"r": 2}], ["offset:16"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - self.assertIn("OpAtomicSMin %uint", emitted_str) - self.assertIn("%c2 %c0 %v_2", emitted_str) - self.assertEqual(len(gen.stored_dsts), 1) - self.assertEqual(gen.stored_dsts[0][0]["r"], 7) - - def test_ds_max_i32_signed_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op("ds_max_rtn_i32", [{"r": 9}, {"r": 4}, {"r": 5}], ["offset:4"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - self.assertIn("OpAtomicSMax %uint", emitted_str) - self.assertIn("%c2 %c0 %v_5", emitted_str) - self.assertEqual(len(gen.stored_dsts), 1) - self.assertEqual(gen.stored_dsts[0][0]["r"], 9) - - def test_lds_minmax_outside_compute_raises_unsupported(self): - for invalid_stage in ("ps", "vs", "gs"): - for op in ("ds_min_u32", "ds_max_u32", "ds_min_i32", "ds_max_i32"): - with self.subTest(stage=invalid_stage, op=op): - gen = self._make_mock_gen(stage=invalid_stage) - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op(op, [{"r": 0}, {"r": 1}], []) - - -class TestNegativeControlsAndBounds(unittest.TestCase): - """Verifies bounds enforcement, invalid opcodes, and malformed constructs.""" - - def test_unsupported_storage_class_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_UC = OpTypePointer UniformConstant %uint -%u = OpVariable %_ptr_UC UniformConstant -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(UnsupportedConstruct): - LdsAtomicMinMaxInterp(spvasm) - - def test_unsupported_opcode_in_body_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c16 = OpConstant %uint 16 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%bad = OpSDiv %uint %c16 %c16 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_invalid_workgroup_size_rejected(self): - for dims in [(0, 1, 1), (1025, 1, 1), (32, 33, 1)]: - with self.subTest(dims=dims): - spvasm = f""" -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize {dims[0]} {dims[1]} {dims[2]} -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(WorkgroupBoundsError): - LdsAtomicMinMaxInterp(spvasm) - - def test_atomic_on_non_lds_pointer_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_fn_uint = OpTypePointer Function %uint -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c5 = OpConstant %uint 5 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%local_v = OpVariable %_ptr_fn_uint Function -%bad = OpAtomicUMin %uint %local_v %c2 %c0 %c5 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_lds_out_of_bounds_access_chain_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c8 = OpConstant %uint 8 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c100_slot = OpConstant %uint 100 -%lds_arr = OpTypeArray %uint %c8 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c100_slot -%dummy = OpAtomicUMin %uint %ptr %c2 %c0 %c0 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicMinMaxInterp(spvasm) - with self.assertRaises(WorkgroupBoundsError): - interp.run() +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import lds_run as L # noqa: E402 (also puts tools/ on sys.path) + +M32 = L.M32 + + +def s32(x): + return x - (1 << 32) if x >> 31 else x + + +FN = {"min_u32": min, "max_u32": max, + "min_i32": lambda m, d: m if s32(m) <= s32(d) else d, "max_i32": lambda m, d: m if s32(m) >= s32(d) else d} + + +def model(ops, init): + lds = dict(init) + rtns = [] + for name, addr, off, (d,) in ops: + a = addr + off + rtns.append(lds[a] if "_rtn_" in name else 0xDEAD) + lds[a] = FN[name.replace("_rtn_", "_")[3:]](lds[a], d) + return rtns, {a: lds[a] for a in sorted({addr + off for _, addr, off, _ in ops})} + + +class TestHandTable(unittest.TestCase): + # M D min_u max_u min_i max_i + TABLE = ((0, 0, 0, 0, 0, 0), + (1, 2, 1, 2, 1, 2), + (5, 3, 3, 5, 3, 5), + (0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000, 0x80000000, 0x7FFFFFFF), + (0x80000000, 0x7FFFFFFF, 0x7FFFFFFF, 0x80000000, 0x80000000, 0x7FFFFFFF), + (0xFFFFFFFF, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF, 0), + (0xFFFFFFFF, 1, 1, 0xFFFFFFFF, 0xFFFFFFFF, 1), + (0x80000000, 0x80000001, 0x80000000, 0x80000001, 0x80000000, 0x80000001), + (7, 7, 7, 7, 7, 7)) + + def test_one_operation(self): + for m, d, *want in self.TABLE: + for kind, w in zip(("min_u32", "max_u32", "min_i32", "max_i32"), want): + for rtn in (True, False): + name = f"ds_{kind[:3]}_rtn_{kind[4:]}" if rtn else f"ds_{kind}" + with self.subTest(op=name, m=hex(m), d=hex(d)): + rtns, fin = L.run_chain([(name, 0x40, 0, (d,))], {0x40: m}) + self.assertEqual((rtns, fin), ([m if rtn else 0xDEAD], {0x40: w})) + + def test_signed_and_unsigned_diverge_on_the_same_operands(self): + ops = [("ds_min_rtn_u32", 0x10, 0, (0x80000000,)), ("ds_min_rtn_i32", 0x14, 0, (0x80000000,))] + rtns, fin = L.run_chain(ops, {0x10: 1, 0x14: 1}) + self.assertEqual(rtns, [1, 1]) + self.assertEqual(fin, {0x10: 1, 0x14: 0x80000000}) + + def test_offset_adds_to_the_address_in_bytes(self): + rtns, fin = L.run_chain([("ds_max_rtn_u32", 0x20, 0x24, (9,))], {0x44: 4, 0x40: 100}) + self.assertEqual((rtns, fin), ([4], {0x44: 9})) + + def test_running_reduction_in_program_order(self): + # min of 50, 20, 70, 20, 5 into one dword starting at 100: each _rtn_ shows the minimum so far. + ops = [("ds_min_rtn_u32", 8, 0, (d,)) for d in (50, 20, 70, 20, 5)] + self.assertEqual(L.run_chain(ops, {8: 100}), ([100, 50, 20, 20, 20], {8: 5})) + + +class TestSeeded(unittest.TestCase): + def test_random_sequences(self): + rng = random.Random(0x3141) + edge = (0, 1, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF) + for trial in range(8): + addrs = [0x10, 0x30, 0x7C, 0x100] + init = {a: rng.choice((rng.getrandbits(32), *edge)) for a in addrs} + ops = [] + for _ in range(12): + kind = rng.choice(tuple(FN)) + name = f"ds_{kind[:3]}_rtn_{kind[4:]}" if rng.random() < 0.6 else f"ds_{kind}" + eff = rng.choice(addrs) + off = rng.choice((0, 0, 0x10, 0x20)) + ops.append((name, eff - off, off, (rng.choice((rng.getrandbits(32), *edge)),))) + with self.subTest(trial=trial): + self.assertEqual(L.run_chain(ops, init), model(ops, init)) if __name__ == "__main__": diff --git a/tests/semantic/test_lds_atomic_xchg.py b/tests/semantic/test_lds_atomic_xchg.py index dd9a9eddc..8ccb22364 100644 --- a/tests/semantic/test_lds_atomic_xchg.py +++ b/tests/semantic/test_lds_atomic_xchg.py @@ -1,1295 +1,75 @@ -"""Semantic interpreter tests for LDS atomic exchange operations (ds_wrxchg_rtn_b32, ds_wrxchg2_rtn_b32). +"""ds_wrxchg_rtn_b32 through the translator (the two-dword form is in test_lds_wrxchg2.py). -Standard library only; no GPU, no LLVM, no external tools, no game files. +Standard library only; no GPU, no LLVM, no game files. -Run directly: - python -I tests/semantic/test_lds_atomic_xchg.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -v +RDNA2 ISA, "Data Share Instructions": ds_wrxchg_rtn_b32 vdst, vaddr, vdata is the atomic exchange: vdst receives the +old dword at (vaddr + offset) / 4 and the dword becomes vdata. There is no plain (non-returning) form of the +single-dword exchange. -Background & Specification Rules: - * AMD RDNA2 / GFX10 Local Data Share (LDS) Architecture: - - LDS is an on-chip software-managed scratchpad memory shared across all invocations - in a workgroup (threadgroup). - - Single atomic exchange (ds_wrxchg_rtn_b32): - Syntax: `ds_wrxchg_rtn_b32 vdst, vaddr, vdata [offset:N]` - Atomically swaps memory contents with vdata and returns prior value: - effective_byte_address = (vaddr + offset) & 0xFFFFFFFF - dword_index = (effective_byte_address >> 2) & (lds_dwords - 1) - old_val = LDS[dword_index] - LDS[dword_index] = vdata & 0xFFFFFFFF - vdst = old_val - - Dual atomic exchange (ds_wrxchg2_rtn_b32, ds_wrxchg2st64_rtn_b32): - Syntax: `ds_wrxchg2_rtn_b32 vdst, vaddr, vdata0, vdata1 [offset0:N] [offset1:M]` - Executes two 32-bit atomic exchanges from a single base address with two 8-bit offsets. - Unit stride is 4 bytes (1 dword) for `ds_wrxchg2_rtn_b32`, or 256 bytes (64 dwords) - for `ds_wrxchg2st64_rtn_b32`. - Address calculation: - eff_byte0 = (vaddr + offset0 * unit) & 0xFFFFFFFF - dword_idx0 = (eff_byte0 >> 2) & (lds_dwords - 1) - eff_byte1 = (vaddr + offset1 * unit) & 0xFFFFFFFF - dword_idx1 = (eff_byte1 >> 2) & (lds_dwords - 1) - Serialization / Address Collision: - When dword_idx0 == dword_idx1 (both offsets alias to the same LDS location), - hardware serializes the operations: port 0 executes first, then port 1. - Therefore: - vdst[0] = initial_old_value - LDS[dword_idx] = vdata0 - vdst[1] = vdata0 (observes port 0 write) - LDS[dword_idx] = vdata1 (final state) - - Active lane masking: - LDS instructions are vector operations governed by the execution mask (EXEC). - Only active lanes participate in LDS mutations and destination register updates. - Inactive lanes leave LDS memory untouched and preserve destination VGPR contents. - - Modulo wrapping & dword alignment: - Byte addresses are converted to dword indices by truncating the low 2 bits (>> 2). - Indices wrap modulo lds_dwords (a power-of-two capacity, 16..16384 dwords). - 32-bit address overflow wraps strictly modulo 2^32. - * SPIR-V Representation: - - LDS is allocated in the Workgroup storage class as an array of uint: - %lds_arr = OpTypeArray %uint - %_ptr_WG_lds = OpTypePointer Workgroup %lds_arr - %_ptr_WG_uint = OpTypePointer Workgroup %uint - %lds = OpVariable %_ptr_WG_lds Workgroup - - Atomic exchange maps directly to OpAtomicExchange: - %old = OpAtomicExchange %uint %ptr %scope %semantics %val - where %scope is Workgroup (2) and %semantics is Relaxed (0). - - Dual atomic exchange translates into two sequential OpAtomicExchange instructions - with their respective OpAccessChain pointers. +Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run in +tests/semantic/spirv_mini_interp.py (one lane: that interpreter does not share LDS between lanes, see lds_run.py). +It writes a few LDS dwords, runs exchanges on them and stores each returned value and the final dwords. The tables +are written out by hand; seeded random sequences are checked against a plain-Python LDS. Until this file, the LDS +tests of this name ran a self-built interpreter that checked only the shape of the SPIR-V. """ -from __future__ import annotations - import os -import re +import random import sys import unittest -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import lds_run as L # noqa: E402 (also puts tools/ on sys.path) import rdna2spirv # noqa: E402 - -MASK = 0xFFFFFFFF -DEFAULT_LDS_DWORDS = 16384 # 64 KiB default capacity in dwords - - -class UnsupportedConstruct(NotImplementedError): - """The module uses an unmodelled SPIR-V opcode, type, or storage class.""" - - -class WorkgroupBoundsError(ValueError): - """Workgroup dimension or memory bounds violation.""" - - -_IGNORED = frozenset({ - "OpCapability", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", - "OpReturn", "OpFunctionEnd", "OpName", "OpSource", "OpSelectionMerge", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -def reference_atomic_xchg(current_val: int, new_val: int) -> tuple[int, int]: - """Reference 32-bit atomic exchange: returns (old_val, updated_mem_val).""" - old = current_val & MASK - new = new_val & MASK - return old, new - - -def reference_atomic_xchg2( - current_val0: int, - current_val1: int, - new_val0: int, - new_val1: int, - aliased: bool = False, -) -> tuple[int, int, int, int]: - """Reference dual atomic exchange: returns (old0, old1, final_mem0, final_mem1). - - If aliased is True, both ports access the exact same dword address. - Per AMD GFX10 / RDNA2 specification, port 0 executes first followed by port 1, - so old0 is current_val0, old1 is new_val0, and the final memory holds new_val1. - """ - if aliased: - old0 = current_val0 & MASK - old1 = new_val0 & MASK - final0 = new_val1 & MASK - final1 = final0 - return old0, old1, final0, final1 - else: - old0 = current_val0 & MASK - old1 = current_val1 & MASK - final0 = new_val0 & MASK - final1 = new_val1 & MASK - return old0, old1, final0, final1 - - -def calc_lds_byte_offset( - vaddr: int, - byte_offset: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, -) -> tuple[int, int, int]: - """Reference ISA calculation for single LDS address: (effective_byte, dword_idx, byte_in_dword).""" - vaddr = vaddr & MASK - byte_offset = byte_offset & 0xFFFF # 16-bit unsigned offset in RDNA2 DS instructions - eff_byte = (vaddr + byte_offset) & MASK - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - byte_in_dword = eff_byte & 3 - return eff_byte, dword_idx, byte_in_dword - - -def calc_lds_dual_offsets( - vaddr: int, - offset0: int = 0, - offset1: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, - st64: bool = False, -) -> tuple[tuple[int, int], tuple[int, int]]: - """Reference ISA calculation for dual LDS addresses. - - Returns: - ((eff_byte0, dword_idx0), (eff_byte1, dword_idx1)) - """ - vaddr = vaddr & MASK - unit = 256 if st64 else 4 - off0_bytes = (offset0 & 0xFF) * unit - off1_bytes = (offset1 & 0xFF) * unit - eff_byte0 = (vaddr + off0_bytes) & MASK - eff_byte1 = (vaddr + off1_bytes) & MASK - dword_idx0 = (eff_byte0 >> 2) & (lds_dwords - 1) - dword_idx1 = (eff_byte1 >> 2) & (lds_dwords - 1) - return (eff_byte0, dword_idx0), (eff_byte1, dword_idx1) - - -class LdsSemanticInterpreter: - """Deterministic semantic interpreter for RDNA2 LDS atomic exchange and memory instructions. - - Models LDS shared scratchpad memory, per-lane VGPR register files, and execution masks. - """ - - def __init__(self, lds_dwords: int = DEFAULT_LDS_DWORDS, num_vgprs: int = 256, num_lanes: int = 64): - self.lds_dwords = lds_dwords - self.lds = [0] * lds_dwords - self.num_vgprs = num_vgprs - self.num_lanes = num_lanes - self.vgprs = [[0] * num_vgprs for _ in range(num_lanes)] - self.active_lanes = [True] * num_lanes - - def set_vgpr(self, reg_idx: int, value: int, lane: int = 0) -> None: - self.vgprs[lane][reg_idx] = value & MASK - - def get_vgpr(self, reg_idx: int, lane: int = 0) -> int: - return self.vgprs[lane][reg_idx] - - def set_lds_dword(self, dword_idx: int, value: int) -> None: - self.lds[dword_idx & (self.lds_dwords - 1)] = value & MASK - - def get_lds_dword(self, dword_idx: int) -> int: - return self.lds[dword_idx & (self.lds_dwords - 1)] - - def set_lane_active(self, lane: int, active: bool) -> None: - self.active_lanes[lane] = bool(active) - - def ds_write_b32(self, vaddr_reg: int, vdata_reg: int, offset: int = 0, lane: int = 0) -> int | None: - """Execute ds_write_b32 vaddr, vdata [offset:offset].""" - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.lds[dword_idx] = vdata & MASK - return dword_idx - - def ds_read_b32(self, vdst_reg: int, vaddr_reg: int, offset: int = 0, lane: int = 0) -> int | None: - """Execute ds_read_b32 vdst, vaddr [offset:offset].""" - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.vgprs[lane][vdst_reg] = self.lds[dword_idx] - return dword_idx - - def ds_wrxchg_rtn_b32( - self, - vdst_reg: int, - vaddr_reg: int, - vdata_reg: int, - offset: int = 0, - lane: int = 0, - ) -> tuple[int, int] | None: - """Execute ds_wrxchg_rtn_b32 vdst, vaddr, vdata [offset:offset]. - - Returns (dword_idx, old_val) if active, or None if inactive. - """ - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - old_val = self.lds[dword_idx] - self.lds[dword_idx] = vdata & MASK - self.vgprs[lane][vdst_reg] = old_val - return dword_idx, old_val - - def ds_wrxchg2_rtn_b32( - self, - vdst_reg: int, - vaddr_reg: int, - vdata0_reg: int, - vdata1_reg: int, - offset0: int = 0, - offset1: int = 0, - st64: bool = False, - lane: int = 0, - ) -> tuple[tuple[int, int], tuple[int, int]] | None: - """Execute ds_wrxchg2_rtn_b32 / ds_wrxchg2st64_rtn_b32. - - Dual atomic exchange at two separate offsets from vaddr. - vdst occupies two consecutive registers: vdst and vdst+1. - Returns ((idx0, old0), (idx1, old1)) if active, or None if inactive. - """ - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata0 = self.vgprs[lane][vdata0_reg] - vdata1 = self.vgprs[lane][vdata1_reg] - (_, idx0), (_, idx1) = calc_lds_dual_offsets(vaddr, offset0, offset1, self.lds_dwords, st64=st64) - - if idx0 == idx1: - # Address collision: port 0 executes first, port 1 observes port 0 write - old0 = self.lds[idx0] - self.lds[idx0] = vdata0 & MASK - old1 = self.lds[idx1] # equals vdata0 - self.lds[idx1] = vdata1 & MASK - else: - old0 = self.lds[idx0] - self.lds[idx0] = vdata0 & MASK - old1 = self.lds[idx1] - self.lds[idx1] = vdata1 & MASK - - self.vgprs[lane][vdst_reg] = old0 - self.vgprs[lane][vdst_reg + 1] = old1 - return (idx0, old0), (idx1, old1) - - def parse_and_execute(self, instruction_text: str, lane: int = 0) -> tuple[int, ...] | int | None: - """Parse and execute an LDS assembly instruction string for the specified lane.""" - line = instruction_text.strip() - if not line or line.startswith(";"): - return None - - # Extract modifiers: offset:N, offset0:N, offset1:N - offset = 0 - m_off = re.search(r"\boffset:(\S+)", line) - if m_off: - offset = int(m_off.group(1), 0) - line = re.sub(r"\boffset:\S+", "", line).strip() - - offset0 = 0 - m_off0 = re.search(r"\boffset0:(\S+)", line) - if m_off0: - offset0 = int(m_off0.group(1), 0) - line = re.sub(r"\boffset0:\S+", "", line).strip() - - offset1 = 0 - m_off1 = re.search(r"\boffset1:(\S+)", line) - if m_off1: - offset1 = int(m_off1.group(1), 0) - line = re.sub(r"\boffset1:\S+", "", line).strip() - - parts = line.split(None, 1) - op = parts[0] - args_str = parts[1] if len(parts) > 1 else "" - raw_args = [a.strip() for a in args_str.split(",") if a.strip()] - - def reg_num(tok: str) -> int: - cleaned = tok.replace("v", "").replace("[", "").replace("]", "") - if ":" in cleaned: - cleaned = cleaned.split(":")[0] - return int(cleaned) - - if op == "ds_wrxchg_rtn_b32": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - vdata = reg_num(raw_args[2]) - res = self.ds_wrxchg_rtn_b32(vdst, vaddr, vdata, offset=offset, lane=lane) - return res[0] if res else None - - elif op in ("ds_wrxchg2_rtn_b32", "ds_wrxchg2st64_rtn_b32"): - st64 = "st64" in op - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - vdata0 = reg_num(raw_args[2]) - vdata1 = reg_num(raw_args[3]) - res = self.ds_wrxchg2_rtn_b32( - vdst, vaddr, vdata0, vdata1, offset0=offset0, offset1=offset1, st64=st64, lane=lane - ) - return (res[0][0], res[1][0]) if res else None - - elif op == "ds_write_b32": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - return self.ds_write_b32(vaddr, vdata, offset=offset, lane=lane) - - elif op == "ds_read_b32": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - return self.ds_read_b32(vdst, vaddr, offset=offset, lane=lane) - - else: - raise UnsupportedConstruct(f"Opcode {op} not supported by LdsSemanticInterpreter") - - -class LdsAtomicSpirvInterp: - """Strict semantic interpreter for compute SPIR-V modules exercising LDS atomic exchange.""" - - def __init__(self, spvasm: str): - self.spvasm = spvasm - self.types: dict[str, tuple] = {} - self.constants: dict[str, int | bool] = {} - self.ptr_types: dict[str, tuple[str, str]] = {} - self.var_class: dict[str, str] = {} - self.local_size: tuple[int, int, int] = (1, 1, 1) - self.lds_var: str | None = None - self.lds_size: int = 0 - self.body: list[tuple[str | None, str, list[str], str]] = [] - self._parse() - - def _parse(self) -> None: - in_body = False - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"Cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - self.body.append((res, op, a, line)) - continue - if op == "OpFunction": - in_body = True - continue - if op == "OpExecutionMode" and len(a) >= 5 and a[1] == "LocalSize": - lx, ly, lz = int(a[2]), int(a[3]), int(a[4]) - if lx < 1 or ly < 1 or lz < 1 or (lx * ly * lz) > 1024: - raise WorkgroupBoundsError(f"Invalid LocalSize {lx}x{ly}x{lz}") - self.local_size = (lx, ly, lz) - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit int supported") - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeBool": - self.types[res] = ("bool",) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - size = int(self.constants[a[1]]) - self.types[res] = ("arr", a[0], size) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - self.constants[res] = int(a[1], 0) & MASK - elif op == "OpConstantTrue": - self.constants[res] = True - elif op == "OpConstantFalse": - self.constants[res] = False - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - if a[1] != cls: - raise UnsupportedConstruct("OpVariable storage class mismatch") - self.var_class[res] = cls - if cls == "Workgroup": - if self.lds_var is not None: - raise UnsupportedConstruct("Multiple Workgroup variables") - self.lds_var = res - arr_ty = self.types[pointee] - if arr_ty[0] != "arr": - raise UnsupportedConstruct("Workgroup variable must be an array") - self.lds_size = arr_ty[2] - elif cls not in ("Output", "Function"): - raise UnsupportedConstruct(f"Unsupported storage class {cls}") - else: - raise UnsupportedConstruct(f"Header opcode {op}") - - def run( - self, - num_invocations: int | None = None, - seed_lds: dict[int, int] | None = None, - lane_inputs: list[dict[str, int]] | None = None, - ) -> tuple[list[int], list[dict[str, int]]]: - """Executes the workgroup and returns (final_lds, outputs_per_lane).""" - lx, ly, lz = self.local_size - total_invocations = lx * ly * lz - count = total_invocations if num_invocations is None else min(num_invocations, total_invocations) - - lds = [0] * self.lds_size - if seed_lds: - for idx, val in seed_lds.items(): - if 0 <= idx < self.lds_size: - lds[idx] = val & MASK - - lane_outputs = [] - for lidx in range(count): - inputs = lane_inputs[lidx] if lane_inputs and lidx < len(lane_inputs) else {} - out = self._run_lane(lidx, lds, inputs) - lane_outputs.append(out) - - return list(lds), lane_outputs - - def _run_lane(self, lidx: int, lds: list[int], inputs: dict[str, int]) -> dict[str, int]: - values = dict(self.constants) - values.update(inputs) - var_box: dict[str, list[int]] = {} - pointers: dict[str, tuple[str, list[int], int | None]] = {} - outputs: list[str] = [] - - if self.lds_var: - pointers[self.lds_var] = ("lds", lds, None) - - for res, cls in self.var_class.items(): - if cls == "Output": - var_box[res] = [0] - pointers[res] = ("out", var_box[res], 0) - outputs.append(res) - elif cls == "Function": - var_box[res] = [0] - pointers[res] = ("fn", var_box[res], 0) - - def val(x: str) -> int: - if x in values: - return values[x] - raise UnsupportedConstruct(f"Undefined identifier {x}") - - for res, op, a, _ in self.body: - if op in _IGNORED: - continue - if op == "OpBranch" or op == "OpBranchConditional": - continue - if op == "OpVariable": - cls, _ = self.ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("Non-Function variable in body") - var_box[res] = [val(a[2]) if len(a) > 2 else 0] - pointers[res] = ("fn", var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if base not in pointers: - raise UnsupportedConstruct(f"OpAccessChain on non-pointer {base}") - ptag = pointers[base][0] - if ptag == "lds": - idx = val(a[2]) - if not (0 <= idx < len(lds)): - raise WorkgroupBoundsError(f"LDS access out of bounds: {idx} >= {len(lds)}") - pointers[res] = ("lds", lds, idx) - elif ptag in ("out", "fn"): - pointers[res] = pointers[base] - else: - raise UnsupportedConstruct(f"Access chain on {ptag}") - elif op == "OpLoad": - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag == "lds": - values[res] = ptr[1][ptr[2]] & MASK - elif ptag in ("out", "fn"): - values[res] = ptr[1][ptr[2]] & MASK - elif op == "OpStore": - ptr = pointers[a[0]] - v = val(a[1]) & MASK - ptag = ptr[0] - if ptag == "lds": - ptr[1][ptr[2]] = v - elif ptag in ("out", "fn"): - ptr[1][ptr[2]] = v - elif op == "OpAtomicExchange": - # %res = OpAtomicExchange %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicExchange on non-LDS pointer {ptag}") - new_val = val(a[4]) & MASK - old = ptr[1][ptr[2]] & MASK - ptr[1][ptr[2]] = new_val - values[res] = old - elif op == "OpIAdd": - values[res] = (val(a[1]) + val(a[2])) & MASK - elif op == "OpISub": - values[res] = (val(a[1]) - val(a[2])) & MASK - elif op == "OpShiftRightLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) >> sh) & MASK - elif op == "OpShiftLeftLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) << sh) & MASK - elif op == "OpBitwiseAnd": - values[res] = val(a[1]) & val(a[2]) & MASK - elif op == "OpBitwiseOr": - values[res] = (val(a[1]) | val(a[2])) & MASK - elif op == "OpBitwiseXor": - values[res] = (val(a[1]) ^ val(a[2])) & MASK - elif op == "OpSelect": - cond = val(a[1]) - values[res] = val(a[2]) if cond else val(a[3]) - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpBitcast": - values[res] = val(a[1]) & MASK - else: - raise UnsupportedConstruct(f"Opcode {op} not modelled in body") - - return {name: var_box[name][0] & MASK for name in outputs} - - -class TestAtomicXchgReferenceMath(unittest.TestCase): - """Verifies 32-bit exchange math, boundary representations, and collision serialization.""" - - def test_single_exchange_basic(self): - old, mem = reference_atomic_xchg(0x12345678, 0x9ABCDEF0) - self.assertEqual(old, 0x12345678) - self.assertEqual(mem, 0x9ABCDEF0) - - def test_single_exchange_boundary_values(self): - cases = [ - (0, 0, 0, 0), - (0xFFFFFFFF, 0, 0xFFFFFFFF, 0), - (0, 0xFFFFFFFF, 0, 0xFFFFFFFF), - (0x80000000, 0x7FFFFFFF, 0x80000000, 0x7FFFFFFF), - (0x55555555, 0xAAAAAAAA, 0x55555555, 0xAAAAAAAA), - ] - for cur, new_val, exp_old, exp_mem in cases: - with self.subTest(cur=hex(cur), new_val=hex(new_val)): - old, mem = reference_atomic_xchg(cur, new_val) - self.assertEqual(old, exp_old) - self.assertEqual(mem, exp_mem) - - def test_repeated_sequential_exchanges(self): - # Chaining 10 updates through a single memory cell - val = 0 - for i in range(1, 11): - old, val = reference_atomic_xchg(val, i * 100) - self.assertEqual(old, (i - 1) * 100) - self.assertEqual(val, 1000) - - def test_dual_exchange_distinct_addresses(self): - old0, old1, mem0, mem1 = reference_atomic_xchg2(10, 20, 100, 200, aliased=False) - self.assertEqual(old0, 10) - self.assertEqual(old1, 20) - self.assertEqual(mem0, 100) - self.assertEqual(mem1, 200) - - def test_dual_exchange_aliased_addresses_serialization(self): - # Port 0 writes 100 to slot (old=10); Port 1 reads 100 and writes 200 - old0, old1, mem0, mem1 = reference_atomic_xchg2(10, 10, 100, 200, aliased=True) - self.assertEqual(old0, 10) - self.assertEqual(old1, 100) - self.assertEqual(mem0, 200) - self.assertEqual(mem1, 200) - - -class TestLdsAddressingAndOffsets(unittest.TestCase): - """Verifies single and dual LDS byte offsets, dword truncation, st64 strides, and wrapping.""" - - def test_single_offset_alignment_and_truncation(self): - lds_dwords = 256 - # Aligned dword addresses - eff, dword, byte_off = calc_lds_byte_offset(64, 0, lds_dwords) - self.assertEqual(eff, 64) - self.assertEqual(dword, 16) - self.assertEqual(byte_off, 0) - - # Unaligned low bits truncated by >> 2 - for b in (0, 1, 2, 3): - _, dword, byte_pos = calc_lds_byte_offset(64, b, lds_dwords) - self.assertEqual(dword, 16) - self.assertEqual(byte_pos, b) - - def test_single_offset_16bit_masking_and_wrapping(self): - lds_dwords = 512 - # Offset is 16-bit unsigned (masked to 0xFFFF) - eff, dword, _ = calc_lds_byte_offset(0, 0x10004, lds_dwords) - self.assertEqual(eff, 4) - self.assertEqual(dword, 1) - - def test_dual_offset_unit_strides(self): - # ds_wrxchg2_rtn_b32 has 4-byte (1 dword) stride - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 5, 12, lds_dwords=1024, st64=False) - self.assertEqual(eff0, 20) - self.assertEqual(idx0, 5) - self.assertEqual(eff1, 48) - self.assertEqual(idx1, 12) - - def test_dual_offset_st64_stride(self): - # ds_wrxchg2st64_rtn_b32 has 256-byte (64 dwords) stride - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 1, 3, lds_dwords=1024, st64=True) - self.assertEqual(eff0, 256) - self.assertEqual(idx0, 64) - self.assertEqual(eff1, 768) - self.assertEqual(idx1, 192) - - def test_boundary_power_of_two_wrapping(self): - # LDS with 64 dwords (256 bytes) - lds_dwords = 64 - # Byte 256 wraps to dword 0 - _, idx, _ = calc_lds_byte_offset(256, 0, lds_dwords) - self.assertEqual(idx, 0) - # Byte 260 wraps to dword 1 - _, idx, _ = calc_lds_byte_offset(256, 4, lds_dwords) - self.assertEqual(idx, 1) - # 32-bit wrap - _, idx, _ = calc_lds_byte_offset(0xFFFFFFFC, 4, lds_dwords) - self.assertEqual(idx, 0) - - def test_dual_offset_aliasing_detection(self): - # When offset0 == offset1, idx0 == idx1 - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(100, 4, 4, lds_dwords=256) - self.assertEqual(eff0, eff1) - self.assertEqual(idx0, idx1) - - -class TestLdsSemanticInterpreter(unittest.TestCase): - """Executes RDNA2 instructions in the software semantic interpreter.""" - - def setUp(self): - self.interp = LdsSemanticInterpreter(lds_dwords=256, num_vgprs=64) - - def test_ds_wrxchg_rtn_b32_basic(self): - # Seed LDS[10] = 0x12345678 - self.interp.set_lds_dword(10, 0x12345678) - self.interp.set_vgpr(0, 40) # vaddr: byte 40 -> dword 10 - self.interp.set_vgpr(1, 0xABCDEF01) # vdata - self.interp.set_vgpr(2, 0) # vdst - - res = self.interp.ds_wrxchg_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, offset=0) - self.assertEqual(res, (10, 0x12345678)) - # Destination register receives old value - self.assertEqual(self.interp.get_vgpr(2), 0x12345678) - # Memory location updated with new value - self.assertEqual(self.interp.get_lds_dword(10), 0xABCDEF01) - # Surrounding slots untouched - self.assertEqual(self.interp.get_lds_dword(9), 0) - self.assertEqual(self.interp.get_lds_dword(11), 0) - - def test_ds_wrxchg_rtn_b32_with_offset(self): - self.interp.set_lds_dword(8, 0x5555) - self.interp.set_vgpr(0, 16) # byte 16 (dword 4) - self.interp.set_vgpr(1, 0x7777) - # offset 16 bytes (+4 dwords) -> dword 8 - self.interp.ds_wrxchg_rtn_b32(vdst_reg=3, vaddr_reg=0, vdata_reg=1, offset=16) - self.assertEqual(self.interp.get_vgpr(3), 0x5555) - self.assertEqual(self.interp.get_lds_dword(8), 0x7777) - - def test_ds_wrxchg2_rtn_b32_distinct_locations(self): - self.interp.set_lds_dword(5, 0xAAAA) - self.interp.set_lds_dword(7, 0xBBBB) - self.interp.set_vgpr(0, 0) # vaddr = 0 - self.interp.set_vgpr(1, 0x1111) # vdata0 - self.interp.set_vgpr(2, 0x2222) # vdata1 - # vdst = v10 (v10:v11) - res = self.interp.ds_wrxchg2_rtn_b32( - vdst_reg=10, vaddr_reg=0, vdata0_reg=1, vdata1_reg=2, offset0=5, offset1=7 - ) - self.assertEqual(res, ((5, 0xAAAA), (7, 0xBBBB))) - self.assertEqual(self.interp.get_vgpr(10), 0xAAAA) - self.assertEqual(self.interp.get_vgpr(11), 0xBBBB) - self.assertEqual(self.interp.get_lds_dword(5), 0x1111) - self.assertEqual(self.interp.get_lds_dword(7), 0x2222) - - def test_ds_wrxchg2_rtn_b32_aliased_collision(self): - # Both offset0 and offset1 point to dword 4 - self.interp.set_lds_dword(4, 0x9999) - self.interp.set_vgpr(0, 0) - self.interp.set_vgpr(1, 0x1234) # vdata0 - self.interp.set_vgpr(2, 0x5678) # vdata1 - self.interp.ds_wrxchg2_rtn_b32( - vdst_reg=8, vaddr_reg=0, vdata0_reg=1, vdata1_reg=2, offset0=4, offset1=4 - ) - # Port 0 read initial 0x9999 - self.assertEqual(self.interp.get_vgpr(8), 0x9999) - # Port 1 read port 0's written value 0x1234 - self.assertEqual(self.interp.get_vgpr(9), 0x1234) - # Final memory holds port 1's written value 0x5678 - self.assertEqual(self.interp.get_lds_dword(4), 0x5678) - - def test_ds_wrxchg2st64_rtn_b32_execution(self): - self.interp.set_lds_dword(64, 0x100) - self.interp.set_lds_dword(128, 0x200) - self.interp.set_vgpr(0, 0) - self.interp.set_vgpr(1, 0x300) - self.interp.set_vgpr(2, 0x400) - # st64 multiplies offsets 1 and 2 by 64 dwords - self.interp.ds_wrxchg2_rtn_b32( - vdst_reg=4, vaddr_reg=0, vdata0_reg=1, vdata1_reg=2, offset0=1, offset1=2, st64=True - ) - self.assertEqual(self.interp.get_vgpr(4), 0x100) - self.assertEqual(self.interp.get_vgpr(5), 0x200) - self.assertEqual(self.interp.get_lds_dword(64), 0x300) - self.assertEqual(self.interp.get_lds_dword(128), 0x400) - - def test_inactive_lane_preserves_state(self): - self.interp.set_lds_dword(2, 0x5555) - self.interp.set_vgpr(0, 8, lane=1) # byte 8 -> dword 2 - self.interp.set_vgpr(1, 0x9999, lane=1) - self.interp.set_vgpr(5, 0xDEAD, lane=1) # preset vdst - self.interp.set_lane_active(1, False) - - res = self.interp.ds_wrxchg_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, lane=1) - self.assertIsNone(res) - # Destination unchanged - self.assertEqual(self.interp.get_vgpr(5, lane=1), 0xDEAD) - # LDS unchanged - self.assertEqual(self.interp.get_lds_dword(2), 0x5555) - - def test_assembly_parser_dispatch(self): - self.interp.set_lds_dword(3, 0xCAFE) - self.interp.set_vgpr(0, 12) # byte 12 -> dword 3 - self.interp.set_vgpr(1, 0xBEEF) - - # Single exchange with offset - self.interp.parse_and_execute("ds_wrxchg_rtn_b32 v4, v0, v1 offset:0") - self.assertEqual(self.interp.get_vgpr(4), 0xCAFE) - self.assertEqual(self.interp.get_lds_dword(3), 0xBEEF) - - # Dual exchange with bracketed register pair - self.interp.set_lds_dword(10, 0x11) - self.interp.set_lds_dword(20, 0x22) - self.interp.set_vgpr(2, 0) - self.interp.set_vgpr(3, 0x33) - self.interp.set_vgpr(4, 0x44) - self.interp.parse_and_execute("ds_wrxchg2_rtn_b32 v[6:7], v2, v3, v4 offset0:10 offset1:20") - self.assertEqual(self.interp.get_vgpr(6), 0x11) - self.assertEqual(self.interp.get_vgpr(7), 0x22) - self.assertEqual(self.interp.get_lds_dword(10), 0x33) - self.assertEqual(self.interp.get_lds_dword(20), 0x44) - - def test_spinlock_acquire_release_pattern(self): - # Modeling a mutual exclusion spinlock on LDS[0] - # 0 = Unlocked, 1 = Locked - self.interp.set_lds_dword(0, 0) # initially unlocked - self.interp.set_vgpr(0, 0) # vaddr = 0 - self.interp.set_vgpr(1, 1) # lock payload = 1 - self.interp.set_vgpr(2, 0) # unlock payload = 0 - - # Thread 0 acquires lock - self.interp.ds_wrxchg_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, lane=0) - self.assertEqual(self.interp.get_vgpr(5, lane=0), 0) # 0 -> Acquired! - self.assertEqual(self.interp.get_lds_dword(0), 1) # LDS is now 1 (locked) - - # Thread 1 attempts to acquire lock - self.interp.set_vgpr(0, 0, lane=1) - self.interp.set_vgpr(1, 1, lane=1) - self.interp.ds_wrxchg_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, lane=1) - self.assertEqual(self.interp.get_vgpr(5, lane=1), 1) # 1 -> Failed/Contended! - - # Thread 0 releases lock - self.interp.ds_wrxchg_rtn_b32(vdst_reg=6, vaddr_reg=0, vdata_reg=2, lane=0) - self.assertEqual(self.interp.get_lds_dword(0), 0) # Unlocked - - # Thread 1 retries and acquires - self.interp.ds_wrxchg_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, lane=1) - self.assertEqual(self.interp.get_vgpr(5, lane=1), 0) # 0 -> Acquired! - - -class TestSpirvAtomicXchgInterpreter(unittest.TestCase): - """Executes SPIR-V compute shaders with OpAtomicExchange on LDS memory.""" - - def test_op_atomic_exchange_basic(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c7 = OpConstant %uint 7 -%c999 = OpConstant %uint 999 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c7 -%old = OpAtomicExchange %uint %ptr %c2 %c0 %c999 -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={7: 0x1234}) - # Output gets old value - self.assertEqual(lane_out[0]["%out"], 0x1234) - # LDS holds new value - self.assertEqual(final_lds[7], 999) - # Other slots pristine - self.assertEqual(final_lds[0], 0) - self.assertEqual(final_lds[6], 0) - - def test_chained_atomic_exchanges_single_invocation(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out1 %out2 %out3 -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out1 = OpVariable %_ptr_Output_uint Output -%out2 = OpVariable %_ptr_Output_uint Output -%out3 = OpVariable %_ptr_Output_uint Output -%c32 = OpConstant %uint 32 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c3 = OpConstant %uint 3 -%v1 = OpConstant %uint 100 -%v2 = OpConstant %uint 200 -%v3 = OpConstant %uint 300 -%lds_arr = OpTypeArray %uint %c32 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c3 -%r1 = OpAtomicExchange %uint %ptr %c2 %c0 %v1 -%r2 = OpAtomicExchange %uint %ptr %c2 %c0 %v2 -%r3 = OpAtomicExchange %uint %ptr %c2 %c0 %v3 -OpStore %out1 %r1 -OpStore %out2 %r2 -OpStore %out3 %r3 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={3: 50}) - # Sequence of observations: - # r1 observes initial 50 (slot becomes 100) - # r2 observes 100 (slot becomes 200) - # r3 observes 200 (slot becomes 300) - self.assertEqual(lane_out[0]["%out1"], 50) - self.assertEqual(lane_out[0]["%out2"], 100) - self.assertEqual(lane_out[0]["%out3"], 200) - self.assertEqual(final_lds[3], 300) - - def test_dual_exchange_spirv_sequence(self): - # Emulating ds_wrxchg2_rtn_b32 via two OpAtomicExchange instructions - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out0 %out1 -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out0 = OpVariable %_ptr_Output_uint Output -%out1 = OpVariable %_ptr_Output_uint Output -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%idx0 = OpConstant %uint 4 -%idx1 = OpConstant %uint 8 -%val0 = OpConstant %uint 1111 -%val1 = OpConstant %uint 2222 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr0 = OpAccessChain %_ptr_WG_uint %lds %idx0 -%r0 = OpAtomicExchange %uint %ptr0 %c2 %c0 %val0 -%ptr1 = OpAccessChain %_ptr_WG_uint %lds %idx1 -%r1 = OpAtomicExchange %uint %ptr1 %c2 %c0 %val1 -OpStore %out0 %r0 -OpStore %out1 %r1 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={4: 10, 8: 20}) - self.assertEqual(lane_out[0]["%out0"], 10) - self.assertEqual(lane_out[0]["%out1"], 20) - self.assertEqual(final_lds[4], 1111) - self.assertEqual(final_lds[8], 2222) - - def test_spirv_address_calculation_pipeline(self): - # Simulating address math: (base + offset) >> 2 & (lds_dwords - 1) - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c15 = OpConstant %uint 15 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c_base = OpConstant %uint 44 -%c_offset = OpConstant %uint 16 -%c_val = OpConstant %uint 8888 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%sum = OpIAdd %uint %c_base %c_offset -%idx = OpShiftRightLogical %uint %sum %c2 -%masked = OpBitwiseAnd %uint %idx %c15 -%ptr = OpAccessChain %_ptr_WG_uint %lds %masked -%old = OpAtomicExchange %uint %ptr %c2 %c0 %c_val -OpStore %out %old -OpReturn -OpFunctionEnd -""" - # (44 + 16) = 60; 60 >> 2 = 15; 15 & 15 = 15 - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={15: 777}) - self.assertEqual(lane_out[0]["%out"], 777) - self.assertEqual(final_lds[15], 8888) - - -class TestWorkgroupMultiLaneAtomicXchg(unittest.TestCase): - """Verifies workgroup multi-lane contention, permutation conservation, and mutex allocation.""" - - def test_multi_lane_shared_slot_exchange_conservation(self): - # 8 lanes in a workgroup each swap their unique identifier into LDS[0] - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 8 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%res = OpAtomicExchange %uint %ptr %c2 %c0 %payload -OpStore %out %res -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - seed_value = 0x5555 - lane_payloads = [{"%payload": 100 + i} for i in range(8)] - final_lds, lane_outs = interp.run( - num_invocations=8, - seed_lds={0: seed_value}, - lane_inputs=lane_payloads, - ) - - returned_values = [o["%out"] for o in lane_outs] - # Every returned value must be distinct - self.assertEqual(len(set(returned_values)), 8) - - # The multiset of (all returned values + final value in LDS) MUST equal - # the initial seed plus all 8 swapped values (conservation of values). - all_values = set(returned_values) | {final_lds[0]} - expected_set = {seed_value} | {100 + i for i in range(8)} - self.assertEqual(all_values, expected_set) - # Exactly one lane observed the initial seed - self.assertIn(seed_value, returned_values) - - def test_multi_lane_mutex_race(self): - # 16 lanes race to swap 1 into LDS[0]. Seed is 0 (unlocked). - # Exactly ONE lane receives 0 (lock winner); 15 lanes receive 1 (contenders). - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 16 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%ticket = OpAtomicExchange %uint %ptr %c2 %c0 %c1 -OpStore %out %ticket -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_outs = interp.run(num_invocations=16, seed_lds={0: 0}) - # Final state of lock is 1 (held) - self.assertEqual(final_lds[0], 1) - tickets = [o["%out"] for o in lane_outs] - # Exactly one lane got 0 (acquired) - self.assertEqual(tickets.count(0), 1) - # 15 lanes got 1 (spin / busy) - self.assertEqual(tickets.count(1), 15) - - def test_wave32_token_ring_exchange(self): - # 32 lanes in wave32 pass tokens through individual LDS slots - interp = LdsSemanticInterpreter(lds_dwords=32, num_vgprs=8, num_lanes=32) - # Seed each LDS slot with initial token = slot * 10 - for slot in range(32): - interp.set_lds_dword(slot, slot * 10) - - # Each lane i exchanges with slot (i + 1) % 32 using payload 1000 + i - for lane in range(32): - target_slot = (lane + 1) % 32 - interp.set_vgpr(0, target_slot * 4, lane=lane) # vaddr - interp.set_vgpr(1, 1000 + lane, lane=lane) # vdata - interp.ds_wrxchg_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, lane=lane) - - # Verify each lane received the token previously in target_slot - for lane in range(32): - target_slot = (lane + 1) % 32 - self.assertEqual(interp.get_vgpr(2, lane=lane), target_slot * 10) - self.assertEqual(interp.get_lds_dword(target_slot), 1000 + lane) - - -class TestTranslatorIntegration(unittest.TestCase): - """Verifies tools/rdna2spirv.py handling and SPIR-V code generation for LDS atomic exchanges.""" - - def _make_mock_gen(self, stage: str = "cs"): - class MockGen: - def __init__(self): - self.stage = stage - self.uses_lds = False - self.lds_dwords = 256 - self.lds_bound = None # not bounds-checked (SHADER-309): the wrapped access - self.wave64 = True - self._tmp = 0 - self.emitted: list[str] = [] - self.stored_dsts: list[tuple[dict, str]] = [] - - def tmp(self) -> str: - self._tmp += 1 - return f"%t{self._tmp}" - - def cu(self, v: int) -> str: - return f"%c{v}" - - def active_b(self) -> str: - return "%exec_active" - - def src_u(self, arg: dict) -> str: - return f"%v_{arg['r']}" - - def dst(self, d: dict, v: str) -> None: - self.stored_dsts.append((d, v)) - - def emit(self, line: str) -> None: - self.emitted.append(line) - - LDS_ATOMICS = rdna2spirv.Gen.LDS_ATOMICS - mod_int = staticmethod(rdna2spirv.Gen.mod_int) - lds_ptr = rdna2spirv.Gen.lds_ptr - lds_access = rdna2spirv.Gen.lds_access - lds_atomic = rdna2spirv.Gen.lds_atomic - lds_op = rdna2spirv.Gen.lds_op - - return MockGen() - - def test_lds_atomics_table_contains_ds_wrxchg_rtn_b32(self): - # Gen.LDS_ATOMICS maps ds_wrxchg_rtn_b32 to OpAtomicExchange - self.assertIn("ds_wrxchg_rtn_b32", rdna2spirv.Gen.LDS_ATOMICS) - self.assertEqual(rdna2spirv.Gen.LDS_ATOMICS["ds_wrxchg_rtn_b32"], "OpAtomicExchange") - - def test_ds_wrxchg_rtn_b32_compute_emission(self): - gen = self._make_mock_gen(stage="cs") - # ds_wrxchg_rtn_b32 v5, v0, v1, offset:16 (dst=v5, addr=v0, data=v1) - gen.lds_op("ds_wrxchg_rtn_b32", [{"r": 5}, {"r": 0}, {"r": 1}], ["offset:16"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - # Must guard with active mask - self.assertIn("OpBranchConditional %exec_active", emitted_str) - # Must compute pointer with offset 16 - self.assertIn("OpIAdd %uint %v_0 %c16", emitted_str) - self.assertIn("OpShiftRightLogical %uint", emitted_str) - self.assertIn("OpBitwiseAnd %uint", emitted_str) - self.assertIn("OpAccessChain %_ptr_WG_uint %lds", emitted_str) - - # Must emit OpAtomicExchange with scope Workgroup (2) and Relaxed (0) - self.assertIn("OpAtomicExchange %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - - # Returning form MUST store old value into destination v5 - self.assertEqual(len(gen.stored_dsts), 1) - dest_reg, val_id = gen.stored_dsts[0] - self.assertEqual(dest_reg["r"], 5) - self.assertTrue(val_id.startswith("%t")) - - def test_ds_wrxchg_rtn_b32_mesh_stage_emission(self): - # Mesh shader (ms) is compute-like and also permits LDS operations - gen = self._make_mock_gen(stage="ms") - gen.lds_op("ds_wrxchg_rtn_b32", [{"r": 2}, {"r": 3}, {"r": 4}], []) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - self.assertIn("OpAtomicExchange %uint", emitted_str) - self.assertEqual(len(gen.stored_dsts), 1) - - def test_ds_wrxchg_rtn_b32_non_compute_rejected(self): - # Pixel (ps), vertex (vs), geometry (gs) shaders reject LDS instructions - for invalid_stage in ("ps", "vs", "gs"): - with self.subTest(stage=invalid_stage): - gen = self._make_mock_gen(stage=invalid_stage) - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_wrxchg_rtn_b32", [{"r": 0}, {"r": 1}, {"r": 2}], []) - - def test_ds_wrxchg2_rtn_b32_translator_emission(self): - gen = self._make_mock_gen(stage="cs") - dst = {"k": "vgpr", "r": 0, "n": 2} - gen.lds_op("ds_wrxchg2_rtn_b32", [dst, {"r": 2}, {"r": 3}, {"r": 4}], ["offset0:1", "offset1:2"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - self.assertEqual(emitted_str.count("OpAtomicExchange %uint"), 2) - self.assertEqual(len(gen.stored_dsts), 2) - self.assertEqual(gen.stored_dsts[0][0]["r"], 0) - self.assertEqual(gen.stored_dsts[1][0]["r"], 1) - - def test_ds_wrxchg2st64_rtn_b32_translator_emission(self): - gen = self._make_mock_gen(stage="cs") - dst = {"k": "vgpr", "r": 6, "n": 2} - gen.lds_op("ds_wrxchg2st64_rtn_b32", [dst, {"r": 1}, {"r": 2}, {"r": 3}], ["offset0:1", "offset1:3"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - self.assertEqual(emitted_str.count("OpAtomicExchange %uint"), 2) - self.assertIn("OpIAdd %uint %v_1 %c256", emitted_str) - self.assertIn("OpIAdd %uint %v_1 %c768", emitted_str) - self.assertEqual(len(gen.stored_dsts), 2) - - def test_ds_wrxchg2_rtn_b32_invalid_dst_rejected(self): - gen = self._make_mock_gen(stage="cs") +import support # noqa: E402 + +XCHG = "ds_wrxchg_rtn_b32" + + +def model(ops, init): + lds = dict(init) + rtns = [] + for _, addr, off, (d,) in ops: + rtns.append(lds[addr + off]) + lds[addr + off] = d + return rtns, {a: lds[a] for a in sorted({addr + off for _, addr, off, _ in ops})} + + +class TestExchange(unittest.TestCase): + def test_by_hand(self): + for m, d in ((0, 0xFFFFFFFF), (0x12345678, 0), (0x80000000, 0x80000000), (0xFFFFFFFF, 0x7FFFFFFF), (5, 5)): + with self.subTest(m=hex(m), d=hex(d)): + self.assertEqual(L.run_chain([(XCHG, 0x40, 0, (d,))], {0x40: m}), ([m], {0x40: d})) + + def test_offset_adds_to_the_address_in_bytes(self): + rtns, fin = L.run_chain([(XCHG, 0x20, 0x24, (9,))], {0x44: 4, 0x40: 100, 0x48: 200}) + self.assertEqual((rtns, fin), ([4], {0x44: 9})) + + def test_a_chain_passes_each_value_on(self): + # Exchanging 2, 3, 4 into a dword that holds 1 returns 1, 2, 3 and leaves 4. + ops = [(XCHG, 8, 0, (v,)) for v in (2, 3, 4)] + self.assertEqual(L.run_chain(ops, {8: 1}), ([1, 2, 3], {8: 4})) + + def test_other_dwords_are_untouched(self): + ops = [(XCHG, 0x10, 0, (0xAAAA,)), (XCHG, 0x14, 0, (0xBBBB,))] + self.assertEqual(L.run_chain(ops, {0x10: 1, 0x14: 2, 0x18: 3}), ([1, 2], {0x10: 0xAAAA, 0x14: 0xBBBB})) + + def test_seeded_sequences(self): + rng = random.Random(0x7C6) + for trial in range(8): + addrs = [0x10, 0x30, 0x7C, 0x100] + init = {a: rng.getrandbits(32) for a in addrs} + ops = [] + for _ in range(12): + eff, off = rng.choice(addrs), rng.choice((0, 0, 0x10, 0x20)) + ops.append((XCHG, eff - off, off, (rng.getrandbits(32),))) + with self.subTest(trial=trial): + self.assertEqual(L.run_chain(ops, init), model(ops, init)) + + +class TestOutsideCompute(unittest.TestCase): + def test_pixel_shader_refuses_the_exchange(self): with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_wrxchg2_rtn_b32", [{"k": "vgpr", "r": 0, "n": 1}, {"r": 1}, {"r": 2}, {"r": 3}], []) - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_wrxchg2_rtn_b32", [{"k": "sgpr", "r": 0, "n": 2}, {"r": 1}, {"r": 2}, {"r": 3}], []) - - -class TestNegativeControlsAndValidation(unittest.TestCase): - """Verifies error handling for malformed SPIR-V, out-of-bounds sizes, and unsupported constructs.""" - - def test_unsupported_storage_class_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_UC = OpTypePointer UniformConstant %uint -%u = OpVariable %_ptr_UC UniformConstant -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(UnsupportedConstruct): - LdsAtomicSpirvInterp(spvasm) - - def test_invalid_workgroup_size_rejected(self): - for dims in [(0, 1, 1), (1025, 1, 1), (32, 33, 1)]: - with self.subTest(dims=dims): - spvasm = f""" -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize {dims[0]} {dims[1]} {dims[2]} -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(WorkgroupBoundsError): - LdsAtomicSpirvInterp(spvasm) - - def test_atomic_exchange_on_non_lds_pointer_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_fn_uint = OpTypePointer Function %uint -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c5 = OpConstant %uint 5 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%local_v = OpVariable %_ptr_fn_uint Function -%bad = OpAtomicExchange %uint %local_v %c2 %c0 %c5 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_unmodelled_opcode_in_body_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c16 = OpConstant %uint 16 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%bad = OpUDiv %uint %c16 %c16 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() + support.translate_lines("ps_lds_xchg", [f"{XCHG} v1, v0, v2", "s_endpgm"]) if __name__ == "__main__": diff --git a/tests/semantic/test_lds_atomics_cas.py b/tests/semantic/test_lds_atomics_cas.py index c4667edd5..5c6682d08 100644 --- a/tests/semantic/test_lds_atomics_cas.py +++ b/tests/semantic/test_lds_atomics_cas.py @@ -7,7 +7,10 @@ no GPU, no LLVM, no game files. """ import os import random +import re +import shutil import struct +import subprocess import sys import tempfile import unittest @@ -20,13 +23,11 @@ sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "to sys.path.insert(0, HERE) import rdna2spirv # noqa: E402 +import spirv_asm # noqa: E402 import spirv_mini_interp as si # noqa: E402 M32 = 0xFFFFFFFF STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" dword 0); bounds checking must hit LDS[128] and preserve LDS[0]. + guard_val = 0xCAFE1234 + for op, rtn, init_val, data_val, expected in self.CAS_BOUNDS_CASES: + with self.subTest(op=op): + body = [ + "v_mov_b32_e32 v0, 0", + f"v_mov_b32_e32 v1, {guard_val:#x}", + "ds_write_b32 v0, v1", + "v_mov_b32_e32 v2, 512", + f"v_mov_b32_e32 v10, {init_val:#x}", + "ds_write_b32 v2, v10", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32_e32 v8, 0xfc00", + "ds_read_b32 v9, v8 offset:1536", + f"v_mov_b32_e32 v3, {data_val:#x}", + "v_mov_b32_e32 v5, 0xdead", + f"{op} v5, v2, v3" if rtn else f"{op} v2, v3", + "s_waitcnt lgkmcnt(0)", + "ds_read_b32 v4, v0", + "ds_read_b32 v11, v2", + "s_waitcnt lgkmcnt(0)", + f"v_mov_b32_e32 v6, {OUT:#x}", + "global_store_dword v6, v5, s[0:1]", + f"v_mov_b32_e32 v7, {OUT + 4:#x}", + "global_store_dword v7, v4, s[0:1]", + f"v_mov_b32_e32 v12, {OUT + 8:#x}", + "global_store_dword v12, v11, s[0:1]", + ] + mem = run_cs(body, lds_units=3) + gen = rdna2spirv.translate.last_gen + self.assertEqual((gen.lds_bound, gen.lds_dwords), (384, 384)) + self.assertEqual( + (mem.get(OUT), mem.get(OUT + 4), mem.get(OUT + 8)), + (init_val if rtn else 0xDEAD, guard_val, expected), + ) + + def test_zero_lds_allocation_returns_zero_and_drops_write(self): + # LDS_SIZE=0 with a constant extent past 0 yields lds_bound=0; _rtn_ returns 0 and non-_rtn_ preserves vdst. + for op, rtn in (("ds_inc_rtn_u32", True), ("ds_inc_u32", False), ("ds_min_rtn_f32", True)): + with self.subTest(op=op): + body = [ + "v_mov_b32_e32 v1, 0", + "v_mov_b32_e32 v3, 7", + "v_mov_b32_e32 v5, 0xdead", + f"{op} v5, v1, v3 offset:4" if rtn else f"{op} v1, v3 offset:4", + "s_waitcnt lgkmcnt(0)", + f"v_mov_b32_e32 v6, {OUT:#x}", + "global_store_dword v6, v5, s[0:1]", + ] + mem = run_cs(body, lds_units=0) + self.assertEqual(rdna2spirv.translate.last_gen.lds_bound, 0) + self.assertEqual(mem.get(OUT), 0 if rtn else 0xDEAD) + + def test_wave64_emulate_shrunk_lds_checks_bounds_and_skips_wrap_mask(self): + # Under --wave64-emulate with LDS_SIZE=100 (51200 B = 12800 dwords) and 64 threads, + # fit_shared_memory shrinks %lds to 12800 dwords and sets lds_bound=12800 without offset tricks. + shrunk = translate( + ["s_mov_b64 exec, -1", "v_mov_b32_e32 v1, 0", "v_readfirstlane_b32 s16, v1", + "v_mov_b32_e32 v3, 2", "ds_inc_rtn_u32 v5, v1, v3"], + lds_units=100, threads=64, emulate=True, + ) + gen = rdna2spirv.translate.last_gen + self.assertTrue(gen.wave64 and gen.emulate) + self.assertEqual((gen.lds_bound, gen.lds_dwords), (12800, 12800)) + self.assertGreaterEqual(len(re.findall(r"^\s*%\w+_lin = OpLabel$", shrunk, re.M)), 1) + self.assertIsNone(re.search(r"= OpBitwiseAnd %uint %\w+ %\w+\n\s*%\w+ = OpAccessChain %_ptr_WG_uint\w* %lds ", + shrunk)) + + unbounded = translate(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 2", "ds_inc_rtn_u32 v5, v1, v3"]) + self.assertIsNone(rdna2spirv.translate.last_gen.lds_bound) + self.assertEqual(len(re.findall(r"^\s*%\w+_lin = OpLabel$", unbounded, re.M)), 0) + + def _bounds_validation_modules(self): + return ( + ("unbounded_min_rtn", translate( + ["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 0x3f800000", "ds_min_rtn_f32 v5, v1, v3"])), + ("bounded_inc_rtn", translate([ + "v_mov_b32_e32 v8, 0xfc00", "ds_read_b32 v9, v8 offset:1024", + "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 2", "ds_inc_rtn_u32 v5, v1, v3", + ], lds_units=1)), + ("bounded_inc_no_rtn", translate([ + "v_mov_b32_e32 v8, 0xfc00", "ds_read_b32 v9, v8 offset:1024", + "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 2", "ds_inc_u32 v1, v3", + ], lds_units=1)), + ("npot_max_rtn", translate([ + "v_mov_b32_e32 v8, 0xfc00", "ds_read_b32 v9, v8 offset:1536", + "v_mov_b32_e32 v1, 512", "v_mov_b32_e32 v3, 0x40800000", "ds_max_rtn_f32 v5, v1, v3", + ], lds_units=3)), + ("zero_lds_dec_rtn", translate( + ["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 7", "ds_dec_rtn_u32 v5, v1, v3 offset:4"], lds_units=0)), + ("emulate_shrunk_rsub_rtn", translate( + ["s_mov_b64 exec, -1", "v_mov_b32_e32 v1, 0", "v_readfirstlane_b32 s16, v1", + "v_mov_b32_e32 v3, 5", "ds_rsub_rtn_u32 v5, v1, v3"], + lds_units=100, threads=64, emulate=True)), + ) + + def test_bounds_checked_cas_spirv_assembly(self): + for label, spv in self._bounds_validation_modules(): + with self.subTest(case=label): + binary = spirv_asm.assemble(spv, target_env="vulkan1.2") + self.assertEqual(struct.unpack_from(" - %_ptr_WG_lds = OpTypePointer Workgroup %lds_arr - %_ptr_WG_uint = OpTypePointer Workgroup %uint - %lds = OpVariable %_ptr_WG_lds Workgroup - - Allocation sizing: - - Minimum allocation is 16 dwords (64 bytes). - - Maximum allocation on RDNA2 is 16,384 dwords (64 KiB = 65,536 bytes). - - Quantized to powers of two between 16 and 16,384 dwords. - - COMPUTE_PGM_RSRC2 register field LDS_SIZE [23:15] specifies allocated LDS in units of - 512 bytes (128 dwords). - - Static constant offsets in ds_* instructions (offset:N, offset0:N, offset1:N with st64) - expand the required allocation to cover all statically addressed dwords up to the 16K cap. - - Output metadata reports lds_bytes = 4 * lds_dwords. - - Pointer calculation & hardware wrapping bounds: - - Byte addresses in DS instructions are converted to dwords and wrapped: - s1 = addr + byte_off - i = s1 >> 2 - m = i & (lds_dwords - 1) - p = OpAccessChain %_ptr_WG_uint %lds m - - The bitwise AND with (lds_dwords - 1) enforces hardware modulo bounds within the workgroup - allocation. Any out-of-bounds byte or dword index wraps around deterministically. - - Workgroup dimension bounds: - - OpExecutionMode %main LocalSize lx ly lz - - Total workgroup size W = lx * ly * lz must satisfy: 1 <= W <= 1024. - - Invocation coordinates LocalInvocationId (x, y, z) satisfy 0 <= x < lx, 0 <= y < ly, 0 <= z < lz. - - LocalInvocationIndex = z * lx * ly + y * lx + x is bounded in [0, W - 1]. - - System register RSRC2 specifies USER_SGPR count [5:1], TGID enable bits [9:7], TG_SIZE_EN [10], - and TIDIG_COMP_CNT [12:11]. TG_SIZE_EN is unsupported and must be rejected. +Each case translates a hand-written listing with tools/rdna2spirv.py (support.translate_lines) and reads the array +length from the SPIR-V assembly; the wrap cases also run the shader in tests/semantic/spirv_mini_interp.py. The sizes +are worked out by hand from the rules above. Until this file, the LDS tests of this name ran a self-built +interpreter that copied the older rule (offsets grow the array) instead of calling the translator. """ import os import re -import struct import sys import unittest -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import lds_run as L # noqa: E402 (also puts tools/ on sys.path) import rdna2spirv # noqa: E402 -MASK = 0xFFFFFFFF - - -class UnsupportedConstruct(NotImplementedError): - """The module uses an unsupported or unmodelled SPIR-V construct.""" - - -class WorkgroupBoundsError(ValueError): - """Workgroup dimensions or invocation bounds are violated.""" - - -# Instructions carrying no runtime semantics for straight-line compute modules -_IGNORED = frozenset({ - "OpCapability", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", - "OpReturn", "OpFunctionEnd", "OpName", "OpSource", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -def compute_lds_allocation(base_dwords, ds_instructions=None): - """Calculates the power-of-two LDS allocation (in dwords) matching rdna2spirv.py logic.""" - need = base_dwords - if ds_instructions: - for ins in ds_instructions: - op = ins.get("op", "") - if not op.startswith("ds_") or op.startswith(("ds_swizzle", "ds_bpermute", "ds_permute")): - continue - for m in ins.get("mods", []): - k, _, v = m.partition(":") - if not v[:1].isdigit(): - continue - if k == "offset": - need = max(need, int(v, 0) // 4 + 4) - elif k in ("offset0", "offset1"): - need = max(need, int(v, 0) * (64 if "st64" in op else 1) * 2 + 4) - n = 16 - while n < need: - n *= 2 - return min(n, 16384) - - -def decode_rsrc2_lds_dwords(rsrc2): - """Extracts base LDS dwords declared in COMPUTE_PGM_RSRC2 word [23:15] (512 B / 128 dword units).""" - units = (rsrc2 >> 15) & 0x1FF - return units * 128 - - -def validate_workgroup_size(lx, ly, lz): - """Validates compute workgroup dimensions against Vulkan and RDNA2 limits (1 <= total <= 1024).""" - if lx < 1 or ly < 1 or lz < 1: - raise WorkgroupBoundsError(f"Invalid workgroup dimensions ({lx}, {ly}, {lz}): all must be >= 1") - total = lx * ly * lz - if total > 1024: - raise WorkgroupBoundsError(f"Workgroup size {total} ({lx}x{ly}x{lz}) exceeds hardware limit 1024") - return total - - -class LdsComputeInterp: - """A semantic interpreter for straight-line compute SPIR-V modules with LDS Workgroup memory.""" - - def __init__(self, spvasm): - self.spvasm = spvasm - self.types = {} - self.constants = {} - self.ptr_types = {} - self.var_class = {} - self.local_size = (1, 1, 1) - self.lds_var = None - self.lds_size = 0 - self.body = [] - self._parse_header() - - def _parse_header(self): - in_body = False - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"Cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - self.body.append((res, op, a, line)) - continue - if op == "OpFunction": - in_body = True - continue - if op == "OpExecutionMode" and len(a) >= 5 and a[1] == "LocalSize": - self.local_size = (int(a[2]), int(a[3]), int(a[4])) - validate_workgroup_size(*self.local_size) - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit int supported") - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - size = int(self.constants[a[1]]) - self.types[res] = ("arr", a[0], size) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - self.constants[res] = int(a[1], 0) & MASK - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - if a[1] != cls: - raise UnsupportedConstruct("OpVariable storage class mismatch") - self.var_class[res] = cls - if cls == "Workgroup": - if self.lds_var is not None: - raise UnsupportedConstruct("Multiple Workgroup variables") - self.lds_var = res - arr_ty = self.types[pointee] - if arr_ty[0] != "arr": - raise UnsupportedConstruct("Workgroup variable must be an array") - self.lds_size = arr_ty[2] - elif cls not in ("Output", "Function"): - raise UnsupportedConstruct(f"Unsupported storage class {cls}") - - def run_workgroup(self, num_invocations=None, seed_lds=None): - """Executes invocations within the workgroup and returns (final_lds, outputs_per_lane).""" - lx, ly, lz = self.local_size - total_invocations = lx * ly * lz - count = total_invocations if num_invocations is None else min(num_invocations, total_invocations) - - # Allocate shared LDS Workgroup storage - lds = [0] * self.lds_size - if seed_lds: - for idx, val in seed_lds.items(): - if 0 <= idx < self.lds_size: - lds[idx] = val & MASK - - lane_outputs = [] - - for linear_idx in range(count): - tz = linear_idx // (lx * ly) - rem = linear_idx % (lx * ly) - ty = rem // lx - tx = rem % lx - - out = self._run_lane(tx, ty, tz, linear_idx, lds) - lane_outputs.append(out) - - return list(lds), lane_outputs - - def _run_lane(self, tx, ty, tz, lidx, lds): - values = dict(self.constants) - var_box = {} - pointers = {} - outputs = [] - - if self.lds_var: - pointers[self.lds_var] = ("lds", lds, None) - - for res, cls in self.var_class.items(): - if cls == "Output": - var_box[res] = [0] - pointers[res] = ("out", var_box[res], 0) - outputs.append(res) - elif cls == "Function": - var_box[res] = [0] - pointers[res] = ("fn", var_box[res], 0) - - def val(x): - if x in values: - return values[x] - raise UnsupportedConstruct(f"Undefined identifier {x}") - - for res, op, a, _ in self.body: - if op in _IGNORED: - continue - if op == "OpVariable": - cls, _ = self.ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("Non-Function variable in body") - var_box[res] = [val(a[2]) if len(a) > 2 else 0] - pointers[res] = ("fn", var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if base not in pointers: - raise UnsupportedConstruct("OpAccessChain on non-pointer") - ptag = pointers[base][0] - if ptag == "lds": - idx = val(a[2]) - if not (0 <= idx < len(lds)): - raise WorkgroupBoundsError(f"LDS access out of bounds: index {idx} >= {len(lds)}") - pointers[res] = ("lds", lds, idx) - elif ptag in ("out", "fn"): - pointers[res] = pointers[base] - else: - raise UnsupportedConstruct(f"Access chain on {ptag}") - elif op == "OpLoad": - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag == "lds": - values[res] = ptr[1][ptr[2]] & MASK - elif ptag in ("out", "fn"): - values[res] = ptr[1][ptr[2]] & MASK - elif op == "OpStore": - ptr = pointers[a[0]] - v = val(a[1]) & MASK - ptag = ptr[0] - if ptag == "lds": - ptr[1][ptr[2]] = v - elif ptag in ("out", "fn"): - ptr[1][ptr[2]] = v - elif op == "OpIAdd": - values[res] = (val(a[1]) + val(a[2])) & MASK - elif op == "OpISub": - values[res] = (val(a[1]) - val(a[2])) & MASK - elif op == "OpShiftRightLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) >> sh) & MASK - elif op == "OpShiftLeftLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) << sh) & MASK - elif op == "OpBitwiseAnd": - values[res] = val(a[1]) & val(a[2]) & MASK - elif op == "OpBitwiseOr": - values[res] = (val(a[1]) | val(a[2])) & MASK - elif op == "OpBitwiseXor": - values[res] = (val(a[1]) ^ val(a[2])) & MASK - elif op == "OpSelect": - values[res] = val(a[2]) if val(a[1]) else val(a[3]) - elif op == "OpBitcast": - values[res] = val(a[1]) & MASK - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpAtomicIAdd": - ptr = pointers[a[1]] - addend = val(a[4]) - old = ptr[1][ptr[2]] - ptr[1][ptr[2]] = (old + addend) & MASK - values[res] = old & MASK - elif op == "OpAtomicExchange": - ptr = pointers[a[1]] - new_val = val(a[4]) & MASK - old = ptr[1][ptr[2]] - ptr[1][ptr[2]] = new_val - values[res] = old & MASK - else: - raise UnsupportedConstruct(f"Opcode {op}") - - return {name: var_box[name][0] & MASK for name in outputs} - - -class TestLdsAllocationMath(unittest.TestCase): - """Verifies Local Data Share (LDS) layout allocation quantization and power-of-two growth.""" - - def test_default_minimum_allocation(self): - self.assertEqual(compute_lds_allocation(0), 16) - self.assertEqual(compute_lds_allocation(1), 16) - self.assertEqual(compute_lds_allocation(16), 16) - - def test_power_of_two_rounding(self): - cases = [ - (17, 32), - (31, 32), - (32, 32), - (33, 64), - (64, 64), - (65, 128), - (128, 128), - (129, 256), - (256, 256), - (257, 512), - (512, 512), - (513, 1024), - (1024, 1024), - (1025, 2048), - (2048, 2048), - (4096, 4096), - (8192, 8192), - (16384, 16384), - ] - for req, expected in cases: - with self.subTest(requested=req): - self.assertEqual(compute_lds_allocation(req), expected) - - def test_maximum_allocation_clamp(self): - # RDNA2 LDS is capped at 16,384 dwords (64 KiB) - self.assertEqual(compute_lds_allocation(16385), 16384) - self.assertEqual(compute_lds_allocation(32768), 16384) - self.assertEqual(compute_lds_allocation(65536), 16384) - - def test_rsrc2_lds_size_decoding(self): - # COMPUTE_PGM_RSRC2 [23:15] in 512 B (128 dword) units - rsrc2_sample = 0x8088 # cs_lds sample: unit = 1 -> 128 dwords (512 B) - self.assertEqual(decode_rsrc2_lds_dwords(rsrc2_sample), 128) - self.assertEqual(compute_lds_allocation(decode_rsrc2_lds_dwords(rsrc2_sample)), 128) - - # Zero LDS declared - self.assertEqual(decode_rsrc2_lds_dwords(0x0008), 0) - self.assertEqual(compute_lds_allocation(decode_rsrc2_lds_dwords(0x0008)), 16) - - # 4 units = 512 dwords (2048 B) - rsrc2_4units = 4 << 15 - self.assertEqual(decode_rsrc2_lds_dwords(rsrc2_4units), 512) - self.assertEqual(compute_lds_allocation(decode_rsrc2_lds_dwords(rsrc2_4units)), 512) - - # 128 units = 16,384 dwords (64 KiB) - rsrc2_max = 128 << 15 - self.assertEqual(decode_rsrc2_lds_dwords(rsrc2_max), 16384) - self.assertEqual(compute_lds_allocation(decode_rsrc2_lds_dwords(rsrc2_max)), 16384) - - def test_constant_offset_expansion(self): - # Instruction with offset:256 expands need = 256 // 4 + 4 = 68 -> power of two 128 - insns = [{"op": "ds_write_b32", "mods": ["offset:256"]}] - self.assertEqual(compute_lds_allocation(16, insns), 128) - - # Offset 1020 bytes -> 1020 // 4 + 4 = 259 -> 512 dwords - insns = [{"op": "ds_read_b32", "mods": ["offset:1020"]}] - self.assertEqual(compute_lds_allocation(16, insns), 512) - - def test_ds_read2_st64_offset_expansion(self): - # Non-st64 offset: unit is 4 bytes - insns_normal = [{"op": "ds_read2_b32", "mods": ["offset0:10", "offset1:20"]}] - # need = 20 * 1 * 2 + 4 = 44 -> power of two 64 - self.assertEqual(compute_lds_allocation(16, insns_normal), 64) - - # st64 offset: unit is 64 * 4 = 256 bytes (64 dwords) - insns_st64 = [{"op": "ds_write2st64_b32", "mods": ["offset0:2", "offset1:4"]}] - # need = 4 * 64 * 2 + 4 = 516 -> power of two 1024 - self.assertEqual(compute_lds_allocation(16, insns_st64), 1024) - - def test_metadata_lds_bytes_consistency(self): - for dwords in (16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384): - lds_bytes = 4 * dwords - self.assertEqual(lds_bytes % 64, 0) - self.assertEqual(lds_bytes // 4, dwords) - - -class TestWorkgroupBounds(unittest.TestCase): - """Verifies workgroup size constraints, invocation bounds, and system register validity.""" - - def test_valid_workgroup_dimensions(self): - valid_cases = [ - (1, 1, 1, 1), - (32, 1, 1, 32), - (64, 1, 1, 64), - (128, 1, 1, 128), - (256, 1, 1, 256), - (1024, 1, 1, 1024), - (32, 32, 1, 1024), - (8, 8, 16, 1024), - (16, 16, 4, 1024), - (4, 4, 4, 64), - ] - for lx, ly, lz, expected_total in valid_cases: - with self.subTest(dims=(lx, ly, lz)): - self.assertEqual(validate_workgroup_size(lx, ly, lz), expected_total) - - def test_out_of_bounds_workgroup_sizes_rejected(self): - invalid_cases = [ - (0, 1, 1), - (1, 0, 1), - (1, 1, 0), - (-1, 1, 1), - (1025, 1, 1), - (32, 33, 1), # 1056 > 1024 - (64, 32, 1), # 2048 > 1024 - (16, 16, 5), # 1280 > 1024 - (2048, 1, 1), - ] - for lx, ly, lz in invalid_cases: - with self.subTest(dims=(lx, ly, lz)): - with self.assertRaises(WorkgroupBoundsError): - validate_workgroup_size(lx, ly, lz) - - def test_rsrc2_system_registers_and_tgid(self): - # COMPUTE_PGM_RSRC2: - # USER_SGPR [5:1] - # TGID_X_EN [7], TGID_Y_EN [8], TGID_Z_EN [9] - # TG_SIZE_EN [10] (unsupported) - # TIDIG_COMP_CNT [12:11] - rsrc2 = 0x8088 # user=4, TGID_X=1, LDS_SIZE=1 - user_sgprs = (rsrc2 >> 1) & 0x1F - self.assertEqual(user_sgprs, 4) - tgid_x = (rsrc2 >> 7) & 1 - tgid_y = (rsrc2 >> 8) & 1 - tgid_z = (rsrc2 >> 9) & 1 - self.assertEqual((tgid_x, tgid_y, tgid_z), (1, 0, 0)) - - # TG_SIZE_EN bit 10 must raise unsupported - rsrc2_with_tg_size = rsrc2 | (1 << 10) - self.assertTrue((rsrc2_with_tg_size >> 10) & 1) - - def test_linear_invocation_index_bounds(self): - lx, ly, lz = 8, 4, 2 - total = validate_workgroup_size(lx, ly, lz) - seen = set() - for z in range(lz): - for y in range(ly): - for x in range(lx): - idx = z * (lx * ly) + y * lx + x - self.assertGreaterEqual(idx, 0) - self.assertLess(idx, total) - seen.add(idx) - self.assertEqual(len(seen), total) - - -class TestLdsAddressWrapping(unittest.TestCase): - """Verifies hardware LDS pointer address calculation, alignment, and modulo masking.""" - - def test_aligned_and_unaligned_byte_offsets(self): - for byte_addr, expected_dword in [ - (0, 0), (1, 0), (2, 0), (3, 0), - (4, 1), (5, 1), (6, 1), (7, 1), - (60, 15), (63, 15), (64, 16), - ]: - with self.subTest(byte=byte_addr): - dword_idx = (byte_addr >> 2) & MASK - self.assertEqual(dword_idx, expected_dword) - - def test_power_of_two_mask_bounds(self): - for lds_dwords in (16, 32, 64, 128, 512, 1024, 16384): - mask = lds_dwords - 1 - for offset in (0, 1, 15, lds_dwords - 1, lds_dwords, lds_dwords + 5, 0x12345678, 0xFFFFFFFF): - wrapped = offset & mask - self.assertGreaterEqual(wrapped, 0) - self.assertLess(wrapped, lds_dwords) - - def test_wrap_around_upper_boundary(self): - lds_dwords = 128 - mask = lds_dwords - 1 - # 128 dwords = 512 bytes - # Byte address 512 wraps to dword index 0 - idx_512 = (512 >> 2) & mask - self.assertEqual(idx_512, 0) - - # Byte address 516 wraps to dword index 1 - idx_516 = (516 >> 2) & mask - self.assertEqual(idx_516, 1) - - def test_negative_byte_offset_wrapping(self): - # In uint32 arithmetic, a negative byte offset -4 is 0xFFFFFFFC - lds_dwords = 64 - mask = lds_dwords - 1 - sum_val = 0xFFFFFFFC - dword_idx = sum_val >> 2 - wrapped = dword_idx & mask - self.assertEqual(wrapped, lds_dwords - 1) - - -class TestLdsInterpreterExecution(unittest.TestCase): - """Executes semantic SPIR-V compute kernels modeling LDS Workgroup memory layout and bounds.""" - - def test_lds_store_and_load_roundtrip(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c5 = OpConstant %uint 5 -%c42 = OpConstant %uint 1337 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%p_write = OpAccessChain %_ptr_WG_uint %lds %c5 -OpStore %p_write %c42 -%p_read = OpAccessChain %_ptr_WG_uint %lds %c5 -%val = OpLoad %uint %p_read -OpStore %out %val -OpReturn -OpFunctionEnd -""" - interp = LdsComputeInterp(spvasm) - self.assertEqual(interp.lds_size, 16) - final_lds, lane_outputs = interp.run_workgroup(num_invocations=1) - self.assertEqual(final_lds[5], 1337) - self.assertEqual(lane_outputs[0]["%out"], 1337) - - def test_lds_bounds_masking_execution(self): - # Write to index (16 + 3) = 19; with mask 15 (0xF), it wraps to slot 3 - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c15 = OpConstant %uint 15 -%c_raw_idx = OpConstant %uint 19 -%c_payload = OpConstant %uint 0xCAFEBABE -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%masked_idx = OpBitwiseAnd %uint %c_raw_idx %c15 -%p_write = OpAccessChain %_ptr_WG_uint %lds %masked_idx -OpStore %p_write %c_payload -%p_read = OpAccessChain %_ptr_WG_uint %lds %masked_idx -%val = OpLoad %uint %p_read -OpStore %out %val -OpReturn -OpFunctionEnd -""" - interp = LdsComputeInterp(spvasm) - final_lds, lane_outputs = interp.run_workgroup(num_invocations=1) - self.assertEqual(final_lds[3], 0xCAFEBABE) - self.assertEqual(lane_outputs[0]["%out"], 0xCAFEBABE) - - def test_workgroup_multi_lane_lds_exchange(self): - # 4-thread workgroup: each thread writes its seeded payload to slot t, - # then thread 0 verifies slot 3 and thread 3 verifies slot 0. - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 4 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c2 = OpConstant %uint 2 -%c3 = OpConstant %uint 3 -%c100 = OpConstant %uint 100 -%c200 = OpConstant %uint 200 -%c300 = OpConstant %uint 300 -%c400 = OpConstant %uint 400 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%p0 = OpAccessChain %_ptr_WG_uint %lds %c0 -OpStore %p0 %c100 -%p1 = OpAccessChain %_ptr_WG_uint %lds %c1 -OpStore %p1 %c200 -%p2 = OpAccessChain %_ptr_WG_uint %lds %c2 -OpStore %p2 %c300 -%p3 = OpAccessChain %_ptr_WG_uint %lds %c3 -OpStore %p3 %c400 -%p_read = OpAccessChain %_ptr_WG_uint %lds %c2 -%val = OpLoad %uint %p_read -OpStore %out %val -OpReturn -OpFunctionEnd -""" - interp = LdsComputeInterp(spvasm) - final_lds, lane_outputs = interp.run_workgroup(num_invocations=4) - self.assertEqual(final_lds[0], 100) - self.assertEqual(final_lds[1], 200) - self.assertEqual(final_lds[2], 300) - self.assertEqual(final_lds[3], 400) - self.assertEqual(lane_outputs[0]["%out"], 300) - - def test_unsupported_storage_class_rejected(self): - # Storage classes outside Workgroup, Output, Function are rejected - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_UC = OpTypePointer UniformConstant %uint -%v = OpVariable %_ptr_UC UniformConstant -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(UnsupportedConstruct): - LdsComputeInterp(spvasm) - - def test_invalid_workgroup_size_rejected_in_interpreter(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 2048 1 1 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(WorkgroupBoundsError): - LdsComputeInterp(spvasm) - - -class TestTranslatorLdsIntegration(unittest.TestCase): - """Cross-checks LDS layout emission and pointer masking against tools/rdna2spirv.py.""" - - def test_translator_lds_ptr_masking_tokens(self): - # Instantiate a mock RDNA2 generator and verify pointer generation logic - class MockGen: - def __init__(self): - self.lds_dwords = 512 - self.lds_bound = None # not bounds-checked (SHADER-309) - self._tmp = 0 - self.emitted = [] - - def tmp(self): - self._tmp += 1 - return f"%t{self._tmp}" - - def cu(self, v): - return f"%c{v}" - - def emit(self, line): - self.emitted.append(line) - - lds_ptr = rdna2spirv.Gen.lds_ptr - lds_access = rdna2spirv.Gen.lds_access - lds_atomic = rdna2spirv.Gen.lds_atomic - - gen = MockGen() - ptr = gen.lds_ptr("%addr_reg", 16) - self.assertIn("OpAccessChain %_ptr_WG_uint %lds", gen.emitted[-1]) - # Mask must be lds_dwords - 1 = 511 - self.assertIn("OpBitwiseAnd %uint %t2 %c511", gen.emitted[-2]) - # Shift must be 2 (byte to dword) - self.assertIn("OpShiftRightLogical %uint %t1 %c2", gen.emitted[-3]) - # Base addition of byte offset - self.assertIn("OpIAdd %uint %addr_reg %c16", gen.emitted[-4]) - self.assertEqual(ptr, "%t4") +LDS_SIZE_SHIFT = 15 + + +def rsrc2(units, extra=0): + """4 user SGPRs, workgroup id in s4 (0x88) with `units` x 512 bytes of LDS.""" + return 0x88 | (units << LDS_SIZE_SHIFT) | extra + + +def translate(line, units, size=(32, 1, 1)): + return L.translate(["v_mov_b32_e32 v1, 0", line], rsrc2(units), size) + + +def lds_dwords(line, units=0, size=(32, 1, 1)): + spv = translate(line, units, size) + m = re.search(r"%lds_arr = OpTypeArray %uint (%\S+)", spv) + assert m, "no LDS array declared" + c = re.search(re.escape(m.group(1)) + r" = OpConstant %uint (\d+)", spv) + return int(c.group(1)) + + +def bounds_checked(line, units=0): + return "OpULessThan %bool" in translate(line, units) + + +READ = "ds_read_b32 v2, v1" + + +class TestAllocationSize(unittest.TestCase): + def test_declared_size_by_hand(self): + # (LDS_SIZE units, dwords): 128 per unit rounded up to a power of two, 16 .. 16384. + for units, want in ((0, 16), (1, 128), (2, 256), (3, 512), (5, 1024), (8, 1024), (9, 2048), (32, 4096), + (33, 8192), (64, 8192), (65, 16384), (128, 16384)): + with self.subTest(units=units): + self.assertEqual(lds_dwords(READ, units), want) + self.assertFalse(bounds_checked(READ, units)) + + def test_offset_inside_the_declaration_changes_nothing(self): + # 1 unit = 128 dwords = 512 bytes: the last dword is at byte 0x1FC. + for off in (0, 0x40, 0x1FC): + with self.subTest(offset=hex(off)): + self.assertEqual(lds_dwords(f"ds_read_b32 v2, v1 offset:{off:#x}", 1), 128) + self.assertFalse(bounds_checked(f"ds_read_b32 v2, v1 offset:{off:#x}", 1)) + + def test_offset_past_the_declaration_bounds_checks_at_exactly_the_declared_size(self): + # byte 0x200 is dword 128: one past the end of a 1-unit allocation. A 3-unit one is 384 dwords (not a power of + # two): the array is 384 then, not rounded up to 512. + for units, off, want in ((1, 0x200, 128), (1, 0x1000, 128), (3, 0x600, 384), (2, 0x400, 256)): + line = f"ds_read_b32 v2, v1 offset:{off:#x}" + with self.subTest(units=units, offset=hex(off)): + self.assertEqual(lds_dwords(line, units), want) + self.assertTrue(bounds_checked(line, units)) + + def test_nothing_declared_and_an_offset_gives_an_empty_checked_array(self): + line = "ds_read_b32 v2, v1 offset:0x100" + self.assertTrue(bounds_checked(line, 0)) + self.assertEqual(lds_dwords(line, 0), 1) # a 0-length array is not legal SPIR-V; every access fails the check + + def test_two_address_and_wide_offsets_count_their_width(self): + # 1 unit = 128 dwords. read2_b32 offset1:127 ends at dword 127 (fits); 128 does not. st64: 64 dwords per unit, + # so offset1:1 ends at dword 64 (fits) and offset1:2 at dword 128 (does not). b64 elements are two dwords. + for line, over in (("ds_read2_b32 v[2:3], v1 offset1:127", False), ("ds_read2_b32 v[2:3], v1 offset1:128", True), + ("ds_read2st64_b32 v[2:3], v1 offset1:1", False), + ("ds_read2st64_b32 v[2:3], v1 offset1:2", True), + ("ds_read2_b64 v[2:5], v1 offset1:63", False), ("ds_read2_b64 v[2:5], v1 offset1:64", True), + ("ds_read_b128 v[2:5], v1 offset:0x1F0", False), ("ds_read_b128 v[2:5], v1 offset:0x1F4", True), + ("ds_read_u8 v2, v1 offset:0x1FF", False), ("ds_read_u8 v2, v1 offset:0x200", True)): + with self.subTest(line=line): + self.assertEqual(bounds_checked(line, 1), over) + + def test_non_ds_listing_declares_none(self): + self.assertNotIn("%lds_arr", L.translate(["v_mov_b32_e32 v1, 0"], rsrc2(8))) + + def test_declared_size_over_64k_is_refused(self): + with self.assertRaises(rdna2spirv.Unsupported): + translate(READ, 129) # 129 x 512 B = 66048 B + self.assertEqual(lds_dwords(READ, 128), 16384) + + +class TestRefusals(unittest.TestCase): + def test_tg_size_en_refused(self): + with self.assertRaises(rdna2spirv.Unsupported): + L.translate([READ], rsrc2(8, extra=1 << 10)) + + def test_group_over_1024_refused(self): + for size in ((1025, 1, 1), (32, 33, 1), (16, 16, 5)): + with self.subTest(size=size), self.assertRaises(rdna2spirv.Unsupported): + L.translate([READ], rsrc2(8), size) + + def test_group_of_1024_accepted(self): + for size in ((1024, 1, 1), (32, 32, 1), (8, 8, 16)): + with self.subTest(size=size): + self.assertIn("%lds_arr", L.translate([READ], rsrc2(8), size)) + + +class TestWrap(unittest.TestCase): + def wrap_case(self, units, write_addr, read_addr): + """Lane i writes 0x900 + i at write_addr + 4 i, then reads read_addr + 4 i (addresses held in VGPRs).""" + body = ["v_lshlrev_b32_e32 v3, 2, v0", "v_add_nc_u32_e32 v1, %#x, v3" % write_addr, + "v_add_nc_u32_e32 v2, 0x900, v0", "ds_write_b32 v1, v2", "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32_e32 v4, %#x, v3" % read_addr, "ds_read_b32 v5, v4", "s_waitcnt lgkmcnt(0)"] \ + + L.store("v5", 0) + mem = L.run(body, rsrc2=rsrc2(units)) + return [L.out(mem, i, 0) for i in range(32)] + + def test_dynamic_address_wraps_at_the_array(self): + # 1 unit = 128 dwords = 512 bytes: byte 0x200 is byte 0, in either direction. + self.assertEqual(self.wrap_case(1, 0x200, 0), [0x900 + i for i in range(32)]) + self.assertEqual(self.wrap_case(1, 0, 0x400), [0x900 + i for i in range(32)]) + self.assertEqual(self.wrap_case(1, 0x100, 0x100), [0x900 + i for i in range(32)]) # no wrap: the same word + self.assertEqual(self.wrap_case(1, 0x80, 0x100), [0] * 32) # a different word + + def test_wraps_at_the_power_of_two_above_the_declaration(self): + # 3 units = 384 dwords, array 512 dwords = 2 KiB: byte 0x800 is byte 0, byte 0x600 (dword 384) is not byte 0. + self.assertEqual(self.wrap_case(3, 0x800, 0), [0x900 + i for i in range(32)]) + self.assertEqual(self.wrap_case(3, 0x600, 0), [0] * 32) + + def test_wraps_at_the_cap(self): + self.assertEqual(self.wrap_case(128, 0x10000, 0), [0x900 + i for i in range(32)]) if __name__ == "__main__": diff --git a/tests/semantic/test_lds_direct.py b/tests/semantic/test_lds_direct.py index 5b4d28155..9338b689c 100644 --- a/tests/semantic/test_lds_direct.py +++ b/tests/semantic/test_lds_direct.py @@ -1,796 +1,95 @@ -from __future__ import annotations +"""ds_write2_b32, ds_read2_b32, ds_write2st64_b32 and ds_read2st64_b32 through the translator. -"""Semantic interpreter tests for LDS direct dual-offset reads (ds_read2_b32, ds_read2st64_b32). +Standard library only; no GPU, no LLVM, no game files. -Covers: - * AMD RDNA2 ISA specification for LDS (Local Data Share) dual-offset read operations - (AMD RDNA 2 Instruction Set Architecture, Section 9 "Data Share Instructions"): - - ds_read2_b32: v[vdst:vdst+1], vaddr offset0:o0 offset1:o1 - Reads two independent 32-bit dwords directly from LDS into consecutive - vector registers without separate address generation instructions: - effective_byte_address0 = (vaddr + offset0 * 4) & 0xFFFFFFFF - effective_byte_address1 = (vaddr + offset1 * 4) & 0xFFFFFFFF - Where offset0 and offset1 are 8-bit unsigned integers [0, 255] scaled by 4 bytes. - - ds_read2st64_b32: v[vdst:vdst+1], vaddr offset0:o0 offset1:o1 - Reads two independent 32-bit dwords with stride-64 dwords (256 bytes): - effective_byte_address0 = (vaddr + offset0 * 256) & 0xFFFFFFFF - effective_byte_address1 = (vaddr + offset1 * 256) & 0xFFFFFFFF - Where offset0 and offset1 are 8-bit unsigned integers [0, 255] scaled by 256 bytes. - - Dual destination registers: - v[vdst] receives LDS dword from effective address 0. - v[vdst + 1] receives LDS dword from effective address 1. - - Single base address register: - vaddr specifies the 32-bit base byte address for both accesses. - Base address is read before destination registers are modified, so vdst may - overlap with vaddr safely. - - Sub-dword alignment & dword indexing: - Low 2 bits (effective_byte_address & 3) represent intra-dword byte offset; - for b32 operations, the dword index truncates these bits: - dword_index = (effective_byte_address >> 2) & (lds_dwords - 1) - - 32-bit address wrapping: (vaddr + offset * unit) wraps strictly modulo 2^32. - - LDS capacity wrapping: dword indices wrap modulo lds_dwords (power-of-two size). - - Active lane execution: - LDS direct reads execute conditionally on lane active mask (EXEC). - Inactive lanes leave both destination VGPRs (vdst and vdst+1) unmodified. - * SPIR-V translation mapping (tools/rdna2spirv.py): - - Compute (cs) and mesh (ms) shader stages: - ds_read2_b32 and ds_read2st64_b32 compute unit = 4 * (64 if st64 else 1). - Emits: - %s1 = OpIAdd %uint {addr} {offset * unit} - %i = OpShiftRightLogical %uint %s1 2 - %m = OpBitwiseAnd %uint %i {lds_dwords - 1} - %p = OpAccessChain %_ptr_WG_uint %lds %m - %v = OpLoad %uint %p - Followed by register writes to vgpr r and r + 1, guarded by %active via OpSelect. - - Other stages (ps, vs, gs) raise rdna2spirv.Unsupported. - * Deterministic semantic interpreter and test harness: - - Simulates LDS memory array, VGPR register file, and lane execution state. - - Cross-checks RDNA2 ISA offset calculations against reference functions and SPIR-V pointer math. - - Validates stride scaling, asymmetric offsets, overlapping source/dest, inactive lanes, - and negative controls (sabotaged units, dropped destination writes, and swapped offsets). +RDNA2 ISA, "Data Share Instructions": the 2-address forms access two dwords at + ADDR0 = vaddr + offset0 * 4, ADDR1 = vaddr + offset1 * 4 (the st64 forms: offset * 4 * 64) + * ds_write2_b32 vaddr, vdata0, vdata1: MEM[ADDR0] = vdata0, MEM[ADDR1] = vdata1 + * ds_read2_b32 vdst[0:1], vaddr: vdst[0] = MEM[ADDR0], vdst[1] = MEM[ADDR1] +(offset0 and offset1 are 8-bit unit counts; the b64 forms are in test_lds_read2_write2_b64.py.) -Run directly: - python -I tests/semantic/test_lds_direct.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -p test_lds_direct.py +Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run for 32 lanes in +tests/semantic/spirv_mini_interp.py. Lane i uses vaddr = 4 i, so with offsets that are multiples of 32 dwords +(non-st64) or of 64 dwords (st64) the lanes never share a dword. A plain-Python LDS model, written from the +formula above, gives the expected words for seeded random offsets; the hand-written cases pin the unit. """ - import os import random -import re import sys import unittest -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import lds_run as L # noqa: E402 (also puts tools/ on sys.path) import rdna2spirv # noqa: E402 -import shader_ir # noqa: E402 - -MASK32 = 0xFFFFFFFF -DEFAULT_LDS_DWORDS = 16384 # 64 KB LDS capacity in dwords - - -def calc_lds_dual_offset( - vaddr: int, - offset0: int = 0, - offset1: int = 0, - is_st64: bool = False, - lds_dwords: int = DEFAULT_LDS_DWORDS, -) -> tuple[tuple[int, int, int], tuple[int, int, int]]: - """Reference ISA calculation for LDS dual-offset read effective byte addresses and dword indices. - - Args: - vaddr: 32-bit base byte address in VGPR. - offset0: 8-bit unsigned integer offset for first dword. - offset1: 8-bit unsigned integer offset for second dword. - is_st64: True if stride-64 (256 bytes per offset count); False for 4 bytes. - lds_dwords: LDS capacity in 32-bit dwords (power of two). - - Returns: - ((eff_byte0, dword_idx0, byte_in_dword0), (eff_byte1, dword_idx1, byte_in_dword1)) - """ - vaddr = vaddr & MASK32 - unit = 256 if is_st64 else 4 - mask = lds_dwords - 1 - - off0_bytes = (offset0 & 0xFF) * unit - eff0 = (vaddr + off0_bytes) & MASK32 - dword0 = (eff0 >> 2) & mask - byte0 = eff0 & 3 - - off1_bytes = (offset1 & 0xFF) * unit - eff1 = (vaddr + off1_bytes) & MASK32 - dword1 = (eff1 >> 2) & mask - byte1 = eff1 & 3 - - return (eff0, dword0, byte0), (eff1, dword1, byte1) - - -def emulate_spirv_lds_ptr(addr_val: int, byte_off: int, lds_dwords: int = DEFAULT_LDS_DWORDS) -> int: - """Emulate the exact SPIR-V pointer index sequence emitted by rdna2spirv.Gen.lds_ptr. - - Sequence: - %s1 = OpIAdd %uint {addr} {byte_off} - %i = OpShiftRightLogical %uint %s1 2 - %m = OpBitwiseAnd %uint %i {lds_dwords - 1} - Returns: - dword index %m into %lds array. - """ - s1 = (addr_val + byte_off) & MASK32 - i = (s1 >> 2) & MASK32 - m = i & (lds_dwords - 1) - return m - - -class LdsDirectSemanticInterpreter: - """Deterministic semantic interpreter for RDNA2 LDS direct dual-offset read instructions. - - Models LDS shared memory array, VGPR register files, and lane execution state. - """ - - def __init__(self, lds_dwords: int = DEFAULT_LDS_DWORDS, num_vgprs: int = 256) -> None: - self.lds_dwords = lds_dwords - self.lds = [0] * lds_dwords - self.num_vgprs = num_vgprs - self.vgprs = [0] * num_vgprs - self.active_lane = True - - def set_vgpr(self, reg_idx: int, value: int) -> None: - self.vgprs[reg_idx] = value & MASK32 - - def get_vgpr(self, reg_idx: int) -> int: - return self.vgprs[reg_idx] - - def set_lds_dword(self, dword_idx: int, value: int) -> None: - self.lds[dword_idx & (self.lds_dwords - 1)] = value & MASK32 - - def get_lds_dword(self, dword_idx: int) -> int: - return self.lds[dword_idx & (self.lds_dwords - 1)] - - def ds_write_b32(self, vaddr_reg: int, vdata_reg: int, offset: int = 0) -> int | None: - """Execute ds_write_b32 vaddr, vdata [offset:offset].""" - if not self.active_lane: - return None - vaddr = self.vgprs[vaddr_reg] - eff_byte = (vaddr + (offset & 0xFFFF)) & MASK32 - dword_idx = (eff_byte >> 2) & (self.lds_dwords - 1) - self.lds[dword_idx] = self.vgprs[vdata_reg] & MASK32 - return dword_idx - - def ds_read2_b32( - self, vdst_reg: int, vaddr_reg: int, offset0: int = 0, offset1: int = 0 - ) -> tuple[int, int] | None: - """Execute ds_read2_b32 v[vdst:vdst+1], vaddr offset0:o0 offset1:o1.""" - if not self.active_lane: - return None - # Base address register is read before destination registers are modified - vaddr = self.vgprs[vaddr_reg] - (eff0, dword0, _), (eff1, dword1, _) = calc_lds_dual_offset( - vaddr, offset0, offset1, is_st64=False, lds_dwords=self.lds_dwords - ) - val0 = self.lds[dword0] - val1 = self.lds[dword1] - self.vgprs[vdst_reg] = val0 - self.vgprs[vdst_reg + 1] = val1 - return dword0, dword1 - - def ds_read2st64_b32( - self, vdst_reg: int, vaddr_reg: int, offset0: int = 0, offset1: int = 0 - ) -> tuple[int, int] | None: - """Execute ds_read2st64_b32 v[vdst:vdst+1], vaddr offset0:o0 offset1:o1.""" - if not self.active_lane: - return None - vaddr = self.vgprs[vaddr_reg] - (eff0, dword0, _), (eff1, dword1, _) = calc_lds_dual_offset( - vaddr, offset0, offset1, is_st64=True, lds_dwords=self.lds_dwords - ) - val0 = self.lds[dword0] - val1 = self.lds[dword1] - self.vgprs[vdst_reg] = val0 - self.vgprs[vdst_reg + 1] = val1 - return dword0, dword1 - - def parse_and_execute(self, instruction_text: str) -> tuple[int, int] | int | None: - """Parse and execute a single LDS instruction text line.""" - line = instruction_text.strip() - if not line or line.startswith(";"): - return None - - # Parse modifiers: offset0:N, offset1:N, offset:N - offset0 = 0 - offset1 = 0 - offset = 0 - - m0 = re.search(r"\boffset0:(\S+)", line) - if m0: - offset0 = int(m0.group(1), 0) - line = re.sub(r"\boffset0:\S+", "", line).strip() - - m1 = re.search(r"\boffset1:(\S+)", line) - if m1: - offset1 = int(m1.group(1), 0) - line = re.sub(r"\boffset1:\S+", "", line).strip() - - m = re.search(r"\boffset:(\S+)", line) - if m: - offset = int(m.group(1), 0) - line = re.sub(r"\boffset:\S+", "", line).strip() - - parts = line.split(None, 1) - op = parts[0] - args_str = parts[1] if len(parts) > 1 else "" - args = [a.strip() for a in args_str.split(",") if a.strip()] - - if op in ("ds_read2_b32", "ds_read2st64_b32"): - # Syntax: op v[dst:dst+1] or vdst, vaddr - dst_match = re.match(r"^v\[(\d+):(\d+)\]$", args[0]) - if dst_match: - vdst_reg = int(dst_match.group(1)) - else: - vdst_reg = int(args[0].replace("v", "")) - vaddr_reg = int(args[1].replace("v", "")) - - if op == "ds_read2_b32": - return self.ds_read2_b32(vdst_reg, vaddr_reg, offset0, offset1) - else: - return self.ds_read2st64_b32(vdst_reg, vaddr_reg, offset0, offset1) - - elif op == "ds_write_b32": - vaddr_reg = int(args[0].replace("v", "")) - vdata_reg = int(args[1].replace("v", "")) - return self.ds_write_b32(vaddr_reg, vdata_reg, offset) - else: - raise NotImplementedError(f"Unsupported instruction: {op}") - - -class DualOffsetCalculationTests(unittest.TestCase): - """Test effective byte addresses and dword offset calculations per RDNA2 ISA.""" - - def test_zero_offsets_both_zero(self): - cases = [ - (0, 0), - (4, 1), - (64, 16), - (1024, 256), - (65532, 16383), - ] - for vaddr, exp_dword in cases: - with self.subTest(vaddr=vaddr): - (eff0, dword0, byte0), (eff1, dword1, byte1) = calc_lds_dual_offset( - vaddr, offset0=0, offset1=0, is_st64=False - ) - self.assertEqual(eff0, vaddr) - self.assertEqual(eff1, vaddr) - self.assertEqual(dword0, exp_dword) - self.assertEqual(dword1, exp_dword) - self.assertEqual(byte0, 0) - self.assertEqual(byte1, 0) - - def test_ds_read2_b32_dword_scaling(self): - """ds_read2_b32 scales offset0 and offset1 by 4 bytes (1 dword).""" - cases = [ - (0, 1, 2, 4, 8, 1, 2), - (0, 4, 8, 16, 32, 4, 8), - (100, 5, 10, 120, 140, 30, 35), - (0x1000, 0x10, 0x20, 0x1040, 0x1080, 0x1040 // 4, 0x1080 // 4), - ] - for vaddr, off0, off1, exp_eff0, exp_eff1, exp_dw0, exp_dw1 in cases: - with self.subTest(vaddr=vaddr, off0=off0, off1=off1): - (eff0, dw0, b0), (eff1, dw1, b1) = calc_lds_dual_offset( - vaddr, off0, off1, is_st64=False - ) - self.assertEqual(eff0, exp_eff0) - self.assertEqual(eff1, exp_eff1) - self.assertEqual(dw0, exp_dw0) - self.assertEqual(dw1, exp_dw1) - self.assertEqual(b0, 0) - self.assertEqual(b1, 0) - - def test_ds_read2st64_b32_stride64_scaling(self): - """ds_read2st64_b32 scales offset0 and offset1 by 256 bytes (64 dwords).""" - cases = [ - (0, 1, 2, 256, 512, 64, 128), - (0, 4, 8, 1024, 2048, 256, 512), - (512, 1, 3, 768, 1280, 192, 320), - (0x2000, 2, 4, 0x2200, 0x2400, 0x2200 // 4, 0x2400 // 4), - ] - for vaddr, off0, off1, exp_eff0, exp_eff1, exp_dw0, exp_dw1 in cases: - with self.subTest(vaddr=vaddr, off0=off0, off1=off1): - (eff0, dw0, b0), (eff1, dw1, b1) = calc_lds_dual_offset( - vaddr, off0, off1, is_st64=True - ) - self.assertEqual(eff0, exp_eff0) - self.assertEqual(eff1, exp_eff1) - self.assertEqual(dw0, exp_dw0) - self.assertEqual(dw1, exp_dw1) - self.assertEqual(b0, 0) - self.assertEqual(b1, 0) - - def test_independent_asymmetric_dual_offsets(self): - """Dual offsets operate independently, including when off0 > off1.""" - vaddr = 400 - # off0 = 30 -> +120 bytes -> 520 (dword 130) - # off1 = 5 -> +20 bytes -> 420 (dword 105) - (eff0, dw0, _), (eff1, dw1, _) = calc_lds_dual_offset(vaddr, 30, 5, is_st64=False) - self.assertEqual(eff0, 520) - self.assertEqual(eff1, 420) - self.assertEqual(dw0, 130) - self.assertEqual(dw1, 105) - - def test_8bit_offset_boundary_limits(self): - """8-bit offsets support values up to 255 (0xFF).""" - # ds_read2_b32: max reach is 255 * 4 = 1020 bytes - (eff0, dw0, _), (eff1, dw1, _) = calc_lds_dual_offset(0, 0, 255, is_st64=False) - self.assertEqual(eff0, 0) - self.assertEqual(dw0, 0) - self.assertEqual(eff1, 1020) - self.assertEqual(dw1, 255) - - # ds_read2st64_b32: max reach is 255 * 256 = 65280 bytes (16320 dwords) - (eff0_st, dw0_st, _), (eff1_st, dw1_st, _) = calc_lds_dual_offset(0, 0, 255, is_st64=True) - self.assertEqual(eff0_st, 0) - self.assertEqual(dw0_st, 0) - self.assertEqual(eff1_st, 65280) - self.assertEqual(dw1_st, 16320) - - def test_sub_dword_unaligned_base_address(self): - """Unaligned base byte addresses are truncated by >> 2 to the containing dword.""" - cases = [ - (1, 0, 0, 1, 1, 0, 0, 1, 1), - (2, 1, 2, 6, 10, 1, 2, 2, 2), - (3, 4, 8, 19, 35, 4, 8, 3, 3), - ] - for vaddr, o0, o1, exp_eff0, exp_eff1, exp_dw0, exp_dw1, exp_b0, exp_b1 in cases: - with self.subTest(vaddr=vaddr): - (eff0, dw0, b0), (eff1, dw1, b1) = calc_lds_dual_offset(vaddr, o0, o1, is_st64=False) - self.assertEqual(eff0, exp_eff0) - self.assertEqual(eff1, exp_eff1) - self.assertEqual(dw0, exp_dw0) - self.assertEqual(dw1, exp_dw1) - self.assertEqual(b0, exp_b0) - self.assertEqual(b1, exp_b1) - - def test_32bit_address_arithmetic_wrapping(self): - """(vaddr + offset * unit) wraps strictly modulo 2^32.""" - cases = [ - (0xFFFFFFFC, 1, 2, 0, 4, 0, 1), - (0xFFFFFF00, 1, 2, 0, 0x100, 0, 0x40), - ] - # First case with b32: 0xFFFFFFFC + 4 = 0 (wrapped), + 8 = 4 - (eff0, dw0, _), (eff1, dw1, _) = calc_lds_dual_offset(0xFFFFFFFC, 1, 2, is_st64=False) - self.assertEqual(eff0, 0) - self.assertEqual(dw0, 0) - self.assertEqual(eff1, 4) - self.assertEqual(dw1, 1) - - # Second case with st64: 0xFFFFFF00 + 256 = 0 (wrapped), + 512 = 256 - (eff0_st, dw0_st, _), (eff1_st, dw1_st, _) = calc_lds_dual_offset(0xFFFFFF00, 1, 2, is_st64=True) - self.assertEqual(eff0_st, 0) - self.assertEqual(dw0_st, 0) - self.assertEqual(eff1_st, 256) - self.assertEqual(dw1_st, 64) - - def test_lds_size_wrapping(self): - """Dword indices wrap modulo lds_dwords (power of two).""" - lds_dwords = 1024 # 4 KB capacity - # Base 4096 = exactly 1 LDS capacity wrap - (eff0, dw0, _), (eff1, dw1, _) = calc_lds_dual_offset( - 4096, 4, 8, is_st64=False, lds_dwords=lds_dwords - ) - self.assertEqual(dw0, 4) - self.assertEqual(dw1, 8) - - def test_randomized_equivalence_with_spirv_math(self): - """500 pseudo-random iterations verifying dual offsets against SPIR-V emulation.""" - rng = random.Random(0x4C445332) - for _ in range(500): - vaddr = rng.randint(0, MASK32) - off0 = rng.randint(0, 255) - off1 = rng.randint(0, 255) - is_st64 = rng.choice([False, True]) - lds_dwords = 1 << rng.randint(6, 14) - - (eff0, dw0, _), (eff1, dw1, _) = calc_lds_dual_offset( - vaddr, off0, off1, is_st64=is_st64, lds_dwords=lds_dwords - ) - - unit = 256 if is_st64 else 4 - dw0_spirv = emulate_spirv_lds_ptr(vaddr, off0 * unit, lds_dwords=lds_dwords) - dw1_spirv = emulate_spirv_lds_ptr(vaddr, off1 * unit, lds_dwords=lds_dwords) - - self.assertEqual(dw0, dw0_spirv) - self.assertEqual(dw1, dw1_spirv) - self.assertTrue(0 <= dw0 < lds_dwords) - self.assertTrue(0 <= dw1 < lds_dwords) - - -class LdsDirectExecutionTests(unittest.TestCase): - """Test full execution state transitions for ds_read2_b32 and ds_read2st64_b32.""" - - def test_basic_ds_read2_b32_execution(self): - interp = LdsDirectSemanticInterpreter() - # Seed LDS at dwords 32 and 34 - interp.set_lds_dword(32, 0x11111111) - interp.set_lds_dword(34, 0x22222222) - - # Base address v0 = 128 (dword 32). off0 = 0 (dword 32), off1 = 2 (dword 34) - interp.set_vgpr(0, 128) - interp.set_vgpr(2, 0) - interp.set_vgpr(3, 0) - - dwords = interp.ds_read2_b32(vdst_reg=2, vaddr_reg=0, offset0=0, offset1=2) - self.assertEqual(dwords, (32, 34)) - self.assertEqual(interp.get_vgpr(2), 0x11111111) - self.assertEqual(interp.get_vgpr(3), 0x22222222) - - def test_basic_ds_read2st64_b32_execution(self): - interp = LdsDirectSemanticInterpreter() - # Stride 64 dwords (256 bytes) - # Base address v1 = 0 - # off0 = 1 -> byte 256 -> dword 64 - # off1 = 3 -> byte 768 -> dword 192 - interp.set_lds_dword(64, 0xAAAAAAAA) - interp.set_lds_dword(192, 0xBBBBBBBB) - - interp.set_vgpr(1, 0) - interp.set_vgpr(4, 0) - interp.set_vgpr(5, 0) - - dwords = interp.ds_read2st64_b32(vdst_reg=4, vaddr_reg=1, offset0=1, offset1=3) - self.assertEqual(dwords, (64, 192)) - self.assertEqual(interp.get_vgpr(4), 0xAAAAAAAA) - self.assertEqual(interp.get_vgpr(5), 0xBBBBBBBB) - - def test_identical_dual_offsets(self): - """When offset0 == offset1, both destination registers receive the identical dword.""" - interp = LdsDirectSemanticInterpreter() - interp.set_lds_dword(50, 0xCAFEBABE) - interp.set_vgpr(0, 200) # dword 50 - - interp.ds_read2_b32(vdst_reg=6, vaddr_reg=0, offset0=0, offset1=0) - self.assertEqual(interp.get_vgpr(6), 0xCAFEBABE) - self.assertEqual(interp.get_vgpr(7), 0xCAFEBABE) - - def test_inverted_offsets_execution(self): - """offset0 > offset1 correctly loads high offset to vdst and low offset to vdst+1.""" - interp = LdsDirectSemanticInterpreter() - interp.set_lds_dword(10, 0x10101010) - interp.set_lds_dword(25, 0x25252525) - - interp.set_vgpr(0, 0) - # off0 = 25 (dword 25), off1 = 10 (dword 10) - interp.ds_read2_b32(vdst_reg=8, vaddr_reg=0, offset0=25, offset1=10) - self.assertEqual(interp.get_vgpr(8), 0x25252525) - self.assertEqual(interp.get_vgpr(9), 0x10101010) - - def test_destination_overlaps_source_address_register(self): - """Base address register is sampled before destination registers are updated.""" - interp = LdsDirectSemanticInterpreter() - # vdst = 2, vaddr = 2: vdst overlaps vaddr - interp.set_vgpr(2, 64) # base address 64 -> dword 16 - interp.set_lds_dword(16, 0x33333333) - interp.set_lds_dword(17, 0x44444444) - - interp.ds_read2_b32(vdst_reg=2, vaddr_reg=2, offset0=0, offset1=1) - self.assertEqual(interp.get_vgpr(2), 0x33333333) - self.assertEqual(interp.get_vgpr(3), 0x44444444) - - # vdst = 4, vaddr = 5: vdst+1 overlaps vaddr - interp.set_vgpr(5, 128) # base address 128 -> dword 32 - interp.set_lds_dword(32, 0x55555555) - interp.set_lds_dword(33, 0x66666666) - - interp.ds_read2_b32(vdst_reg=4, vaddr_reg=5, offset0=0, offset1=1) - self.assertEqual(interp.get_vgpr(4), 0x55555555) - self.assertEqual(interp.get_vgpr(5), 0x66666666) - - def test_inactive_lane_preserves_both_destination_vgprs(self): - """When active_lane is False, neither destination register is altered.""" - interp = LdsDirectSemanticInterpreter() - interp.set_vgpr(0, 100) - interp.set_vgpr(2, 0x77777777) - interp.set_vgpr(3, 0x88888888) - interp.set_lds_dword(25, 0x99999999) - interp.set_lds_dword(26, 0xAAAAAAAA) - - interp.active_lane = False - res = interp.ds_read2_b32(vdst_reg=2, vaddr_reg=0, offset0=0, offset1=1) - self.assertIsNone(res) - self.assertEqual(interp.get_vgpr(2), 0x77777777) - self.assertEqual(interp.get_vgpr(3), 0x88888888) - - # Same for st64 - res_st = interp.ds_read2st64_b32(vdst_reg=2, vaddr_reg=0, offset0=1, offset1=2) - self.assertIsNone(res_st) - self.assertEqual(interp.get_vgpr(2), 0x77777777) - self.assertEqual(interp.get_vgpr(3), 0x88888888) - - def test_parse_and_execute_bracket_range_syntax(self): - """Instruction text with v[dst:dst+1] range syntax parses and executes correctly.""" - interp = LdsDirectSemanticInterpreter() - interp.set_lds_dword(10, 0x12345678) - interp.set_lds_dword(12, 0x9ABCDEF0) - interp.set_vgpr(1, 32) # dword 8 - - # 32 + 2*4 = 40 (dword 10), 32 + 4*4 = 48 (dword 12) - ret = interp.parse_and_execute("ds_read2_b32 v[6:7], v1 offset0:2 offset1:4") - self.assertEqual(ret, (10, 12)) - self.assertEqual(interp.get_vgpr(6), 0x12345678) - self.assertEqual(interp.get_vgpr(7), 0x9ABCDEF0) - - def test_parse_and_execute_single_reg_syntax(self): - """Instruction text with single vdst syntax parses and executes correctly.""" - interp = LdsDirectSemanticInterpreter() - interp.set_lds_dword(1, 0x11112222) - interp.set_lds_dword(2, 0x33334444) - interp.set_vgpr(2, 0) - - ret = interp.parse_and_execute("ds_read2_b32 v10, v2 offset0:1 offset1:2") - self.assertEqual(ret, (1, 2)) - self.assertEqual(interp.get_vgpr(10), 0x11112222) - self.assertEqual(interp.get_vgpr(11), 0x33334444) - - def test_parse_and_execute_st64_hex_offsets(self): - """Hexadecimal offset modifiers with ds_read2st64_b32.""" - interp = LdsDirectSemanticInterpreter() - # offset0: 0x02 -> 2 * 256 = 512 (dword 128) - # offset1: 0x04 -> 4 * 256 = 1024 (dword 256) - interp.set_lds_dword(128, 0xDEADBEEF) - interp.set_lds_dword(256, 0xFEEDFACE) - interp.set_vgpr(3, 0) - - ret = interp.parse_and_execute("ds_read2st64_b32 v[8:9], v3 offset0:0x02 offset1:0x04") - self.assertEqual(ret, (128, 256)) - self.assertEqual(interp.get_vgpr(8), 0xDEADBEEF) - self.assertEqual(interp.get_vgpr(9), 0xFEEDFACE) - - def test_parse_and_execute_default_omitted_offsets(self): - """Omitted offset modifiers default to 0.""" - interp = LdsDirectSemanticInterpreter() - interp.set_lds_dword(0, 0x55555555) - interp.set_lds_dword(1, 0x66666666) - interp.set_vgpr(4, 0) - - # Both omitted - ret = interp.parse_and_execute("ds_read2_b32 v[12:13], v4") - self.assertEqual(ret, (0, 0)) - self.assertEqual(interp.get_vgpr(12), 0x55555555) - self.assertEqual(interp.get_vgpr(13), 0x55555555) - - # offset1 omitted -> defaults to 0 - ret2 = interp.parse_and_execute("ds_read2_b32 v[14:15], v4 offset0:1") - self.assertEqual(ret2, (1, 0)) - self.assertEqual(interp.get_vgpr(14), 0x66666666) - self.assertEqual(interp.get_vgpr(15), 0x55555555) - - def test_consecutive_dual_read_stream(self): - """Simulate unrolled reduction or FFT loading multiple dwords via dual reads.""" - interp = LdsDirectSemanticInterpreter() - for i in range(8): - interp.set_lds_dword(i, 0x100 + i) - - interp.set_vgpr(0, 0) - # Load dwords 0, 1 into v[2:3] - interp.parse_and_execute("ds_read2_b32 v[2:3], v0 offset0:0 offset1:1") - # Load dwords 2, 3 into v[4:5] - interp.parse_and_execute("ds_read2_b32 v[4:5], v0 offset0:2 offset1:3") - # Load dwords 4, 5 into v[6:7] - interp.parse_and_execute("ds_read2_b32 v[6:7], v0 offset0:4 offset1:5") - # Load dwords 6, 7 into v[8:9] - interp.parse_and_execute("ds_read2_b32 v[8:9], v0 offset0:6 offset1:7") - - for i in range(8): - self.assertEqual(interp.get_vgpr(2 + i), 0x100 + i) - - -class Rdna2SpirvDirectEmissionTests(unittest.TestCase): - """Verify tools/rdna2spirv.py SPIR-V emission for ds_read2_b32 and ds_read2st64_b32.""" - - def test_ds_read2_b32_emission_in_cs(self): - g = rdna2spirv.Gen(stage="cs") - # ds_read2_b32 v[0:1], v2 offset0:4 offset1:8 - g.lds_op( - "ds_read2_b32", - [{"k": "vgpr", "r": 0, "n": 2}, {"k": "vgpr", "r": 2, "n": 1}], - ["offset0:4", "offset1:8"], - ) - body = "\n".join(g.body) - - self.assertTrue(g.uses_lds) - self.assertIn("OpSelectionMerge", body) - self.assertIn("OpBranchConditional", body) - # Check OpLoad instructions: 1 vaddr load + 2 LDS loads + 2 destination VGPR old loads = 5 - self.assertEqual(body.count("OpLoad %uint %t"), 1 + 2 + 2) - - # Check byte offsets: 4 * 4 = 16 (0x10), 8 * 4 = 32 (0x20) - c16 = g.cu(16) - c32 = g.cu(32) - self.assertIn(f"OpIAdd %uint", body) - self.assertIn(c16, body) - self.assertIn(c32, body) - - # Check destination register writes: v0 and v1 - c0 = g.cu(0) - c1 = g.cu(1) - self.assertIn(f"OpAccessChain %_ptr_Function_uint %vgpr {c0}", body) - self.assertIn(f"OpAccessChain %_ptr_Function_uint %vgpr {c1}", body) - - def test_ds_read2st64_b32_emission_in_cs(self): - g = rdna2spirv.Gen(stage="cs") - # ds_read2st64_b32 v[4:5], v10 offset0:1 offset1:2 - g.lds_op( - "ds_read2st64_b32", - [{"k": "vgpr", "r": 4, "n": 2}, {"k": "vgpr", "r": 10, "n": 1}], - ["offset0:1", "offset1:2"], - ) - body = "\n".join(g.body) - - self.assertTrue(g.uses_lds) - # Check byte offsets: 1 * 256 = 256 (0x100), 2 * 256 = 512 (0x200) - c256 = g.cu(256) - c512 = g.cu(512) - self.assertIn(c256, body) - self.assertIn(c512, body) - - # Check destination registers: v4 and v5 - c4 = g.cu(4) - c5 = g.cu(5) - self.assertIn(f"OpAccessChain %_ptr_Function_uint %vgpr {c4}", body) - self.assertIn(f"OpAccessChain %_ptr_Function_uint %vgpr {c5}", body) - - def test_ds_read2_emission_in_ms(self): - """Mesh shaders (ms) allow LDS direct reads.""" - g = rdna2spirv.Gen(stage="ms") - g.lds_op( - "ds_read2_b32", - [{"k": "vgpr", "r": 2, "n": 2}, {"k": "vgpr", "r": 0, "n": 1}], - ["offset0:0", "offset1:1"], - ) - self.assertTrue(g.uses_lds) - body = "\n".join(g.body) - self.assertIn("OpSelectionMerge", body) - - def test_disasm_parser_integration(self): - """Verify integration between shader_ir.parse_line and Gen.lds_op.""" - ins = shader_ir.parse_line("\tds_read2_b32 v[8:9], v3 offset0:10 offset1:20") - self.assertEqual(ins["op"], "ds_read2_b32") - self.assertEqual(ins["args"][0]["r"], 8) - self.assertEqual(ins["args"][0]["n"], 2) - self.assertEqual(ins["args"][1]["r"], 3) - - g = rdna2spirv.Gen(stage="cs") - g.lds_op(ins["op"], ins["args"], ins["mods"]) - body = "\n".join(g.body) - c40 = g.cu(40) # 10 * 4 - c80 = g.cu(80) # 20 * 4 - self.assertIn(c40, body) - self.assertIn(c80, body) - - def test_unsupported_stages_reject(self): - """Pixel, vertex, and geometry stages must reject ds_read2 instructions.""" - for stage in ("ps", "vs", "gs"): - with self.subTest(stage=stage): - g = rdna2spirv.Gen(stage=stage) - with self.assertRaises(rdna2spirv.Unsupported): - g.lds_op( - "ds_read2_b32", - [{"k": "vgpr", "r": 0, "n": 2}, {"k": "vgpr", "r": 1, "n": 1}], - [], - ) - with self.assertRaises(rdna2spirv.Unsupported): - g.lds_op( - "ds_read2st64_b32", - [{"k": "vgpr", "r": 0, "n": 2}, {"k": "vgpr", "r": 1, "n": 1}], - [], - ) - - -class NegativeControlAndMutationTests(unittest.TestCase): - """Verify that intentional corruptions in dual-offset LDS read semantics are strictly caught.""" - - def test_detects_b32_stride_corruption(self): - """Corrupting ds_read2_b32 unit from 4 to 1 (treating offset as bytes) fails.""" - vaddr = 0 - off0 = 8 - off1 = 16 - (eff0, dw0, _), (eff1, dw1, _) = calc_lds_dual_offset(vaddr, off0, off1, is_st64=False) - self.assertEqual(dw0, 8) - self.assertEqual(dw1, 16) - - # Corrupted unit: byte scaling (unit = 1 instead of 4) - corrupted_dw0 = ((vaddr + off0 * 1) >> 2) & (DEFAULT_LDS_DWORDS - 1) - self.assertEqual(corrupted_dw0, 2) - self.assertNotEqual(dw0, corrupted_dw0) - - def test_detects_st64_stride_corruption(self): - """Corrupting ds_read2st64_b32 unit from 256 to 4 (treating st64 as regular read2) fails.""" - vaddr = 0 - off0 = 2 - off1 = 4 - (eff0, dw0, _), (eff1, dw1, _) = calc_lds_dual_offset(vaddr, off0, off1, is_st64=True) - self.assertEqual(dw0, 128) - self.assertEqual(dw1, 256) - - # Corrupted unit: unit = 4 instead of 256 - corrupted_dw0 = ((vaddr + off0 * 4) >> 2) & (DEFAULT_LDS_DWORDS - 1) - self.assertEqual(corrupted_dw0, 2) - self.assertNotEqual(dw0, corrupted_dw0) - - def test_detects_offset_swap_corruption(self): - """Swapping offset0 and offset1 results in mismatched values when offsets differ.""" - interp = LdsDirectSemanticInterpreter() - interp.set_lds_dword(10, 0xAAAAAAAA) - interp.set_lds_dword(20, 0xBBBBBBBB) - interp.set_vgpr(0, 0) - - # Correct: off0=10 (v2 gets 0xAAAA), off1=20 (v3 gets 0xBBBB) - interp.ds_read2_b32(vdst_reg=2, vaddr_reg=0, offset0=10, offset1=20) - self.assertEqual(interp.get_vgpr(2), 0xAAAAAAAA) - self.assertEqual(interp.get_vgpr(3), 0xBBBBBBBB) - - # Mutated: swapped offsets - interp.set_vgpr(4, 0) - interp.set_vgpr(5, 0) - interp.ds_read2_b32(vdst_reg=4, vaddr_reg=0, offset0=20, offset1=10) - self.assertNotEqual(interp.get_vgpr(2), interp.get_vgpr(4)) - self.assertNotEqual(interp.get_vgpr(3), interp.get_vgpr(5)) - - def test_detects_single_vgpr_write_corruption(self): - """Failing to write the second destination VGPR (vdst+1) is detected.""" - interp = LdsDirectSemanticInterpreter() - interp.set_lds_dword(1, 0x11111111) - interp.set_lds_dword(2, 0x22222222) - interp.set_vgpr(0, 0) - interp.set_vgpr(2, 0) - interp.set_vgpr(3, 0xFFFFFFFF) # Sentinel in vdst+1 - - # Correct read updates both v2 and v3 - interp.ds_read2_b32(vdst_reg=2, vaddr_reg=0, offset0=1, offset1=2) - self.assertEqual(interp.get_vgpr(2), 0x11111111) - self.assertEqual(interp.get_vgpr(3), 0x22222222) - - # If only vdst were written, vdst+1 would retain sentinel - self.assertNotEqual(interp.get_vgpr(3), 0xFFFFFFFF) - - def test_detects_shift_corruption(self): - """Corrupting >> 2 shift to >> 3 (treating dwords as 8-byte uint64) fails.""" - vaddr = 16 - off = 4 # 4 * 4 = 16 bytes -> eff = 32 -> dword 8 - (eff0, dw0, _), _ = calc_lds_dual_offset(vaddr, off, 0, is_st64=False) - self.assertEqual(dw0, 8) - - corrupted_dw = ((vaddr + off * 4) >> 3) & (DEFAULT_LDS_DWORDS - 1) - self.assertEqual(corrupted_dw, 4) - self.assertNotEqual(dw0, corrupted_dw) - - def test_detects_missing_lds_wrap_mask(self): - """Omitting (lds_dwords - 1) mask fails for out-of-bounds addresses.""" - lds_dwords = 512 - vaddr = 512 * 4 * 3 + 16 # 3 full wraps + 16 bytes (dword 4) - (eff0, dw0, _), _ = calc_lds_dual_offset(vaddr, 0, 0, lds_dwords=lds_dwords) - self.assertEqual(dw0, 4) - - corrupted_unmasked = (vaddr >> 2) - self.assertNotEqual(dw0, corrupted_unmasked) - - def test_detects_inactive_lane_leak_corruption(self): - """Corrupted interpreter that ignores active_lane flag fails check.""" - interp = LdsDirectSemanticInterpreter() - interp.set_vgpr(2, 0x12341234) - interp.set_vgpr(3, 0x56785678) - interp.active_lane = False - - interp.ds_read2_b32(vdst_reg=2, vaddr_reg=0, offset0=0, offset1=1) - # Should be preserved - self.assertEqual(interp.get_vgpr(2), 0x12341234) - self.assertEqual(interp.get_vgpr(3), 0x56785678) +import support # noqa: E402 + +RSRC2_8K = 0x80088 # 4 user SGPRs, workgroup id in s4, LDS_SIZE = 16 x 512 bytes +LDS_BYTES = 8192 + + +def lane_program(write, read, unit_bytes, off0, off1, roff0, roff1): + """Lane i writes (0x5000 + i, 0x6000 + i) with `write`, reads two dwords with `read`, and reads the dwords at + the write offsets back with plain ds_read_b32 (byte offsets off * unit_bytes).""" + body = ["v_lshlrev_b32_e32 v1, 2, v0", "v_add_nc_u32_e32 v2, 0x5000, v0", "v_add_nc_u32_e32 v3, 0x6000, v0", + f"{write} v1, v2, v3 offset0:{off0} offset1:{off1}", "s_waitcnt lgkmcnt(0)", + f"{read} v[4:5], v1 offset0:{roff0} offset1:{roff1}", + f"ds_read_b32 v6, v1 offset:{off0 * unit_bytes}", f"ds_read_b32 v7, v1 offset:{off1 * unit_bytes}", + "s_waitcnt lgkmcnt(0)"] + for k, r in enumerate(("v4", "v5", "v6", "v7")): + body += L.store(r, k) + return body + + +def model(lane, unit_bytes, off0, off1, roff0, roff1): + lds = {(4 * lane + off0 * unit_bytes) % LDS_BYTES: 0x5000 + lane, + (4 * lane + off1 * unit_bytes) % LDS_BYTES: 0x6000 + lane} # off1 wins a tie, as the later store + rd = lambda off: lds.get((4 * lane + off * unit_bytes) % LDS_BYTES, 0) # noqa: E731 + return [rd(roff0), rd(roff1), rd(off0), rd(off1)] + + +class TestRead2Write2(unittest.TestCase): + def run_case(self, write, read, unit_bytes, off0, off1, roff0, roff1): + mem = L.run(lane_program(write, read, unit_bytes, off0, off1, roff0, roff1), rsrc2=RSRC2_8K) + for i in range(32): + self.assertEqual([L.out(mem, i, k) for k in range(4)], model(i, unit_bytes, off0, off1, roff0, roff1), + f"lane {i}") + + def test_b32_by_hand(self): + # write at +0 and +128 bytes (offset 32 dwords); read2 with the offsets swapped returns [second, first]. + mem = L.run(lane_program("ds_write2_b32", "ds_read2_b32", 4, 0, 32, 32, 0), rsrc2=RSRC2_8K) + for i in range(32): + self.assertEqual([L.out(mem, i, k) for k in range(4)], [0x6000 + i, 0x5000 + i, 0x5000 + i, 0x6000 + i]) + + def test_st64_by_hand(self): + # st64: offsets count 256-byte units; writes at +0 and +256 (offset1:1), read2st64 with (1, 0). + mem = L.run(lane_program("ds_write2st64_b32", "ds_read2st64_b32", 256, 0, 1, 1, 0), rsrc2=RSRC2_8K) + for i in range(32): + self.assertEqual([L.out(mem, i, k) for k in range(4)], [0x6000 + i, 0x5000 + i, 0x5000 + i, 0x6000 + i]) + + def test_equal_offsets_read_the_same_dword_twice(self): + mem = L.run(lane_program("ds_write2_b32", "ds_read2_b32", 4, 0, 32, 32, 32), rsrc2=RSRC2_8K) + for i in range(32): + self.assertEqual([L.out(mem, i, k) for k in range(2)], [0x6000 + i, 0x6000 + i]) + + def test_seeded_offsets(self): + rng = random.Random(0xD1EC7) + for _ in range(8): + a, b = rng.sample(range(0, 255, 32), 2) + ra, rb = rng.choice((a, b)), rng.choice((a, b)) + with self.subTest(kind="b32", off0=a, off1=b, r0=ra, r1=rb): + self.run_case("ds_write2_b32", "ds_read2_b32", 4, a, b, ra, rb) + c, d = rng.sample(range(0, 8), 2) + rc, rd = rng.choice((c, d)), rng.choice((c, d)) + with self.subTest(kind="st64", off0=c, off1=d, r0=rc, r1=rd): + self.run_case("ds_write2st64_b32", "ds_read2st64_b32", 256, c, d, rc, rd) + + +class TestOutsideCompute(unittest.TestCase): + def test_pixel_shader_refuses_read2_and_write2(self): + for line in ("ds_read2_b32 v[0:1], v2 offset1:1", "ds_write2_b32 v0, v1, v2 offset1:1", + "ds_read2st64_b32 v[0:1], v2 offset1:1", "ds_write2st64_b32 v0, v1, v2 offset1:1"): + with self.subTest(line=line), self.assertRaises(rdna2spirv.Unsupported): + support.translate_lines("ps_lds_read2", [line, "s_endpgm"]) if __name__ == "__main__": diff --git a/tests/semantic/test_lds_read_write.py b/tests/semantic/test_lds_read_write.py index aa0fbdf46..904ba264d 100644 --- a/tests/semantic/test_lds_read_write.py +++ b/tests/semantic/test_lds_read_write.py @@ -1,514 +1,175 @@ -"""Semantic interpreter tests for LDS read/write byte offset calculation (ds_read_b32, ds_write_b32). +"""ds_write_b32/b64/b96/b128, ds_read_b32/b64/b96/b128, ds_write_b8/b16 and ds_read_u8/i8/u16/i16 through the translator. -Covers: - * AMD RDNA2 ISA specification for LDS (Local Data Share) data share operations - (AMD RDNA 2 Instruction Set Architecture, Section 9 "Data Share Instructions"): - - ds_read_b32: vdst, vaddr [offset:offset] - Reads 32 bits from LDS at effective byte address: - effective_byte_address = (vaddr + offset) & 0xFFFFFFFF - - ds_write_b32: vaddr, vdata [offset:offset] - Writes 32 bits into LDS at effective byte address: - effective_byte_address = (vaddr + offset) & 0xFFFFFFFF - - Offset field: 16-bit unsigned byte offset in [0, 65535]. Default: 0 if omitted. - - Dword addressing: LDS is structured as 32-bit dwords (4 bytes per dword). - dword_index = (effective_byte_address >> 2) & (lds_dwords - 1) - - Sub-dword alignment: low 2 bits (effective_byte_address & 3) represent intra-dword - byte position; for b32 operations, the dword index truncates these bits. - - 32-bit address wrapping: (vaddr + offset) wraps modulo 2^32. - - LDS size wrapping: dword indices wrap modulo lds_dwords (power-of-two size). - - Active lane execution: LDS writes and reads execute conditionally on the lane's - active mask. Inactive lanes do not modify LDS memory and preserve destination VGPRs. - * SPIR-V translation mapping (tools/rdna2spirv.py): - - In compute shaders (cs) and mesh shaders (ms), LDS operations allocate: - %lds_arr = OpTypeArray %uint lds_dwords - %lds = OpVariable %_ptr_WG_lds Workgroup - - Pointer calculation (lds_ptr): - %s1 = OpIAdd %uint {addr} {byte_off} - %i = OpShiftRightLogical %uint %s1 2 - %m = OpBitwiseAnd %uint %i {lds_dwords - 1} - %p = OpAccessChain %_ptr_WG_uint %lds %m - - ds_read_b32 emits OpLoad %uint %p, followed by OpSelect with %active to preserve - inactive VGPR values. - - ds_write_b32 emits OpStore %p %vdata guarded by OpBranchConditional on %active. - - LDS operations in non-compute stages (ps, vs, gs) raise Unsupported. - * Deterministic semantic interpreter and SPIR-V instruction emulation: - - Simulates LDS memory array, VGPR register files, and lane execution masks. - - Cross-checks RDNA2 ISA offset calculations against plain-Python reference functions - and translated SPIR-V instruction sequences. - - Evaluates address aliasing, independent offsets, unaligned bases, boundary wrapping, - and negative controls (sabotaged shifts, masks, and offsets). +Standard library only; no GPU, no LLVM, no game files. -Run directly: - python -I tests/semantic/test_lds_read_write.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -v +RDNA2 ISA, "Data Share Instructions": the address is vaddr + offset (bytes), the dword at ADDR / 4; the b64/b96/b128 +forms move 2/3/4 consecutive dwords, low first (the dword at ADDR + 4 k goes to / comes from VGPR k of the group). +LDS is `LDS_SIZE` bytes and the address wraps at that size. The 8/16-bit forms address a byte of the dword at ADDR / 4: +byte position (ADDR & 3), halfword (ADDR & 2), zero or sign extended on a read; a write replaces only those bits. + +Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run for 32 lanes in +tests/semantic/spirv_mini_interp.py; every lane works in its own LDS words and stores what it read to an output +buffer. The expected words are written out by hand from the rules above, and a plain-Python LDS model gives the same +words for seeded random data. Until this file, the LDS tests of this name ran a self-built interpreter that never +reached the translator. """ import os import random -import re import sys import unittest -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import lds_run as L # noqa: E402 (also puts tools/ on sys.path) import rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -DEFAULT_LDS_DWORDS = 16384 # 64 KB default LDS capacity in dwords - - -def calc_lds_byte_offset(vaddr, byte_offset=0, lds_dwords=DEFAULT_LDS_DWORDS): - """Reference ISA calculation for LDS read/write effective byte address and dword index. - - Returns: - (effective_byte_address, dword_index, byte_in_dword) - """ - vaddr = vaddr & MASK32 - byte_offset = byte_offset & 0xFFFF # 16-bit unsigned offset in RDNA2 DS instructions - eff_byte = (vaddr + byte_offset) & MASK32 - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - byte_in_dword = eff_byte & 3 - return eff_byte, dword_idx, byte_in_dword - - -def emulate_spirv_lds_ptr(addr_val, byte_off, lds_dwords=DEFAULT_LDS_DWORDS): - """Emulate the exact SPIR-V instruction sequence emitted by rdna2spirv.Gen.lds_ptr. - - Sequence: - %s1 = OpIAdd %uint {addr} {byte_off} - %i = OpShiftRightLogical %uint %s1 2 - %m = OpBitwiseAnd %uint %i {lds_dwords - 1} - Returns: - dword index %m into %lds - """ - s1 = (addr_val + byte_off) & MASK32 - i = (s1 >> 2) & MASK32 - m = i & (lds_dwords - 1) - return m - - -class LdsSemanticInterpreter: - """Deterministic semantic interpreter for RDNA2 LDS read/write instructions. - - Models LDS shared memory storage, VGPR register files, and lane execution state. - """ - - def __init__(self, lds_dwords=DEFAULT_LDS_DWORDS, num_vgprs=256): - self.lds_dwords = lds_dwords - self.lds = [0] * lds_dwords - self.num_vgprs = num_vgprs - self.vgprs = [0] * num_vgprs - self.active_lane = True - - def set_vgpr(self, reg_idx, value): - self.vgprs[reg_idx] = value & MASK32 - - def get_vgpr(self, reg_idx): - return self.vgprs[reg_idx] - - def set_lds_dword(self, dword_idx, value): - self.lds[dword_idx & (self.lds_dwords - 1)] = value & MASK32 - - def get_lds_dword(self, dword_idx): - return self.lds[dword_idx & (self.lds_dwords - 1)] - - def ds_write_b32(self, vaddr_reg, vdata_reg, offset=0): - """Execute ds_write_b32 vaddr, vdata [offset:offset].""" - if not self.active_lane: - return None - vaddr = self.vgprs[vaddr_reg] - vdata = self.vgprs[vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.lds[dword_idx] = vdata & MASK32 - return dword_idx - - def ds_read_b32(self, vdst_reg, vaddr_reg, offset=0): - """Execute ds_read_b32 vdst, vaddr [offset:offset].""" - if not self.active_lane: - # Inactive lane leaves destination VGPR unchanged - return None - vaddr = self.vgprs[vaddr_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.vgprs[vdst_reg] = self.lds[dword_idx] - return dword_idx - - def parse_and_execute(self, instruction_text): - """Parse and execute a single LDS instruction line.""" - line = instruction_text.strip() - if not line or line.startswith(";"): - return None - - # Parse modifiers: e.g. offset:0x20 or offset:32 - offset = 0 - mod_match = re.search(r"\boffset:(\S+)", line) - if mod_match: - offset_str = mod_match.group(1) - offset = int(offset_str, 0) - line = re.sub(r"\boffset:\S+", "", line).strip() - - parts = line.split(None, 1) - op = parts[0] - args = [a.strip() for a in parts[1].split(",")] if len(parts) > 1 else [] - - if op == "ds_write_b32": - # ds_write_b32 vaddr, vdata - vaddr_reg = int(args[0].replace("v", "")) - vdata_reg = int(args[1].replace("v", "")) - return self.ds_write_b32(vaddr_reg, vdata_reg, offset) - elif op == "ds_read_b32": - # ds_read_b32 vdst, vaddr - vdst_reg = int(args[0].replace("v", "")) - vaddr_reg = int(args[1].replace("v", "")) - return self.ds_read_b32(vdst_reg, vaddr_reg, offset) - else: - raise NotImplementedError(f"Unsupported LDS instruction: {op}") - - -class LdsByteOffsetCalculationTests(unittest.TestCase): - """Test effective byte address and dword offset calculations per RDNA2 ISA.""" - - def test_zero_offset_calculation(self): - cases = [ - (0, 0), - (4, 1), - (8, 2), - (64, 16), - (1024, 256), - (65532, 16383), - ] - for vaddr, expected_dword in cases: - with self.subTest(vaddr=vaddr): - eff_byte, dword_idx, byte_in_dword = calc_lds_byte_offset(vaddr, 0) - self.assertEqual(eff_byte, vaddr) - self.assertEqual(dword_idx, expected_dword) - self.assertEqual(byte_in_dword, 0) - - def test_positive_aligned_immediate_offsets(self): - cases = [ - (0, 4, 4, 1), - (0, 16, 16, 4), - (0, 64, 64, 16), - (100, 20, 120, 30), - (0x1000, 0x200, 0x1200, 0x1200 // 4), - (60000, 4000, 64000, 16000), - ] - for vaddr, offset, exp_eff, exp_dword in cases: - with self.subTest(vaddr=vaddr, offset=offset): - eff_byte, dword_idx, byte_in_dword = calc_lds_byte_offset(vaddr, offset) - self.assertEqual(eff_byte, exp_eff) - self.assertEqual(dword_idx, exp_dword) - self.assertEqual(byte_in_dword, 0) - - def test_hexadecimal_offset_parsing_and_calculation(self): - interpreter = LdsSemanticInterpreter() - interpreter.set_vgpr(0, 0x200) - interpreter.set_vgpr(1, 0x12345678) - - # 0x200 + 0x40 = 0x240 -> dword 0x240 // 4 = 0x90 = 144 - dword_idx = interpreter.parse_and_execute("ds_write_b32 v0, v1 offset:0x40") - self.assertEqual(dword_idx, 144) - self.assertEqual(interpreter.get_lds_dword(144), 0x12345678) - - # Read back via hex offset - interpreter.parse_and_execute("ds_read_b32 v2, v0 offset:0x40") - self.assertEqual(interpreter.get_vgpr(2), 0x12345678) - - def test_sub_dword_unaligned_base_address(self): - """Unaligned base addresses are truncated by >> 2 to the containing dword.""" - cases = [ - (1, 0, 1, 0, 1), - (2, 0, 2, 0, 2), - (3, 0, 3, 0, 3), - (5, 0, 5, 1, 1), - (6, 2, 8, 2, 0), - (7, 1, 8, 2, 0), - (7, 5, 12, 3, 0), - ] - for vaddr, offset, exp_eff, exp_dword, exp_byte in cases: - with self.subTest(vaddr=vaddr, offset=offset): - eff_byte, dword_idx, byte_in_dword = calc_lds_byte_offset(vaddr, offset) - self.assertEqual(eff_byte, exp_eff) - self.assertEqual(dword_idx, exp_dword) - self.assertEqual(byte_in_dword, exp_byte) - - def test_32bit_address_wrapping(self): - """(vaddr + offset) wraps modulo 2^32.""" - cases = [ - (0xFFFFFFFC, 4, 0, 0), - (0xFFFFFFFC, 8, 4, 1), - (0xFFFFFFFF, 1, 0, 0), - (0xFFFFFFFF, 5, 4, 1), - (0xFFFFFF00, 0x200, 0x100, 0x40), - ] - for vaddr, offset, exp_eff, exp_dword in cases: - with self.subTest(vaddr=hex(vaddr), offset=offset): - eff_byte, dword_idx, byte_in_dword = calc_lds_byte_offset(vaddr, offset) - self.assertEqual(eff_byte, exp_eff) - self.assertEqual(dword_idx, exp_dword) - - def test_lds_size_wrapping(self): - """Dword indices wrap modulo lds_dwords (power of two).""" - lds_dwords = 1024 # 4 KB LDS capacity = 4096 bytes - cases = [ - (4096, 0, 0), # Exactly 1 wrap - (4096, 16, 4), # Wrap + 4 dwords - (8192, 0, 0), # 2 wraps - (4092, 8, 1), # Cross boundary: 4092 + 8 = 4100 -> byte 4 -> dword 1 - (10000, 0, (10000 >> 2) & 1023), - ] - for vaddr, offset, exp_dword in cases: - with self.subTest(vaddr=vaddr, offset=offset): - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, lds_dwords) - self.assertEqual(dword_idx, exp_dword) - - def test_max_16bit_immediate_offset(self): - """RDNA2 DS offset field allows 16-bit values up to 65535.""" - max_aligned_offset = 65532 # 0xFFFC - eff_byte, dword_idx, byte_in_dword = calc_lds_byte_offset(0, max_aligned_offset) - self.assertEqual(eff_byte, 65532) - self.assertEqual(dword_idx, 65532 // 4) - self.assertEqual(byte_in_dword, 0) - - max_offset = 65535 # 0xFFFF - eff_byte, dword_idx, byte_in_dword = calc_lds_byte_offset(0, max_offset) - self.assertEqual(eff_byte, 65535) - self.assertEqual(dword_idx, 65535 // 4) - self.assertEqual(byte_in_dword, 3) - - def test_randomized_property_equivalence_with_spirv(self): - """Verify 500 pseudo-random test vectors match across ISA and SPIR-V emulation.""" - rng = random.Random(0x1EA105DA) - for _ in range(500): - vaddr = rng.randint(0, MASK32) - offset = rng.randint(0, 0xFFFF) - lds_dwords = 1 << rng.randint(6, 14) # 64 to 16384 dwords - - eff_isa, dword_isa, _ = calc_lds_byte_offset(vaddr, offset, lds_dwords) - dword_spirv = emulate_spirv_lds_ptr(vaddr, offset, lds_dwords) - - self.assertEqual(dword_isa, dword_spirv) - self.assertTrue(0 <= dword_isa < lds_dwords) - - -class LdsSemanticInterpreterExecutionTests(unittest.TestCase): - """Test full execution state transitions for ds_write_b32 and ds_read_b32.""" - - def test_write_read_roundtrip_zero_offset(self): - interp = LdsSemanticInterpreter() - interp.set_vgpr(0, 128) # base byte address 128 -> dword 32 - interp.set_vgpr(1, 0xCAFEBABE) # data to write - - interp.ds_write_b32(vaddr_reg=0, vdata_reg=1, offset=0) - self.assertEqual(interp.get_lds_dword(32), 0xCAFEBABE) - - interp.set_vgpr(2, 0) # destination register cleared - interp.ds_read_b32(vdst_reg=2, vaddr_reg=0, offset=0) - self.assertEqual(interp.get_vgpr(2), 0xCAFEBABE) - - def test_write_read_roundtrip_with_offset(self): - interp = LdsSemanticInterpreter() - interp.set_vgpr(0, 200) # base byte address 200 - interp.set_vgpr(1, 0x11223344) # data - - # Write to 200 + 48 = 248 -> dword 62 - interp.ds_write_b32(vaddr_reg=0, vdata_reg=1, offset=48) - self.assertEqual(interp.get_lds_dword(62), 0x11223344) - - # Read back with same base and offset - interp.ds_read_b32(vdst_reg=3, vaddr_reg=0, offset=48) - self.assertEqual(interp.get_vgpr(3), 0x11223344) - - def test_address_aliasing_via_different_bases_and_offsets(self): - """Different (base, offset) pairs pointing to the same effective address resolve identically.""" - interp = LdsSemanticInterpreter() - # Pair 1: base 100 + offset 28 = 128 (dword 32) - interp.set_vgpr(0, 100) - interp.set_vgpr(1, 0xDEADBEEF) - interp.ds_write_b32(vaddr_reg=0, vdata_reg=1, offset=28) - - # Pair 2: base 128 + offset 0 = 128 (dword 32) - interp.set_vgpr(2, 128) - interp.ds_read_b32(vdst_reg=4, vaddr_reg=2, offset=0) - self.assertEqual(interp.get_vgpr(4), 0xDEADBEEF) - - # Pair 3: base 0 + offset 128 = 128 (dword 32) - interp.set_vgpr(3, 0) - interp.ds_read_b32(vdst_reg=5, vaddr_reg=3, offset=128) - self.assertEqual(interp.get_vgpr(5), 0xDEADBEEF) - - def test_disjoint_offsets_isolation(self): - """Writes to consecutive offsets do not overwrite neighbouring dwords.""" - interp = LdsSemanticInterpreter() - base_reg = 0 - interp.set_vgpr(base_reg, 512) - - data = [0x11111111, 0x22222222, 0x33333333, 0x44444444] - for i, val in enumerate(data): - interp.set_vgpr(1, val) - interp.ds_write_b32(vaddr_reg=base_reg, vdata_reg=1, offset=4 * i) - - # Verify each dword individually - for i, expected in enumerate(data): - target_reg = 10 + i - interp.ds_read_b32(vdst_reg=target_reg, vaddr_reg=base_reg, offset=4 * i) - self.assertEqual(interp.get_vgpr(target_reg), expected) - - def test_inactive_lane_does_not_modify_lds(self): - interp = LdsSemanticInterpreter() - interp.set_vgpr(0, 64) - interp.set_vgpr(1, 0x99999999) - interp.set_lds_dword(16, 0x00000000) - - # Inactive lane executes write - interp.active_lane = False - interp.ds_write_b32(vaddr_reg=0, vdata_reg=1, offset=0) - self.assertEqual(interp.get_lds_dword(16), 0x00000000) - - def test_inactive_lane_does_not_modify_destination_vgpr(self): - interp = LdsSemanticInterpreter() - interp.set_vgpr(0, 64) - interp.set_vgpr(2, 0x55555555) # Existing value - interp.set_lds_dword(16, 0xAAAAAAAA) - - # Inactive lane executes read - interp.active_lane = False - interp.ds_read_b32(vdst_reg=2, vaddr_reg=0, offset=0) - # Value preserved - self.assertEqual(interp.get_vgpr(2), 0x55555555) - - -class TranslatorLdsEmissionTests(unittest.TestCase): - """Verify tools/rdna2spirv.py SPIR-V emission for LDS byte offset calculations.""" - - def test_lds_ptr_emits_iadd_shift_mask_accesschain(self): - g = rdna2spirv.Gen(stage="cs") - ptr = g.lds_ptr("%vaddr", 32) - body = "\n".join(g.body) - - c32 = g.cu(32) - c2 = g.cu(2) - c_mask = g.cu(g.lds_dwords - 1) - - self.assertIn(f"OpIAdd %uint %vaddr {c32}", body) - self.assertIn(f"OpShiftRightLogical %uint", body) - self.assertIn(f"{c2}", body) - self.assertIn(f"OpBitwiseAnd %uint", body) - self.assertIn(f"{c_mask}", body) - self.assertIn(f"OpAccessChain %_ptr_WG_uint %lds", body) - self.assertTrue(ptr.startswith("%t")) - - def test_ds_write_b32_emission_in_compute(self): - g = rdna2spirv.Gen(stage="cs") - # ds_write_b32 vaddr=v1, vdata=v2, offset:16 - g.lds_op("ds_write_b32", [{"k": "vgpr", "r": 1, "n": 1}, {"k": "vgpr", "r": 2, "n": 1}], ["offset:16"]) - body = "\n".join(g.body) - - self.assertTrue(g.uses_lds) - self.assertIn("OpStore", body) - self.assertIn("OpSelectionMerge", body) - self.assertIn("OpBranchConditional", body) - c16 = g.cu(16) - self.assertIn(f"OpIAdd %uint", body) - self.assertIn(c16, body) - - def test_ds_read_b32_emission_in_compute(self): - g = rdna2spirv.Gen(stage="cs") - # ds_read_b32 vdst=v0, vaddr=v1, offset:64 - g.lds_op("ds_read_b32", [{"k": "vgpr", "r": 0, "n": 1}, {"k": "vgpr", "r": 1, "n": 1}], ["offset:64"]) - body = "\n".join(g.body) - - self.assertTrue(g.uses_lds) - self.assertIn("OpLoad %uint", body) - self.assertIn("OpSelect %uint", body) - c64 = g.cu(64) - self.assertIn(c64, body) - - def test_mesh_stage_permits_lds_operations(self): - g = rdna2spirv.Gen(stage="ms") - g.lds_op("ds_write_b32", [{"k": "vgpr", "r": 0, "n": 1}, {"k": "vgpr", "r": 1, "n": 1}], ["offset:0"]) - self.assertTrue(g.uses_lds) - self.assertIn("OpStore", "\n".join(g.body)) - - def test_pixel_and_vertex_stages_reject_lds_operations(self): - for stage in ("ps", "vs"): - with self.subTest(stage=stage): - g = rdna2spirv.Gen(stage=stage) - with self.assertRaises(rdna2spirv.Unsupported): - g.lds_op("ds_read_b32", [{"k": "vgpr", "r": 0, "n": 1}, {"k": "vgpr", "r": 1, "n": 1}], []) - with self.assertRaises(rdna2spirv.Unsupported): - g.lds_op("ds_write_b32", [{"k": "vgpr", "r": 0, "n": 1}, {"k": "vgpr", "r": 1, "n": 1}], []) - - -class SpirvEquivalenceTests(unittest.TestCase): - """Verify bit-exact agreement between emitted SPIR-V pointer math and semantic interpreter.""" - - def test_offset_step_coverage(self): - # Step through offsets 0, 4, 8, ... up to 256 with various base addresses - bases = [0, 4, 12, 100, 1024, 65520, 0xFFFFFFE0] - for base in bases: - for byte_off in range(0, 256, 4): - with self.subTest(base=base, byte_off=byte_off): - _, expected_dword, _ = calc_lds_byte_offset(base, byte_off) - spirv_dword = emulate_spirv_lds_ptr(base, byte_off) - self.assertEqual(expected_dword, spirv_dword) - - -class NegativeControlTests(unittest.TestCase): - """Verify that corruptions in LDS byte offset calculations are strictly caught.""" - - def test_detects_shift_by_three_corruption(self): - """Corrupting shift from >> 2 to >> 3 (treating dwords as 8-byte units) fails.""" - vaddr = 16 - offset = 16 - _, correct_dword, _ = calc_lds_byte_offset(vaddr, offset) - self.assertEqual(correct_dword, 8) - - # Sabotaged calculation: shift right by 3 - corrupted_dword = ((vaddr + offset) >> 3) & (DEFAULT_LDS_DWORDS - 1) - self.assertEqual(corrupted_dword, 4) - self.assertNotEqual(correct_dword, corrupted_dword) - - def test_detects_omitted_byte_offset_corruption(self): - """Ignoring immediate offset fails when offset is non-zero.""" - vaddr = 64 - offset = 64 - _, correct_dword, _ = calc_lds_byte_offset(vaddr, offset) - self.assertEqual(correct_dword, 32) - - # Sabotaged calculation: offset dropped - corrupted_dword = (vaddr >> 2) & (DEFAULT_LDS_DWORDS - 1) - self.assertEqual(corrupted_dword, 16) - self.assertNotEqual(correct_dword, corrupted_dword) - - def test_detects_missing_wrap_mask_corruption(self): - """Omitting the LDS size wrapping mask fails for out-of-bounds addresses.""" - lds_dwords = 1024 - vaddr = 4096 * 2 + 16 # Beyond 1024 dwords - offset = 0 - _, correct_dword, _ = calc_lds_byte_offset(vaddr, offset, lds_dwords) - self.assertEqual(correct_dword, 4) - - # Sabotaged calculation: missing mask - unmasked_dword = (vaddr + offset) >> 2 - self.assertEqual(unmasked_dword, 2052) - self.assertNotEqual(correct_dword, unmasked_dword) - - def test_detects_dword_scaled_offset_corruption(self): - """Treating byte offset as dwords (multiplying by 4) fails.""" - vaddr = 0 - offset = 16 # 16 bytes = 4 dwords - _, correct_dword, _ = calc_lds_byte_offset(vaddr, offset) - self.assertEqual(correct_dword, 4) - - # Sabotaged calculation: treating offset as dwords (adding 16 dwords) - corrupted_dword = (vaddr >> 2) + offset - self.assertEqual(corrupted_dword, 16) - self.assertNotEqual(correct_dword, corrupted_dword) +import support # noqa: E402 + +M32 = L.M32 +LDS_BYTES = 4096 + + +class Model: + """Plain-Python LDS: a dict of dwords by index, addresses wrapping at LDS_BYTES.""" + + def __init__(self): + self.w = {} + + def write32(self, addr, v): + self.w[(addr % LDS_BYTES) // 4] = v & M32 + + def read32(self, addr): + return self.w.get((addr % LDS_BYTES) // 4, 0) + + def write_bits(self, addr, v, bits): + sh = (addr & 3) * 8 + m = ((1 << bits) - 1) << sh + self.w[(addr % LDS_BYTES) // 4] = (self.read32(addr) & ~m & M32) | ((v << sh) & m) + + def read_bits(self, addr, bits, signed): + v = (self.read32(addr) >> ((addr & 3) * 8)) & ((1 << bits) - 1) + if signed and v >> (bits - 1): + v = (v | (M32 << bits)) & M32 + return v + + +class TestDwordForms(unittest.TestCase): + def test_b32_offset_by_hand(self): + # lane i: v1 = 8 i; write 0x1000 + i at v1 + 0x10, read it back at v1 + 0x10 through a different split. + body = ["v_lshlrev_b32_e32 v1, 3, v0", "v_add_nc_u32_e32 v2, 0x1000, v0", + "ds_write_b32 v1, v2 offset:0x10", "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32_e32 v3, 0x10, v1", "ds_read_b32 v4, v3", "s_waitcnt lgkmcnt(0)", + "ds_read_b32 v5, v1 offset:0x10", "s_waitcnt lgkmcnt(0)"] + L.store("v4", 0) + L.store("v5", 1) + mem = L.run(body) + for i in range(32): + self.assertEqual((L.out(mem, i, 0), L.out(mem, i, 1)), (0x1000 + i, 0x1000 + i), f"lane {i}") + + def test_wide_forms_by_hand(self): + # lane i: v1 = 16 i; v[4:7] = four known words; write as b128, read back as b128, b96, b64 and b32 + offsets. + body = ["v_lshlrev_b32_e32 v1, 4, v0", "v_add_nc_u32_e32 v4, 0x100, v0", "v_add_nc_u32_e32 v5, 0x200, v0", + "v_add_nc_u32_e32 v6, 0x300, v0", "v_add_nc_u32_e32 v7, 0x400, v0", + "ds_write_b128 v1, v[4:7]", "s_waitcnt lgkmcnt(0)", + "ds_read_b128 v[8:11], v1", "ds_read_b96 v[12:14], v1", "ds_read_b64 v[16:17], v1 offset:8", + "ds_read_b32 v18, v1 offset:12", "s_waitcnt lgkmcnt(0)"] + for k, r in enumerate(("v8", "v9", "v10", "v11", "v12", "v13", "v14")): + body += L.store(r, k) + body += L.store("v16", 7) + mem = L.run(body) + for i in range(32): + got = [L.out(mem, i, k) for k in range(8)] + want = [0x100 + i, 0x200 + i, 0x300 + i, 0x400 + i, 0x100 + i, 0x200 + i, 0x300 + i, 0x300 + i] + self.assertEqual(got, want, f"lane {i}") + + def test_b64_and_b96_write(self): + body = ["v_lshlrev_b32_e32 v1, 4, v0", "v_add_nc_u32_e32 v4, 0x11, v0", "v_add_nc_u32_e32 v5, 0x22, v0", + "v_add_nc_u32_e32 v6, 0x33, v0", + "ds_write_b64 v1, v[4:5] offset:4", "ds_write_b96 v1, v[4:6] offset:0x800", "s_waitcnt lgkmcnt(0)", + "ds_read_b32 v8, v1 offset:4", "ds_read_b32 v9, v1 offset:8", "ds_read_b32 v10, v1 offset:0x800", + "ds_read_b32 v11, v1 offset:0x808", "s_waitcnt lgkmcnt(0)"] + for k, r in enumerate(("v8", "v9", "v10", "v11")): + body += L.store(r, k) + mem = L.run(body) + for i in range(32): + self.assertEqual([L.out(mem, i, k) for k in range(4)], [0x11 + i, 0x22 + i, 0x11 + i, 0x33 + i], f"lane {i}") + + def test_address_wraps_at_lds_size(self): + # LDS_SIZE is 4 KiB here (and no offset grows it): byte 4096 + 8 is byte 8, with the offset or without. + body = ["v_mov_b32_e32 v1, 0x1008", "v_add_nc_u32_e32 v2, 0x7000, v0", + "v_lshlrev_b32_e32 v3, 6, v0", # lane i uses its own word: 64 i + "v_add_nc_u32_e32 v1, v1, v3", + "ds_write_b32 v1, v2", "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32_e32 v4, 8, v3", "ds_read_b32 v5, v4", "ds_read_b32 v6, v3 offset:8", + "s_waitcnt lgkmcnt(0)"] + L.store("v5", 0) + L.store("v6", 1) + mem = L.run(body) + for i in range(32): + self.assertEqual((L.out(mem, i, 0), L.out(mem, i, 1)), (0x7000 + i, 0x7000 + i), f"lane {i}") + + +class TestSubDwordForms(unittest.TestCase): + WORD = 0x7F80FF01 # bytes 01 FF 80 7F + + def test_reads_by_hand(self): + body = ["v_lshlrev_b32_e32 v1, 3, v0", "v_mov_b32_e32 v2, 0x7f80ff01", + "ds_write_b32 v1, v2 offset:0x40", "s_waitcnt lgkmcnt(0)", + "ds_read_u8 v4, v1 offset:0x41", "ds_read_i8 v5, v1 offset:0x41", "ds_read_i8 v6, v1 offset:0x43", + "ds_read_u16 v7, v1 offset:0x42", "ds_read_i16 v8, v1 offset:0x40", "ds_read_i16 v9, v1 offset:0x42", + "s_waitcnt lgkmcnt(0)"] + for k, r in enumerate(("v4", "v5", "v6", "v7", "v8", "v9")): + body += L.store(r, k) + mem = L.run(body) + want = [0xFF, 0xFFFFFFFF, 0x7F, 0x7F80, 0xFFFFFF01, 0x7F80] + # i16 at byte 0 is 0xFF01 -> sign extended 0xFFFFFF01; at byte 2 is 0x7F80 (positive). + for i in range(32): + self.assertEqual([L.out(mem, i, k) for k in range(6)], want, f"lane {i}") + + def test_writes_replace_only_their_bits(self): + body = ["v_lshlrev_b32_e32 v1, 3, v0", "v_mov_b32_e32 v2, 0x11223344", "v_mov_b32_e32 v3, 0xaabbccdd", + "ds_write_b32 v1, v2", "s_waitcnt lgkmcnt(0)", + "ds_write_b8 v1, v3 offset:1", "ds_write_b16 v1, v3 offset:2", "s_waitcnt lgkmcnt(0)", + "ds_read_b32 v4, v1", "s_waitcnt lgkmcnt(0)", + "ds_write_b8_d16_hi v1, v3", "ds_write_b16_d16_hi v1, v3 offset:4", "s_waitcnt lgkmcnt(0)", + "ds_read_b32 v5, v1", "ds_read_b32 v6, v1 offset:4", "s_waitcnt lgkmcnt(0)"] + for k, r in enumerate(("v4", "v5", "v6")): + body += L.store(r, k) + mem = L.run(body) + # 0x11223344: b8 0xdd at byte 1 -> 0x1122dd44; b16 0xccdd at byte 2 -> 0xccdddd44; + # b8_d16_hi stores bits 23:16 of v3 (0xbb) at byte 0 -> 0xccdddbb... = 0xccddddbb; + # b16_d16_hi stores bits 31:16 of v3 (0xaabb) at byte 4: the neighbouring dword was never written (0) -> 0xaabb. + for i in range(32): + self.assertEqual([L.out(mem, i, k) for k in range(3)], [0xCCDDDD44, 0xCCDDDDBB, 0xAABB], f"lane {i}") + + def test_seeded_against_the_model(self): + rng = random.Random(0x1D5F) + for trial in range(6): + ops = [] + body = ["v_lshlrev_b32_e32 v1, 4, v0"] + model = Model() + base = 0 # the model is lane 0's words; every lane runs the same program on its own + word, wr = rng.getrandbits(32), rng.getrandbits(32) + body += [f"v_mov_b32_e32 v2, {word:#x}", f"v_mov_b32_e32 v3, {wr:#x}", "ds_write_b32 v1, v2", + "s_waitcnt lgkmcnt(0)"] + model.write32(base, word) + for _ in range(4): + kind = rng.choice(("b8", "b16")) + off = rng.randrange(0, 4 if kind == "b8" else 3, 1 if kind == "b8" else 2) + body += [f"ds_write_{kind} v1, v3 offset:{off}", "s_waitcnt lgkmcnt(0)"] + model.write_bits(base + off, wr, 8 if kind == "b8" else 16) + wr = rng.getrandbits(32) + body += [f"v_mov_b32_e32 v3, {wr:#x}"] + for k, (op, bits, sg) in enumerate((("u8", 8, 0), ("i8", 8, 1), ("u16", 16, 0), ("i16", 16, 1))): + off = rng.randrange(0, 4, bits // 8) + body += [f"ds_read_{op} v{4 + k}, v1 offset:{off}", "s_waitcnt lgkmcnt(0)"] + L.store(f"v{4 + k}", k) + ops.append(model.read_bits(base + off, bits, sg)) + body += ["ds_read_b32 v9, v1", "s_waitcnt lgkmcnt(0)"] + L.store("v9", 4) + ops.append(model.read32(base)) + mem = L.run(body) + for i in (0, 5, 31): + self.assertEqual([L.out(mem, i, k) for k in range(5)], ops, f"trial {trial} lane {i}") + + +class TestOutsideCompute(unittest.TestCase): + def test_pixel_shader_refuses_lds(self): + for line in ("ds_read_b32 v1, v0", "ds_write_b32 v0, v1", "ds_add_u32 v0, v1"): + with self.subTest(line=line), self.assertRaises(rdna2spirv.Unsupported): + support.translate_lines("ps_lds_refused", [line, "s_endpgm"]) if __name__ == "__main__": diff --git a/tests/semantic/test_lds_src2.py b/tests/semantic/test_lds_src2.py new file mode 100644 index 000000000..74adc4f9a --- /dev/null +++ b/tests/semantic/test_lds_src2.py @@ -0,0 +1,140 @@ +"""The DS `*_src2_*` forms (`ds_add_src2_u32`, `ds_max_src2_f64`, ...): GFX10.1 encodings the translator refuses. + +These ops read their second operand from LDS instead of a VGPR. They exist in the GFX10.1 encoding the console's +gfx1013 shares, and not on gfx103x: llvm-mc 21.1.8 assembles all 31 forms below for `-mcpu=gfx1013` (DS opcodes +0x80-0x95 and 0xc0-0xd3) and rejects every one of them for `-mcpu=gfx1030` ("instruction not supported on this +GPU"), where it also decodes their bytes as an invalid encoding. They take one 16-bit `offset:`, not the +`offset0:`/`offset1:` pair of the two-address DS ops, which llvm-mc rejects on them ("not a valid operand"). The +address of the LDS operand is derived from that offset; neither the translator nor this file models it, and it has +not been measured on hardware. + +`tools/rdna2spirv.py` has no rule for them and raises `Unsupported` naming the op, so a listing that holds one is +refused rather than translated as something else. `RefusedTests` pins that, with the plain `ds_add_u32` as the +control that the program reaches the translator. `EncodingTests` checks the gfx1013/gfx1030 split and the operand +form with llvm-mc, and is skipped when no llvm-mc with the AMDGPU target is found (LLVM_MC, as for the tools). + +This replaces `test_lds_add_sub_src2_u32.py`, a stand-alone model of `ds_add_src2_u32`/`ds_sub_src2_u32` that never +ran the translator and wrote the ops with `offset0`/`offset1` (TEST-738, found by @Vonsek). + +Standard library only; no GPU and no game files (llvm-mc optional). +""" +import os +import struct +import subprocess +import sys +import tempfile +import unittest + +sys.dont_write_bytecode = True + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.path.insert(0, HERE) +sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) + +import support # noqa: E402 +from mc_command import mc_command # noqa: E402 +from rdna2spirv import Unsupported # noqa: E402 + +SRC2_32 = [ + "ds_add_src2_u32", "ds_sub_src2_u32", "ds_rsub_src2_u32", "ds_inc_src2_u32", "ds_dec_src2_u32", + "ds_min_src2_i32", "ds_max_src2_i32", "ds_min_src2_u32", "ds_max_src2_u32", + "ds_and_src2_b32", "ds_or_src2_b32", "ds_xor_src2_b32", "ds_write_src2_b32", + "ds_min_src2_f32", "ds_max_src2_f32", "ds_add_src2_f32", +] +SRC2_64 = [ + "ds_add_src2_u64", "ds_sub_src2_u64", "ds_rsub_src2_u64", "ds_inc_src2_u64", "ds_dec_src2_u64", + "ds_min_src2_i64", "ds_max_src2_i64", "ds_min_src2_u64", "ds_max_src2_u64", + "ds_and_src2_b64", "ds_or_src2_b64", "ds_xor_src2_b64", "ds_write_src2_b64", + "ds_min_src2_f64", "ds_max_src2_f64", +] +SRC2 = SRC2_32 + SRC2_64 + +# Compute FSSM header: RSRC2 0x8088 (4 user SGPRs, workgroup id x, 128 bytes of LDS), 64x1x1 threads. +CS_FSSM = bytearray(0x148) +struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 64, 1, 1) +CS_FSSM = bytes(CS_FSSM) + + +def translate(op_line): + return support.translate_lines("cs_ds_src2", ["v_mov_b32_e32 v1, 0", op_line, "s_endpgm"], fssm=CS_FSSM) + + +class RefusedTests(unittest.TestCase): + def test_plain_ds_add_reaches_the_translator(self): + self.assertIn("OpEntryPoint", translate("ds_add_u32 v1, v1")) + + def test_every_src2_form_is_refused_by_name(self): + for op in SRC2: + for operands in ("v1", "v1 offset:4", "v1 offset:65535"): + with self.subTest(op=op, operands=operands): + with self.assertRaises(Unsupported) as caught: + translate(f"{op} {operands}") + self.assertIn(op, str(caught.exception)) + + +def _llvm_mc(): + """llvm-mc's argv if it runs and has an AMDGPU target that knows gfx1013, else None.""" + cmd = mc_command() + try: + r = subprocess.run(cmd + ["-triple=amdgcn", "-mcpu=gfx1013", "-show-encoding"], input="s_endpgm\n", + capture_output=True, text=True, timeout=60) + except (OSError, subprocess.TimeoutExpired): + return None + return cmd if r.returncode == 0 and "encoding" in r.stdout else None + + +MC = _llvm_mc() + + +def assemble(cpu, text): + """(returncode, stdout, stderr) of llvm-mc assembling `text` for `cpu`, through a file (no BOM, no pipe).""" + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "in.s") + with open(path, "w", encoding="ascii", newline="\n") as f: + f.write(text) + r = subprocess.run(MC + ["-triple=amdgcn", f"-mcpu={cpu}", "-show-encoding", path], + capture_output=True, text=True, timeout=60) + return r.returncode, r.stdout, r.stderr + + +def encodings(stdout): + """The encoding bytes llvm-mc printed, one list per instruction.""" + out = [] + for line in stdout.splitlines(): + if "encoding: [" in line: + body = line.split("encoding: [", 1)[1].split("]", 1)[0] + out.append([int(b, 16) for b in body.split(",")]) + return out + + +@unittest.skipUnless(MC, "needs llvm-mc with the AMDGPU target (set LLVM_MC)") +class EncodingTests(unittest.TestCase): + def test_gfx1013_has_every_form_with_a_16_bit_offset(self): + for op in SRC2: + with self.subTest(op=op): + rc, out, err = assemble("gfx1013", f"{op} v1 offset:4660\n") + self.assertEqual(rc, 0, err) + (enc,) = encodings(out) + word0 = int.from_bytes(bytes(enc[:4]), "little") + self.assertEqual(word0 >> 26, 0b110110, "not a DS encoding") + opcode = (word0 >> 18) & 0xFF + wide = op in SRC2_64 + self.assertTrue(0xC0 <= opcode <= 0xD3 if wide else 0x80 <= opcode <= 0x95, hex(opcode)) + self.assertEqual(word0 & 0xFFFF, 4660, "offset is not the 16-bit field") + + def test_gfx1030_has_none_of_them(self): + for op in SRC2: + with self.subTest(op=op): + rc, out, err = assemble("gfx1030", f"{op} v1\n") + self.assertNotEqual(rc, 0) + self.assertIn("not supported on this GPU", err) + + def test_offset0_offset1_is_not_their_operand_form(self): + rc, out, err = assemble("gfx1013", "ds_add_src2_u32 v1 offset0:1 offset1:2\n") + self.assertNotEqual(rc, 0) + self.assertIn("not a valid operand", err) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_lds_u16_cross_dword.py b/tests/semantic/test_lds_u16_cross_dword.py new file mode 100644 index 000000000..0e0c8b581 --- /dev/null +++ b/tests/semantic/test_lds_u16_cross_dword.py @@ -0,0 +1,110 @@ +"""16-bit LDS reads and writes at byte 3 of a dword, which cross into the next dword. + +RDNA2 LDS in unaligned mode reads and writes bytes 3 and 4 for a halfword at byte 3: llc -mcpu=gfx1030 +-mattr=+unaligned-access-mode emits a single `ds_read_u16 ... offset:3` / `ds_write_b16 ... offset:3` for an align-1 +i16 LDS access (without that mode it splits the access into two byte accesses). Before this fix the reads extracted +16 bits at bit 24 of one dword (undefined in SPIR-V) and the writes kept only byte 3. Hand-written wave32 compute +listings, translated and run in spirv_mini_interp; no GPU or game files. +""" +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import spirv_mini_interp as si # noqa: E402 +import support # noqa: E402 +from test_cs_shared_memory_limit import out, run_one # noqa: E402 +from test_lds_subword_d16 import FSSM, VSHARP # noqa: E402 + +WORDS = [0x44332211, 0x88776655, 0xCCBBAA99] +LDS = b"".join(w.to_bytes(4, "little") for w in WORDS) +PRE = 0xDEADBEEF +DATA = 0xA1B2C3D4 + + +def init_lds(): + lines = [] + for k, w in enumerate(WORDS): + lines += [f"v_mov_b32_e32 v1, {4 * k}", f"v_mov_b32_e32 v2, {w:#x}", "ds_write_b32 v1, v2"] + return lines + ["s_waitcnt lgkmcnt(0)"] + + +def run(lines, words): + spv = support.translate_lines("cs_lds_u16_cross", lines + out(*range(10, 10 + words)) + ["s_endpgm"], + fssm=FSSM) + memory = {} + si.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0), "%sg_lane": 0}, + push_constants=VSHARP + [0] * 28, memory=memory) + return [memory.get(4 * k) for k in range(words)] + + +def sext16(v): + return (v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF + + +def expected_read(op, addr): + h = int.from_bytes(LDS[addr:addr + 2], "little") + return {"ds_read_u16": h, "ds_read_i16": sext16(h), "ds_read_u16_d16": (PRE & 0xFFFF0000) | h, + "ds_read_u16_d16_hi": (PRE & 0xFFFF) | (h << 16)}[op] + + +def expected_words(addr, half): + b = bytearray(LDS) + b[addr:addr + 2] = half.to_bytes(2, "little") + return [int.from_bytes(b[4 * k:4 * k + 4], "little") for k in range(len(WORDS))] + + +class LdsU16CrossDwordTests(unittest.TestCase): + def test_reads(self): + # byte 3 (vaddr), byte 7 (offset:7), and the non-crossing halfwords around them, unchanged + for op in ("ds_read_u16", "ds_read_i16", "ds_read_u16_d16", "ds_read_u16_d16_hi"): + for vaddr, off in ((3, 0), (0, 7), (4, 3), (1, 0), (2, 0), (5, 0), (0, 6)): + with self.subTest(op=op, vaddr=vaddr, offset=off): + mod = f" offset:{off}" if off else "" + got = run(init_lds() + [f"v_mov_b32_e32 v4, {vaddr}", f"v_mov_b32_e32 v10, {PRE:#x}", + f"{op} v10, v4{mod}", "s_waitcnt lgkmcnt(0)"], 1) + self.assertEqual(got, [expected_read(op, vaddr + off)]) + + def test_writes(self): + for op, half in (("ds_write_b16", DATA & 0xFFFF), ("ds_write_b16_d16_hi", DATA >> 16)): + for vaddr, off in ((3, 0), (0, 7), (4, 3), (1, 0), (2, 0), (6, 0)): + with self.subTest(op=op, vaddr=vaddr, offset=off): + mod = f" offset:{off}" if off else "" + got = run(init_lds() + [f"v_mov_b32_e32 v4, {vaddr}", f"v_mov_b32_e32 v5, {DATA:#x}", + f"{op} v4, v5{mod}", "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v1, 0", + "ds_read_b32 v10, v1", "ds_read_b32 v11, v1 offset:4", + "ds_read_b32 v12, v1 offset:8", "s_waitcnt lgkmcnt(0)"], 3) + self.assertEqual(got, expected_words(vaddr + off, half)) + + def test_chained_crossing_writes_keep_each_others_bytes(self): + # Halfwords at bytes 3, 7 and 11: each one's high byte and the next one's low byte share a dword, so each + # write must keep the other bytes of both dwords it touches. Read back as halfwords and as dwords. + lines = [] + for k in range(4): + lines += [f"v_mov_b32_e32 v1, {4 * k}", "v_mov_b32_e32 v2, 0", "ds_write_b32 v1, v2"] + lines += ["v_mov_b32_e32 v1, 0"] + for k, h in enumerate((0x1141, 0x2242, 0x3343)): + lines += [f"v_mov_b32_e32 v2, {h:#x}", f"ds_write_b16 v1, v2 offset:{4 * k + 3}"] + lines += ["s_waitcnt lgkmcnt(0)", "ds_read_u16 v10, v1 offset:3", "ds_read_u16 v11, v1 offset:7", + "ds_read_u16 v12, v1 offset:11", "ds_read_b32 v13, v1", "ds_read_b32 v14, v1 offset:4", + "ds_read_b32 v15, v1 offset:8", "ds_read_b32 v16, v1 offset:12", "s_waitcnt lgkmcnt(0)"] + self.assertEqual(run(lines, 7), [0x1141, 0x2242, 0x3343, 0x41000000, 0x42000011, 0x43000022, 0x33]) + + def test_crossing_past_the_allocation_reads_zero_and_drops_the_high_byte(self): + # 512 B allocated (offset:1024 elsewhere makes the shader bounds-checked). A halfword at byte 511 has its + # high byte at byte 512: written nowhere (word 0 keeps its sentinel), read as 0. + _, mem = run_one(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0x5e17", "ds_write_b32 v1, v2", + "v_mov_b32_e32 v3, 0x1fc", "v_mov_b32_e32 v2, 0x00ffffff", "ds_write_b32 v3, v2", + "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v4, 0xc3d4", "ds_write_b16 v3, v4 offset:3", + "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v5, 0xdead", "v_mov_b32_e32 v6, 0xdead", + "v_mov_b32_e32 v7, 0xdead", "ds_read_u16 v5, v3 offset:3", "ds_read_b32 v6, v1", + "ds_read_b32 v7, v3", "v_mov_b32_e32 v8, 0xdead", "ds_read_b32 v8, v1 offset:1024", + "s_waitcnt lgkmcnt(0)"] + out(5, 6, 7, 8), 1) + self.assertEqual([mem.get(4 * k) for k in range(4)], [0xD4, 0x5E17, 0xD4FFFFFF, 0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_mem_crash_forms.py b/tests/semantic/test_mem_crash_forms.py new file mode 100644 index 000000000..a809d157f --- /dev/null +++ b/tests/semantic/test_mem_crash_forms.py @@ -0,0 +1,42 @@ +"""Memory-op forms that the assembler accepts and the translator must refuse cleanly, not crash on. + +An image instruction whose result operand is not a VGPR range (`image_sample off, v[1:2], s[16:23], s[24:27] ...`: +llvm-mc takes `off` there) used to raise a KeyError('r') in the translator when it wrote the result. It is a form no +compiler emits (a sample with a dmask and nowhere to put the texels); the translator now raises Unsupported for the +result operand instead. A probe of about 60,000 DS, MUBUF, MTBUF, MIMG, SMEM and FLAT/GLOBAL/SCRATCH operand and +modifier variations (glc, slc, dlc, lds, tfe, d16, a16, unorm, dmask, dim, offset, idxen, offen, addr64, format; as +written and as llvm-mc prints them; pixel and compute stages) found no other crash. Standard library only; no GPU. +""" +import unittest + +import support +import rdna2spirv + +CASES = ( + "image_sample off, v[1:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D slc", + "image_sample off, v[1:2], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D tfe lwe", + "image_sample_c_lz off, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D", + "image_sample_c_lz off, v[1:4], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_CUBE d16", + "image_sample_o off, v[1:4], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_3D tfe", + "image_sample_l off, v[1:4], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY lwe", + "image_load off, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D", + "image_load_mip off, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D", + "image_gather4 off, v[1:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D", + "image_gather4_lz off, v[1:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D", + "image_get_lod off, v[1:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D", +) + + +class ImageResultOperand(unittest.TestCase): + def test_non_vgpr_result_is_unsupported_not_a_crash(self): + for line in CASES: + with self.subTest(line=line): + text = "; mem_crash\n\t" + line + "\n\tv_mov_b32 v50, 1\n\texp mrt0 v50, v50, v50, v50 done vm\n\ts_endpgm\n" + try: + support.translate_listing("ps_mem_crash", text.encode("utf-8")) + except rdna2spirv.Unsupported: + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_mesh_cull_store.py b/tests/semantic/test_mesh_cull_store.py new file mode 100644 index 000000000..872d69e55 --- /dev/null +++ b/tests/semantic/test_mesh_cull_store.py @@ -0,0 +1,95 @@ +"""SHADER-575: a mesh shader's CullPrimitiveEXT is written as a constant on each side of a branch. + +llvmpipe (Mesa 25.2.8, LLVM 20) aborts compiling the wave64-emulated mesh epilogue when the per-primitive cull bool is +stored as a computed value ("Cannot emit physreg copy instruction"), and Mesa 26.3.1 drew no primitives for the same +shaders. Storing %true or %false behind a branch on the same bool means the same on every driver and compiles there. + +The program is runtime/test/shaders/ms_tri.asm, the mesh GPU test (128 threads, 64/64 outputs, triangles), translated +natively and with --wave64-emulate. Standard library only; the spirv-val check needs SPIRV-Tools. +""" +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import support # noqa: E402 (path set above) +import rdna2spirv # noqa: E402 + +MS_TRI = os.path.join(support.ROOT, "runtime", "test", "shaders", "ms_tri.asm") + + +def _dxbc(chunks): + """A DXBC container with the given (fourcc, payload) parts.""" + hdr = 32 + 4 * len(chunks) + offsets, body = [], bytearray() + for tag, payload in chunks: + offsets.append(hdr + len(body)) + body += tag + struct.pack(" S0 (borrow) + s_subb_u32 D = S0 - S1 - SCC (mod 2^32), SCC = 1 if S1 + SCC > S0 (borrow) +The operands are SGPRs, 32-bit literals or inline constants (-16..64); the carry-in is made with s_cmp_eq_u32. + +Each case translates a hand-written pixel shader with tools/rdna2spirv.py (support.translate_lines), runs it +(support.mrt0_words) and compares the destination and SCC with a plain-Python reference and with hand-written words. +test_carry_chain.py already runs the 64-bit add/subtract chains and the vector forms; this file covers the operand +forms and the SCC in/out of the scalar ones. Until this file, the test of this name ran a self-built interpreter and +never called the translator. +""" +import os +import random +import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from typing import List, Optional, Tuple, Union -# ============================================================================== -# RDNA2 SALU Architectural Constants -# ============================================================================== +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import support # noqa: E402 -MASK_U32: int = 0xFFFF_FFFF -MODULO_U32: int = 0x1_0000_0000 -SIGN_BIT_U32: int = 0x8000_0000 -MAX_U32: int = 0xFFFF_FFFF -NUM_SGPRS: int = 256 +M32 = 0xFFFFFFFF -# ============================================================================== -# Reference Mathematical Oracles for s_add_co_u32 & s_sub_co_u32 -# ============================================================================== - -def oracle_s_add_co_u32(src0: int, src1: int) -> Tuple[int, int]: - """Reference mathematical oracle for RDNA2 s_add_co_u32 / s_add_u32. - - Computes 32-bit unsigned addition: - D = (S0 + S1) mod 2^32 - SCC = 1 if (S0 + S1 >= 2^32) else 0 (Carry Out) - """ - s0 = src0 & MASK_U32 - s1 = src1 & MASK_U32 - raw_sum = s0 + s1 - res = raw_sum & MASK_U32 - carry = 1 if raw_sum >= MODULO_U32 else 0 - return res, carry - - -def oracle_s_sub_co_u32(src0: int, src1: int) -> Tuple[int, int]: - """Reference mathematical oracle for RDNA2 s_sub_co_u32 / s_sub_u32. - - Computes 32-bit unsigned subtraction: - D = (S0 - S1) mod 2^32 - SCC = 1 if (S0 < S1) else 0 (Borrow Out) - """ - s0 = src0 & MASK_U32 - s1 = src1 & MASK_U32 - raw_diff = s0 - s1 - res = raw_diff & MASK_U32 - borrow = 1 if s0 < s1 else 0 - return res, borrow - - -# ============================================================================== -# Architectural Hardware Model -# ============================================================================== - -@dataclass -class ScalarModel: - """Architectural model representing the RDNA2 Scalar ALU (SALU) register file and status.""" - sgprs: List[int] = field(default_factory=lambda: [0] * NUM_SGPRS) - scc: int = 0 - - def read_sgpr(self, index: int) -> int: - if not (0 <= index < NUM_SGPRS): - raise IndexError(f"SGPR index {index} out of bounds [0, {NUM_SGPRS - 1}]") - return self.sgprs[index] & MASK_U32 - - def write_sgpr(self, index: int, val: int) -> None: - if not (0 <= index < NUM_SGPRS): - raise IndexError(f"SGPR index {index} out of bounds [0, {NUM_SGPRS - 1}]") - self.sgprs[index] = val & MASK_U32 - - def set_scc(self, val: int) -> None: - self.scc = 1 if val else 0 - - -# ============================================================================== -# Phase 1 Unit Tests: Reference Oracles & Mathematical Properties -# ============================================================================== - -class TestReferenceOracleAddCoU32(unittest.TestCase): - """Exhaustive mathematical verification for oracle_s_add_co_u32.""" - - def test_zero_identities(self) -> None: - self.assertEqual(oracle_s_add_co_u32(0, 0), (0, 0)) - self.assertEqual(oracle_s_add_co_u32(42, 0), (42, 0)) - self.assertEqual(oracle_s_add_co_u32(0, 1337), (1337, 0)) - self.assertEqual(oracle_s_add_co_u32(MAX_U32, 0), (MAX_U32, 0)) - - def test_commutativity(self) -> None: - vectors = [ - (0, 1), - (100, 200), - (MAX_U32, 1), - (0x8000_0000, 0x8000_0000), - (0x1234_5678, 0x9ABC_DEF0), - ] - for a, b in vectors: - with self.subTest(a=a, b=b): - res_ab, c_ab = oracle_s_add_co_u32(a, b) - res_ba, c_ba = oracle_s_add_co_u32(b, a) - self.assertEqual(res_ab, res_ba) - self.assertEqual(c_ab, c_ba) - - def test_boundary_carry_transitions(self) -> None: - # Just before carry - self.assertEqual(oracle_s_add_co_u32(MAX_U32 - 1, 1), (MAX_U32, 0)) - self.assertEqual(oracle_s_add_co_u32(0x7FFF_FFFF, 0x8000_0000), (MAX_U32, 0)) - # Exact carry threshold - self.assertEqual(oracle_s_add_co_u32(MAX_U32, 1), (0, 1)) - self.assertEqual(oracle_s_add_co_u32(1, MAX_U32), (0, 1)) - self.assertEqual(oracle_s_add_co_u32(MAX_U32, 2), (1, 1)) - # Both high operands - self.assertEqual(oracle_s_add_co_u32(MAX_U32, MAX_U32), (MAX_U32 - 1, 1)) - self.assertEqual(oracle_s_add_co_u32(0x8000_0000, 0x8000_0000), (0, 1)) - self.assertEqual(oracle_s_add_co_u32(0x8000_0000, 0x8000_0001), (1, 1)) - - -class TestReferenceOracleSubCoU32(unittest.TestCase): - """Exhaustive mathematical verification for oracle_s_sub_co_u32.""" - - def test_zero_identities(self) -> None: - self.assertEqual(oracle_s_sub_co_u32(0, 0), (0, 0)) - self.assertEqual(oracle_s_sub_co_u32(42, 0), (42, 0)) - self.assertEqual(oracle_s_sub_co_u32(MAX_U32, 0), (MAX_U32, 0)) - - def test_self_subtraction(self) -> None: - values = [0, 1, 42, 0x7FFF_FFFF, 0x8000_0000, MAX_U32] - for v in values: - with self.subTest(v=v): - res, borrow = oracle_s_sub_co_u32(v, v) - self.assertEqual(res, 0) - self.assertEqual(borrow, 0) - - def test_boundary_borrow_transitions(self) -> None: - # Minimal borrow cases: 0 - 1 - self.assertEqual(oracle_s_sub_co_u32(0, 1), (MAX_U32, 1)) - self.assertEqual(oracle_s_sub_co_u32(0, MAX_U32), (1, 1)) - self.assertEqual(oracle_s_sub_co_u32(1, 2), (MAX_U32, 1)) - # Borrow from 0x8000_0000 - self.assertEqual(oracle_s_sub_co_u32(0x8000_0000, 1), (0x7FFF_FFFF, 0)) - self.assertEqual(oracle_s_sub_co_u32(0x7FFF_FFFF, 0x8000_0000), (MAX_U32, 1)) - # High boundary subtractions without borrow - self.assertEqual(oracle_s_sub_co_u32(MAX_U32, 1), (MAX_U32 - 1, 0)) - self.assertEqual(oracle_s_sub_co_u32(MAX_U32, MAX_U32), (0, 0)) - - def test_add_sub_inverse_relation(self) -> None: - pairs = [ - (10, 5), - (5, 10), - (0, 100), - (MAX_U32, 12345), - (0x8000_0000, 0x1234_5678), - ] - for a, b in pairs: - with self.subTest(a=a, b=b): - diff, _ = oracle_s_sub_co_u32(a, b) - recovered, _ = oracle_s_add_co_u32(diff, b) - self.assertEqual(recovered, a & MASK_U32) - - -class TestArchitecturalModel(unittest.TestCase): - """Verification of the ScalarModel register file and SCC status representation.""" - - def test_sgpr_read_write(self) -> None: - model = ScalarModel() - self.assertEqual(model.read_sgpr(0), 0) - model.write_sgpr(0, 0xDEAD_BEEF) - self.assertEqual(model.read_sgpr(0), 0xDEAD_BEEF) - # Verify 32-bit truncation - model.write_sgpr(1, 0x1_1234_5678) - self.assertEqual(model.read_sgpr(1), 0x1234_5678) - - def test_sgpr_bounds(self) -> None: - model = ScalarModel() - with self.assertRaises(IndexError): - model.read_sgpr(-1) - with self.assertRaises(IndexError): - model.read_sgpr(NUM_SGPRS) - with self.assertRaises(IndexError): - model.write_sgpr(NUM_SGPRS + 10, 1) - - def test_scc_flag(self) -> None: - model = ScalarModel() - self.assertEqual(model.scc, 0) - model.set_scc(1) - self.assertEqual(model.scc, 1) - model.set_scc(0) - self.assertEqual(model.scc, 0) - model.set_scc(42) - self.assertEqual(model.scc, 1) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class SOPOpcode(Enum): - """SOP2 scalar ALU opcodes.""" - S_ADD_CO_U32 = "s_add_co_u32" - S_SUB_CO_U32 = "s_sub_co_u32" - S_ADD_U32 = "s_add_u32" - S_SUB_U32 = "s_sub_u32" - - -@dataclass(frozen=True) -class SGPROperand: - """Represents a 32-bit Scalar General-Purpose Register operand.""" - index: int - - def __post_init__(self) -> None: - if not (0 <= self.index < NUM_SGPRS): - raise ValueError(f"SGPR index {self.index} out of range [0, {NUM_SGPRS - 1}]") - - @property - def name(self) -> str: - return f"s{self.index}" - - -@dataclass(frozen=True) -class LiteralU32: - """Represents an arbitrary 32-bit literal constant in the instruction stream.""" - value: int - - def __post_init__(self) -> None: - if not (0 <= self.value <= MAX_U32): - raise ValueError(f"Literal constant 0x{self.value:X} out of range [0, 0x{MAX_U32:X}]") - - @property - def name(self) -> str: - return f"0x{self.value:08X}" - - -@dataclass(frozen=True) -class InlineConstant: - """Represents an inline integer constant (-16..64) encoded directly in operand field.""" - value: int - - def __post_init__(self) -> None: - if not (-16 <= self.value <= 64): - raise ValueError(f"Inline integer constant {self.value} out of range [-16, 64]") - - @property - def name(self) -> str: - return f"{self.value}" - - -SOP2Operand = Union[SGPROperand, LiteralU32, InlineConstant] - - -@dataclass(frozen=True) -class SAddSubCoU32Instruction: - """Symbolic AST node representing a 32-bit SALU add/sub with carry instruction.""" - opcode: SOPOpcode - dst: SGPROperand - src0: SOP2Operand - src1: SOP2Operand - - def __post_init__(self) -> None: - if not isinstance(self.dst, SGPROperand): - raise TypeError(f"Destination operand must be SGPROperand, got {type(self.dst).__name__}") - if self.opcode not in ( - SOPOpcode.S_ADD_CO_U32, - SOPOpcode.S_SUB_CO_U32, - SOPOpcode.S_ADD_U32, - SOPOpcode.S_SUB_U32, - ): - raise ValueError(f"Invalid opcode for SAddSubCoU32Instruction: {self.opcode}") - - # Hardware constraint: at most one 32-bit literal constant allowed in SOP2 encoding - literal_count = sum(1 for src in (self.src0, self.src1) if isinstance(src, LiteralU32)) - if literal_count > 1: - raise ValueError("SOP2 instructions cannot encode more than one 32-bit literal constant") - - def disassemble(self) -> str: - return f"{self.opcode.value} {self.dst.name}, {self.src0.name}, {self.src1.name}" - - -class TestSymbolicAST(unittest.TestCase): - """Verification of symbolic AST node typing, bounds, constraints, and disassembly.""" - - def test_sgpr_operand_valid(self) -> None: - op = SGPROperand(0) - self.assertEqual(op.name, "s0") - op_max = SGPROperand(NUM_SGPRS - 1) - self.assertEqual(op_max.name, f"s{NUM_SGPRS - 1}") - - def test_sgpr_operand_out_of_range(self) -> None: - with self.assertRaises(ValueError): - SGPROperand(-1) - with self.assertRaises(ValueError): - SGPROperand(NUM_SGPRS) - - def test_literal_u32_valid(self) -> None: - lit = LiteralU32(0x1234_5678) - self.assertEqual(lit.name, "0x12345678") - self.assertEqual(lit.value, 0x1234_5678) - - def test_literal_u32_out_of_range(self) -> None: - with self.assertRaises(ValueError): - LiteralU32(-1) - with self.assertRaises(ValueError): - LiteralU32(0x1_0000_0000) - - def test_inline_constant_valid(self) -> None: - for val in (-16, 0, 1, 64): - c = InlineConstant(val) - self.assertEqual(c.name, str(val)) - self.assertEqual(c.value, val) - - def test_inline_constant_out_of_range(self) -> None: - with self.assertRaises(ValueError): - InlineConstant(-17) - with self.assertRaises(ValueError): - InlineConstant(65) - - def test_instruction_disassembly(self) -> None: - instr_add = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(1), - src1=SGPROperand(2), - ) - self.assertEqual(instr_add.disassemble(), "s_add_co_u32 s0, s1, s2") - - instr_sub = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(4), - src0=SGPROperand(5), - src1=LiteralU32(0xDEADBEEF), - ) - self.assertEqual(instr_sub.disassemble(), "s_sub_co_u32 s4, s5, 0xDEADBEEF") - - instr_inline = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_U32, - dst=SGPROperand(10), - src0=SGPROperand(11), - src1=InlineConstant(1), - ) - self.assertEqual(instr_inline.disassemble(), "s_add_u32 s10, s11, 1") - - def test_instruction_invalid_dst(self) -> None: - with self.assertRaises(TypeError): - SAddSubCoU32Instruction( # type: ignore[arg-type] - opcode=SOPOpcode.S_ADD_CO_U32, - dst=LiteralU32(42), # type: ignore[arg-type] - src0=SGPROperand(0), - src1=SGPROperand(1), - ) - - def test_instruction_multiple_literals_rejected(self) -> None: - with self.assertRaises(ValueError): - SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(0), - src0=LiteralU32(0x100), - src1=LiteralU32(0x200), - ) - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 SALU instructions.""" - - def resolve_operand(self, op: SOP2Operand, state: ScalarModel) -> int: - if isinstance(op, SGPROperand): - return state.read_sgpr(op.index) - elif isinstance(op, LiteralU32): - return op.value & MASK_U32 - elif isinstance(op, InlineConstant): - return op.value & MASK_U32 - else: - raise TypeError(f"Unsupported operand type: {type(op).__name__}") - - def step(self, instr: SAddSubCoU32Instruction, state: ScalarModel) -> Tuple[int, int]: - # Atomic read phase - s0_val = self.resolve_operand(instr.src0, state) - s1_val = self.resolve_operand(instr.src1, state) - - # Computation phase - if instr.opcode in (SOPOpcode.S_ADD_CO_U32, SOPOpcode.S_ADD_U32): - res, cc = oracle_s_add_co_u32(s0_val, s1_val) - elif instr.opcode in (SOPOpcode.S_SUB_CO_U32, SOPOpcode.S_SUB_U32): - res, cc = oracle_s_sub_co_u32(s0_val, s1_val) - else: - raise ValueError(f"Unsupported opcode: {instr.opcode}") - - # Update condition code and destination SGPR - state.set_scc(cc) - state.write_sgpr(instr.dst.index, res) - return res, cc - - def run_program( - self, program: List[SAddSubCoU32Instruction], state: ScalarModel - ) -> List[Tuple[int, int]]: - results: List[Tuple[int, int]] = [] - for instr in program: - results.append(self.step(instr, state)) - return results - - -class TestScalarInterpreter(unittest.TestCase): - """Verification of deterministic scalar instruction interpretation.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarModel() - - def test_scalar_add_execution(self) -> None: - self.state.write_sgpr(1, 100) - self.state.write_sgpr(2, 250) - instr = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(1), - src1=SGPROperand(2), - ) - res, cc = self.interp.step(instr, self.state) - self.assertEqual(res, 350) - self.assertEqual(cc, 0) - self.assertEqual(self.state.read_sgpr(0), 350) - self.assertEqual(self.state.scc, 0) - - def test_scalar_add_carry_generation(self) -> None: - self.state.write_sgpr(1, MAX_U32) - self.state.write_sgpr(2, 5) - instr = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_U32, - dst=SGPROperand(0), - src0=SGPROperand(1), - src1=SGPROperand(2), - ) - res, cc = self.interp.step(instr, self.state) - self.assertEqual(res, 4) - self.assertEqual(cc, 1) - self.assertEqual(self.state.read_sgpr(0), 4) - self.assertEqual(self.state.scc, 1) - - def test_scalar_sub_execution(self) -> None: - self.state.write_sgpr(1, 500) - self.state.write_sgpr(2, 200) - instr = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(3), - src0=SGPROperand(1), - src1=SGPROperand(2), - ) - res, cc = self.interp.step(instr, self.state) - self.assertEqual(res, 300) - self.assertEqual(cc, 0) - self.assertEqual(self.state.read_sgpr(3), 300) - self.assertEqual(self.state.scc, 0) - - def test_scalar_sub_borrow_generation(self) -> None: - self.state.write_sgpr(1, 10) - self.state.write_sgpr(2, 20) - instr = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_U32, - dst=SGPROperand(3), - src0=SGPROperand(1), - src1=SGPROperand(2), - ) - res, cc = self.interp.step(instr, self.state) - self.assertEqual(res, MAX_U32 - 9) - self.assertEqual(cc, 1) - self.assertEqual(self.state.read_sgpr(3), MAX_U32 - 9) - self.assertEqual(self.state.scc, 1) - - def test_scalar_with_literal_and_inline_constants(self) -> None: - self.state.write_sgpr(1, 0x1000) - # Add literal - instr_lit = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(2), - src0=SGPROperand(1), - src1=LiteralU32(0x2000), - ) - res_lit, cc_lit = self.interp.step(instr_lit, self.state) - self.assertEqual(res_lit, 0x3000) - self.assertEqual(cc_lit, 0) - - # Sub inline constant - instr_inline = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(3), - src0=SGPROperand(2), - src1=InlineConstant(1), - ) - res_in, cc_in = self.interp.step(instr_inline, self.state) - self.assertEqual(res_in, 0x2FFF) - self.assertEqual(cc_in, 0) - - def test_scalar_program_chain(self) -> None: - # Program: s0 = 0; s0 += 10; s0 += 20; s0 -= 5 - program = [ - SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(0), - src1=InlineConstant(10), - ), - SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(0), - src1=InlineConstant(20), - ), - SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(0), - src1=InlineConstant(5), - ), - ] - results = self.interp.run_program(program, self.state) - self.assertEqual(results, [(10, 0), (30, 0), (25, 0)]) - self.assertEqual(self.state.read_sgpr(0), 25) - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and 32/64-Bit EXEC Masking -# ============================================================================== - -@dataclass -class SIMDMultiLaneState: - """Architectural state for a wavefront (Wave32 or Wave64) with shared SALU.""" - wave_size: int = 32 - exec_mask: int = field(init=False) - scalar_model: ScalarModel = field(default_factory=ScalarModel) - vgprs: List[List[int]] = field(init=False) - - def __post_init__(self) -> None: - if self.wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got {self.wave_size}") - self.exec_mask = (1 << self.wave_size) - 1 - self.vgprs = [[0] * 256 for _ in range(self.wave_size)] - - def is_lane_active(self, lane: int) -> bool: - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size - 1}]") - return bool(self.exec_mask & (1 << lane)) - - def read_lane_vgpr(self, lane: int, reg_idx: int) -> int: - return self.vgprs[lane][reg_idx] & MASK_U32 - - def write_lane_vgpr(self, lane: int, reg_idx: int, val: int) -> None: - self.vgprs[lane][reg_idx] = val & MASK_U32 - - -class SIMDExecutionEngine: - """Execution engine testing interaction between shared SALU and divergent SIMD lanes.""" - - def __init__(self) -> None: - self.scalar_interp = ScalarInterpreter() - - def step_salu( - self, instr: SAddSubCoU32Instruction, simd_state: SIMDMultiLaneState - ) -> Tuple[int, int]: - """SALU execution is uniform and unconditional across the wavefront.""" - return self.scalar_interp.step(instr, simd_state.scalar_model) - - def vector_add_scalar_broadcast( - self, dst_vgpr: int, src_vgpr: int, src_sgpr: int, simd_state: SIMDMultiLaneState - ) -> List[Optional[int]]: - """Simulate VALU lane operation consuming scalar SGPR result under EXEC mask.""" - scalar_val = simd_state.scalar_model.read_sgpr(src_sgpr) - results: List[Optional[int]] = [None] * simd_state.wave_size - for lane in range(simd_state.wave_size): - if simd_state.is_lane_active(lane): - lane_val = simd_state.read_lane_vgpr(lane, src_vgpr) - out_val, _ = oracle_s_add_co_u32(lane_val, scalar_val) - simd_state.write_lane_vgpr(lane, dst_vgpr, out_val) - results[lane] = out_val - return results - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Verification of SIMD multi-lane divergence and 32/64-bit EXEC masking interaction.""" - - def setUp(self) -> None: - self.engine = SIMDExecutionEngine() - - def test_salu_unconditional_execution_with_zero_exec_mask(self) -> None: - # SALU must execute even when EXEC is 0 (all lanes masked off) - for wave_size in (32, 64): - with self.subTest(wave_size=wave_size): - state = SIMDMultiLaneState(wave_size=wave_size) - state.exec_mask = 0 # Inactive wavefront - state.scalar_model.write_sgpr(1, 100) - state.scalar_model.write_sgpr(2, 200) - - instr = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(1), - src1=SGPROperand(2), - ) - res, cc = self.engine.step_salu(instr, state) - self.assertEqual(res, 300) - self.assertEqual(cc, 0) - # Ensure SGPR and SCC were updated unconditionally - self.assertEqual(state.scalar_model.read_sgpr(0), 300) - self.assertEqual(state.scalar_model.scc, 0) - - def test_salu_broadcast_to_wave32(self) -> None: - state = SIMDMultiLaneState(wave_size=32) - # Set divergent EXEC: only even lanes active (0x55555555) - state.exec_mask = 0x5555_5555 - # Set up lane VGPRs: v0[lane] = lane * 10 - for lane in range(32): - state.write_lane_vgpr(lane, 0, lane * 10) - state.write_lane_vgpr(lane, 1, 0xEEEE_EEEE) # sentinel initial dst - - # Compute scalar offset via SALU: s0 = 1000 + 24 - state.scalar_model.write_sgpr(2, 1000) - salu_instr = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_U32, - dst=SGPROperand(0), - src0=SGPROperand(2), - src1=InlineConstant(24), - ) - self.engine.step_salu(salu_instr, state) - self.assertEqual(state.scalar_model.read_sgpr(0), 1024) - - # Broadcast s0 to active lanes: v1[lane] = v0[lane] + s0 - results = self.engine.vector_add_scalar_broadcast(dst_vgpr=1, src_vgpr=0, src_sgpr=0, simd_state=state) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(results[lane], (lane * 10) + 1024) - self.assertEqual(state.read_lane_vgpr(lane, 1), (lane * 10) + 1024) - else: - self.assertIsNone(results[lane]) - # Inactive lane must remain untouched - self.assertEqual(state.read_lane_vgpr(lane, 1), 0xEEEE_EEEE) - - def test_salu_broadcast_to_wave64(self) -> None: - state = SIMDMultiLaneState(wave_size=64) - # Lower 32 lanes active, upper 32 lanes masked out - state.exec_mask = 0x0000_0000_FFFF_FFFF - - for lane in range(64): - state.write_lane_vgpr(lane, 5, 500) - state.write_lane_vgpr(lane, 6, 0x1111_1111) - - # SALU computes scalar reduction/subtraction: s4 = 100 - 30 - state.scalar_model.write_sgpr(10, 100) - salu_sub = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(4), - src0=SGPROperand(10), - src1=InlineConstant(30), - ) - self.engine.step_salu(salu_sub, state) - self.assertEqual(state.scalar_model.read_sgpr(4), 70) - self.assertEqual(state.scalar_model.scc, 0) - - # Vector lanes consume s4 - results = self.engine.vector_add_scalar_broadcast(dst_vgpr=6, src_vgpr=5, src_sgpr=4, simd_state=state) - for lane in range(64): - if lane < 32: - self.assertEqual(results[lane], 570) - self.assertEqual(state.read_lane_vgpr(lane, 6), 570) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.read_lane_vgpr(lane, 6), 0x1111_1111) - - -# ============================================================================== -# Register Aliasing and In-Place Operand Preservation -# ============================================================================== - -class TestRegisterAliasingAndPreservation(unittest.TestCase): - """Verification of atomic read-before-write semantics and register aliasing.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarModel() - - def test_in_place_accumulator_dst_equals_src0(self) -> None: - # s0 = s0 + s1 - self.state.write_sgpr(0, 100) - self.state.write_sgpr(1, 50) - instr_add = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(0), - src1=SGPROperand(1), - ) - res, cc = self.interp.step(instr_add, self.state) - self.assertEqual(res, 150) - self.assertEqual(cc, 0) - self.assertEqual(self.state.read_sgpr(0), 150) - self.assertEqual(self.state.read_sgpr(1), 50) # src1 preserved - - # s0 = s0 - s1 - instr_sub = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(0), - src1=SGPROperand(1), - ) - res_sub, cc_sub = self.interp.step(instr_sub, self.state) - self.assertEqual(res_sub, 100) - self.assertEqual(cc_sub, 0) - self.assertEqual(self.state.read_sgpr(0), 100) - - def test_in_place_accumulator_dst_equals_src1(self) -> None: - # s1 = s0 + s1 - self.state.write_sgpr(0, 200) - self.state.write_sgpr(1, 80) - instr_add = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(1), - src0=SGPROperand(0), - src1=SGPROperand(1), - ) - res, cc = self.interp.step(instr_add, self.state) - self.assertEqual(res, 280) - self.assertEqual(self.state.read_sgpr(1), 280) - self.assertEqual(self.state.read_sgpr(0), 200) # src0 preserved - - # s1 = s0 - s1 => 200 - 280 = -80 (mod 2^32), borrow = 1 - instr_sub = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(1), - src0=SGPROperand(0), - src1=SGPROperand(1), - ) - res_sub, cc_sub = self.interp.step(instr_sub, self.state) - self.assertEqual(res_sub, (200 - 280) & MASK_U32) - self.assertEqual(cc_sub, 1) - self.assertEqual(self.state.read_sgpr(1), (200 - 280) & MASK_U32) - self.assertEqual(self.state.read_sgpr(0), 200) - - def test_self_referential_source_aliasing(self) -> None: - # s2 = s0 + s0 (doubling) - self.state.write_sgpr(0, 0x4000_0000) - instr_double = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(2), - src0=SGPROperand(0), - src1=SGPROperand(0), - ) - res_double, cc_double = self.interp.step(instr_double, self.state) - self.assertEqual(res_double, 0x8000_0000) - self.assertEqual(cc_double, 0) - self.assertEqual(self.state.read_sgpr(0), 0x4000_0000) # Preserved - - # Doubling with carry: 0x8000_0000 + 0x8000_0000 = 0, carry = 1 - self.state.write_sgpr(0, 0x8000_0000) - res_double2, cc_double2 = self.interp.step(instr_double, self.state) - self.assertEqual(res_double2, 0) - self.assertEqual(cc_double2, 1) - - # s3 = s0 - s0 (always 0, borrow = 0) - instr_zero = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(3), - src0=SGPROperand(0), - src1=SGPROperand(0), - ) - res_zero, cc_zero = self.interp.step(instr_zero, self.state) - self.assertEqual(res_zero, 0) - self.assertEqual(cc_zero, 0) - self.assertEqual(self.state.read_sgpr(3), 0) - - def test_tri_aliasing_dst_src0_src1(self) -> None: - # In-place self-addition: s0 = s0 + s0 - self.state.write_sgpr(0, 0x0000_0008) - instr_tri_add = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(0), - src1=SGPROperand(0), - ) - res, cc = self.interp.step(instr_tri_add, self.state) - self.assertEqual(res, 16) - self.assertEqual(cc, 0) - self.assertEqual(self.state.read_sgpr(0), 16) - - # In-place self-subtraction: s0 = s0 - s0 - instr_tri_sub = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_SUB_CO_U32, - dst=SGPROperand(0), - src0=SGPROperand(0), - src1=SGPROperand(0), - ) - res_sub, cc_sub = self.interp.step(instr_tri_sub, self.state) - self.assertEqual(res_sub, 0) - self.assertEqual(cc_sub, 0) - self.assertEqual(self.state.read_sgpr(0), 0) - - def test_unreferenced_register_preservation(self) -> None: - # Populate all SGPRs with distinct sentinel values - for i in range(NUM_SGPRS): - self.state.write_sgpr(i, (i * 0x0101_0101) & MASK_U32) - - # Perform operation modifying only s42 - instr = SAddSubCoU32Instruction( - opcode=SOPOpcode.S_ADD_CO_U32, - dst=SGPROperand(42), - src0=SGPROperand(10), - src1=InlineConstant(7), - ) - self.interp.step(instr, self.state) - - # Verify all registers except s42 maintain exact original value - for i in range(NUM_SGPRS): - if i == 42: - expected = ((10 * 0x0101_0101) + 7) & MASK_U32 - self.assertEqual(self.state.read_sgpr(i), expected) - else: - self.assertEqual(self.state.read_sgpr(i), (i * 0x0101_0101) & MASK_U32) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass(frozen=True) -class SALUStatusFlags: - """Architectural and algebraic condition flags for SALU operations.""" - carry_or_borrow: int - zero: bool - sign: bool - signed_overflow: bool - parity_even: bool - - -def evaluate_salu_flags( - opcode: SOPOpcode, src0: int, src1: int, result: int, cc: int -) -> SALUStatusFlags: - """Evaluate architectural condition codes and algebraic status flags.""" - s0 = src0 & MASK_U32 - s1 = src1 & MASK_U32 - res = result & MASK_U32 - - zero = (res == 0) - sign = bool(res & SIGN_BIT_U32) - - is_add = opcode in (SOPOpcode.S_ADD_CO_U32, SOPOpcode.S_ADD_U32) - if is_add: - # Addition overflow occurs when operands have same sign, but result has different sign - signed_overflow = bool((~(s0 ^ s1) & (s0 ^ res)) & SIGN_BIT_U32) +def ref(op, s0, s1, scc): + if op == "s_add_u32": + t = s0 + s1 + elif op == "s_addc_u32": + t = s0 + s1 + scc + elif op == "s_sub_u32": + t = s0 - s1 else: - # Subtraction overflow occurs when operands have different signs, and result sign differs from s0 - signed_overflow = bool(((s0 ^ s1) & (s0 ^ res)) & SIGN_BIT_U32) - - parity_even = (bin(res).count("1") % 2 == 0) - - return SALUStatusFlags( - carry_or_borrow=cc, - zero=zero, - sign=sign, - signed_overflow=signed_overflow, - parity_even=parity_even, - ) - - -def simulate_64bit_add(a64: int, b64: int) -> Tuple[int, int]: - """Simulate 64-bit addition via s_add_co_u32 (lo) and s_addc_u32 (hi with SCC carry).""" - a_lo, a_hi = a64 & MASK_U32, (a64 >> 32) & MASK_U32 - b_lo, b_hi = b64 & MASK_U32, (b64 >> 32) & MASK_U32 - - # Step 1: low dword s_add_co_u32 - r_lo, carry = oracle_s_add_co_u32(a_lo, b_lo) - - # Step 2: high dword s_addc_u32 (add with carry) - r_hi_temp = a_hi + b_hi + carry - r_hi = r_hi_temp & MASK_U32 - carry_out = 1 if r_hi_temp >= MODULO_U32 else 0 - - res64 = (r_hi << 32) | r_lo - return res64, carry_out - - -def simulate_64bit_sub(a64: int, b64: int) -> Tuple[int, int]: - """Simulate 64-bit subtraction via s_sub_co_u32 (lo) and s_subb_u32 (hi with SCC borrow).""" - a_lo, a_hi = a64 & MASK_U32, (a64 >> 32) & MASK_U32 - b_lo, b_hi = b64 & MASK_U32, (b64 >> 32) & MASK_U32 - - # Step 1: low dword s_sub_co_u32 - r_lo, borrow = oracle_s_sub_co_u32(a_lo, b_lo) - - # Step 2: high dword s_subb_u32 (sub with borrow) - diff_hi = a_hi - b_hi - borrow - r_hi = diff_hi & MASK_U32 - borrow_out = 1 if a_hi < (b_hi + borrow) else 0 - - res64 = (r_hi << 32) | r_lo - return res64, borrow_out - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Verification of condition codes, signed overflow, and multi-word ripple carry/borrow.""" - - def test_signed_overflow_vs_unsigned_carry_addition(self) -> None: - # Case 1: 0x7FFF_FFFF + 1 = 0x8000_0000 (signed overflow, no carry) - res, cc = oracle_s_add_co_u32(0x7FFF_FFFF, 1) - flags = evaluate_salu_flags(SOPOpcode.S_ADD_CO_U32, 0x7FFF_FFFF, 1, res, cc) - self.assertEqual(res, 0x8000_0000) - self.assertEqual(cc, 0) - self.assertTrue(flags.signed_overflow) - self.assertTrue(flags.sign) - self.assertFalse(flags.zero) - - # Case 2: 0xFFFF_FFFF + 1 = 0 (carry, no signed overflow) - res2, cc2 = oracle_s_add_co_u32(MAX_U32, 1) - flags2 = evaluate_salu_flags(SOPOpcode.S_ADD_CO_U32, MAX_U32, 1, res2, cc2) - self.assertEqual(res2, 0) - self.assertEqual(cc2, 1) - self.assertFalse(flags2.signed_overflow) - self.assertFalse(flags2.sign) - self.assertTrue(flags2.zero) - - # Case 3: 0x8000_0000 + 0x8000_0000 = 0 (both signed overflow AND carry) - res3, cc3 = oracle_s_add_co_u32(0x8000_0000, 0x8000_0000) - flags3 = evaluate_salu_flags(SOPOpcode.S_ADD_CO_U32, 0x8000_0000, 0x8000_0000, res3, cc3) - self.assertEqual(res3, 0) - self.assertEqual(cc3, 1) - self.assertTrue(flags3.signed_overflow) - self.assertTrue(flags3.zero) - - def test_signed_overflow_vs_unsigned_borrow_subtraction(self) -> None: - # Case 1: 0x8000_0000 - 1 = 0x7FFF_FFFF (signed overflow, no borrow) - res, cc = oracle_s_sub_co_u32(0x8000_0000, 1) - flags = evaluate_salu_flags(SOPOpcode.S_SUB_CO_U32, 0x8000_0000, 1, res, cc) - self.assertEqual(res, 0x7FFF_FFFF) - self.assertEqual(cc, 0) - self.assertTrue(flags.signed_overflow) - self.assertFalse(flags.sign) - - # Case 2: 0 - 1 = 0xFFFF_FFFF (borrow, no signed overflow) - res2, cc2 = oracle_s_sub_co_u32(0, 1) - flags2 = evaluate_salu_flags(SOPOpcode.S_SUB_CO_U32, 0, 1, res2, cc2) - self.assertEqual(res2, MAX_U32) - self.assertEqual(cc2, 1) - self.assertFalse(flags2.signed_overflow) - self.assertTrue(flags2.sign) - - # Case 3: 0x7FFF_FFFF - 0x8000_0000 = 0xFFFF_FFFF (both signed overflow AND borrow) - res3, cc3 = oracle_s_sub_co_u32(0x7FFF_FFFF, 0x8000_0000) - flags3 = evaluate_salu_flags(SOPOpcode.S_SUB_CO_U32, 0x7FFF_FFFF, 0x8000_0000, res3, cc3) - self.assertEqual(res3, MAX_U32) - self.assertEqual(cc3, 1) - self.assertTrue(flags3.signed_overflow) - self.assertTrue(flags3.sign) - - def test_64bit_ripple_carry_multi_word_addition(self) -> None: - test_pairs = [ - (0x0000_0000_FFFF_FFFF, 0x0000_0000_0000_0001), - (0x1234_5678_FFFF_FFFF, 0x0000_0000_0000_0001), - (0x7FFF_FFFF_FFFF_FFFF, 0x0000_0000_0000_0001), - (0xFFFF_FFFF_FFFF_FFFF, 0x0000_0000_0000_0001), - (0xAAAA_AAAA_5555_5555, 0x5555_5555_AAAA_AAAA), - ] - for a, b in test_pairs: - with self.subTest(a=hex(a), b=hex(b)): - res64, carry_out = simulate_64bit_add(a, b) - expected_sum = (a + b) & 0xFFFF_FFFF_FFFF_FFFF - expected_carry = 1 if (a + b) >= (1 << 64) else 0 - self.assertEqual(res64, expected_sum) - self.assertEqual(carry_out, expected_carry) - - def test_64bit_ripple_borrow_multi_word_subtraction(self) -> None: - test_pairs = [ - (0x0000_0001_0000_0000, 0x0000_0000_0000_0001), - (0x1000_0000_0000_0000, 0x0000_0000_0000_0001), - (0x0000_0000_0000_0000, 0x0000_0000_0000_0001), - (0x1234_5678_0000_0000, 0x0000_0000_0000_0005), - (0xFFFF_FFFF_FFFF_FFFF, 0x0000_0000_0000_0001), - ] - for a, b in test_pairs: - with self.subTest(a=hex(a), b=hex(b)): - res64, borrow_out = simulate_64bit_sub(a, b) - expected_diff = (a - b) & 0xFFFF_FFFF_FFFF_FFFF - expected_borrow = 1 if a < b else 0 - self.assertEqual(res64, expected_diff) - self.assertEqual(borrow_out, expected_borrow) - - -# ============================================================================== -# IEEE 754 Binary32 Boundary Extremes and Subnormal Bitfield Manipulation -# ============================================================================== - -F32_POS_ZERO: int = 0x0000_0000 -F32_NEG_ZERO: int = 0x8000_0000 -F32_POS_ONE: int = 0x3F80_0000 -F32_NEG_ONE: int = 0xBF80_0000 -F32_POS_INF: int = 0x7F80_0000 -F32_NEG_INF: int = 0xFF80_0000 -F32_CANONICAL_QNAN: int = 0x7FC0_0000 -F32_SNAN: int = 0x7F80_0001 -F32_MIN_SUBNORMAL: int = 0x0000_0001 -F32_MAX_SUBNORMAL: int = 0x007F_FFFF -F32_MIN_NORMAL: int = 0x0080_0000 -F32_MAX_NORMAL: int = 0x7F7F_FFFF - -F32_EXP_MASK: int = 0x7F80_0000 -F32_FRAC_MASK: int = 0x007F_FFFF -F32_QNAN_BIT: int = 0x0040_0000 - - -def u32_to_f32(bits: int) -> float: - """Reinterpret unsigned 32-bit integer as IEEE 754 single-precision float.""" - return struct.unpack(" int: - """Reinterpret IEEE 754 single-precision float as unsigned 32-bit integer.""" - return struct.unpack(" bool: - """Check if bit pattern corresponds to IEEE 754 single-precision NaN.""" - return ((bits & F32_EXP_MASK) == F32_EXP_MASK) and ((bits & F32_FRAC_MASK) != 0) - - -def is_f32_subnormal(bits: int) -> bool: - """Check if bit pattern corresponds to IEEE 754 single-precision subnormal.""" - return ((bits & F32_EXP_MASK) == 0) and ((bits & F32_FRAC_MASK) != 0) - - -def is_f32_inf(bits: int) -> bool: - """Check if bit pattern corresponds to IEEE 754 single-precision infinity.""" - return ((bits & F32_EXP_MASK) == F32_EXP_MASK) and ((bits & F32_FRAC_MASK) == 0) - - -class TestIEEE754BitwiseBoundariesAndSubnormals(unittest.TestCase): - """Verification of SALU integer arithmetic on IEEE 754 bit representations.""" - - def test_subnormal_to_normal_boundary_transition(self) -> None: - # Incrementing largest subnormal gives smallest positive normal - res, carry = oracle_s_add_co_u32(F32_MAX_SUBNORMAL, 1) - self.assertEqual(res, F32_MIN_NORMAL) - self.assertEqual(carry, 0) - self.assertTrue(is_f32_subnormal(F32_MAX_SUBNORMAL)) - self.assertFalse(is_f32_subnormal(res)) - self.assertAlmostEqual(u32_to_f32(res), 1.1754943508222875e-38, places=44) - - # Decrementing smallest normal gives largest subnormal - res_sub, borrow = oracle_s_sub_co_u32(F32_MIN_NORMAL, 1) - self.assertEqual(res_sub, F32_MAX_SUBNORMAL) - self.assertEqual(borrow, 0) - self.assertTrue(is_f32_subnormal(res_sub)) - - def test_subnormal_zero_boundary(self) -> None: - # Smallest subnormal - 1 gives +0.0 - res, borrow = oracle_s_sub_co_u32(F32_MIN_SUBNORMAL, 1) - self.assertEqual(res, F32_POS_ZERO) - self.assertEqual(borrow, 0) - - # +0.0 - Smallest subnormal gives underflow/borrow - res_under, borrow_under = oracle_s_sub_co_u32(F32_POS_ZERO, F32_MIN_SUBNORMAL) - self.assertEqual(res_under, MAX_U32) - self.assertEqual(borrow_under, 1) - - def test_biased_exponent_scaling_arithmetic(self) -> None: - # 1.0f is 0x3F80_0000. Adding 1 to the exponent field (0x0080_0000) produces 2.0f (0x4000_0000) - exp_step = 0x0080_0000 - res_double, carry = oracle_s_add_co_u32(F32_POS_ONE, exp_step) - self.assertEqual(res_double, 0x4000_0000) - self.assertEqual(carry, 0) - self.assertEqual(u32_to_f32(res_double), 2.0) - - # Decrementing exponent field of 1.0f produces 0.5f (0x3F00_0000) - res_half, borrow = oracle_s_sub_co_u32(F32_POS_ONE, exp_step) - self.assertEqual(res_half, 0x3F00_0000) - self.assertEqual(borrow, 0) - self.assertEqual(u32_to_f32(res_half), 0.5) - - def test_nan_payload_arithmetic(self) -> None: - # Modifying NaN payload via SALU addition - res, carry = oracle_s_add_co_u32(F32_CANONICAL_QNAN, 0x0000_0007) - self.assertEqual(res, 0x7FC0_0007) - self.assertEqual(carry, 0) - self.assertTrue(is_f32_nan(res)) - # Ensure quiet bit is preserved - self.assertTrue(bool(res & F32_QNAN_BIT)) - - def test_infinity_boundary_transitions(self) -> None: - # Adding 1 to +infinity turns it into a signaling NaN pattern (0x7F800001) - res_snan, carry = oracle_s_add_co_u32(F32_POS_INF, 1) - self.assertEqual(res_snan, F32_SNAN) - self.assertEqual(carry, 0) - self.assertTrue(is_f32_nan(res_snan)) - - # Subtracting 1 from +infinity turns it into max normal float (0x7F7FFFFF) - res_max_norm, borrow = oracle_s_sub_co_u32(F32_POS_INF, 1) - self.assertEqual(res_max_norm, F32_MAX_NORMAL) - self.assertEqual(borrow, 0) - self.assertFalse(is_f32_nan(res_max_norm)) - self.assertFalse(is_f32_inf(res_max_norm)) - - -# ============================================================================== -# Negative Controls, Syntax Rejection, and Parser Validation -# ============================================================================== - -def parse_salu_operand(token: str) -> SOP2Operand: - """Parse a single assembly operand token into a typed SOP2Operand.""" - token = token.strip() - if not token: - raise ValueError("Operand token cannot be empty") - - if token.startswith("s") and token[1:].isdigit(): - idx = int(token[1:]) - return SGPROperand(idx) - - if token.startswith("0x") or token.startswith("0X"): - val = int(token, 16) - return LiteralU32(val) - - try: - val = int(token) - if -16 <= val <= 64: - return InlineConstant(val) - return LiteralU32(val) - except ValueError: - pass - - raise ValueError(f"Unrecognized operand syntax: '{token}'") - - -def parse_salu_instruction(asm_line: str) -> SAddSubCoU32Instruction: - """Parse a SALU assembly instruction string into an AST node.""" - line = asm_line.strip() - if not line: - raise ValueError("Empty instruction line") - - parts = line.split(None, 1) - if len(parts) != 2: - raise ValueError(f"Invalid instruction format: '{asm_line}'") - - op_str, args_str = parts - try: - opcode = SOPOpcode(op_str) - except ValueError: - raise ValueError(f"Unsupported opcode: '{op_str}'") - - arg_tokens = [arg.strip() for arg in args_str.split(",")] - if len(arg_tokens) != 3: - raise ValueError(f"Expected 3 comma-separated operands, got {len(arg_tokens)}: '{args_str}'") - - dst_token = arg_tokens[0] - if not (dst_token.startswith("s") and dst_token[1:].isdigit()): - raise TypeError(f"Destination must be an SGPR, got '{dst_token}'") - dst = SGPROperand(int(dst_token[1:])) - - src0 = parse_salu_operand(arg_tokens[1]) - src1 = parse_salu_operand(arg_tokens[2]) - - return SAddSubCoU32Instruction(opcode=opcode, dst=dst, src0=src0, src1=src1) - - -class TestNegativeControlsAndSyntaxRejection(unittest.TestCase): - """Verification that invalid opcodes, illegal syntax, and malformed inputs are rejected.""" - - def test_parser_valid_instructions(self) -> None: - instr1 = parse_salu_instruction("s_add_co_u32 s0, s1, s2") - self.assertEqual(instr1.opcode, SOPOpcode.S_ADD_CO_U32) - self.assertEqual(instr1.dst, SGPROperand(0)) - self.assertEqual(instr1.src0, SGPROperand(1)) - self.assertEqual(instr1.src1, SGPROperand(2)) - - instr2 = parse_salu_instruction("s_sub_co_u32 s10, s20, 0x1234") - self.assertEqual(instr2.opcode, SOPOpcode.S_SUB_CO_U32) - self.assertEqual(instr2.dst, SGPROperand(10)) - self.assertEqual(instr2.src0, SGPROperand(20)) - self.assertEqual(instr2.src1, LiteralU32(0x1234)) - - instr3 = parse_salu_instruction("s_add_u32 s5, s6, 1") - self.assertEqual(instr3.src1, InlineConstant(1)) - - def test_parser_unsupported_opcodes(self) -> None: - invalid_opcodes = [ - "v_add_f32 s0, s1, s2", - "s_mul_u32 s0, s1, s2", - "s_invalid_op s0, s1, s2", - "s_add_co_i32 s0, s1, s2", - ] - for line in invalid_opcodes: - with self.subTest(line=line): - with self.assertRaises(ValueError): - parse_salu_instruction(line) - - def test_parser_invalid_operands_and_vgpr_rejection(self) -> None: - # SALU cannot take VGPRs as operands - with self.assertRaises(ValueError): - parse_salu_instruction("s_add_co_u32 s0, v1, s2") - with self.assertRaises(ValueError): - parse_salu_instruction("s_add_co_u32 s0, s1, v2") - # SALU destination cannot be VGPR - with self.assertRaises(TypeError): - parse_salu_instruction("s_add_co_u32 v0, s1, s2") - # SALU destination cannot be literal or inline constant - with self.assertRaises(TypeError): - parse_salu_instruction("s_add_co_u32 42, s1, s2") - - def test_parser_sgpr_out_of_bounds(self) -> None: - with self.assertRaises(ValueError): - parse_salu_instruction("s_add_co_u32 s256, s0, s1") - with self.assertRaises(ValueError): - parse_salu_instruction("s_add_co_u32 s0, s500, s1") - - def test_parser_multiple_literals_rejection(self) -> None: - with self.assertRaises(ValueError): - parse_salu_instruction("s_add_co_u32 s0, 0x1000, 0x2000") - - -# ============================================================================== -# Mutation Detection Engine -# ============================================================================== - -class TestMutationDetectionEngine(unittest.TestCase): - """Mutation testing: verifies that all intentional mutants are killed by test vectors.""" - - def test_mutant_add_sub_killed(self) -> None: - # Mutant: replaces addition with subtraction - def mutant(s0: int, s1: int) -> Tuple[int, int]: - return (s0 - s1) & MASK_U32, 1 if s0 < s1 else 0 - - # Vector (10, 5) detects mutant - gold = oracle_s_add_co_u32(10, 5) - mut = mutant(10, 5) - self.assertNotEqual(gold, mut) - - def test_mutant_add_xor_killed(self) -> None: - # Mutant: replaces addition with bitwise XOR - def mutant(s0: int, s1: int) -> Tuple[int, int]: - return (s0 ^ s1) & MASK_U32, 0 - - gold = oracle_s_add_co_u32(1, 1) - mut = mutant(1, 1) - self.assertNotEqual(gold, mut) - - def test_mutant_add_no_carry_killed(self) -> None: - # Mutant: carry is always 0 - def mutant(s0: int, s1: int) -> Tuple[int, int]: - return (s0 + s1) & MASK_U32, 0 - - gold = oracle_s_add_co_u32(MAX_U32, 1) - mut = mutant(MAX_U32, 1) - self.assertNotEqual(gold, mut) - - def test_mutant_add_off_by_one_carry_killed(self) -> None: - # Mutant: carry only when > 0x1_0000_0000 (misses exact threshold) - def mutant(s0: int, s1: int) -> Tuple[int, int]: - raw = s0 + s1 - return raw & MASK_U32, 1 if raw > MODULO_U32 else 0 - - gold = oracle_s_add_co_u32(MAX_U32, 1) - mut = mutant(MAX_U32, 1) - self.assertEqual(gold[1], 1) - self.assertEqual(mut[1], 0) - self.assertNotEqual(gold, mut) - - def test_mutant_sub_no_borrow_killed(self) -> None: - # Mutant: borrow is always 0 - def mutant(s0: int, s1: int) -> Tuple[int, int]: - return (s0 - s1) & MASK_U32, 0 - - gold = oracle_s_sub_co_u32(0, 1) - mut = mutant(0, 1) - self.assertNotEqual(gold, mut) - - def test_mutant_sub_strict_underflow_borrow_killed(self) -> None: - # Mutant: borrow when s0 <= s1 (incorrectly flags borrow on equality) - def mutant(s0: int, s1: int) -> Tuple[int, int]: - return (s0 - s1) & MASK_U32, 1 if s0 <= s1 else 0 - - gold = oracle_s_sub_co_u32(5, 5) - mut = mutant(5, 5) - self.assertEqual(gold[1], 0) - self.assertEqual(mut[1], 1) - self.assertNotEqual(gold, mut) - - def test_mutant_truncate_31bit_killed(self) -> None: - # Mutant: truncates to 31 bits instead of 32 bits - def mutant(s0: int, s1: int) -> Tuple[int, int]: - return (s0 + s1) & 0x7FFF_FFFF, 0 - - gold = oracle_s_add_co_u32(0x8000_0000, 0) - mut = mutant(0x8000_0000, 0) - self.assertNotEqual(gold, mut) + t = s0 - s1 - scc + return t & M32, int(t >= 1 << 32) if "add" in op else int(t < 0) + + +def operand(kind, reg, v): + """(setup lines, operand text) giving S0/S1 the value v.""" + if kind == "sgpr": + return [f"s_mov_b32 s{reg}, {v:#x}"], f"s{reg}" + return [], f"{v:#x}" # a literal (or inline constant when it is one) + + +def run(op, s0, s1, scc, k0="sgpr", k1="sgpr"): + a, t0 = operand(k0, 10, s0) + b, t1 = operand(k1, 11, s1) + lines = a + b + ["s_mov_b32 s12, 0", "s_cmp_eq_u32 s12, %d" % (0 if scc else 1), # SCC = scc + f"{op} s13, {t0}, {t1}", "s_cselect_b32 s14, 1, 0", "v_mov_b32_e32 v0, s13", "v_mov_b32_e32 v1, s14", + "exp mrt0 v0, v1, v0, v0 done vm", "s_endpgm"] + return tuple(support.mrt0_words(support.translate_lines("ps_salu_add_sub_co", lines))[:2]) + + +OPS = ("s_add_u32", "s_addc_u32", "s_sub_u32", "s_subb_u32") +EDGE = (0, 1, 2, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFE, 0xFFFFFFFF) + + +class TestByHand(unittest.TestCase): + def test_words(self): + # (op, S0, S1, SCC in) -> (D, SCC out), written out from the formulas above. + for case, want in ( + (("s_add_u32", 0xFFFFFFFF, 1, 0), (0, 1)), (("s_add_u32", 0x7FFFFFFF, 1, 1), (0x80000000, 0)), + (("s_addc_u32", 0xFFFFFFFF, 0, 1), (0, 1)), (("s_addc_u32", 0xFFFFFFFF, 0, 0), (0xFFFFFFFF, 0)), + (("s_addc_u32", 5, 6, 1), (12, 0)), (("s_addc_u32", 0xFFFFFFFF, 0xFFFFFFFF, 1), (0xFFFFFFFF, 1)), + (("s_sub_u32", 0, 1, 0), (0xFFFFFFFF, 1)), (("s_sub_u32", 5, 5, 1), (0, 0)), + (("s_subb_u32", 5, 5, 1), (0xFFFFFFFF, 1)), (("s_subb_u32", 5, 5, 0), (0, 0)), + (("s_subb_u32", 0, 0xFFFFFFFF, 1), (0, 1)), (("s_subb_u32", 0x80000000, 1, 1), (0x7FFFFFFE, 0)), + ): + with self.subTest(case=case): + self.assertEqual(ref(*case), want) + self.assertEqual(run(*case), want) + + +class TestForms(unittest.TestCase): + def test_operand_forms(self): + for op in OPS: + for k0, k1 in (("sgpr", "sgpr"), ("literal", "sgpr"), ("sgpr", "literal")): + for s0, s1, scc in ((0xFFFFFFFF, 1, 1), (0x80000000, 0x80000000, 0), (7, 0x12345678, 1), (3, 3, 0)): + with self.subTest(op=op, forms=(k0, k1), s0=hex(s0), s1=hex(s1), scc=scc): + self.assertEqual(run(op, s0, s1, scc, k0, k1), ref(op, s0, s1, scc)) + + def test_inline_constants(self): + for op in OPS: + for s0, s1 in ((64, 1), (0, 16), (63, 64), (1, 0)): + with self.subTest(op=op, s0=s0, s1=s1): + self.assertEqual(run(op, s0, s1, 1, "literal", "literal"), ref(op, s0, s1, 1)) + + def test_seeded(self): + rng = random.Random(0x5CC) + for _ in range(30): + op, scc = rng.choice(OPS), rng.getrandbits(1) + s0, s1 = rng.choice((rng.getrandbits(32),) + EDGE), rng.choice((rng.getrandbits(32),) + EDGE) + with self.subTest(op=op, s0=hex(s0), s1=hex(s1), scc=scc): + self.assertEqual(run(op, s0, s1, scc), ref(op, s0, s1, scc)) if __name__ == "__main__": diff --git a/tests/semantic/test_salu_and_saveexec_b64.py b/tests/semantic/test_salu_and_saveexec_b64.py index f25399382..3d3fcbe00 100644 --- a/tests/semantic/test_salu_and_saveexec_b64.py +++ b/tests/semantic/test_salu_and_saveexec_b64.py @@ -1,1646 +1,33 @@ -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 s_and_saveexec_b64. +"""s_and_saveexec_b64 through the translator, on every lane of a wave64. -Models the AMD RDNA2 / GFX10 / GCN Scalar Arithmetic Logic Unit (SALU) architectural -specification for: - s_and_saveexec_b64 sdst, ssrc0 +RDNA2 ISA, SOP1: + s_and_saveexec_b64: D = EXEC; EXEC = S0 & EXEC; SCC = (EXEC != 0). -Architectural Semantics (SOP1 Encoding): - 1. Latched State Execution: - sdst[63:0] = EXEC[63:0] - EXEC[63:0] = ssrc0[63:0] & EXEC[63:0] - SCC = (EXEC[63:0] != 0) ? 1 : 0 - 2. Operand Rules: - - sdst: 64-bit destination SGPR pair (or EXEC/VCC special registers). - Receives the previous (saved) value of the 64-bit EXEC mask. - - ssrc0: 64-bit source operand (SGPR pair, literal constant, inline constant, or special register). - - EXEC: 64-bit execution mask governing vector wavefront lane activation in Wave64 mode. - - SCC: Scalar Condition Code bit in the STATUS register, updated to 1 if any lane in the - new EXEC mask is non-zero, and 0 if all lanes are inactive. - 3. Register File Constraints: - - 64-bit SGPR pairs must be 64-bit aligned (even SGPR index: s[0:1], s[2:3], etc.). - - Destination latches previous EXEC before any potential register overwrite. - -Standard library Python only; zero third-party dependencies; zero game data. -Python 3.9+ compatible (from __future__ import annotations). +Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in +tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an +SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of +this name ran a self-built interpreter and never called the translator. """ -from __future__ import annotations - -import enum import os -import re import sys import unittest -from dataclasses import dataclass, field -from typing import Optional, Union -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF -SIGN_BIT64: int = 0x8000000000000000 -ALL_LANES_64: int = 0xFFFFFFFFFFFFFFFF -NO_LANES_64: int = 0x0000000000000000 -EVEN_LANES_64: int = 0x5555555555555555 -ODD_LANES_64: int = 0xAAAAAAAAAAAAAAAA -LOW32_LANES_64: int = 0x00000000FFFFFFFF -HIGH32_LANES_64: int = 0xFFFFFFFF00000000 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import saveexec_run # noqa: E402 (support puts tools/ on sys.path) -# IEEE 754 architectural bit patterns for vector-to-scalar comparison masks -POS_ZERO_F32: int = 0x00000000 -NEG_ZERO_F32: int = 0x80000000 -POS_INF_F32: int = 0x7F800000 -NEG_INF_F32: int = 0xFF800000 -QNAN_F32: int = 0x7FC00000 -SNAN_F32: int = 0x7F800001 -SUBNORM_MIN_F32: int = 0x00000001 -SUBNORM_MAX_F32: int = 0x007FFFFF -POS_ZERO_F64: int = 0x0000000000000000 -NEG_ZERO_F64: int = 0x8000000000000000 -POS_INF_F64: int = 0x7FF0000000000000 -NEG_INF_F64: int = 0xFFF0000000000000 -QNAN_F64: int = 0x7FF8000000000000 -SNAN_F64: int = 0x7FF0000000000001 -SUBNORM_MIN_F64: int = 0x0000000000000001 +class Saveexec(unittest.TestCase): + def test_and_by_hand(self): + # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = S0 & EXEC written out by hand. + lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) + s0, e = lanes(0, 32), lanes(16, 48) + want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), + "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), + "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["and"] + self.assertEqual(saveexec_run.model("and", s0, e), (want, e, 1)) - -def is_nan_f32_bits(bits: int) -> bool: - """Return True if 32-bit word represents an IEEE 754 single-precision NaN.""" - return ((bits & 0x7F800000) == 0x7F800000) and ((bits & 0x007FFFFF) != 0) - - -def is_subnormal_f32_bits(bits: int) -> bool: - """Return True if 32-bit word represents an IEEE 754 single-precision subnormal.""" - return ((bits & 0x7F800000) == 0) and ((bits & 0x007FFFFF) != 0) - - -def is_inf_f32_bits(bits: int) -> bool: - """Return True if 32-bit word represents positive or negative infinity.""" - return ((bits & 0x7F800000) == 0x7F800000) and ((bits & 0x007FFFFF) == 0) - - -def generate_f32_cmp_mask(lanes_f32: list[int], condition: str) -> int: - """Simulate vector float comparison across 64 lanes producing a 64-bit mask.""" - mask = 0 - for lane, val in enumerate(lanes_f32[:64]): - b = val & MASK32 - matched = False - if condition == "nan": - matched = is_nan_f32_bits(b) - elif condition == "subnormal": - matched = is_subnormal_f32_bits(b) - elif condition == "inf": - matched = is_inf_f32_bits(b) - elif condition == "neg_zero": - matched = (b == NEG_ZERO_F32) - elif condition == "pos_zero": - matched = (b == POS_ZERO_F32) - elif condition == "finite": - matched = not (is_nan_f32_bits(b) or is_inf_f32_bits(b)) - if matched: - mask |= (1 << lane) - return mask & MASK64 - - -class RegKind(enum.Enum): - """Register kinds in the RDNA2 architectural state.""" - SGPR = "sgpr" - VGPR = "vgpr" - EXEC = "exec" - VCC = "vcc" - SCC = "scc" - M0 = "m0" - LITERAL = "literal" - INLINE_CONST = "inline_const" - - -@dataclass(frozen=True) -class Register: - """Symbolic register representation with architectural width and alignment validation.""" - kind: RegKind - index: int = 0 - size: int = 32 # 32 or 64 bits - - def validate(self) -> None: - """Validate architectural constraints for registers.""" - if self.kind == RegKind.SGPR: - if not (0 <= self.index <= 105): - raise ValueError(f"SGPR index {self.index} out of architectural range [0..105]") - if self.size == 64 and (self.index % 2 != 0): - raise ValueError(f"64-bit SGPR must be even-aligned: s[{self.index}:{self.index + 1}]") - if self.size == 64 and (self.index > 104): - raise ValueError(f"64-bit SGPR pair s[{self.index}:{self.index + 1}] exceeds max SGPR 105") - elif self.kind == RegKind.VGPR: - if not (0 <= self.index <= 255): - raise ValueError(f"VGPR index {self.index} out of architectural range [0..255]") - if self.size == 64 and (self.index > 254): - raise ValueError(f"64-bit VGPR pair v[{self.index}:{self.index + 1}] exceeds max VGPR 255") - - def __str__(self) -> str: - if self.kind == RegKind.SGPR: - return f"s[{self.index}:{self.index + 1}]" if self.size == 64 else f"s{self.index}" - if self.kind == RegKind.VGPR: - return f"v[{self.index}:{self.index + 1}]" if self.size == 64 else f"v{self.index}" - if self.kind == RegKind.EXEC: - return "exec" if self.size == 64 else "exec_lo" - if self.kind == RegKind.VCC: - return "vcc" if self.size == 64 else "vcc_lo" - if self.kind == RegKind.SCC: - return "scc" - if self.kind == RegKind.M0: - return "m0" - return f"{self.kind.value}:{self.index}" - - -@dataclass(frozen=True) -class Operand: - """Symbolic instruction operand representing either a register or immediate.""" - reg: Optional[Register] = None - imm: Optional[int] = None - size: int = 32 - - @property - def is_reg(self) -> bool: - return self.reg is not None - - @property - def is_imm(self) -> bool: - return self.imm is not None - - def __str__(self) -> str: - if self.reg is not None: - return str(self.reg) - if self.imm is not None: - return f"{self.imm:#x}" if self.imm > 9 or self.imm < -9 else str(self.imm) - return "" - - -class Opcode(enum.Enum): - """Opcode enumeration covering SALU and branch instructions.""" - S_AND_SAVEEXEC_B64 = "s_and_saveexec_b64" - S_OR_SAVEEXEC_B64 = "s_or_saveexec_b64" - S_ANDN2_SAVEEXEC_B64 = "s_andn2_saveexec_b64" - S_MOV_B64 = "s_mov_b64" - S_MOV_B32 = "s_mov_b32" - S_CBRANCH_EXECZ = "s_cbranch_execz" - S_CBRANCH_EXECNZ = "s_cbranch_execnz" - S_CBRANCH_SCC0 = "s_cbranch_scc0" - S_CBRANCH_SCC1 = "s_cbranch_scc1" - S_ENDPGM = "s_endpgm" - - -@dataclass -class Instruction: - """Symbolic typed instruction expression in the AST.""" - opcode: Opcode - dst: Optional[Register] = None - src0: Optional[Operand] = None - src1: Optional[Operand] = None - label_target: Optional[str] = None - comment: str = "" - - def validate(self) -> None: - """Validate instruction operand typing and sizing.""" - if self.opcode == Opcode.S_AND_SAVEEXEC_B64: - if self.dst is None or self.src0 is None: - raise ValueError(f"{self.opcode.value} requires sdst and ssrc0 operands") - if self.dst.size != 64: - raise ValueError(f"{self.opcode.value} destination must be 64-bit") - if self.dst.kind not in (RegKind.SGPR, RegKind.EXEC, RegKind.VCC): - raise ValueError(f"{self.opcode.value} destination must be SGPR, EXEC, or VCC") - self.dst.validate() - if self.src0.is_reg: - assert self.src0.reg is not None - if self.src0.reg.size != 64: - raise ValueError(f"{self.opcode.value} source register must be 64-bit") - self.src0.reg.validate() - elif self.opcode == Opcode.S_MOV_B64: - if self.dst is None or self.src0 is None: - raise ValueError(f"{self.opcode.value} requires dst and src0") - if self.dst.size != 64: - raise ValueError(f"{self.opcode.value} dst must be 64-bit") - self.dst.validate() - - def emit_asm(self) -> str: - """Serialize AST instruction to standard assembly text.""" - parts = [self.opcode.value] - operands = [] - if self.dst is not None: - operands.append(str(self.dst)) - if self.src0 is not None: - operands.append(str(self.src0)) - if self.src1 is not None: - operands.append(str(self.src1)) - if self.label_target is not None: - operands.append(self.label_target) - line = f"{self.opcode.value} {', '.join(operands)}" if operands else self.opcode.value - if self.comment: - line = f"{line:<40} ; {self.comment}" - return line - - -@dataclass -class Program: - """Symbolic program representation containing AST instructions and labels.""" - instructions: list[Instruction] = field(default_factory=list) - labels: dict[str, int] = field(default_factory=dict) - - def add_instruction(self, inst: Instruction) -> None: - inst.validate() - self.instructions.append(inst) - - def add_label(self, name: str) -> None: - self.labels[name] = len(self.instructions) - - def emit_asm(self) -> str: - lines = [] - label_positions = {pos: name for name, pos in self.labels.items()} - for i, inst in enumerate(self.instructions): - if i in label_positions: - lines.append(f"{label_positions[i]}:") - lines.append(f" {inst.emit_asm()}") - if len(self.instructions) in label_positions: - lines.append(f"{label_positions[len(self.instructions)]}:") - return "\n".join(lines) - - -def parse_operand(text: str, default_size: int = 64) -> Operand: - """Parse string operand into typed Operand AST node.""" - text = text.strip() - if text == "exec": - return Operand(reg=Register(RegKind.EXEC, 0, size=64), size=64) - if text == "exec_lo": - return Operand(reg=Register(RegKind.EXEC, 0, size=32), size=32) - if text == "vcc": - return Operand(reg=Register(RegKind.VCC, 0, size=64), size=64) - if text == "vcc_lo": - return Operand(reg=Register(RegKind.VCC, 0, size=32), size=32) - if text == "scc": - return Operand(reg=Register(RegKind.SCC, 0, size=32), size=32) - if text == "m0": - return Operand(reg=Register(RegKind.M0, 0, size=32), size=32) - - # 64-bit pair s[x:y] or v[x:y] - m_pair = re.match(r"^([sv])\[(\d+):(\d+)\]$", text) - if m_pair: - prefix, start, end = m_pair.group(1), int(m_pair.group(2)), int(m_pair.group(3)) - if end != start + 1: - raise ValueError(f"Non-contiguous or >2-register pair not supported: {text}") - kind = RegKind.SGPR if prefix == "s" else RegKind.VGPR - reg = Register(kind=kind, index=start, size=64) - reg.validate() - return Operand(reg=reg, size=64) - - # Single register sX or vX - m_single = re.match(r"^([sv])(\d+)$", text) - if m_single: - prefix, idx = m_single.group(1), int(m_single.group(2)) - kind = RegKind.SGPR if prefix == "s" else RegKind.VGPR - reg = Register(kind=kind, index=idx, size=default_size) - reg.validate() - return Operand(reg=reg, size=default_size) - - # Immediate (decimal or hex) - try: - val = int(text, 0) - return Operand(imm=val, size=default_size) - except ValueError: - raise ValueError(f"Unrecognized operand format: {text}") - - -def parse_instruction(line: str) -> Instruction: - """Parse a single assembly text line into an Instruction AST node.""" - clean = line.split(";", 1)[0].strip() - if not clean: - raise ValueError("Empty instruction line") - parts = clean.split(None, 1) - op_str = parts[0].lower() - try: - opcode = Opcode(op_str) - except ValueError: - raise ValueError(f"Unknown opcode: {op_str}") - - if opcode == Opcode.S_ENDPGM: - return Instruction(opcode=opcode) - - args_str = parts[1] if len(parts) > 1 else "" - raw_args = [a.strip() for a in args_str.split(",") if a.strip()] - - if opcode == Opcode.S_AND_SAVEEXEC_B64: - if len(raw_args) != 2: - raise ValueError(f"{opcode.value} expects exactly 2 operands, got {len(raw_args)}") - dst_op = parse_operand(raw_args[0], default_size=64) - if not dst_op.is_reg: - raise ValueError(f"{opcode.value} destination must be a register") - src0_op = parse_operand(raw_args[1], default_size=64) - inst = Instruction(opcode=opcode, dst=dst_op.reg, src0=src0_op) - inst.validate() - return inst - - if opcode in (Opcode.S_CBRANCH_EXECZ, Opcode.S_CBRANCH_EXECNZ, Opcode.S_CBRANCH_SCC0, Opcode.S_CBRANCH_SCC1): - if len(raw_args) != 1: - raise ValueError(f"{opcode.value} expects a single label target") - return Instruction(opcode=opcode, label_target=raw_args[0]) - - if opcode == Opcode.S_MOV_B64: - if len(raw_args) != 2: - raise ValueError(f"{opcode.value} expects dst, src0") - dst_op = parse_operand(raw_args[0], default_size=64) - src0_op = parse_operand(raw_args[1], default_size=64) - inst = Instruction(opcode=opcode, dst=dst_op.reg, src0=src0_op) - inst.validate() - return inst - - raise NotImplementedError(f"Parser not implemented for opcode {opcode.value}") - - -@dataclass -class ScalarRegisterState: - """Architectural register state for the RDNA2 scalar execution unit.""" - sgprs: list[int] = field(default_factory=lambda: [0] * 106) - exec: int = ALL_LANES_64 - vcc: int = 0 - m0: int = 0 - scc: int = 0 - pc: int = 0 - - def read_sgpr32(self, idx: int) -> int: - return self.sgprs[idx] & MASK32 - - def write_sgpr32(self, idx: int, val: int) -> None: - self.sgprs[idx] = val & MASK32 - - def read_sgpr64(self, idx: int) -> int: - if idx % 2 != 0: - raise ValueError(f"64-bit SGPR read requires even alignment: s[{idx}:{idx+1}]") - lo = self.sgprs[idx] & MASK32 - hi = self.sgprs[idx + 1] & MASK32 - return join_dwords(lo, hi) - - def write_sgpr64(self, idx: int, val: int) -> None: - if idx % 2 != 0: - raise ValueError(f"64-bit SGPR write requires even alignment: s[{idx}:{idx+1}]") - lo, hi = split_dwords(val) - self.sgprs[idx] = lo - self.sgprs[idx + 1] = hi - - def read_operand(self, op: Operand) -> int: - if op.imm is not None: - return op.imm & (MASK64 if op.size == 64 else MASK32) - assert op.reg is not None - reg = op.reg - if reg.kind == RegKind.SGPR: - return self.read_sgpr64(reg.index) if reg.size == 64 else self.read_sgpr32(reg.index) - if reg.kind == RegKind.EXEC: - return self.exec & MASK64 if reg.size == 64 else self.exec & MASK32 - if reg.kind == RegKind.VCC: - return self.vcc & MASK64 if reg.size == 64 else self.vcc & MASK32 - if reg.kind == RegKind.M0: - return self.m0 & MASK32 - if reg.kind == RegKind.SCC: - return self.scc & 1 - raise ValueError(f"Unsupported operand register kind: {reg.kind}") - - def write_reg(self, reg: Register, val: int) -> None: - if reg.kind == RegKind.SGPR: - if reg.size == 64: - self.write_sgpr64(reg.index, val) - else: - self.write_sgpr32(reg.index, val) - elif reg.kind == RegKind.EXEC: - self.exec = val & (MASK64 if reg.size == 64 else MASK32) - elif reg.kind == RegKind.VCC: - self.vcc = val & (MASK64 if reg.size == 64 else MASK32) - elif reg.kind == RegKind.M0: - self.m0 = val & MASK32 - elif reg.kind == RegKind.SCC: - self.scc = val & 1 - else: - raise ValueError(f"Cannot write to register kind {reg.kind}") - - -class ScalarSALUInterpreter: - """Deterministic interpreter simulating the RDNA2 SALU pipeline.""" - - def __init__(self, state: Optional[ScalarRegisterState] = None): - self.state = state if state is not None else ScalarRegisterState() - - def step(self, inst: Instruction, labels: Optional[dict[str, int]] = None) -> bool: - """Execute a single instruction. Returns False if execution terminated.""" - if inst.opcode == Opcode.S_ENDPGM: - return False - - if inst.opcode == Opcode.S_AND_SAVEEXEC_B64: - assert inst.dst is not None and inst.src0 is not None - # Latched execution: read source value - src_val = self.state.read_operand(inst.src0) - old_exec = self.state.exec & MASK64 - new_exec = (old_exec & src_val) & MASK64 - - # sdst receives prior EXEC - self.state.write_reg(inst.dst, old_exec) - # EXEC receives bitwise AND result - self.state.exec = new_exec - # SCC updated to (new_exec != 0) - self.state.scc = 1 if new_exec != 0 else 0 - self.state.pc += 1 - return True - - if inst.opcode == Opcode.S_MOV_B64: - assert inst.dst is not None and inst.src0 is not None - val = self.state.read_operand(inst.src0) - self.state.write_reg(inst.dst, val) - self.state.pc += 1 - return True - - if inst.opcode == Opcode.S_MOV_B32: - assert inst.dst is not None and inst.src0 is not None - val = self.state.read_operand(inst.src0) - self.state.write_reg(inst.dst, val) - self.state.pc += 1 - return True - - if inst.opcode == Opcode.S_CBRANCH_EXECZ: - assert inst.label_target is not None and labels is not None - if self.state.exec == 0: - self.state.pc = labels[inst.label_target] - else: - self.state.pc += 1 - return True - - if inst.opcode == Opcode.S_CBRANCH_EXECNZ: - assert inst.label_target is not None and labels is not None - if self.state.exec != 0: - self.state.pc = labels[inst.label_target] - else: - self.state.pc += 1 - return True - - if inst.opcode == Opcode.S_CBRANCH_SCC0: - assert inst.label_target is not None and labels is not None - if self.state.scc == 0: - self.state.pc = labels[inst.label_target] - else: - self.state.pc += 1 - return True - - if inst.opcode == Opcode.S_CBRANCH_SCC1: - assert inst.label_target is not None and labels is not None - if self.state.scc == 1: - self.state.pc = labels[inst.label_target] - else: - self.state.pc += 1 - return True - - raise NotImplementedError(f"Interpreter support for {inst.opcode.value} not implemented") - - def run(self, program: Program, max_steps: int = 1000) -> ScalarRegisterState: - """Run symbolic program until completion or max_steps exceeded.""" - steps = 0 - self.state.pc = 0 - while self.state.pc < len(program.instructions) and steps < max_steps: - inst = program.instructions[self.state.pc] - running = self.step(inst, program.labels) - steps += 1 - if not running: - break - return self.state - - -@dataclass -class SIMDWavefrontState: - """Architectural state for a 64-lane SIMD wavefront with shared scalar and per-lane vector registers.""" - scalar: ScalarRegisterState = field(default_factory=ScalarRegisterState) - vgprs: list[list[int]] = field(default_factory=lambda: [[0] * 64 for _ in range(256)]) - - def read_vgpr(self, reg_idx: int, lane: int) -> int: - return self.vgprs[reg_idx][lane] & MASK32 - - def write_vgpr(self, reg_idx: int, lane: int, val: int) -> None: - self.vgprs[reg_idx][lane] = val & MASK32 - - def write_vgpr_active_lanes(self, reg_idx: int, lane_val: Union[int, list[int]]) -> None: - """Write to vector register only across active lanes indicated by scalar EXEC mask.""" - exec_mask = self.scalar.exec & MASK64 - for lane in range(64): - if (exec_mask & (1 << lane)) != 0: - val = lane_val[lane] if isinstance(lane_val, list) else lane_val - self.vgprs[reg_idx][lane] = val & MASK32 - - -class SIMDWavefrontInterpreter: - """Wavefront interpreter modeling SIMD multi-lane divergence and 64-bit EXEC masking.""" - - def __init__(self, wave_state: Optional[SIMDWavefrontState] = None): - self.wave = wave_state if wave_state is not None else SIMDWavefrontState() - self.scalar_interp = ScalarSALUInterpreter(self.wave.scalar) - - def execute_vector_mov(self, dst_vgpr: int, src_val: Union[int, list[int]]) -> None: - """Execute vector move under current EXEC mask.""" - self.wave.write_vgpr_active_lanes(dst_vgpr, src_val) - - def execute_vector_add(self, dst_vgpr: int, src0_vgpr: int, src1_vgpr: int) -> None: - """Execute vector addition under current EXEC mask.""" - exec_mask = self.wave.scalar.exec & MASK64 - for lane in range(64): - if (exec_mask & (1 << lane)) != 0: - s0 = self.wave.read_vgpr(src0_vgpr, lane) - s1 = self.wave.read_vgpr(src1_vgpr, lane) - self.wave.write_vgpr(dst_vgpr, lane, (s0 + s1) & MASK32) - - def execute_vector_cmp_eq(self, src0_vgpr: int, imm: int) -> int: - """Vector compare equal against immediate, producing a 64-bit mask in VCC.""" - mask = 0 - for lane in range(64): - if self.wave.read_vgpr(src0_vgpr, lane) == (imm & MASK32): - mask |= (1 << lane) - self.wave.scalar.vcc = mask & MASK64 - return mask & MASK64 - -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF -SIGN_BIT64: int = 0x8000000000000000 -ALL_LANES_64: int = 0xFFFFFFFFFFFFFFFF -NO_LANES_64: int = 0x0000000000000000 -EVEN_LANES_64: int = 0x5555555555555555 -ODD_LANES_64: int = 0xAAAAAAAAAAAAAAAA -LOW32_LANES_64: int = 0x00000000FFFFFFFF -HIGH32_LANES_64: int = 0xFFFFFFFF00000000 - -# IEEE 754 architectural bit patterns for vector-to-scalar comparison masks -POS_ZERO_F32: int = 0x00000000 -NEG_ZERO_F32: int = 0x80000000 -POS_INF_F32: int = 0x7F800000 -NEG_INF_F32: int = 0xFF800000 -QNAN_F32: int = 0x7FC00000 -SNAN_F32: int = 0x7F800001 -SUBNORM_MIN_F32: int = 0x00000001 -SUBNORM_MAX_F32: int = 0x007FFFFF - -POS_ZERO_F64: int = 0x0000000000000000 -NEG_ZERO_F64: int = 0x8000000000000000 -POS_INF_F64: int = 0x7FF0000000000000 -NEG_INF_F64: int = 0xFFF0000000000000 -QNAN_F64: int = 0x7FF8000000000000 -SNAN_F64: int = 0x7FF0000000000001 -SUBNORM_MIN_F64: int = 0x0000000000000001 - - -def is_nan_f32_bits(bits: int) -> bool: - """Return True if 32-bit word represents an IEEE 754 single-precision NaN.""" - return ((bits & 0x7F800000) == 0x7F800000) and ((bits & 0x007FFFFF) != 0) - - -def is_subnormal_f32_bits(bits: int) -> bool: - """Return True if 32-bit word represents an IEEE 754 single-precision subnormal.""" - return ((bits & 0x7F800000) == 0) and ((bits & 0x007FFFFF) != 0) - - -def is_inf_f32_bits(bits: int) -> bool: - """Return True if 32-bit word represents positive or negative infinity.""" - return ((bits & 0x7F800000) == 0x7F800000) and ((bits & 0x007FFFFF) == 0) - - -def generate_f32_cmp_mask(lanes_f32: list[int], condition: str) -> int: - """Simulate vector float comparison across 64 lanes producing a 64-bit mask.""" - mask = 0 - for lane, val in enumerate(lanes_f32[:64]): - b = val & MASK32 - matched = False - if condition == "nan": - matched = is_nan_f32_bits(b) - elif condition == "subnormal": - matched = is_subnormal_f32_bits(b) - elif condition == "inf": - matched = is_inf_f32_bits(b) - elif condition == "neg_zero": - matched = (b == NEG_ZERO_F32) - elif condition == "pos_zero": - matched = (b == POS_ZERO_F32) - elif condition == "finite": - matched = not (is_nan_f32_bits(b) or is_inf_f32_bits(b)) - if matched: - mask |= (1 << lane) - return mask & MASK64 - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def popcount64(val: int) -> int: - """Return the number of active bits in a 64-bit integer.""" - return bin(val & MASK64).count("1") - - -def active_lanes_from_exec(exec_val: int) -> list[int]: - """Extract a list of active lane indices [0..63] from a 64-bit EXEC mask.""" - val = exec_val & MASK64 - return [lane for lane in range(64) if (val & (1 << lane)) != 0] - - -def exec_from_active_lanes(lanes: list[int]) -> int: - """Construct a 64-bit EXEC mask from a list of active lane indices [0..63].""" - mask = 0 - for lane in lanes: - if 0 <= lane < 64: - mask |= (1 << lane) - else: - raise ValueError(f"Lane index {lane} out of 64-bit bounds [0..63]") - return mask & MASK64 - - -def ref_s_and_saveexec_b64(exec_mask: int, ssrc0: int) -> tuple[int, int, int]: - """Pure mathematical reference oracle for RDNA2 s_and_saveexec_b64. - - Args: - exec_mask: Current 64-bit execution mask. - ssrc0: 64-bit source operand mask. - - Returns: - tuple (sdst, new_exec, scc): - - sdst: The saved prior EXEC mask (64-bit). - - new_exec: The updated EXEC mask after bitwise AND with ssrc0 (64-bit). - - scc: 1 if new_exec != 0, else 0. - """ - exec_clean = exec_mask & MASK64 - src_clean = ssrc0 & MASK64 - sdst = exec_clean - new_exec = exec_clean & src_clean - scc = 1 if new_exec != 0 else 0 - return sdst, new_exec, scc - - -class TestSaluAndSaveexecB64Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_oracle_identity_and_zero(self) -> None: - """Test identity with all ones and clearing with zero mask.""" - # EXEC all lanes active, src all lanes active -> saved all, new all, SCC=1 - sdst, new_exec, scc = ref_s_and_saveexec_b64(ALL_LANES_64, ALL_LANES_64) - self.assertEqual(sdst, ALL_LANES_64) - self.assertEqual(new_exec, ALL_LANES_64) - self.assertEqual(scc, 1) - - # EXEC all lanes, src zero -> saved all, new zero, SCC=0 - sdst, new_exec, scc = ref_s_and_saveexec_b64(ALL_LANES_64, NO_LANES_64) - self.assertEqual(sdst, ALL_LANES_64) - self.assertEqual(new_exec, NO_LANES_64) - self.assertEqual(scc, 0) - - # EXEC zero, src all lanes -> saved zero, new zero, SCC=0 - sdst, new_exec, scc = ref_s_and_saveexec_b64(NO_LANES_64, ALL_LANES_64) - self.assertEqual(sdst, NO_LANES_64) - self.assertEqual(new_exec, NO_LANES_64) - self.assertEqual(scc, 0) - - def test_oracle_scc_flag_transitions(self) -> None: - """Verify SCC accurately reflects non-zero state of new_exec.""" - # Single bit mask yields SCC=1 - for lane in (0, 1, 31, 32, 62, 63): - bit = 1 << lane - sdst, new_exec, scc = ref_s_and_saveexec_b64(ALL_LANES_64, bit) - self.assertEqual(sdst, ALL_LANES_64) - self.assertEqual(new_exec, bit) - self.assertEqual(scc, 1) - - # Disjoint masks yield new_exec=0 and SCC=0 - sdst, new_exec, scc = ref_s_and_saveexec_b64(EVEN_LANES_64, ODD_LANES_64) - self.assertEqual(sdst, EVEN_LANES_64) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - - def test_oracle_single_lane_masks(self) -> None: - """Verify single active lane filtering across all 64 lane positions.""" - for lane in range(64): - bit = 1 << lane - sdst, new_exec, scc = ref_s_and_saveexec_b64(bit, bit) - self.assertEqual(sdst, bit) - self.assertEqual(new_exec, bit) - self.assertEqual(scc, 1) - - # Different lane -> zero result - other_bit = 1 << ((lane + 1) % 64) - sdst2, new_exec2, scc2 = ref_s_and_saveexec_b64(bit, other_bit) - self.assertEqual(sdst2, bit) - self.assertEqual(new_exec2, 0) - self.assertEqual(scc2, 0) - - def test_oracle_alternating_bitmasks(self) -> None: - """Test alternating even/odd lane bitmasks.""" - sdst, new_exec, scc = ref_s_and_saveexec_b64(ALL_LANES_64, EVEN_LANES_64) - self.assertEqual(sdst, ALL_LANES_64) - self.assertEqual(new_exec, EVEN_LANES_64) - self.assertEqual(scc, 1) - self.assertEqual(popcount64(new_exec), 32) - - sdst, new_exec, scc = ref_s_and_saveexec_b64(EVEN_LANES_64, EVEN_LANES_64) - self.assertEqual(sdst, EVEN_LANES_64) - self.assertEqual(new_exec, EVEN_LANES_64) - self.assertEqual(scc, 1) - - def test_oracle_split_join_dwords(self) -> None: - """Verify 64-bit SGPR pair split/join helpers.""" - lo, hi = split_dwords(0x123456789ABCDEF0) - self.assertEqual(lo, 0x9ABCDEF0) - self.assertEqual(hi, 0x12345678) - self.assertEqual(join_dwords(lo, hi), 0x123456789ABCDEF0) - - def test_oracle_active_lanes_helpers(self) -> None: - """Test conversion between bitmask and active lane list.""" - lanes = [0, 7, 15, 31, 32, 47, 63] - mask = exec_from_active_lanes(lanes) - self.assertEqual(popcount64(mask), len(lanes)) - self.assertEqual(active_lanes_from_exec(mask), lanes) - - with self.assertRaises(ValueError): - exec_from_active_lanes([64]) - - def test_oracle_wave32_upper_lower_masks(self) -> None: - """Verify behavior on lower 32-bit and upper 32-bit halves.""" - sdst, new_exec, scc = ref_s_and_saveexec_b64(LOW32_LANES_64, HIGH32_LANES_64) - self.assertEqual(sdst, LOW32_LANES_64) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - - sdst, new_exec, scc = ref_s_and_saveexec_b64(ALL_LANES_64, LOW32_LANES_64) - self.assertEqual(sdst, ALL_LANES_64) - self.assertEqual(new_exec, LOW32_LANES_64) - self.assertEqual(scc, 1) - - def test_oracle_commutative_and_associative_properties(self) -> None: - """Verify bitwise boolean algebraic properties.""" - a = 0xF0F0F0F00F0F0F0F - b = 0xCCCCCCCC33333333 - _, res_ab, _ = ref_s_and_saveexec_b64(a, b) - _, res_ba, _ = ref_s_and_saveexec_b64(b, a) - self.assertEqual(res_ab, res_ba) - - -class TestSaluAndSaveexecB64AST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_ast_register_creation_and_bounds(self) -> None: - """Verify register AST nodes and alignment rules.""" - # Valid 64-bit aligned SGPR pair - reg = Register(RegKind.SGPR, 4, size=64) - reg.validate() - self.assertEqual(str(reg), "s[4:5]") - - # Valid 64-bit special registers - exec_reg = Register(RegKind.EXEC, 0, size=64) - exec_reg.validate() - self.assertEqual(str(exec_reg), "exec") - - vcc_reg = Register(RegKind.VCC, 0, size=64) - vcc_reg.validate() - self.assertEqual(str(vcc_reg), "vcc") - - # Invalid unaligned 64-bit SGPR (odd index) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 5, size=64).validate() - - # Out-of-bounds SGPR index (> 104 for 64-bit pair) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 106, size=64).validate() - - def test_ast_instruction_encoding(self) -> None: - """Verify Instruction AST construction and assembly emission.""" - dst = Register(RegKind.SGPR, 4, size=64) - src0 = Operand(reg=Register(RegKind.VCC, 0, size=64), size=64) - inst = Instruction(Opcode.S_AND_SAVEEXEC_B64, dst=dst, src0=src0, comment="save old exec") - inst.validate() - asm = inst.emit_asm() - self.assertTrue(asm.startswith("s_and_saveexec_b64 s[4:5], vcc")) - self.assertIn("; save old exec", asm) - - def test_ast_program_assembly_emission(self) -> None: - """Verify Program container emission with labels and instructions.""" - prog = Program() - prog.add_instruction(Instruction(Opcode.S_MOV_B64, dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=0xFFFFFFFFFFFFFFFF, size=64))) - prog.add_instruction(Instruction(Opcode.S_AND_SAVEEXEC_B64, dst=Register(RegKind.SGPR, 4, size=64), - src0=Operand(reg=Register(RegKind.SGPR, 0, size=64), size=64))) - prog.add_instruction(Instruction(Opcode.S_CBRANCH_EXECZ, label_target="skip_divergent")) - prog.add_label("skip_divergent") - prog.add_instruction(Instruction(Opcode.S_ENDPGM)) - - asm = prog.emit_asm() - self.assertIn("s_and_saveexec_b64 s[4:5], s[0:1]", asm) - self.assertIn("skip_divergent:", asm) - self.assertIn("s_cbranch_execz skip_divergent", asm) - self.assertIn("s_endpgm", asm) - - def test_ast_operand_parsing(self) -> None: - """Verify parsing operands from assembly strings.""" - op_sgpr = parse_operand("s[12:13]") - self.assertTrue(op_sgpr.is_reg) - assert op_sgpr.reg is not None - self.assertEqual(op_sgpr.reg.kind, RegKind.SGPR) - self.assertEqual(op_sgpr.reg.index, 12) - self.assertEqual(op_sgpr.size, 64) - - op_exec = parse_operand("exec") - self.assertTrue(op_exec.is_reg) - assert op_exec.reg is not None - self.assertEqual(op_exec.reg.kind, RegKind.EXEC) - - op_imm = parse_operand("0x5555555555555555") - self.assertTrue(op_imm.is_imm) - self.assertEqual(op_imm.imm, 0x5555555555555555) - - def test_ast_instruction_line_parsing(self) -> None: - """Verify parsing instruction lines.""" - inst = parse_instruction("s_and_saveexec_b64 s[8:9], exec ; save exec") - self.assertEqual(inst.opcode, Opcode.S_AND_SAVEEXEC_B64) - assert inst.dst is not None - self.assertEqual(inst.dst.kind, RegKind.SGPR) - self.assertEqual(inst.dst.index, 8) - assert inst.src0 is not None and inst.src0.reg is not None - self.assertEqual(inst.src0.reg.kind, RegKind.EXEC) - - def test_ast_program_semantic_validation(self) -> None: - """Verify AST semantic validation flags illegal constructs.""" - # Destination not 64-bit - bad_dst = Register(RegKind.SGPR, 4, size=32) - bad_src = Operand(reg=Register(RegKind.SGPR, 6, size=64)) - inst = Instruction(Opcode.S_AND_SAVEEXEC_B64, dst=bad_dst, src0=bad_src) - with self.assertRaises(ValueError): - inst.validate() - - -class TestSaluAndSaveexecB64ScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar instruction interpreter.""" - - def test_interp_basic_execution(self) -> None: - """Verify s_and_saveexec_b64 saves prior EXEC and updates EXEC with mask.""" - state = ScalarRegisterState(exec=0x123456789ABCDEF0) - interp = ScalarSALUInterpreter(state) - - # s_and_saveexec_b64 s[4:5], 0x00000000FFFFFFFF - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 4, size=64), - src0=Operand(imm=0x00000000FFFFFFFF, size=64), - ) - interp.step(inst) - - # s[4:5] must hold saved prior EXEC - self.assertEqual(state.read_sgpr64(4), 0x123456789ABCDEF0) - # EXEC must be masked - self.assertEqual(state.exec, 0x000000009ABCDEF0) - # SCC must be 1 since result is non-zero - self.assertEqual(state.scc, 1) - - def test_interp_exec_zero_clearing(self) -> None: - """Verify s_and_saveexec_b64 with zero mask clears EXEC and clears SCC.""" - state = ScalarRegisterState(exec=ALL_LANES_64, scc=1) - interp = ScalarSALUInterpreter(state) - - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=0, size=64), - ) - interp.step(inst) - - self.assertEqual(state.read_sgpr64(0), ALL_LANES_64) - self.assertEqual(state.exec, 0) - self.assertEqual(state.scc, 0) - - def test_interp_scc_update(self) -> None: - """Verify SCC tracks (new_exec != 0) deterministically.""" - state = ScalarRegisterState(exec=0x8000000000000000) - interp = ScalarSALUInterpreter(state) - - # Mask preserving bit 63 -> SCC=1 - inst1 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 2, size=64), - src0=Operand(imm=0x8000000000000000, size=64), - ) - interp.step(inst1) - self.assertEqual(state.scc, 1) - - # Mask clearing bit 63 -> SCC=0 - inst2 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 4, size=64), - src0=Operand(imm=0x7FFFFFFFFFFFFFFF, size=64), - ) - interp.step(inst2) - self.assertEqual(state.scc, 0) - - def test_interp_saved_exec_to_sgpr_pair(self) -> None: - """Verify 64-bit saved EXEC split into s[d] low and s[d+1] high dwords.""" - state = ScalarRegisterState(exec=0xAABBCCDDEEFF0011) - interp = ScalarSALUInterpreter(state) - - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 10, size=64), - src0=Operand(imm=ALL_LANES_64, size=64), - ) - interp.step(inst) - - self.assertEqual(state.read_sgpr32(10), 0xEEFF0011) - self.assertEqual(state.read_sgpr32(11), 0xAABBCCDD) - - def test_interp_chained_saveexec_flow(self) -> None: - """Verify nested/chained saveexec save and restore.""" - prog = Program() - # s_mov_b64 s[0:1], 0x5555555555555555 (even lanes) - prog.add_instruction(Instruction(Opcode.S_MOV_B64, dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=EVEN_LANES_64, size=64))) - # s_and_saveexec_b64 s[4:5], s[0:1] -> saved=ALL, exec=EVEN - prog.add_instruction(Instruction(Opcode.S_AND_SAVEEXEC_B64, dst=Register(RegKind.SGPR, 4, size=64), - src0=Operand(reg=Register(RegKind.SGPR, 0, size=64), size=64))) - # s_mov_b64 exec, s[4:5] -> restores ALL - prog.add_instruction(Instruction(Opcode.S_MOV_B64, dst=Register(RegKind.EXEC, 0, size=64), - src0=Operand(reg=Register(RegKind.SGPR, 4, size=64), size=64))) - prog.add_instruction(Instruction(Opcode.S_ENDPGM)) - - interp = ScalarSALUInterpreter() - state = interp.run(prog) - - self.assertEqual(state.read_sgpr64(4), ALL_LANES_64) - self.assertEqual(state.exec, ALL_LANES_64) - - def test_interp_conditional_branching_execz(self) -> None: - """Verify s_cbranch_execz jumps when exec is zero.""" - prog = Program() - # s_and_saveexec_b64 s[0:1], 0 -> exec becomes 0 - prog.add_instruction(Instruction(Opcode.S_AND_SAVEEXEC_B64, dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=0, size=64))) - prog.add_instruction(Instruction(Opcode.S_CBRANCH_EXECZ, label_target="target")) - prog.add_instruction(Instruction(Opcode.S_MOV_B32, dst=Register(RegKind.SGPR, 10, size=32), - src0=Operand(imm=999, size=32))) - prog.add_label("target") - prog.add_instruction(Instruction(Opcode.S_MOV_B32, dst=Register(RegKind.SGPR, 10, size=32), - src0=Operand(imm=42, size=32))) - prog.add_instruction(Instruction(Opcode.S_ENDPGM)) - - interp = ScalarSALUInterpreter() - state = interp.run(prog) - self.assertEqual(state.read_sgpr32(10), 42) - - -class TestSaluAndSaveexecB64SIMD(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_simd_lane_divergence_masking(self) -> None: - """Verify vector writes execute strictly across active lanes governed by s_and_saveexec_b64.""" - wave = SIMDWavefrontState() - interp = SIMDWavefrontInterpreter(wave) - - # Initialize all 64 lanes of v0 to 100 - interp.execute_vector_mov(dst_vgpr=0, src_val=100) - for lane in range(64): - self.assertEqual(wave.read_vgpr(0, lane), 100) - - # Set vcc to even lanes (0x5555555555555555) - wave.scalar.vcc = EVEN_LANES_64 - - # Divergent branch setup: s_and_saveexec_b64 s[4:5], vcc - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 4, size=64), - src0=Operand(reg=Register(RegKind.VCC, 0, size=64), size=64), - ) - interp.scalar_interp.step(inst) - - # Verify scalar state: saved EXEC has all 64 lanes, new EXEC has even lanes - self.assertEqual(wave.scalar.read_sgpr64(4), ALL_LANES_64) - self.assertEqual(wave.scalar.exec, EVEN_LANES_64) - self.assertEqual(wave.scalar.scc, 1) - - # Execute vector write to v0 with value 200 under even-lane EXEC mask - interp.execute_vector_mov(dst_vgpr=0, src_val=200) - - # Active (even) lanes must be updated to 200; inactive (odd) lanes must remain 100 - for lane in range(64): - expected = 200 if (lane % 2 == 0) else 100 - self.assertEqual(wave.read_vgpr(0, lane), expected, f"Mismatch at lane {lane}") - - def test_simd_inactive_lanes_preservation(self) -> None: - """Verify inactive lanes preserve all VGPR data across repeated operations.""" - wave = SIMDWavefrontState() - interp = SIMDWavefrontInterpreter(wave) - - # Each lane has distinct initial value - for lane in range(64): - wave.write_vgpr(1, lane, 1000 + lane) - - # Activate only lane 42 - wave.scalar.vcc = 1 << 42 - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 8, size=64), - src0=Operand(reg=Register(RegKind.VCC, 0, size=64), size=64), - ) - interp.scalar_interp.step(inst) - - # Write 9999 to v1 under single-lane mask - interp.execute_vector_mov(dst_vgpr=1, src_val=9999) - - for lane in range(64): - if lane == 42: - self.assertEqual(wave.read_vgpr(1, lane), 9999) - else: - self.assertEqual(wave.read_vgpr(1, lane), 1000 + lane) - - def test_simd_nested_divergence_stack(self) -> None: - """Verify 2-level nested conditional divergence saving masks into SGPR pairs.""" - wave = SIMDWavefrontState() - interp = SIMDWavefrontInterpreter(wave) - - # Level 1: activate lower 32 lanes - # s_and_saveexec_b64 s[4:5], 0x00000000FFFFFFFF - inst1 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 4, size=64), - src0=Operand(imm=LOW32_LANES_64, size=64), - ) - interp.scalar_interp.step(inst1) - self.assertEqual(wave.scalar.read_sgpr64(4), ALL_LANES_64) - self.assertEqual(wave.scalar.exec, LOW32_LANES_64) - - # Level 2 (nested): activate only even lanes within lower 32 lanes - # s_and_saveexec_b64 s[6:7], 0x5555555555555555 - inst2 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 6, size=64), - src0=Operand(imm=EVEN_LANES_64, size=64), - ) - interp.scalar_interp.step(inst2) - self.assertEqual(wave.scalar.read_sgpr64(6), LOW32_LANES_64) - self.assertEqual(wave.scalar.exec, LOW32_LANES_64 & EVEN_LANES_64) - - # Unwind Level 2: restore Level 1 mask - inst_restore1 = Instruction( - Opcode.S_MOV_B64, - dst=Register(RegKind.EXEC, 0, size=64), - src0=Operand(reg=Register(RegKind.SGPR, 6, size=64), size=64), - ) - interp.scalar_interp.step(inst_restore1) - self.assertEqual(wave.scalar.exec, LOW32_LANES_64) - - # Unwind Level 1: restore original all-lanes mask - inst_restore2 = Instruction( - Opcode.S_MOV_B64, - dst=Register(RegKind.EXEC, 0, size=64), - src0=Operand(reg=Register(RegKind.SGPR, 4, size=64), size=64), - ) - interp.scalar_interp.step(inst_restore2) - self.assertEqual(wave.scalar.exec, ALL_LANES_64) - - def test_simd_all_lanes_disabled_early_exit(self) -> None: - """Verify when no lanes match, s_and_saveexec_b64 sets EXEC=0 and SCC=0.""" - wave = SIMDWavefrontState() - interp = SIMDWavefrontInterpreter(wave) - - # Condition mask is 0 - wave.scalar.vcc = 0 - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(reg=Register(RegKind.VCC, 0, size=64), size=64), - ) - interp.scalar_interp.step(inst) - - self.assertEqual(wave.scalar.exec, 0) - self.assertEqual(wave.scalar.scc, 0) - self.assertEqual(len(active_lanes_from_exec(wave.scalar.exec)), 0) - - def test_simd_wave32_compatibility_masking(self) -> None: - """Verify behavior when running 32-lane wave workloads on 64-bit mask.""" - wave = SIMDWavefrontState() - interp = SIMDWavefrontInterpreter(wave) - - # Restrict initially to Wave32 lower half - wave.scalar.exec = LOW32_LANES_64 - - # AND with upper half produces 0 - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=HIGH32_LANES_64, size=64), - ) - interp.scalar_interp.step(inst) - - self.assertEqual(wave.scalar.read_sgpr64(0), LOW32_LANES_64) - self.assertEqual(wave.scalar.exec, 0) - self.assertEqual(wave.scalar.scc, 0) - - -class TestSaluAndSaveexecB64RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_aliasing_sdst_equals_ssrc0(self) -> None: - """Verify sdst == ssrc0: source is latched before destination receives old EXEC.""" - state = ScalarRegisterState(exec=0x1111222233334444) - interp = ScalarSALUInterpreter(state) - - # Preload s[4:5] with mask 0x0000FFFF0000FFFF - mask = 0x0000FFFF0000FFFF - state.write_sgpr64(4, mask) - - # s_and_saveexec_b64 s[4:5], s[4:5] - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 4, size=64), - src0=Operand(reg=Register(RegKind.SGPR, 4, size=64), size=64), - ) - interp.step(inst) - - # s[4:5] must receive the OLD EXEC (0x1111222233334444), NOT the AND result! - self.assertEqual(state.read_sgpr64(4), 0x1111222233334444) - # EXEC receives bitwise AND with original s[4:5] mask - expected_exec = 0x1111222233334444 & mask - self.assertEqual(state.exec, expected_exec) - self.assertEqual(state.scc, 1 if expected_exec != 0 else 0) - - def test_aliasing_ssrc0_is_exec(self) -> None: - """Verify ssrc0 is EXEC: new_exec = EXEC & EXEC = EXEC.""" - val = 0x0123456789ABCDEF - state = ScalarRegisterState(exec=val) - interp = ScalarSALUInterpreter(state) - - # s_and_saveexec_b64 s[6:7], exec - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 6, size=64), - src0=Operand(reg=Register(RegKind.EXEC, 0, size=64), size=64), - ) - interp.step(inst) - - self.assertEqual(state.read_sgpr64(6), val) - self.assertEqual(state.exec, val) - self.assertEqual(state.scc, 1) - - def test_aliasing_sdst_is_exec(self) -> None: - """Verify sdst is EXEC: EXEC receives the final computed mask.""" - initial_exec = 0xFFFFFFFFFFFFFFFF - mask = 0x5555555555555555 - state = ScalarRegisterState(exec=initial_exec) - interp = ScalarSALUInterpreter(state) - state.write_sgpr64(2, mask) - - # s_and_saveexec_b64 exec, s[2:3] - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.EXEC, 0, size=64), - src0=Operand(reg=Register(RegKind.SGPR, 2, size=64), size=64), - ) - interp.step(inst) - - self.assertEqual(state.exec, mask) - self.assertEqual(state.scc, 1) - - def test_aliasing_isolated_registers_untouched(self) -> None: - """Verify unreferenced registers in the register file remain completely invariant.""" - state = ScalarRegisterState(exec=ALL_LANES_64) - interp = ScalarSALUInterpreter(state) - - for i in range(0, 106, 2): - state.write_sgpr64(i, 0x1000000000000000 + i) - state.vcc = 0xAAAAAAAAAAAAAAAA - state.m0 = 0x12345678 - - # s_and_saveexec_b64 s[8:9], 0xF0F0F0F0F0F0F0F0 - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 8, size=64), - src0=Operand(imm=0xF0F0F0F0F0F0F0F0, size=64), - ) - interp.step(inst) - - # s[8:9] modified to old EXEC - self.assertEqual(state.read_sgpr64(8), ALL_LANES_64) - - # All other SGPR pairs must remain untouched - for i in range(0, 106, 2): - if i != 8: - self.assertEqual(state.read_sgpr64(i), 0x1000000000000000 + i, f"SGPR s[{i}:{i+1}] corrupted") - - # VCC and M0 must be untouched - self.assertEqual(state.vcc, 0xAAAAAAAAAAAAAAAA) - self.assertEqual(state.m0, 0x12345678) - - def test_aliasing_in_place_preservation_across_cycles(self) -> None: - """Verify cyclic save/restore preserves values without bit rot.""" - state = ScalarRegisterState(exec=0xFEEDFACECAFEBEEF) - interp = ScalarSALUInterpreter(state) - - # Save to s[0:1], mask with 0x00FF00FF00FF00FF - inst1 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=0x00FF00FF00FF00FF, size=64), - ) - interp.step(inst1) - self.assertEqual(state.read_sgpr64(0), 0xFEEDFACECAFEBEEF) - self.assertEqual(state.exec, 0x00ED00CE00FE00EF) - - # Restore EXEC from s[0:1] - inst2 = Instruction( - Opcode.S_MOV_B64, - dst=Register(RegKind.EXEC, 0, size=64), - src0=Operand(reg=Register(RegKind.SGPR, 0, size=64), size=64), - ) - interp.step(inst2) - self.assertEqual(state.exec, 0xFEEDFACECAFEBEEF) - - -class TestSaluAndSaveexecB64ConditionCodes(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow generation.""" - - def test_scc_monotonic_zero_absorption(self) -> None: - """Verify when EXEC is zero, any s_and_saveexec_b64 maintains zero EXEC and SCC=0.""" - state = ScalarRegisterState(exec=0, scc=0) - interp = ScalarSALUInterpreter(state) - - for mask in (ALL_LANES_64, EVEN_LANES_64, 1, 0x8000000000000000): - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=mask, size=64), - ) - interp.step(inst) - self.assertEqual(state.read_sgpr64(0), 0) - self.assertEqual(state.exec, 0) - self.assertEqual(state.scc, 0, f"SCC violated for mask {mask:#x}") - - def test_scc_transition_matrix(self) -> None: - """Verify full 2x2 state transition matrix for SCC.""" - interp = ScalarSALUInterpreter() - - # 0 -> 1 transition - interp.state.exec = ALL_LANES_64 - interp.state.scc = 0 - inst_to_1 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=1, size=64), - ) - interp.step(inst_to_1) - self.assertEqual(interp.state.scc, 1) - - # 1 -> 1 transition - interp.state.exec = ALL_LANES_64 - interp.state.scc = 1 - inst_keep_1 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=EVEN_LANES_64, size=64), - ) - interp.step(inst_keep_1) - self.assertEqual(interp.state.scc, 1) - - # 1 -> 0 transition - interp.state.exec = ALL_LANES_64 - interp.state.scc = 1 - inst_to_0 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=0, size=64), - ) - interp.step(inst_to_0) - self.assertEqual(interp.state.scc, 0) - - # 0 -> 0 transition - interp.state.exec = 0 - interp.state.scc = 0 - inst_keep_0 = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=0, size=64), - ) - interp.step(inst_keep_0) - self.assertEqual(interp.state.scc, 0) - - def test_scc_divergence_branching_scc0_scc1(self) -> None: - """Verify control flow branching on SCC0 and SCC1 after saveexec.""" - prog = Program() - # s_and_saveexec_b64 s[0:1], 0 -> exec=0, scc=0 - prog.add_instruction(Instruction(Opcode.S_AND_SAVEEXEC_B64, dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=0, size=64))) - # s_cbranch_scc0 branch_target - prog.add_instruction(Instruction(Opcode.S_CBRANCH_SCC0, label_target="scc_zero_target")) - prog.add_instruction(Instruction(Opcode.S_MOV_B32, dst=Register(RegKind.SGPR, 10, size=32), - src0=Operand(imm=111, size=32))) - prog.add_label("scc_zero_target") - prog.add_instruction(Instruction(Opcode.S_MOV_B32, dst=Register(RegKind.SGPR, 10, size=32), - src0=Operand(imm=222, size=32))) - prog.add_instruction(Instruction(Opcode.S_ENDPGM)) - - interp = ScalarSALUInterpreter() - state = interp.run(prog) - self.assertEqual(state.read_sgpr32(10), 222) - - def test_status_flags_carry_borrow_unaffected(self) -> None: - """Verify execution leaves non-SCC architectural status invariant.""" - state = ScalarRegisterState(exec=ALL_LANES_64, m0=0xDEADBEEF) - interp = ScalarSALUInterpreter(state) - - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 2, size=64), - src0=Operand(imm=0x12345678, size=64), - ) - interp.step(inst) - self.assertEqual(state.m0, 0xDEADBEEF) - - def test_scc_single_bit_boundary_detection(self) -> None: - """Verify MSB (lane 63) and LSB (lane 0) boundary bits accurately trigger SCC=1.""" - interp = ScalarSALUInterpreter() - - # Lane 0 - interp.state.exec = ALL_LANES_64 - interp.step(Instruction(Opcode.S_AND_SAVEEXEC_B64, dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=1, size=64))) - self.assertEqual(interp.state.scc, 1) - - # Lane 63 - interp.state.exec = ALL_LANES_64 - interp.step(Instruction(Opcode.S_AND_SAVEEXEC_B64, dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=1 << 63, size=64))) - self.assertEqual(interp.state.scc, 1) - - -class TestSaluAndSaveexecB64IEEE754Boundaries(unittest.TestCase): - """Unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_ieee754_nan_divergence_masking(self) -> None: - """Verify vector NaN classification masks correctly drive s_and_saveexec_b64 divergence.""" - wave = SIMDWavefrontState() - interp = SIMDWavefrontInterpreter(wave) - - # Set up 64 lanes with mixed float values; only lanes 3, 17, 45 have NaNs - float_lanes = [0x3F800000] * 64 # 1.0f - float_lanes[3] = QNAN_F32 - float_lanes[17] = SNAN_F32 - float_lanes[45] = QNAN_F32 - - nan_mask = generate_f32_cmp_mask(float_lanes, "nan") - expected_mask = (1 << 3) | (1 << 17) | (1 << 45) - self.assertEqual(nan_mask, expected_mask) - - # Vector comparison loads VCC - wave.scalar.vcc = nan_mask - - # Divergent block setup: s_and_saveexec_b64 s[4:5], vcc - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 4, size=64), - src0=Operand(reg=Register(RegKind.VCC, 0, size=64), size=64), - ) - interp.scalar_interp.step(inst) - - self.assertEqual(wave.scalar.read_sgpr64(4), ALL_LANES_64) - self.assertEqual(wave.scalar.exec, expected_mask) - self.assertEqual(wave.scalar.scc, 1) - - # Execute NaN fixup on active lanes: write canonical float 0.0 - interp.execute_vector_mov(dst_vgpr=0, src_val=0) - - for lane in range(64): - if lane in (3, 17, 45): - self.assertEqual(wave.read_vgpr(0, lane), 0) - else: - self.assertEqual(wave.read_vgpr(0, lane), 0) # default unwritten is 0 - - def test_ieee754_subnormal_lane_isolation(self) -> None: - """Verify subnormal float detection generates mask and updates EXEC.""" - float_lanes = [0x3F800000] * 64 - float_lanes[0] = SUBNORM_MIN_F32 - float_lanes[63] = SUBNORM_MAX_F32 - - subnorm_mask = generate_f32_cmp_mask(float_lanes, "subnormal") - self.assertEqual(subnorm_mask, (1 << 0) | (1 << 63)) - - interp = ScalarSALUInterpreter(ScalarRegisterState(exec=ALL_LANES_64)) - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 2, size=64), - src0=Operand(imm=subnorm_mask, size=64), - ) - interp.step(inst) - self.assertEqual(interp.state.exec, (1 << 0) | (1 << 63)) - self.assertEqual(interp.state.scc, 1) - - def test_ieee754_signed_zeros_distinction_mask(self) -> None: - """Verify distinguishing +0.0 and -0.0 via sign-bit mask.""" - float_lanes = [POS_ZERO_F32] * 64 - float_lanes[10] = NEG_ZERO_F32 - float_lanes[20] = NEG_ZERO_F32 - - neg_zero_mask = generate_f32_cmp_mask(float_lanes, "neg_zero") - self.assertEqual(neg_zero_mask, (1 << 10) | (1 << 20)) - - interp = ScalarSALUInterpreter(ScalarRegisterState(exec=ALL_LANES_64)) - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=neg_zero_mask, size=64), - ) - interp.step(inst) - self.assertEqual(interp.state.exec, (1 << 10) | (1 << 20)) - self.assertEqual(interp.state.scc, 1) - - def test_ieee754_infinity_boundary_filtering(self) -> None: - """Verify infinities isolation across lanes.""" - float_lanes = [0x3F800000] * 64 - float_lanes[5] = POS_INF_F32 - float_lanes[6] = NEG_INF_F32 - - inf_mask = generate_f32_cmp_mask(float_lanes, "inf") - self.assertEqual(inf_mask, (1 << 5) | (1 << 6)) - - interp = ScalarSALUInterpreter(ScalarRegisterState(exec=ALL_LANES_64)) - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=inf_mask, size=64), - ) - interp.step(inst) - self.assertEqual(interp.state.exec, (1 << 5) | (1 << 6)) - self.assertEqual(interp.state.scc, 1) - - def test_ieee754_raw_float_payload_bitwise_and(self) -> None: - """Verify bitwise operations with IEEE 754 bit-patterns as 64-bit masks.""" - # Using double-precision NaN bit pattern directly as mask - qnan_mask = QNAN_F64 - interp = ScalarSALUInterpreter(ScalarRegisterState(exec=ALL_LANES_64)) - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=64), - src0=Operand(imm=qnan_mask, size=64), - ) - interp.step(inst) - self.assertEqual(interp.state.exec, qnan_mask) - self.assertEqual(interp.state.scc, 1) - - -class TestSaluAndSaveexecB64NegativeControls(unittest.TestCase): - """Unit tests for negative controls, illegal syntax rejection, and boundary enforcement.""" - - def test_rejection_odd_aligned_destination_sgpr(self) -> None: - """Reject unaligned 64-bit destination SGPR pair (e.g. s[1:2]).""" - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 1, size=64).validate() - with self.assertRaises(ValueError): - parse_instruction("s_and_saveexec_b64 s[1:2], s[0:1]") - - def test_rejection_odd_aligned_source_sgpr(self) -> None: - """Reject unaligned 64-bit source SGPR pair (e.g. s[3:4]).""" - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 3, size=64).validate() - with self.assertRaises(ValueError): - parse_instruction("s_and_saveexec_b64 s[0:1], s[3:4]") - - def test_rejection_out_of_bounds_sgpr_index(self) -> None: - """Reject SGPR indices beyond architectural maximum of 105.""" - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 106, size=64).validate() - with self.assertRaises(ValueError): - parse_instruction("s_and_saveexec_b64 s[106:107], s[0:1]") - - def test_rejection_vgpr_destination(self) -> None: - """Reject VGPR destination for SALU s_and_saveexec_b64.""" - with self.assertRaises(ValueError): - parse_instruction("s_and_saveexec_b64 v[0:1], s[0:1]") - - def test_rejection_invalid_operand_count(self) -> None: - """Reject instructions with too few or too many operands.""" - with self.assertRaises(ValueError): - parse_instruction("s_and_saveexec_b64 s[0:1]") - with self.assertRaises(ValueError): - parse_instruction("s_and_saveexec_b64 s[0:1], s[2:3], s[4:5]") - - def test_rejection_32bit_register_size_mismatch(self) -> None: - """Reject 32-bit scalar register for 64-bit opcode.""" - with self.assertRaises(ValueError): - inst = Instruction( - Opcode.S_AND_SAVEEXEC_B64, - dst=Register(RegKind.SGPR, 0, size=32), - src0=Operand(imm=ALL_LANES_64, size=64), - ) - inst.validate() - - -class TestSaluAndSaveexecB64MutationDetection(unittest.TestCase): - """Mutation testing suite: verifies deliberate architectural mutations are caught.""" - - def test_mutation_or_instead_of_and(self) -> None: - """Detect mutation changing bitwise AND to OR.""" - def mutated_eval(exec_mask: int, src: int) -> tuple[int, int, int]: - sdst = exec_mask & MASK64 - new_exec = (exec_mask | src) & MASK64 # Mutation: | instead of & - return sdst, new_exec, (1 if new_exec != 0 else 0) - - # In reference: 0 & 0xFFFFFFFF = 0. In mutated: 0 | 0xFFFFFFFF = 0xFFFFFFFF. - ref_res = ref_s_and_saveexec_b64(0, 0xFFFFFFFF) - mut_res = mutated_eval(0, 0xFFFFFFFF) - self.assertNotEqual(ref_res, mut_res) - - def test_mutation_xor_instead_of_and(self) -> None: - """Detect mutation changing bitwise AND to XOR.""" - def mutated_eval(exec_mask: int, src: int) -> tuple[int, int, int]: - sdst = exec_mask & MASK64 - new_exec = (exec_mask ^ src) & MASK64 # Mutation: ^ instead of & - return sdst, new_exec, (1 if new_exec != 0 else 0) - - # In reference: 1 & 1 = 1. In mutated: 1 ^ 1 = 0. - ref_res = ref_s_and_saveexec_b64(1, 1) - mut_res = mutated_eval(1, 1) - self.assertNotEqual(ref_res, mut_res) - - def test_mutation_andn2_instead_of_and(self) -> None: - """Detect mutation changing AND to ANDN2 (exec & ~src).""" - def mutated_eval(exec_mask: int, src: int) -> tuple[int, int, int]: - sdst = exec_mask & MASK64 - new_exec = (exec_mask & ~src) & MASK64 # Mutation: & ~ - return sdst, new_exec, (1 if new_exec != 0 else 0) - - ref_res = ref_s_and_saveexec_b64(ALL_LANES_64, ALL_LANES_64) - mut_res = mutated_eval(ALL_LANES_64, ALL_LANES_64) - self.assertNotEqual(ref_res, mut_res) - - def test_mutation_sdst_receives_new_exec(self) -> None: - """Detect mutation saving updated EXEC instead of previous EXEC.""" - def mutated_eval(exec_mask: int, src: int) -> tuple[int, int, int]: - new_exec = (exec_mask & src) & MASK64 - sdst = new_exec # Mutation: new_exec instead of old exec_mask - return sdst, new_exec, (1 if new_exec != 0 else 0) - - ref_res = ref_s_and_saveexec_b64(ALL_LANES_64, 0) - mut_res = mutated_eval(ALL_LANES_64, 0) - self.assertNotEqual(ref_res, mut_res) - - def test_mutation_sdst_receives_src(self) -> None: - """Detect mutation saving source operand into sdst.""" - def mutated_eval(exec_mask: int, src: int) -> tuple[int, int, int]: - sdst = src & MASK64 # Mutation: src instead of exec_mask - new_exec = (exec_mask & src) & MASK64 - return sdst, new_exec, (1 if new_exec != 0 else 0) - - ref_res = ref_s_and_saveexec_b64(ALL_LANES_64, 0x12345678) - mut_res = mutated_eval(ALL_LANES_64, 0x12345678) - self.assertNotEqual(ref_res, mut_res) - - def test_mutation_scc_from_sdst_instead_of_new_exec(self) -> None: - """Detect mutation deriving SCC from sdst instead of new_exec.""" - def mutated_eval(exec_mask: int, src: int) -> tuple[int, int, int]: - sdst = exec_mask & MASK64 - new_exec = (exec_mask & src) & MASK64 - scc = 1 if sdst != 0 else 0 # Mutation: sdst != 0 - return sdst, new_exec, scc - - ref_res = ref_s_and_saveexec_b64(ALL_LANES_64, 0) - mut_res = mutated_eval(ALL_LANES_64, 0) - self.assertEqual(ref_res[2], 0) # Reference SCC is 0 - self.assertEqual(mut_res[2], 1) # Mutated SCC is 1 - self.assertNotEqual(ref_res, mut_res) - - def test_mutation_scc_inversion(self) -> None: - """Detect mutation inverting SCC condition.""" - def mutated_eval(exec_mask: int, src: int) -> tuple[int, int, int]: - sdst = exec_mask & MASK64 - new_exec = (exec_mask & src) & MASK64 - scc = 1 if new_exec == 0 else 0 # Mutation: inverted - return sdst, new_exec, scc - - ref_res = ref_s_and_saveexec_b64(ALL_LANES_64, ALL_LANES_64) - mut_res = mutated_eval(ALL_LANES_64, ALL_LANES_64) - self.assertNotEqual(ref_res, mut_res) - - def test_mutation_32bit_truncation(self) -> None: - """Detect mutation truncating 64-bit EXEC to 32 bits.""" - def mutated_eval(exec_mask: int, src: int) -> tuple[int, int, int]: - sdst = exec_mask & MASK64 - new_exec = (exec_mask & src) & MASK32 # Mutation: 32-bit truncation - return sdst, new_exec, (1 if new_exec != 0 else 0) - - # Upper 32-bit mask: ref preserves bits 32..63, mutated zeroes them - ref_res = ref_s_and_saveexec_b64(ALL_LANES_64, HIGH32_LANES_64) - mut_res = mutated_eval(ALL_LANES_64, HIGH32_LANES_64) - self.assertNotEqual(ref_res, mut_res) + def test_and_every_lane(self): + saveexec_run.check(self, "and") if __name__ == "__main__": diff --git a/tests/semantic/test_salu_andn2_saveexec_b64.py b/tests/semantic/test_salu_andn2_saveexec_b64.py index 5bad63eee..df6c62d38 100644 --- a/tests/semantic/test_salu_andn2_saveexec_b64.py +++ b/tests/semantic/test_salu_andn2_saveexec_b64.py @@ -1,1240 +1,33 @@ -from __future__ import annotations +"""s_andn2_saveexec_b64 through the translator, on every lane of a wave64. -"""Semantic reference oracle and architectural model for RDNA2 s_andn2_saveexec_b64. +RDNA2 ISA, SOP1: + s_andn2_saveexec_b64: D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0). -Instruction specification: - s_andn2_saveexec_b64 SDST, SSRC0 (SOP1 format) - -Architecture: - - Target: AMD RDNA2 / GFX10 Scalar ALU (SALU) - - SDST: 64-bit scalar destination register pair (e.g. s[0:1]) - - SSRC0: 64-bit scalar source operand (SGPR pair, literal constant, or inline constant) - - Implicit operand / destination: EXEC (64-bit execution mask register) - - Implicit destination flag: SCC (Scalar Condition Code, bit 0 of status register) - -Operation: - SDST = EXEC - EXEC = SSRC0 & ~EXEC - SCC = 1 if (EXEC != 0) else 0 - -Wavefront control-flow contract: - - Saves current active lane execution mask to SDST. - - Updates EXEC with lanes that are set in SSRC0 and were previously INACTIVE (~EXEC). - - SCC reflects whether any lane in the new EXEC mask is active. - - Used in compiler lowering of conditional branching (if-else inversion, loop exit, divergence). +Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in +tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an +SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of +this name ran a self-built interpreter and never called the translator. """ - -import re +import os import sys import unittest -from dataclasses import dataclass -from enum import Enum, auto -from typing import Optional, Tuple -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import saveexec_run # noqa: E402 (support puts tools/ on sys.path) -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit dword.""" - return val & MASK32 +class Saveexec(unittest.TestCase): + def test_andn2_by_hand(self): + # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = S0 & ~EXEC written out by hand. + lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) + s0, e = lanes(0, 32), lanes(16, 48) + want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), + "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), + "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["andn2"] + self.assertEqual(saveexec_run.model("andn2", s0, e), (want, e, 1)) - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit qword.""" - return val & MASK64 - - -def split_dwords(val64: int) -> Tuple[int, int]: - """Split 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into 64-bit unsigned integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def ref_andn2_b64(s0: int, s1: int) -> int: - """Bit-exact reference for 64-bit AND-NOT operation: D = S0 & (~S1).""" - return (s0 & (~s1 & MASK64)) & MASK64 - - -def ref_scc(val64: int) -> int: - """RDNA2 SCC condition flag update: 1 if 64-bit result is non-zero, else 0.""" - return 1 if (val64 & MASK64) != 0 else 0 - - -def ref_andn2_saveexec_b64(ssrc0: int, current_exec: int) -> Tuple[int, int, int]: - """Bit-exact reference mathematical oracle for RDNA2 s_andn2_saveexec_b64. - - Returns: - (saved_exec, new_exec, scc) - - saved_exec: previous 64-bit EXEC written to SDST - - new_exec: updated 64-bit EXEC written to EXEC register - - scc: updated 1-bit SCC condition code (1 if new_exec != 0 else 0) - """ - saved_exec = current_exec & MASK64 - new_exec = ref_andn2_b64(ssrc0, saved_exec) - scc = ref_scc(new_exec) - return saved_exec, new_exec, scc - - -class RegisterPair: - """Architectural model of an aligned 64-bit scalar register pair s[N:N+1].""" - - def __init__(self, lo: int = 0, hi: int = 0) -> None: - self.lo = lo & MASK32 - self.hi = hi & MASK32 - - @classmethod - def from_u64(cls, val: int) -> RegisterPair: - lo, hi = split_dwords(val) - return cls(lo, hi) - - @property - def as_u64(self) -> int: - return join_dwords(self.lo, self.hi) - - def set_u64(self, val: int) -> None: - self.lo, self.hi = split_dwords(val) - - def __repr__(self) -> str: - return f"RegisterPair(lo={self.lo:#010x}, hi={self.hi:#010x}, u64={self.as_u64:#018x})" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, RegisterPair): - return NotImplemented - return self.lo == other.lo and self.hi == other.hi - - -class ExecRegister: - """Architectural model of the 64-bit wave64 EXEC execution mask register.""" - - def __init__(self, val: int = MASK64) -> None: - self.val = val & MASK64 - - @property - def lo(self) -> int: - return self.val & MASK32 - - @property - def hi(self) -> int: - return (self.val >> 32) & MASK32 - - def is_lane_active(self, lane: int) -> bool: - if not (0 <= lane < 64): - raise IndexError(f"Lane index {lane} out of bounds [0, 63]") - return bool(self.val & (1 << lane)) - - def active_lane_count(self) -> int: - return bin(self.val).count("1") - - def __repr__(self) -> str: - return f"ExecRegister(val={self.val:#018x}, active_lanes={self.active_lane_count()})" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, ExecRegister): - return NotImplemented - return self.val == other.val - - -class SccRegister: - """Architectural model of the 1-bit Scalar Condition Code (SCC) status flag.""" - - def __init__(self, value: int = 0) -> None: - self.value = 1 if value else 0 - - def update(self, result_u64: int) -> None: - self.value = 1 if (result_u64 & MASK64) != 0 else 0 - - def __repr__(self) -> str: - return f"SccRegister({self.value})" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, SccRegister): - return NotImplemented - return self.value == other.value - - -class TestSaluAndn2SaveexecB64Oracle(unittest.TestCase): - """Unit test suite for the reference mathematical oracle and architectural models.""" - - def test_1bit_truth_table_exhaustive(self): - """Verify the complete truth table of AND-NOT across all bit lanes. - - Truth table for S0 & ~S1: - S0=0, S1=0 -> 0 & ~0 = 0 & 1 = 0 - S0=0, S1=1 -> 0 & ~1 = 0 & 0 = 0 - S0=1, S1=0 -> 1 & ~0 = 1 & 1 = 1 - S0=1, S1=1 -> 1 & ~1 = 1 & 0 = 0 - """ - table = { - (0, 0): 0, - (0, 1): 0, - (1, 0): 1, - (1, 1): 0, - } - for (b0, b1), expected_bit in table.items(): - for bit_pos in range(64): - s0 = (1 << bit_pos) if b0 else 0 - exec_val = (1 << bit_pos) if b1 else 0 - saved, new_exec, scc = ref_andn2_saveexec_b64(s0, exec_val) - expected_new_exec = (1 << bit_pos) if expected_bit else 0 - self.assertEqual(saved, exec_val) - self.assertEqual(new_exec, expected_new_exec) - self.assertEqual(scc, 1 if expected_bit else 0) - - def test_de_morgan_duality(self): - """Verify De Morgan's equivalence: A & ~B == ~(~A | B).""" - test_patterns = [ - (0x123456789ABCDEF0, 0x0FEDCBA987654321), - (0xAAAAAAAAAAAAAAAA, 0x5555555555555555), - (0xFFFFFFFF00000000, 0x00000000FFFFFFFF), - (0x0000000000000000, 0xFFFFFFFFFFFFFFFF), - (0xFFFFFFFFFFFFFFFF, 0x0000000000000000), - ] - for a, b in test_patterns: - direct = ref_andn2_b64(a, b) - de_morgan = (~((~a & MASK64) | b)) & MASK64 - self.assertEqual(direct, de_morgan) - - def test_non_commutativity(self): - """Verify that S0 & ~S1 != S1 & ~S0 for asymmetric inputs.""" - a = 0xF0F0F0F0F0F0F0F0 - b = 0x3333333333333333 - res_ab = ref_andn2_b64(a, b) - res_ba = ref_andn2_b64(b, a) - self.assertNotEqual(res_ab, res_ba) - # Specifically: - # A & ~B = 0xF0... & 0xCC... = 0xC0C0C0C0C0C0C0C0 - # B & ~A = 0x33... & 0x0F... = 0x0303030303030303 - self.assertEqual(res_ab, 0xC0C0C0C0C0C0C0C0) - self.assertEqual(res_ba, 0x0303030303030303) - - def test_self_annihilation_and_nullification(self): - """Verify edge case mathematical identities.""" - patterns = [ - 0x0000000000000000, - 0xFFFFFFFFFFFFFFFF, - 0x5555555555555555, - 0x123456789ABCDEF0, - ] - for x in patterns: - # A & ~A == 0 - self.assertEqual(ref_andn2_b64(x, x), 0) - self.assertEqual(ref_scc(ref_andn2_b64(x, x)), 0) - # 0 & ~A == 0 - self.assertEqual(ref_andn2_b64(0, x), 0) - # A & ~0 == A - self.assertEqual(ref_andn2_b64(x, 0), x) - # A & ~MASK64 == 0 - self.assertEqual(ref_andn2_b64(x, MASK64), 0) - - def test_saveexec_contract(self): - """Verify that saved_exec rigorously captures old EXEC before modification.""" - test_execs = [ - 0x0000000000000000, - 0x0000000000000001, - 0x8000000000000000, - 0xFFFFFFFF00000000, - 0x00000000FFFFFFFF, - 0x5555555555555555, - 0xFFFFFFFFFFFFFFFF, - ] - for old_exec in test_execs: - for ssrc0 in [0, MASK64, 0xAAAAAAAAAAAAAAAA, old_exec]: - saved, new_exec, scc = ref_andn2_saveexec_b64(ssrc0, old_exec) - self.assertEqual(saved, old_exec) - self.assertEqual(new_exec, ref_andn2_b64(ssrc0, old_exec)) - self.assertEqual(scc, 1 if new_exec != 0 else 0) - - def test_scc_four_quadrants(self): - """Verify SCC accurately distinguishes lo-dword and hi-dword non-zero states.""" - # 1. both lo and hi zero -> SCC = 0 - self.assertEqual(ref_scc(0x0000000000000000), 0) - # 2. lo non-zero, hi zero -> SCC = 1 - self.assertEqual(ref_scc(0x0000000000000001), 1) - self.assertEqual(ref_scc(0x0000000080000000), 1) - # 3. lo zero, hi non-zero -> SCC = 1 - self.assertEqual(ref_scc(0x0000000100000000), 1) - self.assertEqual(ref_scc(0x8000000000000000), 1) - # 4. both lo and hi non-zero -> SCC = 1 - self.assertEqual(ref_scc(0x123456789ABCDEF0), 1) - self.assertEqual(ref_scc(0xFFFFFFFFFFFFFFFF), 1) - - def test_architectural_register_pair_and_exec(self): - """Verify RegisterPair, ExecRegister, and SccRegister modeling integrity.""" - rp = RegisterPair.from_u64(0x123456789ABCDEF0) - self.assertEqual(rp.lo, 0x9ABCDEF0) - self.assertEqual(rp.hi, 0x12345678) - self.assertEqual(rp.as_u64, 0x123456789ABCDEF0) - - rp.set_u64(0xAAAAAAAAAAAAAAAA) - self.assertEqual(rp.lo, 0xAAAAAAAA) - self.assertEqual(rp.hi, 0xAAAAAAAA) - - exec_reg = ExecRegister(0x0000000000000003) - self.assertTrue(exec_reg.is_lane_active(0)) - self.assertTrue(exec_reg.is_lane_active(1)) - self.assertFalse(exec_reg.is_lane_active(2)) - self.assertEqual(exec_reg.active_lane_count(), 2) - - scc = SccRegister() - self.assertEqual(scc.value, 0) - scc.update(0x0000000100000000) - self.assertEqual(scc.value, 1) - scc.update(0x0) - self.assertEqual(scc.value, 0) - - -# --- Symbolic AST Definitions and Typed Expressions --- - -class OperandKind(Enum): - SGPR_PAIR = auto() # 64-bit SGPR pair s[N:N+1] - SGPR_SINGLE = auto() # 32-bit SGPR sN (invalid for 64-bit SOP1, used in type checking) - LITERAL_U64 = auto() # 64-bit literal constant - INLINE_CONST = auto() # Small inline integer constant (-16 to 64) - SPECIAL_REG = auto() # Special 64-bit register (e.g. exec, vcc) - - -@dataclass -class Operand: - """Symbolic operand for RDNA2 SALU instructions.""" - kind: OperandKind - reg_index: Optional[int] = None - literal_val: Optional[int] = None - name: Optional[str] = None - - def validate(self, is_dst: bool = False) -> None: - if is_dst: - if self.kind != OperandKind.SGPR_PAIR: - raise TypeError(f"Destination must be a 64-bit SGPR pair, got {self.kind}") - if self.reg_index is None or not (0 <= self.reg_index <= 104): - raise ValueError(f"Invalid SGPR pair index: {self.reg_index}") - if self.reg_index % 2 != 0: - raise ValueError(f"64-bit SGPR pair must be even-aligned, got s[{self.reg_index}:{self.reg_index+1}]") - else: - if self.kind == OperandKind.SGPR_PAIR: - if self.reg_index is None or not (0 <= self.reg_index <= 104): - raise ValueError(f"Invalid SGPR pair index: {self.reg_index}") - if self.reg_index % 2 != 0: - raise ValueError(f"64-bit SGPR pair must be even-aligned, got s[{self.reg_index}:{self.reg_index+1}]") - elif self.kind == OperandKind.LITERAL_U64: - if self.literal_val is None or not (0 <= self.literal_val <= MASK64): - raise ValueError(f"Literal 64-bit value out of range: {self.literal_val}") - elif self.kind == OperandKind.INLINE_CONST: - if self.literal_val is None: - raise ValueError("Inline constant value required") - elif self.kind == OperandKind.SPECIAL_REG: - if self.name not in ("exec", "vcc"): - raise ValueError(f"Unsupported special register: {self.name}") - elif self.kind == OperandKind.SGPR_SINGLE: - raise TypeError("Single 32-bit SGPR cannot be used directly as 64-bit operand") - - def to_asm(self) -> str: - if self.kind == OperandKind.SGPR_PAIR: - return f"s[{self.reg_index}:{self.reg_index + 1}]" - elif self.kind == OperandKind.SGPR_SINGLE: - return f"s{self.reg_index}" - elif self.kind == OperandKind.LITERAL_U64: - return f"{self.literal_val:#018x}" - elif self.kind == OperandKind.INLINE_CONST: - return str(self.literal_val) - elif self.kind == OperandKind.SPECIAL_REG: - return str(self.name) - return "unknown" - - -@dataclass -class InstructionAST: - """Symbolic Abstract Syntax Tree node for s_andn2_saveexec_b64.""" - opcode: str - dst: Operand - src0: Operand - - def validate(self) -> None: - if self.opcode != "s_andn2_saveexec_b64": - raise ValueError(f"Unsupported opcode: {self.opcode}") - self.dst.validate(is_dst=True) - self.src0.validate(is_dst=False) - - def to_asm(self) -> str: - return f"{self.opcode} {self.dst.to_asm()}, {self.src0.to_asm()}" - - -RE_PAIR = re.compile(r"^s\[(\d+):(\d+)\]$") -RE_SINGLE = re.compile(r"^s(\d+)$") -RE_HEX = re.compile(r"^0x[0-9a-fA-F]+$") -RE_INT = re.compile(r"^-?\d+$") - - -def parse_sop1_andn2_saveexec_b64(asm: str) -> InstructionAST: - """Parse assembly string into symbolic InstructionAST.""" - line = asm.strip() - if not line: - raise ValueError("Empty assembly statement") - tokens = line.split(None, 1) - if len(tokens) != 2: - raise ValueError(f"Invalid instruction syntax: '{line}'") - opcode, operands_str = tokens - if opcode != "s_andn2_saveexec_b64": - raise ValueError(f"Unexpected opcode: '{opcode}', expected 's_andn2_saveexec_b64'") - - parts = [p.strip() for p in operands_str.split(",")] - if len(parts) != 2: - raise ValueError(f"s_andn2_saveexec_b64 requires exactly 2 operands (dst, src0), got {len(parts)}") - - # Parse dst - m_dst = RE_PAIR.match(parts[0]) - if not m_dst: - m_s = RE_SINGLE.match(parts[0]) - if m_s: - dst = Operand(OperandKind.SGPR_SINGLE, reg_index=int(m_s.group(1))) - else: - raise ValueError(f"Invalid destination format: '{parts[0]}'") - else: - lo, hi = int(m_dst.group(1)), int(m_dst.group(2)) - if hi != lo + 1: - raise ValueError(f"Destination SGPR pair must be contiguous s[N:N+1], got s[{lo}:{hi}]") - dst = Operand(OperandKind.SGPR_PAIR, reg_index=lo) - - # Parse src0 - src_str = parts[1] - m_src_pair = RE_PAIR.match(src_str) - if m_src_pair: - lo, hi = int(m_src_pair.group(1)), int(m_src_pair.group(2)) - if hi != lo + 1: - raise ValueError(f"Source SGPR pair must be contiguous s[N:N+1], got s[{lo}:{hi}]") - src0 = Operand(OperandKind.SGPR_PAIR, reg_index=lo) - elif src_str.lower() in ("exec", "vcc"): - src0 = Operand(OperandKind.SPECIAL_REG, name=src_str.lower()) - elif RE_HEX.match(src_str): - val = int(src_str, 16) & MASK64 - src0 = Operand(OperandKind.LITERAL_U64, literal_val=val) - elif RE_INT.match(src_str): - val = int(src_str) - if -16 <= val <= 64: - src0 = Operand(OperandKind.INLINE_CONST, literal_val=val) - else: - src0 = Operand(OperandKind.LITERAL_U64, literal_val=val & MASK64) - elif RE_SINGLE.match(src_str): - src0 = Operand(OperandKind.SGPR_SINGLE, reg_index=int(RE_SINGLE.match(src_str).group(1))) - else: - raise ValueError(f"Unrecognized source operand: '{src_str}'") - - ast = InstructionAST(opcode=opcode, dst=dst, src0=src0) - ast.validate() - return ast - - -class TestSaluAndn2SaveexecB64SymbolicAST(unittest.TestCase): - """Test suite for symbolic AST opcode definitions and typed expressions.""" - - def test_parse_valid_sgpr_operands(self): - ast = parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], s[2:3]") - self.assertEqual(ast.opcode, "s_andn2_saveexec_b64") - self.assertEqual(ast.dst.kind, OperandKind.SGPR_PAIR) - self.assertEqual(ast.dst.reg_index, 0) - self.assertEqual(ast.src0.kind, OperandKind.SGPR_PAIR) - self.assertEqual(ast.src0.reg_index, 2) - self.assertEqual(ast.to_asm(), "s_andn2_saveexec_b64 s[0:1], s[2:3]") - - def test_parse_literal_and_inline_constants(self): - ast_lit = parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[4:5], 0x123456789ABCDEF0") - self.assertEqual(ast_lit.src0.kind, OperandKind.LITERAL_U64) - self.assertEqual(ast_lit.src0.literal_val, 0x123456789ABCDEF0) - - ast_inline = parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[6:7], -1") - self.assertEqual(ast_inline.src0.kind, OperandKind.INLINE_CONST) - self.assertEqual(ast_inline.src0.literal_val, -1) - - def test_parse_special_registers(self): - ast = parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[8:9], exec") - self.assertEqual(ast.src0.kind, OperandKind.SPECIAL_REG) - self.assertEqual(ast.src0.name, "exec") - self.assertEqual(ast.to_asm(), "s_andn2_saveexec_b64 s[8:9], exec") - - def test_ast_validation_rejects_unaligned_pair(self): - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[1:2], s[2:3]") - - def test_ast_validation_rejects_single_sgpr_dst(self): - with self.assertRaises(TypeError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s0, s[2:3]") - - def test_ast_validation_rejects_non_contiguous_pair(self): - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:2], s[2:3]") - - def test_ast_structural_equality_and_repr(self): - ast1 = parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], s[2:3]") - ast2 = parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], s[2:3]") - self.assertEqual(ast1, ast2) - self.assertIn("s_andn2_saveexec_b64", repr(ast1)) - - -# --- Deterministic Scalar Instruction Interpreter --- - -class ScalarSaluInterpreter: - """Deterministic architectural interpreter for RDNA2 SALU instructions.""" - - def __init__(self, num_sgprs: int = 106) -> None: - self.num_sgprs = num_sgprs - self.sgprs = [0] * num_sgprs - self.exec: int = MASK64 - self.scc: int = 0 - self.cycle_count: int = 0 - - def get_sgpr_u32(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: s{idx}") - return self.sgprs[idx] & MASK32 - - def set_sgpr_u32(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: s{idx}") - self.sgprs[idx] = val & MASK32 - - def get_sgpr_u64(self, idx: int) -> int: - if not (0 <= idx <= self.num_sgprs - 2): - raise IndexError(f"SGPR pair index out of range: s[{idx}:{idx+1}]") - lo = self.get_sgpr_u32(idx) - hi = self.get_sgpr_u32(idx + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, idx: int, val: int) -> None: - if not (0 <= idx <= self.num_sgprs - 2): - raise IndexError(f"SGPR pair index out of range: s[{idx}:{idx+1}]") - lo, hi = split_dwords(val) - self.set_sgpr_u32(idx, lo) - self.set_sgpr_u32(idx + 1, hi) - - def resolve_src0(self, op: Operand) -> int: - if op.kind == OperandKind.SGPR_PAIR: - assert op.reg_index is not None - return self.get_sgpr_u64(op.reg_index) - elif op.kind == OperandKind.LITERAL_U64: - assert op.literal_val is not None - return op.literal_val & MASK64 - elif op.kind == OperandKind.INLINE_CONST: - assert op.literal_val is not None - return op.literal_val & MASK64 - elif op.kind == OperandKind.SPECIAL_REG: - if op.name == "exec": - return self.exec & MASK64 - elif op.name == "vcc": - # VCC can be modeled as SGPR[104:105] or independent - return self.get_sgpr_u64(104) if self.num_sgprs >= 106 else 0 - else: - raise ValueError(f"Unknown special register: {op.name}") - else: - raise TypeError(f"Cannot resolve operand of kind {op.kind}") - - def execute(self, ast: InstructionAST) -> None: - """Deterministically execute one instruction AST.""" - ast.validate() - if ast.opcode == "s_andn2_saveexec_b64": - src0_val = self.resolve_src0(ast.src0) - saved_exec = self.exec & MASK64 - new_exec = ref_andn2_b64(src0_val, saved_exec) - scc_val = ref_scc(new_exec) - - # Destination write occurs - assert ast.dst.reg_index is not None - self.set_sgpr_u64(ast.dst.reg_index, saved_exec) - - # State registers updated - self.exec = new_exec - self.scc = scc_val - self.cycle_count += 1 - else: - raise NotImplementedError(f"Interpreter does not implement opcode {ast.opcode}") - - def execute_asm(self, asm_str: str) -> None: - ast = parse_sop1_andn2_saveexec_b64(asm_str) - self.execute(ast) - - -class TestSaluAndn2SaveexecB64ScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction interpreter.""" - - def test_interp_basic_execution(self): - interp = ScalarSaluInterpreter() - interp.exec = 0xFFFFFFFF00000000 - interp.set_sgpr_u64(2, 0x123456789ABCDEF0) - - interp.execute_asm("s_andn2_saveexec_b64 s[0:1], s[2:3]") - # SDST receives old EXEC - self.assertEqual(interp.get_sgpr_u64(0), 0xFFFFFFFF00000000) - # EXEC = s[2:3] & ~old_exec = 0x123456789ABCDEF0 & 0x00000000FFFFFFFF = 0x000000009ABCDEF0 - self.assertEqual(interp.exec, 0x000000009ABCDEF0) - # Nonzero new EXEC -> SCC = 1 - self.assertEqual(interp.scc, 1) - - def test_interp_with_literal_constant(self): - interp = ScalarSaluInterpreter() - interp.exec = 0x5555555555555555 - interp.execute_asm("s_andn2_saveexec_b64 s[4:5], 0xAAAAAAAAAAAAAAAA") - self.assertEqual(interp.get_sgpr_u64(4), 0x5555555555555555) - # 0xAAAA... & ~0x5555... = 0xAAAA... & 0xAAAA... = 0xAAAAAAAAAAAAAAAA - self.assertEqual(interp.exec, 0xAAAAAAAAAAAAAAAA) - self.assertEqual(interp.scc, 1) - - def test_interp_with_inline_constant(self): - interp = ScalarSaluInterpreter() - interp.exec = 0x00000000FFFFFFFF - interp.execute_asm("s_andn2_saveexec_b64 s[6:7], -1") - self.assertEqual(interp.get_sgpr_u64(6), 0x00000000FFFFFFFF) - # -1 (MASK64) & ~0x00000000FFFFFFFF = 0xFFFFFFFF00000000 - self.assertEqual(interp.exec, 0xFFFFFFFF00000000) - self.assertEqual(interp.scc, 1) - - def test_interp_with_special_reg_exec(self): - interp = ScalarSaluInterpreter() - interp.exec = 0x123456789ABCDEF0 - interp.execute_asm("s_andn2_saveexec_b64 s[8:9], exec") - # SDST receives old EXEC - self.assertEqual(interp.get_sgpr_u64(8), 0x123456789ABCDEF0) - # EXEC = old_exec & ~old_exec = 0 - self.assertEqual(interp.exec, 0x0) - # Zero new EXEC -> SCC = 0 - self.assertEqual(interp.scc, 0) - - def test_interp_sequential_state_flow(self): - interp = ScalarSaluInterpreter() - interp.exec = 0xF0F0F0F0F0F0F0F0 - interp.set_sgpr_u64(0, 0x0F0F0F0F0F0F0F0F) - interp.set_sgpr_u64(2, 0x00FF00FF00FF00FF) - - # Step 1: saveexec with s[0:1] - interp.execute_asm("s_andn2_saveexec_b64 s[4:5], s[0:1]") - self.assertEqual(interp.get_sgpr_u64(4), 0xF0F0F0F0F0F0F0F0) - self.assertEqual(interp.exec, 0x0F0F0F0F0F0F0F0F) - - # Step 2: saveexec with s[2:3] - interp.execute_asm("s_andn2_saveexec_b64 s[6:7], s[2:3]") - self.assertEqual(interp.get_sgpr_u64(6), 0x0F0F0F0F0F0F0F0F) - # new_exec = 0x00FF00FF00FF00FF & ~0x0F0F0F0F0F0F0F0F = 0x00F000F000F000F0 - self.assertEqual(interp.exec, 0x00F000F000F000F0) - self.assertEqual(interp.scc, 1) - - def test_interp_unmodified_registers_preserved(self): - interp = ScalarSaluInterpreter() - for i in range(interp.num_sgprs): - interp.set_sgpr_u32(i, 0xDEAD0000 | i) - - interp.exec = 0xCAFEBABEDEADBEEF - interp.execute_asm("s_andn2_saveexec_b64 s[10:11], 0") - - # Destination s[10:11] updated - self.assertEqual(interp.get_sgpr_u64(10), 0xCAFEBABEDEADBEEF) - - # All other SGPRs must remain unchanged - for i in range(interp.num_sgprs): - if i not in (10, 11): - self.assertEqual(interp.get_sgpr_u32(i), 0xDEAD0000 | i) - - -# --- SIMD Multi-Lane Divergence and EXEC Masking Engine --- - -class WaveEngine: - """Multi-lane SIMD wave execution engine modeling RDNA2 wave32 / wave64.""" - - def __init__(self, wave_size: int = 64, num_vgprs: int = 256) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size: {wave_size}") - self.wave_size = wave_size - self.num_vgprs = num_vgprs - self.vgprs = [[0] * wave_size for _ in range(num_vgprs)] - self.salu = ScalarSaluInterpreter() - self.mask_limit = MASK32 if wave_size == 32 else MASK64 - self.salu.exec = self.mask_limit - - @property - def exec_mask(self) -> int: - return self.salu.exec & self.mask_limit - - @exec_mask.setter - def exec_mask(self, val: int) -> None: - self.salu.exec = val & self.mask_limit - - def is_lane_active(self, lane: int) -> bool: - if not (0 <= lane < self.wave_size): - return False - return bool(self.exec_mask & (1 << lane)) - - def get_vgpr_lane(self, reg: int, lane: int) -> int: - return self.vgprs[reg][lane] & MASK32 - - def set_vgpr_lane(self, reg: int, lane: int, val: int) -> None: - self.vgprs[reg][lane] = val & MASK32 - - def valu_add_u32(self, dst_vgpr: int, src_vgpr: int, addend: int) -> None: - """VALU instruction: updates dst_vgpr only in currently ACTIVE lanes.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - old = self.get_vgpr_lane(src_vgpr, lane) - self.set_vgpr_lane(dst_vgpr, lane, (old + addend) & MASK32) - - def valu_set_u32(self, dst_vgpr: int, val: int) -> None: - """VALU instruction: sets constant in currently ACTIVE lanes.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.set_vgpr_lane(dst_vgpr, lane, val & MASK32) - - -class TestSaluAndn2SaveexecB64SIMDMultiLane(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_simd_divergent_if_else_execution(self): - """Simulate RDNA2 shader conditional branching pattern: - if (cond) { - v0 += 10 - } else { - v0 += 20 - } - Compiler lowering: - s_and_saveexec_b64 s[saved], cond_mask - v_add_u32 v0, v0, 10 - s_andn2_saveexec_b64 s[then], s[saved] - v_add_u32 v0, v0, 20 - s_mov_b64 exec, s[saved] - """ - engine = WaveEngine(wave_size=64) - # Initially only lower 32 lanes active - initial_exec = 0x00000000FFFFFFFF - engine.exec_mask = initial_exec - - # Condition mask: odd lanes within active range - cond_mask = 0xAAAAAAAAAAAAAAAA - - # Step 1: then-branch -> EXEC = old_exec & cond_mask - # s_and_saveexec_b64 s[0:1], cond_mask - saved_exec = engine.exec_mask - engine.salu.set_sgpr_u64(0, saved_exec) - engine.exec_mask = saved_exec & cond_mask - # Then-branch VALU action - engine.valu_add_u32(dst_vgpr=0, src_vgpr=0, addend=10) - - # Step 2: else-branch -> EXEC = s[0:1] & ~EXEC - # s_andn2_saveexec_b64 s[2:3], s[0:1] - engine.salu.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - # Verify s[2:3] saved the then-branch mask - self.assertEqual(engine.salu.get_sgpr_u64(2), initial_exec & cond_mask) - # Verify new EXEC is else-branch mask - expected_else_mask = initial_exec & (~cond_mask & MASK64) - self.assertEqual(engine.exec_mask, expected_else_mask) - # Else-branch VALU action - engine.valu_add_u32(dst_vgpr=0, src_vgpr=0, addend=20) - - # Step 3: restore original EXEC - engine.exec_mask = engine.salu.get_sgpr_u64(0) - - # Verification across all 64 lanes - for lane in range(64): - val = engine.get_vgpr_lane(0, lane) - if lane < 32: - if lane % 2 == 1: - # Odd lanes took then-branch - self.assertEqual(val, 10, f"Lane {lane} expected then-branch result") - else: - # Even lanes took else-branch - self.assertEqual(val, 20, f"Lane {lane} expected else-branch result") - else: - # Lanes >= 32 were inactive throughout - self.assertEqual(val, 0, f"Lane {lane} was inactive, must be 0") - - def test_simd_inactive_lane_preservation(self): - """Verify that inactive lanes under EXEC are untouched before and after saveexec.""" - engine = WaveEngine(wave_size=64) - # Pre-fill all lanes of v1 with distinctive values - for lane in range(64): - engine.set_vgpr_lane(1, lane, 0x1000 + lane) - - # Set EXEC to only lanes 0, 1, 2 - engine.exec_mask = 0x7 - # Invert EXEC against mask 0xF (lanes 0..3) - # new_exec = 0xF & ~0x7 = 0x8 (only lane 3) - engine.salu.set_sgpr_u64(4, 0xF) - engine.salu.execute_asm("s_andn2_saveexec_b64 s[6:7], s[4:5]") - - # Run VALU on v1 - engine.valu_add_u32(dst_vgpr=1, src_vgpr=1, addend=0x5000) - - # Only lane 3 was modified - self.assertEqual(engine.get_vgpr_lane(1, 3), 0x1000 + 3 + 0x5000) - # All other lanes strictly unchanged - for lane in range(64): - if lane != 3: - self.assertEqual(engine.get_vgpr_lane(1, lane), 0x1000 + lane) - - def test_simd_all_active_vs_none_active(self): - engine = WaveEngine(wave_size=64) - engine.exec_mask = MASK64 - # Invert against MASK64: MASK64 & ~MASK64 = 0 - engine.salu.execute_asm("s_andn2_saveexec_b64 s[0:1], -1") - self.assertEqual(engine.exec_mask, 0) - self.assertEqual(engine.salu.scc, 0) - for lane in range(64): - self.assertFalse(engine.is_lane_active(lane)) - - # Now EXEC is 0, invert against MASK64: MASK64 & ~0 = MASK64 - engine.salu.execute_asm("s_andn2_saveexec_b64 s[2:3], -1") - self.assertEqual(engine.exec_mask, MASK64) - self.assertEqual(engine.salu.scc, 1) - for lane in range(64): - self.assertTrue(engine.is_lane_active(lane)) - - def test_simd_wave32_masking(self): - engine = WaveEngine(wave_size=32) - self.assertEqual(engine.exec_mask, MASK32) - # Upper 32 bits should never be set in wave32 mode - engine.salu.set_sgpr_u64(0, 0xFFFFFFFF00000000) - engine.salu.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - # 0xFFFFFFFF00000000 & ~0x00000000FFFFFFFF = 0xFFFFFFFF00000000 - # In wave32 mode, active lanes are clamped to 32 bits - self.assertEqual(engine.exec_mask, 0) - self.assertFalse(engine.is_lane_active(32)) - - -# --- Register Aliasing and In-Place Operand Preservation --- - -class TestSaluAndn2SaveexecB64RegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def test_in_place_dst_src0_aliasing_read_before_write(self): - """Verify sdst == ssrc0: SSRC0 must be read BEFORE SDST is overwritten. - - Instruction: s_andn2_saveexec_b64 s[0:1], s[0:1] - Let S0 = 0xAAAAAAAAAAAAAAAA, EXEC = 0x5555555555555555. - Hardware behavior: - saved_exec = EXEC = 0x5555555555555555 - new_exec = S0 & ~saved_exec = 0xAAAA... & ~0x5555... = 0xAAAAAAAAAAAAAAAA - s[0:1] = saved_exec = 0x5555555555555555 - EXEC = new_exec = 0xAAAAAAAAAAAAAAAA - If SDST was written before SSRC0 was read: - new_exec would compute saved_exec & ~saved_exec = 0 (BUG!). - """ - interp = ScalarSaluInterpreter() - s0_val = 0xAAAAAAAAAAAAAAAA - exec_val = 0x5555555555555555 - interp.set_sgpr_u64(0, s0_val) - interp.exec = exec_val - - interp.execute_asm("s_andn2_saveexec_b64 s[0:1], s[0:1]") - - # Destination receives the OLD EXEC - self.assertEqual(interp.get_sgpr_u64(0), exec_val) - # EXEC receives (S0 & ~EXEC) using the OLD S0 - self.assertEqual(interp.exec, s0_val) - self.assertEqual(interp.scc, 1) - - def test_in_place_aliasing_with_complement(self): - """Verify in-place aliasing when S0 is identical to EXEC. - - S0 = 0x123456789ABCDEF0, EXEC = 0x123456789ABCDEF0. - new_exec = S0 & ~EXEC = 0. - s[2:3] gets 0x123456789ABCDEF0. - EXEC gets 0. - SCC gets 0. - """ - interp = ScalarSaluInterpreter() - val = 0x123456789ABCDEF0 - interp.set_sgpr_u64(2, val) - interp.exec = val - - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], s[2:3]") - self.assertEqual(interp.get_sgpr_u64(2), val) - self.assertEqual(interp.exec, 0) - self.assertEqual(interp.scc, 0) - - def test_chained_saveexec_register_reuse(self): - """Verify re-use of saved EXEC in multi-level nested control flow.""" - interp = ScalarSaluInterpreter() - initial_exec = 0xFFFFFFFFFFFFFFFF - interp.exec = initial_exec - - # First level branching: s[0:1] saves initial_exec - interp.set_sgpr_u64(4, 0x00000000FFFFFFFF) - interp.execute_asm("s_andn2_saveexec_b64 s[0:1], s[4:5]") - # s[0:1] = 0xFFFFFFFFFFFFFFFF - # EXEC = 0x00000000FFFFFFFF & ~0xFFFFFFFFFFFFFFFF = 0 - self.assertEqual(interp.get_sgpr_u64(0), initial_exec) - self.assertEqual(interp.exec, 0) - - # Second level branching: invert using the saved EXEC from s[0:1] - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - # s[2:3] = 0 (the old EXEC) - # EXEC = s[0:1] & ~0 = 0xFFFFFFFFFFFFFFFF & ~0 = 0xFFFFFFFFFFFFFFFF - self.assertEqual(interp.get_sgpr_u64(2), 0) - self.assertEqual(interp.exec, initial_exec) - self.assertEqual(interp.scc, 1) - - def test_high_register_indices_aliasing(self): - """Verify aliasing at the upper boundary of SGPR file (s[104:105]).""" - interp = ScalarSaluInterpreter() - interp.set_sgpr_u64(104, 0xCAFEBABE00000000) - interp.exec = 0x00000000DEADBEEF - - interp.execute_asm("s_andn2_saveexec_b64 s[104:105], s[104:105]") - self.assertEqual(interp.get_sgpr_u64(104), 0x00000000DEADBEEF) - self.assertEqual(interp.exec, 0xCAFEBABE00000000) - self.assertEqual(interp.scc, 1) - - -# --- Condition Codes, Status Flags, and Carry/Borrow Independence --- - -class TestSaluAndn2SaveexecB64StatusFlags(unittest.TestCase): - """Test suite for SCC condition codes, status flags, and carry/borrow independence.""" - - def test_scc_generation_zero_vs_nonzero(self): - """Verify SCC is strictly 0 for zero result, and 1 for any nonzero result.""" - interp = ScalarSaluInterpreter() - - # Zero result test: S0 & ~EXEC = 0 - interp.exec = 0x123456789ABCDEF0 - interp.set_sgpr_u64(0, 0x123456789ABCDEF0) - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - self.assertEqual(interp.exec, 0) - self.assertEqual(interp.scc, 0) - - # Nonzero result test: S0 & ~EXEC != 0 - interp.set_sgpr_u64(0, 0x1) - interp.execute_asm("s_andn2_saveexec_b64 s[4:5], s[0:1]") - self.assertEqual(interp.exec, 1) - self.assertEqual(interp.scc, 1) - - def test_scc_boundary_bits(self): - """Verify each boundary bit position (0, 31, 32, 63) properly asserts SCC.""" - boundary_bits = [0, 31, 32, 63] - for bit in boundary_bits: - interp = ScalarSaluInterpreter() - interp.exec = 0 # all ~EXEC bits are 1 - mask = 1 << bit - interp.set_sgpr_u64(0, mask) - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - self.assertEqual(interp.exec, mask) - self.assertEqual(interp.scc, 1, f"Bit {bit} failed to assert SCC") - - def test_carry_borrow_vcc_independence(self): - """Verify that s_andn2_saveexec_b64 does not touch or corrupt VCC / carry flags.""" - interp = ScalarSaluInterpreter() - # Set VCC registers s[104:105] to an identifiable canary - vcc_canary = 0xFEEDFACECAFEBEEF - interp.set_sgpr_u64(104, vcc_canary) - - interp.exec = 0xFFFFFFFFFFFFFFFF - interp.set_sgpr_u64(0, 0x00000000FFFFFFFF) - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - - # VCC remains untouched - self.assertEqual(interp.get_sgpr_u64(104), vcc_canary) - - def test_conditional_branch_emulation_scc_and_execz(self): - """Verify SCC and EXECZ equivalence for conditional skipping of empty waves.""" - interp = ScalarSaluInterpreter() - - # Case 1: All lanes disabled -> EXEC == 0, SCC == 0 - interp.exec = MASK64 - interp.execute_asm("s_andn2_saveexec_b64 s[0:1], -1") - # In RDNA2, compiler emits s_cbranch_execz or s_cbranch_scc0 to skip dead waves - branch_execz = (interp.exec == 0) - branch_scc0 = (interp.scc == 0) - self.assertTrue(branch_execz) - self.assertTrue(branch_scc0) - self.assertEqual(branch_execz, branch_scc0) - - # Case 2: At least one lane enabled -> EXEC != 0, SCC == 1 - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], 1") - branch_execnz = (interp.exec != 0) - branch_scc1 = (interp.scc == 1) - self.assertTrue(branch_execnz) - self.assertTrue(branch_scc1) - self.assertEqual(branch_execnz, branch_scc1) - - def test_scc_multi_cycle_toggling(self): - """Verify SCC state transitions cleanly between consecutive instructions.""" - interp = ScalarSaluInterpreter() - states = [ - (MASK64, MASK64, 0, 0), # new_exec = 0, scc = 0 - (MASK64, 0, MASK64, 1), # new_exec = MASK64, scc = 1 - (0, MASK64, 0, 0), # new_exec = 0, scc = 0 - (1, 0, 1, 1), # new_exec = 1, scc = 1 - ] - for s0, exec_in, expected_exec, expected_scc in states: - interp.exec = exec_in - interp.set_sgpr_u64(0, s0) - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - self.assertEqual(interp.exec, expected_exec) - self.assertEqual(interp.scc, expected_scc) - - -# --- IEEE 754 Boundary Extremes, Subnormals, and NaN Handling --- - -class TestSaluAndn2SaveexecB64IEEE754Boundaries(unittest.TestCase): - """Test suite for IEEE 754 float/double boundary masks, subnormals, and NaN handling.""" - - # IEEE 754 double-precision bit patterns - F64_POS_ZERO = 0x0000000000000000 - F64_NEG_ZERO = 0x8000000000000000 - F64_POS_INF = 0x7FF0000000000000 - F64_NEG_INF = 0xFFF0000000000000 - F64_CANONICAL_QNAN = 0x7FF8000000000000 - F64_SNAN = 0x7FF0000000000001 - F64_MIN_SUBNORMAL = 0x0000000000000001 - F64_MAX_SUBNORMAL = 0x000FFFFFFFFFFFFF - F64_MIN_NORMAL = 0x0010000000000000 - F64_MAX_NORMAL = 0x7FEFFFFFFFFFFFFF - - def test_bitwise_transparency_on_ieee754_bit_patterns(self): - """Verify s_andn2_saveexec_b64 preserves IEEE 754 bit patterns bit-for-bit. - - Shader scalar logic must not treat float bit patterns as numeric floats - (no flushing of subnormals, no canonicalizing NaNs, no sign-bit destruction). - """ - ieee_patterns = [ - self.F64_POS_ZERO, - self.F64_NEG_ZERO, - self.F64_POS_INF, - self.F64_NEG_INF, - self.F64_CANONICAL_QNAN, - self.F64_SNAN, - self.F64_MIN_SUBNORMAL, - self.F64_MAX_SUBNORMAL, - self.F64_MIN_NORMAL, - self.F64_MAX_NORMAL, - ] - interp = ScalarSaluInterpreter() - for p in ieee_patterns: - # Set EXEC to 0 (all inverted bits in ~EXEC are 1) - interp.exec = 0 - interp.set_sgpr_u64(0, p) - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - # S0 & ~0 == S0 exactly - self.assertEqual(interp.exec, p, f"Failed bitwise transparency on {p:#018x}") - self.assertEqual(interp.get_sgpr_u64(2), 0) - self.assertEqual(interp.scc, 1 if p != 0 else 0) - - def test_float_comparison_mask_divergence_filtering(self): - """Simulate RDNA2 shader routine filtering exceptional float lanes: - Lanes evaluate floating-point values. - v_cmp_class_f64 produces mask of lanes that are NaN or Subnormal. - s_andn2_saveexec_b64 s[nan_saved], s[all_lanes] - Masks out NaN/subnormal lanes so normal calculation proceeds only on valid lanes. - """ - engine = WaveEngine(wave_size=64) - # All 64 lanes active initially - engine.exec_mask = MASK64 - - # Assume lanes 5, 12, 33, 47 contain NaNs or subnormals - exceptional_lanes = {5, 12, 33, 47} - exceptional_mask = 0 - for lane in exceptional_lanes: - exceptional_mask |= (1 << lane) - - # Set up v0 with initial values - for lane in range(64): - engine.set_vgpr_lane(0, lane, 100) - - # Invert EXEC against exceptional mask: - # EXEC_new = MASK64 & ~exceptional_mask (all lanes EXCEPT exceptional lanes) - engine.salu.set_sgpr_u64(0, MASK64) - # We set EXEC to exceptional_mask first (as if v_cmp wrote EXEC) - engine.exec_mask = exceptional_mask - # s_andn2_saveexec_b64 s[2:3], s[0:1] - # s[2:3] = exceptional_mask - # EXEC = MASK64 & ~exceptional_mask - engine.salu.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - - self.assertEqual(engine.salu.get_sgpr_u64(2), exceptional_mask) - expected_valid_mask = MASK64 & ~exceptional_mask - self.assertEqual(engine.exec_mask, expected_valid_mask) - self.assertEqual(engine.salu.scc, 1) - - # Normal VALU operation - engine.valu_add_u32(dst_vgpr=0, src_vgpr=0, addend=50) - - # Verify only valid lanes were updated - for lane in range(64): - val = engine.get_vgpr_lane(0, lane) - if lane in exceptional_lanes: - self.assertEqual(val, 100, f"Exceptional lane {lane} should not have run") - else: - self.assertEqual(val, 150, f"Valid lane {lane} should have updated to 150") - - def test_ieee754_qnan_vs_snan_mask_inversion(self): - """Verify distinct bit positions between QNaN and SNaN in mask logic.""" - interp = ScalarSaluInterpreter() - # QNaN: bit 51 set; SNaN: bit 51 clear, bit 0 set - qnan_mask = self.F64_CANONICAL_QNAN - snan_mask = self.F64_SNAN - - interp.exec = qnan_mask - interp.set_sgpr_u64(0, snan_mask) - interp.execute_asm("s_andn2_saveexec_b64 s[2:3], s[0:1]") - - # new_exec = snan_mask & ~qnan_mask - expected_new = (self.F64_SNAN & (~self.F64_CANONICAL_QNAN & MASK64)) & MASK64 - self.assertEqual(interp.exec, expected_new) - # Since SNaN has bit 0 set and QNaN bit 0 clear: - self.assertEqual(interp.exec & 0x1, 0x1) - self.assertEqual(interp.scc, 1) - - -# --- Mutants for Mutation Testing --- - -def mutant_and_instead_of_andn2(s0: int, exec_val: int) -> Tuple[int, int, int]: - """Mutant A: computes s0 & exec_val instead of s0 & ~exec_val.""" - saved_exec = exec_val & MASK64 - new_exec = (s0 & saved_exec) & MASK64 - return saved_exec, new_exec, ref_scc(new_exec) - - -def mutant_inverted_operands(s0: int, exec_val: int) -> Tuple[int, int, int]: - """Mutant B: computes ~s0 & exec_val instead of s0 & ~exec_val.""" - saved_exec = exec_val & MASK64 - new_exec = ((~s0 & MASK64) & saved_exec) & MASK64 - return saved_exec, new_exec, ref_scc(new_exec) - - -def mutant_no_save_exec(interp: ScalarSaluInterpreter, ast: InstructionAST) -> None: - """Mutant C: forgets to write old EXEC to SDST register.""" - src0_val = interp.resolve_src0(ast.src0) - saved_exec = interp.exec & MASK64 - new_exec = ref_andn2_b64(src0_val, saved_exec) - # Skip writing saved_exec to ast.dst - interp.exec = new_exec - interp.scc = ref_scc(new_exec) - - -def mutant_write_before_read(interp: ScalarSaluInterpreter, ast: InstructionAST) -> None: - """Mutant D: overwrites SDST before resolving SSRC0 (breaks aliased instructions).""" - saved_exec = interp.exec & MASK64 - assert ast.dst.reg_index is not None - interp.set_sgpr_u64(ast.dst.reg_index, saved_exec) - # Now resolving src0 sees saved_exec if src0 aliased dst! - src0_val = interp.resolve_src0(ast.src0) - new_exec = ref_andn2_b64(src0_val, saved_exec) - interp.exec = new_exec - interp.scc = ref_scc(new_exec) - - -def mutant_exec_low32_only(s0: int, exec_val: int) -> Tuple[int, int, int]: - """Mutant E: only updates low 32 bits of EXEC, leaving high 32 bits untouched.""" - saved_exec = exec_val & MASK64 - full_new = ref_andn2_b64(s0, saved_exec) - new_exec = (saved_exec & (MASK32 << 32)) | (full_new & MASK32) - return saved_exec, new_exec, ref_scc(new_exec) - - -def mutant_scc_inverted(s0: int, exec_val: int) -> Tuple[int, int, int]: - """Mutant F: inverts SCC logic (1 if new_exec == 0 else 0).""" - saved_exec, new_exec, scc = ref_andn2_saveexec_b64(s0, exec_val) - return saved_exec, new_exec, 0 if scc else 1 - - -# --- Negative Controls, Syntax Rejection, and Mutation Detection --- - -class TestSaluAndn2SaveexecB64NegativeControlsAndMutations(unittest.TestCase): - """Test suite for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_invalid_opcode(self): - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_and_saveexec_b64 s[0:1], s[2:3]") - - def test_syntax_rejection_insufficient_operands(self): - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1]") - - def test_syntax_rejection_excess_operands(self): - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], s[2:3], s[4:5]") - - def test_syntax_rejection_single_sgpr_destination(self): - with self.assertRaises(TypeError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s0, s[2:3]") - - def test_syntax_rejection_non_contiguous_registers(self): - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:2], s[2:3]") - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], s[2:4]") - - def test_syntax_rejection_out_of_bounds_registers(self): - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[106:107], s[0:1]") - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], s[106:107]") - - def test_syntax_rejection_malformed_tokens(self): - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64") - with self.assertRaises(ValueError): - parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], @invalid") - - def test_mutation_detection_and_instead_of_andn2(self): - s0 = 0xF0F0F0F0F0F0F0F0 - old_exec = 0xF0F0F0F0F0F0F0F0 - # Correct: S0 & ~EXEC = 0 - _, correct_new, _ = ref_andn2_saveexec_b64(s0, old_exec) - # Mutant: S0 & EXEC = 0xF0F0F0F0F0F0F0F0 - _, mutant_new, _ = mutant_and_instead_of_andn2(s0, old_exec) - self.assertEqual(correct_new, 0) - self.assertNotEqual(correct_new, mutant_new) - - def test_mutation_detection_inverted_operands(self): - s0 = 0xFFFFFFFF00000000 - old_exec = 0x0000000000000000 - # Correct: S0 & ~0 = S0 - _, correct_new, _ = ref_andn2_saveexec_b64(s0, old_exec) - # Mutant: ~S0 & 0 = 0 - _, mutant_new, _ = mutant_inverted_operands(s0, old_exec) - self.assertEqual(correct_new, s0) - self.assertNotEqual(correct_new, mutant_new) - - def test_mutation_detection_no_save_exec(self): - interp = ScalarSaluInterpreter() - interp.exec = 0xCAFEBABE12345678 - ast = parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], 0") - mutant_no_save_exec(interp, ast) - # Mutant fails to update s[0:1] with old EXEC - self.assertNotEqual(interp.get_sgpr_u64(0), 0xCAFEBABE12345678) - - def test_mutation_detection_write_before_read(self): - interp = ScalarSaluInterpreter() - interp.exec = 0x5555555555555555 - interp.set_sgpr_u64(0, 0xAAAAAAAAAAAAAAAA) - ast = parse_sop1_andn2_saveexec_b64("s_andn2_saveexec_b64 s[0:1], s[0:1]") - mutant_write_before_read(interp, ast) - # Mutant computes saved_exec & ~saved_exec = 0 instead of S0 & ~saved_exec - self.assertEqual(interp.exec, 0) - # Correct execution gives 0xAAAAAAAAAAAAAAAA - correct_interp = ScalarSaluInterpreter() - correct_interp.exec = 0x5555555555555555 - correct_interp.set_sgpr_u64(0, 0xAAAAAAAAAAAAAAAA) - correct_interp.execute(ast) - self.assertEqual(correct_interp.exec, 0xAAAAAAAAAAAAAAAA) - self.assertNotEqual(interp.exec, correct_interp.exec) - - def test_mutation_detection_exec_low32_only(self): - s0 = 0xFFFFFFFF00000000 - old_exec = 0x0000000000000000 - _, correct_new, _ = ref_andn2_saveexec_b64(s0, old_exec) - _, mutant_new, _ = mutant_exec_low32_only(s0, old_exec) - self.assertEqual(correct_new, 0xFFFFFFFF00000000) - self.assertEqual(mutant_new, 0x0000000000000000) - self.assertNotEqual(correct_new, mutant_new) - - def test_mutation_detection_scc_inverted(self): - s0 = 0x0 - old_exec = 0x0 - _, _, correct_scc = ref_andn2_saveexec_b64(s0, old_exec) - _, _, mutant_scc = mutant_scc_inverted(s0, old_exec) - self.assertEqual(correct_scc, 0) - self.assertEqual(mutant_scc, 1) - self.assertNotEqual(correct_scc, mutant_scc) + def test_andn2_every_lane(self): + saveexec_run.check(self, "andn2") if __name__ == "__main__": diff --git a/tests/semantic/test_salu_b32_lane_masks.py b/tests/semantic/test_salu_b32_lane_masks.py new file mode 100644 index 000000000..9e2f59a7f --- /dev/null +++ b/tests/semantic/test_salu_b32_lane_masks.py @@ -0,0 +1,388 @@ +"""Semantic tests for 32-bit bitwise SALU ops on lane masks (wave32 and wave64 half-masks). + +Covers s_not_b32 and s_and/or/xor/andn2/orn2/nand/nor/xnor/cselect_b32 when operating on lane masks: + - Wave32 s_not_b32 on a lane mask (vcc_lo / exec_lo / mask SGPR): inverted per-lane bits AND uniform + wave-wide SCC (OpGroupNonUniformAny), not per-lane SCC. + - Wave32 s_not_b32 / s_and_b32 / s_or_b32 / s_xor_b32 with immediate or scalar-SGPR operands writing + exec_lo or vcc_lo: skips raw scalar constant folding and computes per-lane mask bits + wave-wide SCC. + - Wave64 32-bit bitwise ops on exec_lo / exec_hi / vcc_lo / vcc_hi / MASK_LO / MASK_HI: + * Writing exec_lo preserves exec_hi (lanes 32..63); writing exec_hi preserves exec_lo (lanes 0..31). + * Writing vcc_lo preserves vcc_hi; writing vcc_hi preserves vcc_lo. + * SCC votes over the written/read 32-lane half only (scc_any_half), unaffected by the other half. + * Opposite-half source (e.g. exec_lo <- vcc_hi, exec_hi <- vcc_lo) collects the source half cleanly. + * s_cselect_b32 into exec_lo / exec_hi preserves the untouched half. + - Preserves scalar constant folding for plain SGPR destinations and spirv-val Vulkan 1.2 validation in + both native and --wave64-emulate modes. + +Standard library only; no GPU, no game files. +""" +from __future__ import annotations + +import gc +import os +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +for _p in (HERE, TOOLS_DIR): + if _p not in sys.path: + sys.path.insert(0, _p) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: + with tempfile.TemporaryDirectory() as tmp: + os.mkdir(os.path.join(tmp, "disasm")) + os.mkdir(os.path.join(tmp, "fssm")) + src = os.path.join(tmp, "disasm", f"cs_{name}.s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(f"; cs_{name}\n") + for ln in lines: + f.write(f"\t{ln}\n") + with open(os.path.join(tmp, f"cs_{name}.dxbc"), "wb") as f: + f.write(STUB_DXBC) + with open(os.path.join(tmp, "fssm", f"cs_{name}.fssm"), "wb") as f: + f.write(bytes(0x138) + struct.pack("<4I", 0x8090, threads, 1, 1)) + old_emulate = rdna2spirv.WAVE64_EMULATE + rdna2spirv.WAVE64_EMULATE = emulate + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(src) + gc.collect() + finally: + rdna2spirv.WAVE64_EMULATE = old_emulate + return spv + + +def run_cs(spv: str, threads: int, s4: int = 0, s5: int = 0, s6: int = 0, s7: int = 0) -> dict[int, int]: + pc = VSHARP + [s4 & M32, s5 & M32, s6 & M32, s7 & M32] + [0] * 24 + return si.run_workgroup( + spv, threads, threads, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=pc, memory={}, + ) + + +def bits_list(mask: int, width: int) -> list[int]: + return [1 if (mask >> i) & 1 else 0 for i in range(width)] + + +class Wave32B32LaneMaskTests(unittest.TestCase): + def test_s_not_b32_on_vcc_into_sgpr_and_scc(self): + asm = W32_BUILD_VCC + [ + "s_not_b32 s10, vcc_lo", + "s_cselect_b32 s11, 1, 0", + "v_cndmask_b32_e64 v4, 0, 1, s10", + "v_mov_b32_e32 v5, s11", + "v_lshlrev_b32_e32 v6, 2, v0", + "buffer_store_dword v4, v6, s[0:3], 0 offen", + "buffer_store_dword v5, v6, s[0:3], 0 offen offset:128", + "s_endpgm", + ] + spv = translate_cs("w32_not_sgpr", asm, 32) + for mask in (0x00000001, 0x00000000, 0xFFFFFFFF, 0xA5A500FF, 0x80000000): + with self.subTest(mask=hex(mask)): + mem = run_cs(spv, 32, s4=mask) + want_mask = (~mask) & M32 + want_scc = 1 if want_mask != 0 else 0 + got_bits = [mem[4 * i] for i in range(32)] + got_scc = [mem[128 + 4 * i] for i in range(32)] + self.assertEqual(got_bits, bits_list(want_mask, 32)) + self.assertEqual(got_scc, [want_scc] * 32) + + def test_s_not_b32_exec_lo_imm_and_sgpr(self): + for src, c in (("1", 1), ("0x0f0f00ff", 0x0F0F00FF), ("-1", M32), ("0", 0), ("s4", 0x55550001)): + with self.subTest(src=src, c=hex(c)): + asm = [ + "v_mov_b32_e32 v4, 10", + f"s_not_b32 exec_lo, {src}", + "s_cselect_b32 s11, 1, 0", + "v_mov_b32_e32 v4, 20", + "s_mov_b32 exec_lo, -1", + "v_mov_b32_e32 v5, s11", + "v_lshlrev_b32_e32 v6, 2, v0", + "buffer_store_dword v4, v6, s[0:3], 0 offen", + "buffer_store_dword v5, v6, s[0:3], 0 offen offset:128", + "s_endpgm", + ] + spv = translate_cs("w32_not_exec", asm, 32) + mem = run_cs(spv, 32, s4=c) + want_mask = (~c) & M32 + want_scc = 1 if want_mask != 0 else 0 + got_v4 = [mem[4 * i] for i in range(32)] + got_scc = [mem[128 + 4 * i] for i in range(32)] + self.assertEqual(got_v4, [20 if (want_mask >> i) & 1 else 10 for i in range(32)]) + self.assertEqual(got_scc, [want_scc] * 32) + + def test_s_not_and_or_xor_imm_into_vcc_lo(self): + cases = [ + ("s_not_b32 vcc_lo, 1", (~1) & M32), + ("s_not_b32 vcc_lo, -1", 0), + ("s_and_b32 vcc_lo, 0x0f, 0x03", 0x03), + ("s_or_b32 vcc_lo, 0x05, 0x10", 0x15), + ("s_xor_b32 vcc_lo, 0x0f, 0x03", 0x0C), + ("s_xor_b32 vcc_lo, 0x0f, 0x0f", 0), + ] + for insn, want_mask in cases: + with self.subTest(insn=insn): + asm = [ + insn, + "s_cselect_b32 s11, 1, 0", + "s_bcnt1_i32_b32 s12, vcc_lo", + "v_cndmask_b32_e64 v4, 0, 1, vcc_lo", + "v_mov_b32_e32 v5, s11", + "v_mov_b32_e32 v7, s12", + "v_lshlrev_b32_e32 v6, 2, v0", + "buffer_store_dword v4, v6, s[0:3], 0 offen", + "buffer_store_dword v5, v6, s[0:3], 0 offen offset:128", + "buffer_store_dword v7, v6, s[0:3], 0 offen offset:256", + "s_endpgm", + ] + spv = translate_cs("w32_imm_vcc", asm, 32) + mem = run_cs(spv, 32) + want_scc = 1 if want_mask != 0 else 0 + want_cnt = bin(want_mask).count("1") + self.assertEqual([mem[4 * i] for i in range(32)], bits_list(want_mask, 32)) + self.assertEqual([mem[128 + 4 * i] for i in range(32)], [want_scc] * 32) + self.assertEqual([mem[256 + 4 * i] for i in range(32)], [want_cnt] * 32) + + +class Wave64HalfMaskBitwiseTests(unittest.TestCase): + def test_exec_lo_and_exec_hi_preserve_other_half_and_vote_own_half_scc(self): + # Test s_not_b32 and all 8 binary ops writing exec_lo or exec_hi. + ops = ["s_not_b32"] + list(BIN_REFS.keys()) + # Pairs (lo_vcc, hi_vcc): include cases where lo==0 & hi!=0, lo!=0 & hi==0, single-bit, all-ones. + pairs = [ + (0x00000001, 0x00000000), + (0x00000000, 0x80000000), + (0xFFFFFFFF, 0x00000000), + (0x00000000, 0xFFFFFFFF), + (0x0F0F00FF, 0x55AA33CC), + ] + for op in ops: + for half in ("lo", "hi"): + reg_e = f"exec_{half}" + reg_v = f"vcc_{half}" + # Start with EXEC = 0x55555555_AAAAAAAA (alternating) so non-trivial ops are distinguished. + init_exec_lo, init_exec_hi = 0x55555555, 0xAAAAAAAA + insn = f"{op} {reg_e}, {reg_v}" if op == "s_not_b32" else f"{op} {reg_e}, {reg_e}, {reg_v}" + asm = W64_BUILD_VCC + [ + "s_mov_b64 s[14:15], exec", + f"s_mov_b32 exec_lo, {init_exec_lo:#x}", + f"s_mov_b32 exec_hi, {init_exec_hi:#x}", + "v_mov_b32_e32 v4, 10", + "s_mov_b64 exec, s[14:15]", + "v_mov_b32_e32 v4, 10", + f"s_mov_b32 exec_lo, {init_exec_lo:#x}", + f"s_mov_b32 exec_hi, {init_exec_hi:#x}", + insn, + "s_cselect_b32 s11, 1, 0", + "v_mov_b32_e32 v4, 20", + "s_mov_b64 exec, s[14:15]", + "v_mov_b32_e32 v5, s11", + "v_lshlrev_b32_e32 v6, 2, v0", + "buffer_store_dword v4, v6, s[0:3], 0 offen", + "buffer_store_dword v5, v6, s[0:3], 0 offen offset:256", + "s_endpgm", + ] + spv = translate_cs(f"w64_{op}_{half}", asm, 64) + for lo, hi in pairs: + with self.subTest(op=op, half=half, lo=hex(lo), hi=hex(hi)): + mem = run_cs(spv, 64, s4=lo, s5=hi) + if half == "lo": + new_h = ((~lo) & M32) if op == "s_not_b32" else BIN_REFS[op](init_exec_lo, lo) + want_exec = new_h | (init_exec_hi << 32) + else: + new_h = ((~hi) & M32) if op == "s_not_b32" else BIN_REFS[op](init_exec_hi, hi) + want_exec = init_exec_lo | (new_h << 32) + want_scc = 1 if new_h != 0 else 0 + got_v4 = [mem[4 * i] for i in range(64)] + got_scc = [mem[256 + 4 * i] for i in range(64)] + self.assertEqual(got_v4, [20 if (want_exec >> i) & 1 else 10 for i in range(64)]) + self.assertEqual(got_scc, [want_scc] * 64) + + def test_wave64_sgpr_half_mask_scc(self): + # Writing an SGPR from vcc_lo / vcc_hi (and MASK_LO s12 / MASK_HI s13) votes only over that half. + asm = W64_BUILD_VCC + [ + "s_and_b32 s10, exec_lo, vcc_lo", + "s_cselect_b32 s20, 1, 0", + "s_and_b32 s11, exec_hi, vcc_hi", + "s_cselect_b32 s21, 1, 0", + "s_not_b32 s16, s12", + "s_cselect_b32 s22, 1, 0", + "s_not_b32 s17, s13", + "s_cselect_b32 s23, 1, 0", + "v_lshlrev_b32_e32 v6, 2, v0", + "v_mov_b32_e32 v4, s20", + "buffer_store_dword v4, v6, s[0:3], 0 offen", + "v_mov_b32_e32 v4, s21", + "buffer_store_dword v4, v6, s[0:3], 0 offen offset:256", + "v_mov_b32_e32 v4, s22", + "buffer_store_dword v4, v6, s[0:3], 0 offen offset:512", + "v_mov_b32_e32 v4, s23", + "buffer_store_dword v4, v6, s[0:3], 0 offen offset:768", + "s_endpgm", + ] + spv = translate_cs("w64_sgpr_half_scc", asm, 64) + for lo, hi in ((0x00000001, 0x00000000), (0x00000000, 0x00000001), + (0xFFFFFFFF, 0x00000000), (0x00000000, 0xFFFFFFFF)): + with self.subTest(lo=hex(lo), hi=hex(hi)): + mem = run_cs(spv, 64, s4=lo, s5=hi) + self.assertEqual([mem[4 * i] for i in range(64)], [int(lo != 0)] * 64) + self.assertEqual([mem[256 + 4 * i] for i in range(64)], [int(hi != 0)] * 64) + self.assertEqual([mem[512 + 4 * i] for i in range(64)], [int(((~lo) & M32) != 0)] * 64) + self.assertEqual([mem[768 + 4 * i] for i in range(64)], [int(((~hi) & M32) != 0)] * 64) + + def test_wave64_vcc_half_const_and_cross_half_exec(self): + # 1) s_and_b32 vcc_lo, vcc_lo, 0x0f0f00ff preserves vcc_hi and sets SCC from lo only. + # 2) s_and_b32 exec_lo, exec_lo, vcc_hi applies vcc_hi bits to lanes 0..31 and preserves exec_hi. + # 3) s_cselect_b32 exec_hi, vcc_hi, 0x0000000f preserves exec_lo. + asm = W64_BUILD_VCC + [ + "s_and_b32 vcc_lo, vcc_lo, 0x0f0f00ff", + "s_cselect_b32 s20, 1, 0", + "v_cndmask_b32_e64 v4, 0, 1, vcc", + "s_mov_b64 s[14:15], exec", + "v_mov_b32_e32 v7, 10", + "s_and_b32 exec_lo, exec_lo, vcc_hi", + "s_cselect_b32 s21, 1, 0", + "v_mov_b32_e32 v7, 20", + "s_mov_b64 exec, s[14:15]", + "v_mov_b32_e32 v8, 30", + "s_cmp_eq_u32 s6, 1", + "s_cselect_b32 exec_hi, vcc_hi, 0x0000000f", + "v_mov_b32_e32 v8, 40", + "s_mov_b64 exec, s[14:15]", + "v_lshlrev_b32_e32 v6, 2, v0", + "buffer_store_dword v4, v6, s[0:3], 0 offen", + "v_mov_b32_e32 v5, s20", + "buffer_store_dword v5, v6, s[0:3], 0 offen offset:256", + "buffer_store_dword v7, v6, s[0:3], 0 offen offset:512", + "v_mov_b32_e32 v5, s21", + "buffer_store_dword v5, v6, s[0:3], 0 offen offset:768", + "buffer_store_dword v8, v6, s[0:3], 0 offen offset:1024", + "s_endpgm", + ] + spv = translate_cs("w64_vcc_const_cross", asm, 64) + for lo, hi, s6 in ((0xF0F0FF00, 0x00010005, 0), (0xFFFFFFFF, 0x80000001, 1), (0x00000001, 0x00000000, 1)): + with self.subTest(lo=hex(lo), hi=hex(hi), s6=s6): + mem = run_cs(spv, 64, s4=lo, s5=hi, s6=s6) + vcc_lo = lo & 0x0F0F00FF + vcc64 = vcc_lo | (hi << 32) + self.assertEqual([mem[4 * i] for i in range(64)], bits_list(vcc64, 64)) + self.assertEqual([mem[256 + 4 * i] for i in range(64)], [int(vcc_lo != 0)] * 64) + exec_cross = hi | (M32 << 32) + self.assertEqual([mem[512 + 4 * i] for i in range(64)], + [20 if (exec_cross >> i) & 1 else 10 for i in range(64)]) + self.assertEqual([mem[768 + 4 * i] for i in range(64)], [int(hi != 0)] * 64) + csel_hi = hi if s6 == 1 else 0x0000000F + exec_csel = M32 | (csel_hi << 32) + self.assertEqual([mem[1024 + 4 * i] for i in range(64)], + [40 if (exec_csel >> i) & 1 else 30 for i in range(64)]) + + def test_wave64_vcc_half_after_whole_vcc_const_write(self): + # Regression for @LloydNicholson's RX 9060 XT finding: s_mov_b64 vcc, -1 (or 0) must keep vcc + # in the lane-mask state so a subsequent 32-bit half op on vcc_lo / vcc_hi extracts per-lane bits + # and preserves the other half. + cases = [ + (["s_mov_b64 vcc, -1", "s_and_b32 vcc_lo, vcc_lo, 0xf0"], 0x000000F0 | (M32 << 32), 1), + (["s_mov_b64 vcc, 0", "s_or_b32 vcc_hi, vcc_hi, 0x0f"], 0x0000000F << 32, 1), + (["s_mov_b64 vcc, -1", "s_not_b32 vcc_hi, 0xfffffff0"], M32 | (0x0000000F << 32), 1), + (["s_mov_b64 vcc, -1", "s_and_b32 vcc_lo, vcc_lo, 0"], M32 << 32, 0), + ] + for idx, (setup, want_vcc, want_scc) in enumerate(cases): + with self.subTest(setup=setup): + asm = setup + [ + "s_cselect_b32 s20, 1, 0", + "v_cndmask_b32_e64 v4, 0, 1, vcc", + "v_mov_b32_e32 v5, s20", + "v_lshlrev_b32_e32 v6, 2, v0", + "buffer_store_dword v4, v6, s[0:3], 0 offen", + "buffer_store_dword v5, v6, s[0:3], 0 offen offset:256", + "s_endpgm", + ] + spv = translate_cs(f"w64_vcc_const_init_{idx}", asm, 64) + mem = run_cs(spv, 64) + self.assertEqual([mem[4 * i] for i in range(64)], bits_list(want_vcc, 64)) + self.assertEqual([mem[256 + 4 * i] for i in range(64)], [want_scc] * 64) + + def test_spirv_val_native_and_wave64_emulate(self): + spirv_as = shutil.which("spirv-as") + spirv_val = shutil.which("spirv-val") + if not (spirv_as and spirv_val): + self.skipTest("spirv-as / spirv-val not on PATH") + asm_w64 = W64_BUILD_VCC + [ + "s_mov_b64 s[14:15], exec", + "s_not_b32 exec_lo, vcc_lo", + "s_and_b32 exec_hi, exec_hi, 0x0f0f00ff", + "s_or_b32 exec_lo, exec_lo, vcc_hi", + "s_xor_b32 vcc_hi, vcc_hi, 0x55555555", + "s_cselect_b32 exec_hi, vcc_hi, 0x000000ff", + "s_mov_b64 exec, s[14:15]", + "s_endpgm", + ] + for emulate in (False, True): + spv = translate_cs(f"w64_val_{int(emulate)}", asm_w64, 64, emulate=emulate) + with tempfile.TemporaryDirectory() as tmp: + spvasm = os.path.join(tmp, "m.spvasm") + spvbin = os.path.join(tmp, "m.spv") + with open(spvasm, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", spvasm, "-o", spvbin], + capture_output=True, text=True) + self.assertEqual(r1.returncode, 0, r1.stderr) + r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", spvbin], + capture_output=True, text=True) + self.assertEqual(r2.returncode, 0, r2.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_salu_cmp_signed.py b/tests/semantic/test_salu_cmp_signed.py new file mode 100644 index 000000000..33149a6cc --- /dev/null +++ b/tests/semantic/test_salu_cmp_signed.py @@ -0,0 +1,118 @@ +"""Semantic interpreter tests for the register-register scalar compares s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}. + +RDNA2 ISA (SOPC): SCC = S0 S1, compared as signed 32-bit values for _i32 and unsigned for _u32. Only eq, lg, +gt, ge, lt and le on _u32 and gt/lt on _i32 had a translation test before; the signed ordering of operands that differ +in bit 31 (0x7FFFFFFF vs 0x80000000, -1 vs 0) is what a wrong signedness gets wrong. +Each case sets SCC, copies it with s_cselect_b32 into one bit of a mask, and the 32-bit mask leaves through exp as two +16-bit halves ORed into 0x40000000 (no NaN or denormal export pattern). The operands are set with s_mov_b32. The +expected bits come from plain-Python integer comparisons. +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +sys.path.insert(0, TOOLS_DIR) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 31 else x + + +CONDS = { + "eq": lambda a, b: a == b, "lg": lambda a, b: a != b, "gt": lambda a, b: a > b, + "ge": lambda a, b: a >= b, "lt": lambda a, b: a < b, "le": lambda a, b: a <= b, +} + +PAIRS = [(0, 0), (1, 0), (0, 1), (M32, 0), (0, M32), (M32, 1), (1, M32), (0x7FFFFFFF, 0x80000000), + (0x80000000, 0x7FFFFFFF), (0x80000000, 0x80000000), (0x80000000, M32), (M32, M32), (5, 5), + (0x7FFFFFFF, 0x7FFFFFFF), (0xFFFFFFFE, M32), (0x00010000, 0x0000FFFF)] + +_TMP = None +_SRC = None + + +def setUpModule(): + global _TMP, _SRC + _TMP = tempfile.TemporaryDirectory() + d = os.path.join(_TMP.name, "disasm") + os.mkdir(d) + _SRC = os.path.join(d, "ps_salu_cmp.s") + with open(os.path.join(_TMP.name, "ps_salu_cmp.dxbc"), "wb") as f: + f.write(STUB_DXBC) + + +def tearDownModule(): + global _TMP + if _TMP is not None: + _TMP.cleanup() + _TMP = None + + +def run_mask(lines): + """Run lines that leave their result bits in s5; return s5.""" + if _TMP is None: + setUpModule() + tail = ["s_and_b32 s10, s5, 0xffff", "s_lshr_b32 s11, s5, 16", "s_or_b32 s10, s10, 0x40000000", + "s_or_b32 s11, s11, 0x40000000", "v_mov_b32 v0, s10", "v_mov_b32 v1, s11"] + asm = ("; test_salu_cmp_signed\n\ts_mov_b32 s5, 0\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) + + "\texp mrt0 v0, v1, v1, v1 done vm\n\ts_endpgm\n") + with open(_SRC, "w", encoding="utf-8") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(_SRC) + lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] + assert lo >> 16 == hi >> 16 == 0x4000, (hex(lo), hex(hi)) + return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 + + +def load(reg, value, dynamic=False): + return [f"s_mov_b32 s{reg}, {value & M32:#x}"] + + +def collect(k): + return [f"s_cselect_b32 s4, 1, 0", f"s_lshl_b32 s4, s4, {k}", "s_or_b32 s5, s5, s4"] + + +def bits(flags): + return sum(1 << i for i, f in enumerate(flags) if f) + + +class ScalarCompareTests(unittest.TestCase): + def check(self, make_lines, expect, label): + lines = [] + for k in range(len(expect)): + lines += make_lines(k, False) + with self.subTest(case=label): + self.assertEqual(run_mask(lines), bits(expect), label) + + def test_s_cmp_i32_u32(self): + for ty in ("i32", "u32"): + conv = s32 if ty == "i32" else (lambda x: x & M32) + for cond, fn in CONDS.items(): + def make(k, dynamic, ty=ty, cond=cond): + a, b = PAIRS[k] + return (load(2, a, dynamic) + load(3, b, dynamic) + + [f"s_cmp_{cond}_{ty} s2, s3"] + collect(k)) + expect = [fn(conv(a), conv(b)) for a, b in PAIRS] + self.check(make, expect, f"s_cmp_{cond}_{ty}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_salu_nand_nor_saveexec_b64.py b/tests/semantic/test_salu_nand_nor_saveexec_b64.py index a00e26748..f9d5ca310 100644 --- a/tests/semantic/test_salu_nand_nor_saveexec_b64.py +++ b/tests/semantic/test_salu_nand_nor_saveexec_b64.py @@ -1,1329 +1,46 @@ -"""Semantic reference oracle and verification for RDNA2 s_nand_saveexec_b64 and s_nor_saveexec_b64. +"""s_nand_saveexec_b64 and s_nor_saveexec_b64 through the translator, on every lane of a wave64. -RDNA2 SALU 64-bit SaveExec Instructions: - s_nand_saveexec_b64: - SDST = EXEC - EXEC = ~(SSRC0 & EXEC) & 0xFFFFFFFFFFFFFFFF - SCC = 1 if EXEC != 0 else 0 +RDNA2 ISA, SOP1: + s_nand_saveexec_b64: D = EXEC; EXEC = ~(S0 & EXEC); SCC = (EXEC != 0). + s_nor_saveexec_b64: D = EXEC; EXEC = ~(S0 | EXEC); SCC = (EXEC != 0). - s_nor_saveexec_b64: - SDST = EXEC - EXEC = ~(SSRC0 | EXEC) & 0xFFFFFFFFFFFFFFFF - SCC = 1 if EXEC != 0 else 0 - -Phase 1: Reference mathematical oracle and architectural model. +Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in +tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an +SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of +this name ran a self-built interpreter and never called the translator. """ -from __future__ import annotations - -import math -import struct +import os +import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from typing import List, Optional, Tuple, Union, Dict, Any -# Bitwise 32-bit and 64-bit architectural masks -MASK32: int = 0xFFFF_FFFF -MASK64: int = 0xFFFF_FFFF_FFFF_FFFF -ALL64: int = 0xFFFF_FFFF_FFFF_FFFF - -# IEEE 754 binary64 (double precision) architectural constants -SIGN_MASK_F64: int = 0x8000_0000_0000_0000 -EXP_MASK_F64: int = 0x7FF0_0000_0000_0000 -FRAC_MASK_F64: int = 0x000F_FFFF_FFFF_FFFF -QNAN_BIT_F64: int = 0x0008_0000_0000_0000 -CANONICAL_QNAN_F64: int = 0x7FF8_0000_0000_0000 - -POS_ZERO_F64: int = 0x0000_0000_0000_0000 -NEG_ZERO_F64: int = 0x8000_0000_0000_0000 -POS_INF_F64: int = 0x7FF0_0000_0000_0000 -NEG_INF_F64: int = 0xFFF0_0000_0000_0000 - - -def words_to_u64(lo: int, hi: int) -> int: - """Combine two 32-bit scalar register words (lo, hi) into a 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def u64_to_words(val: int) -> Tuple[int, int]: - """Split a 64-bit integer into two 32-bit scalar register words (lo, hi).""" - return val & MASK32, (val >> 32) & MASK32 - - -def f64_to_bits(val: float) -> int: - """Convert a Python float (IEEE 754 double) to 64-bit integer bits.""" - return struct.unpack(" float: - """Convert 64-bit integer bits to a Python float (IEEE 754 double).""" - return struct.unpack(" int: - """Return the number of set bits in a 64-bit integer.""" - return bin(val & MASK64).count("1") - - -def find_first_one_64(val: int) -> int: - """Find the lowest set bit index [0..63] in a 64-bit integer, or -1 if zero.""" - v = val & MASK64 - if v == 0: - return -1 - return (v & -v).bit_length() - 1 - - -# ============================================================================== -# Reference Mathematical Oracles -# ============================================================================== - -def oracle_s_nand_b64(s0: int, s1: int) -> int: - """Reference mathematical oracle for 64-bit bitwise NAND: D = ~(s0 & s1).""" - return (~(s0 & s1)) & MASK64 - - -def oracle_s_nor_b64(s0: int, s1: int) -> int: - """Reference mathematical oracle for 64-bit bitwise NOR: D = ~(s0 | s1).""" - return (~(s0 | s1)) & MASK64 - - -def oracle_s_nand_saveexec_b64(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Reference architectural oracle for RDNA2 s_nand_saveexec_b64. - - Semantics: - saved_dst = old_exec - new_exec = ~(ssrc0 & old_exec) & 0xFFFFFFFFFFFFFFFF - scc = 1 if new_exec != 0 else 0 - - Returns: - (saved_dst, new_exec, scc) - """ - saved_dst = old_exec & MASK64 - new_exec = (~(ssrc0 & old_exec)) & MASK64 - scc = 1 if new_exec != 0 else 0 - return saved_dst, new_exec, scc - - -def oracle_s_nor_saveexec_b64(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Reference architectural oracle for RDNA2 s_nor_saveexec_b64. - - Semantics: - saved_dst = old_exec - new_exec = ~(ssrc0 | old_exec) & 0xFFFFFFFFFFFFFFFF - scc = 1 if new_exec != 0 else 0 - - Returns: - (saved_dst, new_exec, scc) - """ - saved_dst = old_exec & MASK64 - new_exec = (~(ssrc0 | old_exec)) & MASK64 - scc = 1 if new_exec != 0 else 0 - return saved_dst, new_exec, scc - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class Opcode(str, Enum): - S_NAND_SAVEEXEC_B64 = "s_nand_saveexec_b64" - S_NOR_SAVEEXEC_B64 = "s_nor_saveexec_b64" - - -class RegType(Enum): - SGPR = auto() - EXEC = auto() - VCC = auto() - SCC = auto() - - -@dataclass(frozen=True) -class Reg64: - """Represents a 64-bit architectural register (SGPR pair, EXEC, or VCC).""" - reg_type: RegType - index: int = 0 - - def __post_init__(self) -> None: - if self.reg_type == RegType.SGPR: - if not (0 <= self.index <= 254): - raise ValueError(f"SGPR pair base index {self.index} out of range [0, 254]") - elif self.reg_type in (RegType.EXEC, RegType.VCC, RegType.SCC): - if self.index != 0: - raise ValueError(f"Special register {self.reg_type.name} does not use non-zero index") - - @property - def lo_reg(self) -> int: - return self.index - - @property - def hi_reg(self) -> int: - return self.index + 1 - - @property - def name(self) -> str: - if self.reg_type == RegType.SGPR: - return f"s[{self.index}:{self.index + 1}]" - elif self.reg_type == RegType.EXEC: - return "exec" - elif self.reg_type == RegType.VCC: - return "vcc" - elif self.reg_type == RegType.SCC: - return "scc" - return f"unk_{self.reg_type.name}" - - -@dataclass(frozen=True) -class Literal64: - """Represents a 64-bit unsigned literal constant or bitmask.""" - value: int - - def __post_init__(self) -> None: - if not (0 <= self.value <= MASK64): - raise ValueError(f"Literal64 value {self.value:#x} out of 64-bit range") - - @property - def name(self) -> str: - return f"{self.value:#018x}" - - -Operand64 = Union[Reg64, Literal64] - - -@dataclass(frozen=True) -class SaveExecInstruction: - """Symbolic AST node representing a 64-bit saveexec instruction.""" - opcode: Opcode - sdst: Reg64 - ssrc0: Operand64 - - def __post_init__(self) -> None: - if self.sdst.reg_type not in (RegType.SGPR, RegType.EXEC): - raise TypeError(f"Destination sdst must be SGPR or EXEC, got {self.sdst.reg_type}") - if isinstance(self.ssrc0, Reg64): - if self.ssrc0.reg_type not in (RegType.SGPR, RegType.EXEC, RegType.VCC): - raise TypeError(f"Source ssrc0 register must be SGPR, EXEC, or VCC, got {self.ssrc0.reg_type}") - - def disassemble(self) -> str: - return f"{self.opcode.value} {self.sdst.name}, {self.ssrc0.name}" - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural scalar register file and status registers for a wavefront.""" - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - exec_mask: int = field(default=ALL64) - vcc: int = 0 - scc: int = 0 - - def get_sgpr64(self, index: int) -> int: - return words_to_u64(self.sgprs[index], self.sgprs[index + 1]) - - def set_sgpr64(self, index: int, val: int) -> None: - lo, hi = u64_to_words(val) - self.sgprs[index] = lo - self.sgprs[index + 1] = hi - - def read_reg64(self, reg: Reg64) -> int: - if reg.reg_type == RegType.SGPR: - return self.get_sgpr64(reg.index) - elif reg.reg_type == RegType.EXEC: - return self.exec_mask - elif reg.reg_type == RegType.VCC: - return self.vcc - elif reg.reg_type == RegType.SCC: - return self.scc - raise ValueError(f"Unknown register type: {reg.reg_type}") - - def write_reg64(self, reg: Reg64, val: int) -> None: - if reg.reg_type == RegType.SGPR: - self.set_sgpr64(reg.index, val) - elif reg.reg_type == RegType.EXEC: - self.exec_mask = val & MASK64 - elif reg.reg_type == RegType.VCC: - self.vcc = val & MASK64 - elif reg.reg_type == RegType.SCC: - self.scc = val & 1 - else: - raise ValueError(f"Unknown register type: {reg.reg_type}") - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 saveexec operations.""" - - def resolve_operand(self, op: Operand64, state: ScalarMachineState) -> int: - if isinstance(op, Reg64): - return state.read_reg64(op) - elif isinstance(op, Literal64): - return op.value - raise TypeError(f"Unsupported operand type: {type(op)}") - - def step(self, instr: SaveExecInstruction, state: ScalarMachineState) -> Tuple[int, int, int]: - # Atomic read phase - s0 = self.resolve_operand(instr.ssrc0, state) - old_exec = state.exec_mask - - # Computation phase - if instr.opcode == Opcode.S_NAND_SAVEEXEC_B64: - saved, new_exec, scc = oracle_s_nand_saveexec_b64(s0, old_exec) - elif instr.opcode == Opcode.S_NOR_SAVEEXEC_B64: - saved, new_exec, scc = oracle_s_nor_saveexec_b64(s0, old_exec) - else: - raise ValueError(f"Unsupported opcode: {instr.opcode}") - - # Write-back phase - state.write_reg64(instr.sdst, saved) - state.exec_mask = new_exec - state.scc = scc - - return saved, new_exec, scc - - -# ============================================================================== -# SIMD Multi-Lane Divergence and 32/64-Bit EXEC Masking -# ============================================================================== - -@dataclass -class SIMDWaveState: - """Architectural state for a SIMD wavefront (Wave32 or Wave64).""" - num_lanes: int = 64 - exec_mask: Optional[int] = None - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - vcc: int = 0 - scc: int = 0 - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - else: - lane_mask = (1 << self.num_lanes) - 1 - self.exec_mask &= lane_mask - - def get_vgpr(self, lane: int, reg_idx: int) -> int: - return self.vgprs[lane][reg_idx] - - def set_vgpr(self, lane: int, reg_idx: int, val: int) -> None: - self.vgprs[lane][reg_idx] = val & MASK32 - - def get_sgpr64(self, idx: int) -> int: - return words_to_u64(self.sgprs[idx], self.sgprs[idx + 1]) - - def set_sgpr64(self, idx: int, val: int) -> None: - lo, hi = u64_to_words(val) - self.sgprs[idx] = lo - self.sgprs[idx + 1] = hi - - def is_lane_active(self, lane: int) -> bool: - return bool(self.exec_mask & (1 << lane)) - - -class SIMDExecutionEngine: - """Simulates wave execution across divergent SIMD lanes governed by EXEC masking.""" - - def resolve_operand(self, op: Operand64, state: SIMDWaveState) -> int: - if isinstance(op, Reg64): - if op.reg_type == RegType.SGPR: - return state.get_sgpr64(op.index) - elif op.reg_type == RegType.EXEC: - return state.exec_mask - elif op.reg_type == RegType.VCC: - return state.vcc - elif op.reg_type == RegType.SCC: - return state.scc - elif isinstance(op, Literal64): - return op.value - raise TypeError(f"Unsupported operand type: {type(op)}") - - def execute_saveexec(self, instr: SaveExecInstruction, state: SIMDWaveState) -> Tuple[int, int, int]: - s0 = self.resolve_operand(instr.ssrc0, state) - old_exec = state.exec_mask - lane_mask = (1 << state.num_lanes) - 1 - - if instr.opcode == Opcode.S_NAND_SAVEEXEC_B64: - saved = old_exec - new_exec = (~(s0 & old_exec)) & lane_mask - scc = 1 if new_exec != 0 else 0 - elif instr.opcode == Opcode.S_NOR_SAVEEXEC_B64: - saved = old_exec - new_exec = (~(s0 | old_exec)) & lane_mask - scc = 1 if new_exec != 0 else 0 - else: - raise ValueError(f"Unsupported opcode: {instr.opcode}") - - if instr.sdst.reg_type == RegType.SGPR: - state.set_sgpr64(instr.sdst.index, saved) - elif instr.sdst.reg_type == RegType.EXEC: - pass # Overwritten by new_exec below - - state.exec_mask = new_exec - state.scc = scc - return saved, new_exec, scc - - def execute_valu_mov( - self, - dst_vgpr: int, - src_val: Union[int, List[int]], - state: SIMDWaveState, - ) -> List[bool]: - """Simulate masked VALU write: only lanes active in state.exec_mask are updated.""" - written = [False] * state.num_lanes - for lane in range(state.num_lanes): - if state.is_lane_active(lane): - val = src_val[lane] if isinstance(src_val, list) else src_val - state.set_vgpr(lane, dst_vgpr, val) - written[lane] = True - return written - - -# ============================================================================== -# Phase 1 Unit Tests: Oracle and Architectural Model -# ============================================================================== - -class TestOracleAndModel(unittest.TestCase): - """Verify bitwise mathematical properties and reference oracle definitions.""" - - def test_truth_table_exhaustive(self) -> None: - """Exhaustive 2-bit truth table verification for NAND and NOR.""" - # Bit combinations: (0,0), (0,1), (1,0), (1,1) - # NAND truth table: ~(0&0)=1, ~(0&1)=1, ~(1&0)=1, ~(1&1)=0 - self.assertEqual(oracle_s_nand_b64(0, 0) & 1, 1) - self.assertEqual(oracle_s_nand_b64(0, 1) & 1, 1) - self.assertEqual(oracle_s_nand_b64(1, 0) & 1, 1) - self.assertEqual(oracle_s_nand_b64(1, 1) & 1, 0) - - # NOR truth table: ~(0|0)=1, ~(0|1)=0, ~(1|0)=0, ~(1|1)=0 - self.assertEqual(oracle_s_nor_b64(0, 0) & 1, 1) - self.assertEqual(oracle_s_nor_b64(0, 1) & 1, 0) - self.assertEqual(oracle_s_nor_b64(1, 0) & 1, 0) - self.assertEqual(oracle_s_nor_b64(1, 1) & 1, 0) - - def test_nand_identities(self) -> None: - """Verify identity, complementation, and zero absorption for NAND.""" - val = 0x0123_4567_89AB_CDEF - # NAND with 0 yields all ones (111...1) - self.assertEqual(oracle_s_nand_b64(val, 0), ALL64) - self.assertEqual(oracle_s_nand_b64(0, val), ALL64) - # NAND with all ones yields bitwise NOT - self.assertEqual(oracle_s_nand_b64(val, ALL64), (~val) & MASK64) - self.assertEqual(oracle_s_nand_b64(ALL64, val), (~val) & MASK64) - # NAND with itself yields bitwise NOT - self.assertEqual(oracle_s_nand_b64(val, val), (~val) & MASK64) - - def test_nor_identities(self) -> None: - """Verify identity, complementation, and zero absorption for NOR.""" - val = 0x0123_4567_89AB_CDEF - # NOR with 0 yields bitwise NOT - self.assertEqual(oracle_s_nor_b64(val, 0), (~val) & MASK64) - self.assertEqual(oracle_s_nor_b64(0, val), (~val) & MASK64) - # NOR with all ones yields 0 - self.assertEqual(oracle_s_nor_b64(val, ALL64), 0) - self.assertEqual(oracle_s_nor_b64(ALL64, val), 0) - # NOR with itself yields bitwise NOT - self.assertEqual(oracle_s_nor_b64(val, val), (~val) & MASK64) - - def test_de_morgan_duality(self) -> None: - """Verify De Morgan's laws: ~(A & B) == ~A | ~B and ~(A | B) == ~A & ~B.""" - patterns = [ - (0xAAAA_AAAA_AAAA_AAAA, 0x5555_5555_5555_5555), - (0xFFFF_0000_FFFF_0000, 0x0000_FFFF_0000_FFFF), - (0x1234_5678_9ABC_DEF0, 0xFEDC_BA98_7654_3210), - (0x8000_0000_0000_0000, 0x0000_0000_0000_0001), - ] - for a, b in patterns: - not_a = (~a) & MASK64 - not_b = (~b) & MASK64 - # NAND duality: ~(A & B) == ~A | ~B - self.assertEqual(oracle_s_nand_b64(a, b), (not_a | not_b) & MASK64) - # NOR duality: ~(A | B) == ~A & ~B - self.assertEqual(oracle_s_nor_b64(a, b), (not_a & not_b) & MASK64) - - def test_nand_saveexec_oracle_semantics(self) -> None: - """Verify s_nand_saveexec_b64 preserves old EXEC in SDST and computes correct new EXEC and SCC.""" - old_exec = 0xFFFF_0000_FFFF_0000 - ssrc0 = 0xAAAA_AAAA_AAAA_AAAA - saved, new_exec, scc = oracle_s_nand_saveexec_b64(ssrc0, old_exec) - - self.assertEqual(saved, old_exec) - expected_new_exec = (~(ssrc0 & old_exec)) & MASK64 - self.assertEqual(new_exec, expected_new_exec) - self.assertEqual(scc, 1 if expected_new_exec != 0 else 0) - - # Test case where new EXEC becomes 0: - # ~(ssrc0 & old_exec) == 0 iff (ssrc0 & old_exec) == ALL64 - saved_zero, new_exec_zero, scc_zero = oracle_s_nand_saveexec_b64(ALL64, ALL64) - self.assertEqual(saved_zero, ALL64) - self.assertEqual(new_exec_zero, 0) - self.assertEqual(scc_zero, 0) - - def test_nor_saveexec_oracle_semantics(self) -> None: - """Verify s_nor_saveexec_b64 preserves old EXEC in SDST and computes correct new EXEC and SCC.""" - old_exec = 0x0000_0000_FFFF_FFFF - ssrc0 = 0xFFFF_0000_0000_0000 - saved, new_exec, scc = oracle_s_nor_saveexec_b64(ssrc0, old_exec) - - self.assertEqual(saved, old_exec) - expected_new_exec = (~(ssrc0 | old_exec)) & MASK64 - self.assertEqual(new_exec, expected_new_exec) - self.assertEqual(scc, 1 if expected_new_exec != 0 else 0) - - # Test case where new EXEC becomes 0: - # ~(ssrc0 | old_exec) == 0 whenever ssrc0 | old_exec == ALL64 - saved_zero, new_exec_zero, scc_zero = oracle_s_nor_saveexec_b64(0xFFFF_FFFF_0000_0000, 0x0000_0000_FFFF_FFFF) - self.assertEqual(saved_zero, 0x0000_0000_FFFF_FFFF) - self.assertEqual(new_exec_zero, 0) - self.assertEqual(scc_zero, 0) - - # Test case where old_exec is 0 and ssrc0 is 0: - # ~(0 | 0) = ALL64, so new EXEC is ALL64, SCC is 1 - saved_full, new_exec_full, scc_full = oracle_s_nor_saveexec_b64(0, 0) - self.assertEqual(saved_full, 0) - self.assertEqual(new_exec_full, ALL64) - self.assertEqual(scc_full, 1) - - -# ============================================================================== -# Phase 2 Unit Tests: Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class TestSymbolicAST(unittest.TestCase): - """Verify symbolic AST construction, typed operand expressions, and disassembly.""" - - def test_reg64_properties(self) -> None: - s0_1 = Reg64(RegType.SGPR, 0) - self.assertEqual(s0_1.lo_reg, 0) - self.assertEqual(s0_1.hi_reg, 1) - self.assertEqual(s0_1.name, "s[0:1]") - - exec_reg = Reg64(RegType.EXEC) - self.assertEqual(exec_reg.name, "exec") - - vcc_reg = Reg64(RegType.VCC) - self.assertEqual(vcc_reg.name, "vcc") - - def test_literal64_properties(self) -> None: - lit = Literal64(0x1234_5678_9ABC_DEF0) - self.assertEqual(lit.value, 0x1234_5678_9ABC_DEF0) - self.assertEqual(lit.name, "0x123456789abcdef0") - - def test_ast_instruction_disassembly(self) -> None: - instr_nand = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 4), - ssrc0=Reg64(RegType.SGPR, 6), - ) - self.assertEqual(instr_nand.disassemble(), "s_nand_saveexec_b64 s[4:5], s[6:7]") - - instr_nor_lit = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 0), - ssrc0=Literal64(0x0000_FFFF_0000_FFFF), - ) - self.assertEqual(instr_nor_lit.disassemble(), "s_nor_saveexec_b64 s[0:1], 0x0000ffff0000ffff") - - instr_nor_vcc = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.EXEC), - ssrc0=Reg64(RegType.VCC), - ) - self.assertEqual(instr_nor_vcc.disassemble(), "s_nor_saveexec_b64 exec, vcc") - - def test_ast_immutability_and_hash(self) -> None: - instr1 = SaveExecInstruction(Opcode.S_NAND_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Reg64(RegType.SGPR, 2)) - instr2 = SaveExecInstruction(Opcode.S_NAND_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Reg64(RegType.SGPR, 2)) - self.assertEqual(instr1, instr2) - s = {instr1, instr2} - self.assertEqual(len(s), 1) - - -# ============================================================================== -# Phase 3 Unit Tests: Deterministic Scalar Instruction Interpreter -# ============================================================================== - -class TestScalarInterpreter(unittest.TestCase): - """Verify deterministic execution and state transitions of ScalarInterpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_nand_saveexec_step(self) -> None: - # Initial: EXEC = 0xFFFF_FFFF_0000_0000, s[2:3] = 0xAAAA_AAAA_AAAA_AAAA - self.state.exec_mask = 0xFFFF_FFFF_0000_0000 - self.state.set_sgpr64(2, 0xAAAA_AAAA_AAAA_AAAA) - - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 4), - ssrc0=Reg64(RegType.SGPR, 2), - ) - - saved, new_exec, scc = self.interp.step(instr, self.state) - - # Saved destination s[4:5] must receive old EXEC - self.assertEqual(saved, 0xFFFF_FFFF_0000_0000) - self.assertEqual(self.state.get_sgpr64(4), 0xFFFF_FFFF_0000_0000) - - # New EXEC = ~(0xAAAA_AAAA_AAAA_AAAA & 0xFFFF_FFFF_0000_0000) = ~(0xAAAA_AAAA_0000_0000) - expected_new_exec = (~(0xAAAA_AAAA_0000_0000)) & MASK64 - self.assertEqual(new_exec, expected_new_exec) - self.assertEqual(self.state.exec_mask, expected_new_exec) - self.assertEqual(scc, 1) - self.assertEqual(self.state.scc, 1) - - def test_nor_saveexec_step(self) -> None: - # Initial: EXEC = 0x0000_0000_FFFF_FFFF, literal = 0x0000_FFFF_0000_0000 - self.state.exec_mask = 0x0000_0000_FFFF_FFFF - - instr = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 0), - ssrc0=Literal64(0x0000_FFFF_0000_0000), - ) - - saved, new_exec, scc = self.interp.step(instr, self.state) - - # Saved destination s[0:1] must receive old EXEC - self.assertEqual(saved, 0x0000_0000_FFFF_FFFF) - self.assertEqual(self.state.get_sgpr64(0), 0x0000_0000_FFFF_FFFF) - - # New EXEC = ~(0x0000_FFFF_0000_0000 | 0x0000_0000_FFFF_FFFF) = ~(0x0000_FFFF_FFFF_FFFF) - expected_new_exec = (~(0x0000_FFFF_FFFF_FFFF)) & MASK64 - self.assertEqual(new_exec, expected_new_exec) - self.assertEqual(self.state.exec_mask, expected_new_exec) - self.assertEqual(scc, 1) - self.assertEqual(self.state.scc, 1) - - def test_step_determinism(self) -> None: - """Run identical step repeatedly to guarantee bit-level determinism.""" - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 6), - ssrc0=Literal64(0x0123_4567_89AB_CDEF), - ) - - results = [] - for _ in range(5): - st = ScalarMachineState(exec_mask=0xF0F0_F0F0_F0F0_F0F0) - res = self.interp.step(instr, st) - results.append((res, st.get_sgpr64(6), st.exec_mask, st.scc)) - - for r in results[1:]: - self.assertEqual(r, results[0]) - - def test_chained_saveexec_sequence(self) -> None: - """Sequential saveexec pipeline verifying state accumulation.""" - self.state.exec_mask = ALL64 - # 1. NOR with 0x0000_0000_FFFF_FFFF -> new_exec = ~(ALL64 | ...) = 0 - instr1 = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 10), - ssrc0=Literal64(0x0000_0000_FFFF_FFFF), - ) - saved1, exec1, scc1 = self.interp.step(instr1, self.state) - self.assertEqual(saved1, ALL64) - self.assertEqual(exec1, 0) - self.assertEqual(scc1, 0) - - # 2. NAND with 0x5555_5555_5555_5555 -> new_exec = ~(... & 0) = ALL64 - instr2 = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 12), - ssrc0=Literal64(0x5555_5555_5555_5555), - ) - saved2, exec2, scc2 = self.interp.step(instr2, self.state) - self.assertEqual(saved2, 0) - self.assertEqual(exec2, ALL64) - self.assertEqual(scc2, 1) - - -# ============================================================================== -# Phase 4 Unit Tests: SIMD Multi-Lane Divergence and 32/64-Bit EXEC Masking -# ============================================================================== - -class TestSIMDDivergenceAndMasking(unittest.TestCase): - """Verify SIMD lane masking, multi-lane divergence, and inactive lane preservation.""" - - def setUp(self) -> None: - self.engine = SIMDExecutionEngine() - - def test_wave64_nand_divergence(self) -> None: - state = SIMDWaveState(num_lanes=64) - # Initialize VGPR 5 to a baseline pattern across all lanes - for lane in range(64): - state.set_vgpr(lane, 5, 0xDEAD0000 + lane) - - # Set initial EXEC to alternating pattern - state.exec_mask = 0x5555_5555_5555_5555 # Even lanes active - # SSRC0 mask = 0x3333_3333_3333_3333 (pairs of lanes) - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 8), - ssrc0=Literal64(0x3333_3333_3333_3333), - ) - - saved, new_exec, scc = self.engine.execute_saveexec(instr, state) - self.assertEqual(saved, 0x5555_5555_5555_5555) - - # Expected new EXEC: ~(0x3333_3333_3333_3333 & 0x5555_5555_5555_5555) - # 0x3333... & 0x5555... = 0x1111_1111_1111_1111 - # ~(0x1111...) = 0xEEEE_EEEE_EEEE_EEEE - expected_new_exec = 0xEEEE_EEEE_EEEE_EEEE - self.assertEqual(new_exec, expected_new_exec) - self.assertEqual(state.exec_mask, expected_new_exec) - self.assertEqual(scc, 1) - - # Execute VALU write to VGPR 5 with new value 0xBEEF0000 + lane - written = self.engine.execute_valu_mov(5, [0xBEEF0000 + l for l in range(64)], state) - - # Verify that only lanes enabled in new_exec received the new value! - for lane in range(64): - if expected_new_exec & (1 << lane): - self.assertTrue(written[lane]) - self.assertEqual(state.get_vgpr(lane, 5), 0xBEEF0000 + lane) - else: - self.assertFalse(written[lane]) - self.assertEqual(state.get_vgpr(lane, 5), 0xDEAD0000 + lane) - - def test_wave64_nor_half_wave_divergence(self) -> None: - state = SIMDWaveState(num_lanes=64) - for lane in range(64): - state.set_vgpr(lane, 12, 0xCAFE0000 + lane) - - # Old EXEC is lower 32 lanes only - state.exec_mask = 0x0000_0000_FFFF_FFFF - # SSRC0 covers upper 32 lanes - instr = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 16), - ssrc0=Literal64(0xFFFF_FFFF_0000_0000), - ) - - saved, new_exec, scc = self.engine.execute_saveexec(instr, state) - self.assertEqual(saved, 0x0000_0000_FFFF_FFFF) - # ~(0xFFFF_FFFF_0000_0000 | 0x0000_0000_FFFF_FFFF) = ~(ALL64) = 0 - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - - # Since all lanes turned off, VALU write should touch 0 lanes - written = self.engine.execute_valu_mov(12, 0x12345678, state) - self.assertFalse(any(written)) - for lane in range(64): - self.assertEqual(state.get_vgpr(lane, 12), 0xCAFE0000 + lane) - - def test_wave32_divergence_and_masking(self) -> None: - state = SIMDWaveState(num_lanes=32) - for lane in range(32): - state.set_vgpr(lane, 7, 0xAA00 + lane) - - state.exec_mask = 0x0000_FFFF # lanes 0..15 - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 2), - ssrc0=Literal64(0x00FF_00FF), - ) - - saved, new_exec, scc = self.engine.execute_saveexec(instr, state) - self.assertEqual(saved, 0x0000_FFFF) - # s0 & old_exec in 32-bit: 0x00FF & 0xFFFF = 0x00FF - # ~(0x00FF) & 0xFFFFFFFF = 0xFFFF_FF00 - self.assertEqual(new_exec, 0xFFFF_FF00) - self.assertEqual(scc, 1) - - written = self.engine.execute_valu_mov(7, 0xBBBB, state) - for lane in range(32): - if lane < 8: - self.assertFalse(written[lane]) - self.assertEqual(state.get_vgpr(lane, 7), 0xAA00 + lane) - else: - self.assertTrue(written[lane]) - self.assertEqual(state.get_vgpr(lane, 7), 0xBBBB) - - -# ============================================================================== -# Phase 5 Unit Tests: Register Aliasing and In-Place Operand Preservation -# ============================================================================== - -class TestRegisterAliasing(unittest.TestCase): - """Verify atomic operand sampling and correctness under all register aliasing permutations.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - - def test_alias_dst_equals_src_nand(self) -> None: - """When sdst == ssrc0, source must be read BEFORE sdst is written with old EXEC.""" - state = ScalarMachineState() - # s[4:5] = 0x1111_1111_1111_1111, EXEC = 0x3333_3333_3333_3333 - state.set_sgpr64(4, 0x1111_1111_1111_1111) - state.exec_mask = 0x3333_3333_3333_3333 - - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 4), - ssrc0=Reg64(RegType.SGPR, 4), - ) - - saved, new_exec, scc = self.interp.step(instr, state) - - # Saved destination s[4:5] must receive old EXEC (0x3333_3333_3333_3333) - self.assertEqual(saved, 0x3333_3333_3333_3333) - self.assertEqual(state.get_sgpr64(4), 0x3333_3333_3333_3333) - - # New EXEC must be ~(0x1111_1111_1111_1111 & 0x3333_3333_3333_3333) = ~(0x1111...) = 0xEEEE... - # If buggy and read after write, it would be ~(0x3333... & 0x3333...) = 0xCCCC... - self.assertEqual(new_exec, 0xEEEE_EEEE_EEEE_EEEE) - self.assertEqual(state.exec_mask, 0xEEEE_EEEE_EEEE_EEEE) - self.assertEqual(scc, 1) - - def test_alias_dst_equals_src_nor(self) -> None: - """When sdst == ssrc0, s_nor_saveexec_b64 must atomically read source first.""" - state = ScalarMachineState() - # s[6:7] = 0x0F0F_0F0F_0F0F_0F0F, EXEC = 0x00FF_00FF_00FF_00FF - state.set_sgpr64(6, 0x0F0F_0F0F_0F0F_0F0F) - state.exec_mask = 0x00FF_00FF_00FF_00FF - - instr = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 6), - ssrc0=Reg64(RegType.SGPR, 6), - ) - - saved, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(saved, 0x00FF_00FF_00FF_00FF) - self.assertEqual(state.get_sgpr64(6), 0x00FF_00FF_00FF_00FF) - - # 0x0F0F | 0x00FF = 0x0FFF - # ~(0x0FFF_0FFF_0FFF_0FFF) = 0xF000_F000_F000_F000 - expected_new_exec = 0xF000_F000_F000_F000 - self.assertEqual(new_exec, expected_new_exec) - self.assertEqual(state.exec_mask, expected_new_exec) - self.assertEqual(scc, 1) - - def test_alias_src_equals_exec(self) -> None: - """When ssrc0 is the EXEC register, NAND and NOR compute complement of EXEC.""" - state = ScalarMachineState() - state.exec_mask = 0x0123_4567_89AB_CDEF - - # s_nand_saveexec_b64 s[0:1], exec - # new_exec = ~(exec & exec) = ~exec - instr_nand = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 0), - ssrc0=Reg64(RegType.EXEC), - ) - saved, new_exec, scc = self.interp.step(instr_nand, state) - self.assertEqual(saved, 0x0123_4567_89AB_CDEF) - self.assertEqual(state.get_sgpr64(0), 0x0123_4567_89AB_CDEF) - self.assertEqual(new_exec, (~0x0123_4567_89AB_CDEF) & MASK64) - self.assertEqual(state.exec_mask, (~0x0123_4567_89AB_CDEF) & MASK64) - - # s_nor_saveexec_b64 s[2:3], exec - # new_exec = ~(exec | exec) = ~exec - state.exec_mask = 0xAAAA_5555_AAAA_5555 - instr_nor = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 2), - ssrc0=Reg64(RegType.EXEC), - ) - saved2, new_exec2, scc2 = self.interp.step(instr_nor, state) - self.assertEqual(saved2, 0xAAAA_5555_AAAA_5555) - self.assertEqual(state.get_sgpr64(2), 0xAAAA_5555_AAAA_5555) - self.assertEqual(new_exec2, 0x5555_AAAA_5555_AAAA) - self.assertEqual(state.exec_mask, 0x5555_AAAA_5555_AAAA) - - def test_alias_dst_and_src_both_exec(self) -> None: - """When both sdst and ssrc0 are EXEC, EXEC is replaced with ~EXEC.""" - state = ScalarMachineState() - state.exec_mask = 0x1234_0000_5678_0000 - - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.EXEC), - ssrc0=Reg64(RegType.EXEC), - ) - saved, new_exec, scc = self.interp.step(instr, state) - self.assertEqual(saved, 0x1234_0000_5678_0000) - self.assertEqual(new_exec, (~0x1234_0000_5678_0000) & MASK64) - self.assertEqual(state.exec_mask, new_exec) - - def test_overlapping_misaligned_sgprs(self) -> None: - """Partial overlap where destination is s[4:5] and source is s[5:6].""" - state = ScalarMachineState() - # s[4]=0x11111111, s[5]=0x22222222, s[6]=0x33333333 - state.sgprs[4] = 0x1111_1111 - state.sgprs[5] = 0x2222_2222 - state.sgprs[6] = 0x3333_3333 - state.exec_mask = ALL64 - - # ssrc0 = s[5:6] -> bits: lo=s[5]=0x22222222, hi=s[6]=0x33333333 - # sdst = s[4:5] -> lo=s[4], hi=s[5] - instr = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 4), - ssrc0=Reg64(RegType.SGPR, 5), - ) - - saved, new_exec, scc = self.interp.step(instr, state) - - # Saved destination s[4:5] gets old EXEC (ALL64) - self.assertEqual(saved, ALL64) - self.assertEqual(state.get_sgpr64(4), ALL64) - - # Source was read before s[5] was clobbered by ALL64's high word! - # ssrc0 was ((0x33333333 << 32) | 0x22222222) - expected_src = ((0x3333_3333) << 32) | 0x2222_2222 - # new_exec = ~(expected_src | ALL64) = 0 - self.assertEqual(new_exec, 0) - self.assertEqual(state.exec_mask, 0) - self.assertEqual(scc, 0) - - def test_in_place_recycling_loop(self) -> None: - """Ping-pong loop recycling registers in-place across multiple iterations.""" - state = ScalarMachineState() - state.exec_mask = 0x00FF_00FF_00FF_00FF - state.set_sgpr64(0, 0xFF00_FF00_FF00_FF00) - - for i in range(4): - instr = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 0), - ssrc0=Reg64(RegType.SGPR, 0), - ) - saved, new_exec, scc = self.interp.step(instr, state) - self.assertEqual(state.exec_mask, new_exec) - self.assertEqual(state.get_sgpr64(0), saved) - - -# ============================================================================== -# Phase 6 Unit Tests: Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass(frozen=True) -class SCCStatusFlags: - """Architectural condition codes, EXEC reduction metrics, and flag states.""" - scc: int - exec_zero: bool - exec_all_ones: bool - saved_exec_zero: bool - saved_exec_all_ones: bool - popcount_saved: int - popcount_new: int - lowest_active_lane: int - highest_active_lane: int - - -def evaluate_saveexec_status(saved: int, new_exec: int, scc: int) -> SCCStatusFlags: - """Extract comprehensive condition codes and active-lane status metrics.""" - n_exec = new_exec & MASK64 - s_dst = saved & MASK64 - pop_saved = popcount64(s_dst) - pop_new = popcount64(n_exec) - lowest = find_first_one_64(n_exec) - highest = (n_exec.bit_length() - 1) if n_exec > 0 else -1 - - return SCCStatusFlags( - scc=scc, - exec_zero=(n_exec == 0), - exec_all_ones=(n_exec == ALL64), - saved_exec_zero=(s_dst == 0), - saved_exec_all_ones=(s_dst == ALL64), - popcount_saved=pop_saved, - popcount_new=pop_new, - lowest_active_lane=lowest, - highest_active_lane=highest, - ) - - -def simulate_add_with_carry(a: int, b: int, cin: int) -> Tuple[int, int]: - """Model 32-bit SALU s_addc_u32 carry-chain: (sum & 0xFFFFFFFF, cout).""" - total = (a & MASK32) + (b & MASK32) + (cin & 1) - res = total & MASK32 - cout = 1 if total > MASK32 else 0 - return res, cout - - -class TestConditionCodesAndStatus(unittest.TestCase): - """Verify SCC generation, 4-corner zero/nonzero matrix, status flags, and carry interactions.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - - def test_nand_scc_four_corner_matrix(self) -> None: - """Verify SCC generation across zero/nonzero matrix for s_nand_saveexec_b64.""" - # 1. old_exec != 0, new_exec == 0 -> SCC must be 0 - state = ScalarMachineState(exec_mask=ALL64) - instr = SaveExecInstruction(Opcode.S_NAND_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(ALL64)) - saved, new_exec, scc = self.interp.step(instr, state) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - flags = evaluate_saveexec_status(saved, new_exec, scc) - self.assertTrue(flags.exec_zero) - self.assertFalse(flags.exec_all_ones) - self.assertEqual(flags.lowest_active_lane, -1) - - # 2. old_exec != 0, new_exec != 0 -> SCC must be 1 - state = ScalarMachineState(exec_mask=0x8000_0000_0000_0000) - instr2 = SaveExecInstruction(Opcode.S_NAND_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(0)) - saved2, new_exec2, scc2 = self.interp.step(instr2, state) - self.assertEqual(new_exec2, ALL64) - self.assertEqual(scc2, 1) - flags2 = evaluate_saveexec_status(saved2, new_exec2, scc2) - self.assertFalse(flags2.exec_zero) - self.assertTrue(flags2.exec_all_ones) - self.assertEqual(flags2.lowest_active_lane, 0) - self.assertEqual(flags2.highest_active_lane, 63) - - # 3. old_exec == 0, new_exec != 0 -> SCC must be 1 (NAND with 0 always yields ALL64) - state = ScalarMachineState(exec_mask=0) - instr3 = SaveExecInstruction(Opcode.S_NAND_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(0x1234)) - saved3, new_exec3, scc3 = self.interp.step(instr3, state) - self.assertEqual(saved3, 0) - self.assertEqual(new_exec3, ALL64) - self.assertEqual(scc3, 1) - - def test_nor_scc_four_corner_matrix(self) -> None: - """Verify SCC generation across zero/nonzero matrix for s_nor_saveexec_b64.""" - # 1. old_exec == 0, ssrc0 == ALL64 -> new_exec = ~(ALL64 | 0) = 0 -> SCC must be 0 - state = ScalarMachineState(exec_mask=0) - instr1 = SaveExecInstruction(Opcode.S_NOR_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(ALL64)) - saved1, new_exec1, scc1 = self.interp.step(instr1, state) - self.assertEqual(saved1, 0) - self.assertEqual(new_exec1, 0) - self.assertEqual(scc1, 0) - - # 2. old_exec == 0, ssrc0 == 0 -> new_exec = ~(0 | 0) = ALL64 -> SCC must be 1 - state.exec_mask = 0 - instr2 = SaveExecInstruction(Opcode.S_NOR_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(0)) - saved2, new_exec2, scc2 = self.interp.step(instr2, state) - self.assertEqual(saved2, 0) - self.assertEqual(new_exec2, ALL64) - self.assertEqual(scc2, 1) - - # 3. old_exec != 0, ssrc0 covers remaining bits -> new_exec = 0 -> SCC must be 0 - state.exec_mask = 0x0000_0000_FFFF_FFFF - instr3 = SaveExecInstruction(Opcode.S_NOR_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(0xFFFF_FFFF_0000_0000)) - saved3, new_exec3, scc3 = self.interp.step(instr3, state) - self.assertEqual(saved3, 0x0000_0000_FFFF_FFFF) - self.assertEqual(new_exec3, 0) - self.assertEqual(scc3, 0) - - # 4. old_exec != 0, new_exec != 0 -> SCC must be 1 - state.exec_mask = 0x0000_0000_FFFF_FFFF - instr4 = SaveExecInstruction(Opcode.S_NOR_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(0)) - saved4, new_exec4, scc4 = self.interp.step(instr4, state) - self.assertEqual(new_exec4, 0xFFFF_FFFF_0000_0000) - self.assertEqual(scc4, 1) - - def test_scc_overwrites_prior_arithmetic_carry(self) -> None: - """Confirm that saveexec clobbers prior arithmetic carry in SCC.""" - # 1. Simulate s_add_u32 producing a carry: 0xFFFFFFFF + 1 -> sum 0, cout 1 - sum_val, cout = simulate_add_with_carry(0xFFFF_FFFF, 1, 0) - self.assertEqual(cout, 1) - - # Set machine SCC to the carry bit - state = ScalarMachineState(exec_mask=ALL64, scc=cout) - self.assertEqual(state.scc, 1) - - # 2. Execute s_nor_saveexec_b64 which produces new_exec == 0 - instr = SaveExecInstruction(Opcode.S_NOR_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(ALL64)) - _, new_exec, scc = self.interp.step(instr, state) - - # SCC must now reflect new_exec != 0 (which is 0), clobbering the previous carry of 1! - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - self.assertEqual(state.scc, 0) - - def test_branch_condition_code_decisions(self) -> None: - """Simulate s_cbranch_scc0 and s_cbranch_scc1 conditional flow.""" - # Active wave: SCC=1 -> branch on scc1 taken, scc0 not taken - state = ScalarMachineState(exec_mask=0x1) - instr = SaveExecInstruction(Opcode.S_NAND_SAVEEXEC_B64, Reg64(RegType.SGPR, 0), Literal64(0)) - _, _, scc = self.interp.step(instr, state) - self.assertEqual(scc, 1) - - branch_scc1_taken = (state.scc == 1) - branch_scc0_taken = (state.scc == 0) - self.assertTrue(branch_scc1_taken) - self.assertFalse(branch_scc0_taken) - - -# ============================================================================== -# Phase 7 Unit Tests: IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# ============================================================================== - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Verify bitwise preservation, inversion, and EXEC transitions for IEEE 754 float bit representations.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - - def test_signed_zero_extremes(self) -> None: - """Test +0.0 (0x0) and -0.0 (0x8000_0000_0000_0000) under saveexec operations.""" - state = ScalarMachineState(exec_mask=NEG_ZERO_F64) - # s_nor_saveexec_b64 with POS_ZERO_F64 - # new_exec = ~(0 | NEG_ZERO_F64) = ~0x8000_0000_0000_0000 = 0x7FFF_FFFF_FFFF_FFFF - instr = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 0), - ssrc0=Literal64(POS_ZERO_F64), - ) - saved, new_exec, scc = self.interp.step(instr, state) - self.assertEqual(saved, NEG_ZERO_F64) - self.assertEqual(new_exec, 0x7FFF_FFFF_FFFF_FFFF) - self.assertEqual(scc, 1) - - # Invert back with NAND - # ~(0x7FFF_FFFF_FFFF_FFFF & NEG_ZERO_F64) = ~(0) = ALL64 - instr_nand = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 2), - ssrc0=Literal64(NEG_ZERO_F64), - ) - saved2, new_exec2, scc2 = self.interp.step(instr_nand, state) - self.assertEqual(saved2, 0x7FFF_FFFF_FFFF_FFFF) - self.assertEqual(new_exec2, ALL64) - self.assertEqual(scc2, 1) - - def test_infinities_and_exponent_masks(self) -> None: - """Verify behavior when EXEC and source carry positive/negative infinity bitmasks.""" - state = ScalarMachineState(exec_mask=POS_INF_F64) # 0x7FF0_0000_0000_0000 - # SSRC0 = NEG_INF_F64 (0xFFF0_0000_0000_0000) - # POS_INF & NEG_INF = POS_INF (0x7FF0_0000_0000_0000) - # new_exec = ~POS_INF = 0x800F_FFFF_FFFF_FFFF - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 4), - ssrc0=Literal64(NEG_INF_F64), - ) - saved, new_exec, scc = self.interp.step(instr, state) - self.assertEqual(saved, POS_INF_F64) - self.assertEqual(new_exec, 0x800F_FFFF_FFFF_FFFF) - self.assertEqual(scc, 1) - - # Confirm bitwise NOR on infinities - # POS_INF | NEG_INF = NEG_INF (0xFFF0_0000_0000_0000) - # ~(NEG_INF) = 0x000F_FFFF_FFFF_FFFF (the entire mantissa/fraction field) - state.exec_mask = POS_INF_F64 - instr_nor = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 6), - ssrc0=Literal64(NEG_INF_F64), - ) - saved_nor, new_exec_nor, scc_nor = self.interp.step(instr_nor, state) - self.assertEqual(new_exec_nor, FRAC_MASK_F64) - self.assertEqual(scc_nor, 1) - - def test_nan_payload_preservation(self) -> None: - """Verify quiet and signaling NaN bit pattern transformations under saveexec.""" - qnan = CANONICAL_QNAN_F64 # 0x7FF8_0000_0000_0000 - snan = 0x7FF0_0000_0000_0001 # Signaling NaN with 1-ULP payload - custom_nan = 0x7FF4_0000_BEEF_CAFE - - state = ScalarMachineState(exec_mask=qnan) - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 8), - ssrc0=Literal64(custom_nan), - ) - saved, new_exec, scc = self.interp.step(instr, state) - self.assertEqual(saved, qnan) - # qnan & custom_nan: - # 0x7FF8_0000_0000_0000 & 0x7FF4_0000_BEEF_CAFE = 0x7FF0_0000_0000_0000 (exponent bits) - # ~(0x7FF0_0000_0000_0000) = 0x800F_FFFF_FFFF_FFFF - self.assertEqual(new_exec, 0x800F_FFFF_FFFF_FFFF) - self.assertEqual(scc, 1) - - def test_subnormal_extremes(self) -> None: - """Verify minimum and maximum double-precision subnormal bit representations.""" - min_subnormal = 0x0000_0000_0000_0001 # 1 ULP in denormal range - max_subnormal = 0x000F_FFFF_FFFF_FFFF # All mantissa bits set, exponent 0 - - state = ScalarMachineState(exec_mask=min_subnormal) - instr = SaveExecInstruction( - opcode=Opcode.S_NOR_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 10), - ssrc0=Literal64(max_subnormal), - ) - saved, new_exec, scc = self.interp.step(instr, state) - self.assertEqual(saved, min_subnormal) - # min_subnormal | max_subnormal = max_subnormal (0x000F_FFFF_FFFF_FFFF) - # ~(0x000F_FFFF_FFFF_FFFF) = 0xFFF0_0000_0000_0000 (sign + exponent bits set) - self.assertEqual(new_exec, 0xFFF0_0000_0000_0000) - self.assertEqual(scc, 1) - - def test_float_roundtrip_integrity(self) -> None: - """Verify float unpacking and reinterpretation across saveexec transitions.""" - test_floats = [1.0, -1.0, 1.5, -0.0, 1e-300, float("inf"), float("-inf")] - for f in test_floats: - bits = f64_to_bits(f) - state = ScalarMachineState(exec_mask=bits) - instr = SaveExecInstruction( - opcode=Opcode.S_NAND_SAVEEXEC_B64, - sdst=Reg64(RegType.SGPR, 0), - ssrc0=Literal64(ALL64), - ) - saved, new_exec, scc = self.interp.step(instr, state) - self.assertEqual(saved, bits) - self.assertEqual(new_exec, (~bits) & MASK64) - - -# ============================================================================== -# Phase 8: Negative Controls, Syntax Rejection, and Mutation Detection -# ============================================================================== - -def mutant_nand_to_and(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Mutant 1: Forgets inversion, computing AND instead of NAND.""" - saved_dst = old_exec & MASK64 - new_exec = (ssrc0 & old_exec) & MASK64 - scc = 1 if new_exec != 0 else 0 - return saved_dst, new_exec, scc - - -def mutant_nor_to_or(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Mutant 2: Forgets inversion, computing OR instead of NOR.""" - saved_dst = old_exec & MASK64 - new_exec = (ssrc0 | old_exec) & MASK64 - scc = 1 if new_exec != 0 else 0 - return saved_dst, new_exec, scc - - -def mutant_nand_swap_nor(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Mutant 3: Swaps NAND for NOR.""" - return oracle_s_nor_saveexec_b64(ssrc0, old_exec) - - -def mutant_saveexec_to_wrexec(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Mutant 4: Overwrites SDST with new EXEC instead of preserving old EXEC.""" - _, new_exec, scc = oracle_s_nand_saveexec_b64(ssrc0, old_exec) - return new_exec, new_exec, scc - - -def mutant_scc_old_exec(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Mutant 5: Sets SCC based on old_exec instead of new_exec.""" - saved_dst, new_exec, _ = oracle_s_nand_saveexec_b64(ssrc0, old_exec) - scc = 1 if old_exec != 0 else 0 - return saved_dst, new_exec, scc - - -def mutant_scc_inverted(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Mutant 6: Inverts SCC definition (1 if zero, 0 if nonzero).""" - saved_dst, new_exec, _ = oracle_s_nand_saveexec_b64(ssrc0, old_exec) - scc = 1 if new_exec == 0 else 0 - return saved_dst, new_exec, scc - - -def mutant_truncate_32(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Mutant 7: Truncates EXEC computation to 32 bits, zeroing upper half.""" - saved_dst, new_exec, scc = oracle_s_nand_saveexec_b64(ssrc0, old_exec) - return saved_dst, new_exec & MASK32, scc - - -def mutant_aliasing_clobber(ssrc0: int, old_exec: int) -> Tuple[int, int, int]: - """Mutant 8: Simulates read-after-write hazard when sdst == ssrc0.""" - # When sdst == ssrc0, ssrc0 gets clobbered with old_exec first - clobbered_ssrc0 = old_exec - return oracle_s_nand_saveexec_b64(clobbered_ssrc0, old_exec) - - -class TestNegativeControlsAndMutationDetection(unittest.TestCase): - """Verify negative control syntax rejection and detection of 8 subtle architectural mutants.""" - - def test_syntax_rejection_out_of_range_sgpr(self) -> None: - """Reject out-of-range base indices for 64-bit SGPR pairs.""" - with self.assertRaises(ValueError): - Reg64(RegType.SGPR, index=255) - with self.assertRaises(ValueError): - Reg64(RegType.SGPR, index=256) - with self.assertRaises(ValueError): - Reg64(RegType.SGPR, index=-1) - - def test_syntax_rejection_special_reg_with_index(self) -> None: - """Reject special registers (EXEC, VCC) declared with nonzero index.""" - with self.assertRaises(ValueError): - Reg64(RegType.EXEC, index=1) - with self.assertRaises(ValueError): - Reg64(RegType.VCC, index=2) - - def test_syntax_rejection_invalid_literal(self) -> None: - """Reject literal constants that exceed 64-bit bounds or are negative.""" - with self.assertRaises(ValueError): - Literal64(MASK64 + 1) - with self.assertRaises(ValueError): - Literal64(-1) - - def test_syntax_rejection_invalid_wave_lane_count(self) -> None: - """Reject non-architectural wave sizes (only Wave32 and Wave64 permitted).""" - with self.assertRaises(ValueError): - SIMDWaveState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDWaveState(num_lanes=48) - with self.assertRaises(ValueError): - SIMDWaveState(num_lanes=128) - - def test_detect_mutant_1_nand_to_and(self) -> None: - """Mutant 1 (NAND without inversion) must be caught by oracle tests.""" - ref = oracle_s_nand_saveexec_b64(0xAAAA_AAAA_AAAA_AAAA, 0x5555_5555_5555_5555) - mut = mutant_nand_to_and(0xAAAA_AAAA_AAAA_AAAA, 0x5555_5555_5555_5555) - self.assertNotEqual(ref[1], mut[1]) - - def test_detect_mutant_2_nor_to_or(self) -> None: - """Mutant 2 (NOR without inversion) must be caught.""" - ref = oracle_s_nor_saveexec_b64(0x0000_FFFF_0000_FFFF, 0xFFFF_0000_FFFF_0000) - mut = mutant_nor_to_or(0x0000_FFFF_0000_FFFF, 0xFFFF_0000_FFFF_0000) - self.assertNotEqual(ref[1], mut[1]) - - def test_detect_mutant_3_nand_swap_nor(self) -> None: - """Mutant 3 (NAND swapped for NOR) must be caught.""" - ref = oracle_s_nand_saveexec_b64(0x1234_5678_9ABC_DEF0, 0xFEDC_BA98_7654_3210) - mut = mutant_nand_swap_nor(0x1234_5678_9ABC_DEF0, 0xFEDC_BA98_7654_3210) - self.assertNotEqual(ref[1], mut[1]) - - def test_detect_mutant_4_saveexec_to_wrexec(self) -> None: - """Mutant 4 (overwriting SDST with new EXEC instead of old) must be caught.""" - ref = oracle_s_nand_saveexec_b64(ALL64, 0x1234) - mut = mutant_saveexec_to_wrexec(ALL64, 0x1234) - self.assertNotEqual(ref[0], mut[0]) - - def test_detect_mutant_5_scc_old_exec(self) -> None: - """Mutant 5 (SCC derived from old_exec instead of new_exec) must be caught.""" - # When old_exec != 0 but new_exec becomes 0 (e.g. ALL64 & ALL64 -> 0) - ref = oracle_s_nand_saveexec_b64(ALL64, ALL64) - mut = mutant_scc_old_exec(ALL64, ALL64) - self.assertEqual(ref[2], 0) - self.assertEqual(mut[2], 1) - self.assertNotEqual(ref[2], mut[2]) - - def test_detect_mutant_6_scc_inverted(self) -> None: - """Mutant 6 (inverted SCC) must be caught.""" - ref = oracle_s_nand_saveexec_b64(0, ALL64) - mut = mutant_scc_inverted(0, ALL64) - self.assertEqual(ref[2], 1) - self.assertEqual(mut[2], 0) - self.assertNotEqual(ref[2], mut[2]) - - def test_detect_mutant_7_truncate_32(self) -> None: - """Mutant 7 (truncation to 32-bit EXEC) must be caught on Wave64 high-lane bits.""" - ref = oracle_s_nand_saveexec_b64(0, ALL64) - mut = mutant_truncate_32(0, ALL64) - self.assertEqual(ref[1], ALL64) - self.assertEqual(mut[1], MASK32) - self.assertNotEqual(ref[1], mut[1]) - - def test_detect_mutant_8_aliasing_clobber(self) -> None: - """Mutant 8 (aliasing clobber hazard) must be caught.""" - ssrc0 = 0x1111_1111_1111_1111 - old_exec = 0x3333_3333_3333_3333 - ref = oracle_s_nand_saveexec_b64(ssrc0, old_exec) - mut = mutant_aliasing_clobber(ssrc0, old_exec) - self.assertNotEqual(ref[1], mut[1]) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import saveexec_run # noqa: E402 (support puts tools/ on sys.path) + + +class Saveexec(unittest.TestCase): + def test_nand_by_hand(self): + # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = ~(S0 & EXEC) written out by hand. + lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) + s0, e = lanes(0, 32), lanes(16, 48) + want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), + "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), + "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["nand"] + self.assertEqual(saveexec_run.model("nand", s0, e), (want, e, 1)) + + def test_nor_by_hand(self): + # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = ~(S0 | EXEC) written out by hand. + lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) + s0, e = lanes(0, 32), lanes(16, 48) + want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), + "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), + "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["nor"] + self.assertEqual(saveexec_run.model("nor", s0, e), (want, e, 1)) + + def test_nand_every_lane(self): + saveexec_run.check(self, "nand") + + def test_nor_every_lane(self): + saveexec_run.check(self, "nor") if __name__ == "__main__": diff --git a/tests/semantic/test_salu_or_saveexec_b64.py b/tests/semantic/test_salu_or_saveexec_b64.py index 2b13f85d3..aee06de3f 100644 --- a/tests/semantic/test_salu_or_saveexec_b64.py +++ b/tests/semantic/test_salu_or_saveexec_b64.py @@ -1,1357 +1,34 @@ -from __future__ import annotations +"""s_or_saveexec_b64 through the translator, on every lane of a wave64. -import math -import random -import struct +RDNA2 ISA, SOP1: + s_or_saveexec_b64: D = EXEC; EXEC = S0 | EXEC; SCC = (EXEC != 0). + +Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in +tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an +SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of +this name ran a self-built interpreter and never called the translator. +""" +import os import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from typing import Dict, List, Optional, Sequence, Set, Tuple, Union -# ============================================================================== -# Architectural Constants for AMD RDNA2 / GCN Scalar ALU -# ============================================================================== +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import saveexec_run # noqa: E402 (support puts tools/ on sys.path) -MASK32: int = 0xFFFF_FFFF -MASK64: int = 0xFFFF_FFFF_FFFF_FFFF -SIGN_BIT64: int = 0x8000_0000_0000_0000 -EXP_MASK64: int = 0x7FF0_0000_0000_0000 -FRAC_MASK64: int = 0x000F_FFFF_FFFF_FFFF -CANONICAL_QNAN64: int = 0x7FF8_0000_0000_0000 -ALL_LANES_ACTIVE_64: int = 0xFFFF_FFFF_FFFF_FFFF -NO_LANES_ACTIVE_64: int = 0x0000_0000_0000_0000 -EVEN_LANES_64: int = 0x5555_5555_5555_5555 -ODD_LANES_64: int = 0xAAAA_AAAA_AAAA_AAAA -LOWER_HALF_ACTIVE_64: int = 0x0000_0000_FFFF_FFFF -UPPER_HALF_ACTIVE_64: int = 0xFFFF_FFFF_0000_0000 +class Saveexec(unittest.TestCase): + def test_or_by_hand(self): + # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = S0 | EXEC written out by hand. + lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) + s0, e = lanes(0, 32), lanes(16, 48) + want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), + "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), + "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["or"] + self.assertEqual(saveexec_run.model("or", s0, e), (want, e, 1)) - -# ============================================================================== -# Helper Conversions and Bitwise Primitives -# ============================================================================== - -def u64(val: int) -> int: - """Mask integer to architectural unsigned 64-bit bounds.""" - return val & MASK64 - - -def u32(val: int) -> int: - """Mask integer to architectural unsigned 32-bit bounds.""" - return val & MASK32 - - -def split_u64_to_u32s(val: int) -> Tuple[int, int]: - """Split 64-bit register/mask into (lo, hi) 32-bit words.""" - v = u64(val) - lo = v & MASK32 - hi = (v >> 32) & MASK32 - return lo, hi - - -def combine_u32s_to_u64(lo: int, hi: int) -> int: - """Combine (lo, hi) 32-bit words into a 64-bit integer.""" - return u64((u32(hi) << 32) | u32(lo)) - - -def popcount64(val: int) -> int: - """Return count of set bits (active execution lanes) in 64-bit mask.""" - return bin(u64(val)).count("1") - - -def f64_to_bits(val: float) -> int: - """Convert a Python float to 64-bit IEEE 754 bitcast.""" - return struct.unpack(" float: - """Convert 64-bit integer bits to Python float.""" - return struct.unpack(" Tuple[int, int, int]: - """Reference mathematical oracle for AMD RDNA2 s_or_saveexec_b64. - - ISA Specification (AMD RDNA2 ISA: Scalar ALU Operations): - Instruction: S_OR_SAVEEXEC_B64 SDEST, SSRC0 - Operation: - SDEST = EXEC - EXEC = SSRC0 | EXEC - SCC = (EXEC != 0) - - Args: - exec_in: The initial 64-bit execution mask (EXEC[63:0]). - src_val: The 64-bit scalar operand from SSRC0. - - Returns: - Tuple of (saved_sdst, new_exec, scc): - saved_sdst: The previous EXEC value saved to SDEST. - new_exec: The updated 64-bit EXEC mask (src_val | exec_in). - scc: Scalar Condition Code, 1 if new_exec != 0 else 0. - """ - saved_sdst = u64(exec_in) - new_exec = u64(src_val | exec_in) - scc = 1 if new_exec != 0 else 0 - return saved_sdst, new_exec, scc - - -# ============================================================================== -# Phase 1: Reference Mathematical Oracle & Architectural Model Tests -# ============================================================================== - -class TestSOrSaveExecB64Oracle(unittest.TestCase): - """Verifies mathematical invariants, identity laws, and RDNA2 oracle behavior.""" - - def test_truth_table_per_bit(self) -> None: - """Verify the 1-bit boolean truth table for OR logic across all lanes.""" - truth_table = { - (0, 0): 0, - (0, 1): 1, - (1, 0): 1, - (1, 1): 1, - } - for (exec_bit, src_bit), expected_exec in truth_table.items(): - for bit_pos in (0, 1, 15, 31, 32, 47, 63): - exec_in = exec_bit << bit_pos - src_val = src_bit << bit_pos - saved, new_exec, scc = oracle_s_or_saveexec_b64(exec_in, src_val) - self.assertEqual(saved, exec_in) - expected_val = expected_exec << bit_pos - self.assertEqual(new_exec, expected_val) - self.assertEqual(scc, 1 if expected_val != 0 else 0) - - def test_identity_zero(self) -> None: - """OR with 0 leaves EXEC unchanged and saves original EXEC.""" - test_patterns = [ - NO_LANES_ACTIVE_64, - ALL_LANES_ACTIVE_64, - EVEN_LANES_64, - ODD_LANES_64, - LOWER_HALF_ACTIVE_64, - UPPER_HALF_ACTIVE_64, - 0x1234_5678_9ABC_DEF0, - ] - for pat in test_patterns: - saved, new_exec, scc = oracle_s_or_saveexec_b64(pat, 0) - self.assertEqual(saved, pat) - self.assertEqual(new_exec, pat) - self.assertEqual(scc, 1 if pat != 0 else 0) - - def test_dominance_all_ones(self) -> None: - """OR with ALL_LANES_ACTIVE forces new EXEC to all ones and SCC=1.""" - test_patterns = [ - NO_LANES_ACTIVE_64, - ALL_LANES_ACTIVE_64, - EVEN_LANES_64, - ODD_LANES_64, - 0x0000_0000_0000_0001, - ] - for pat in test_patterns: - saved, new_exec, scc = oracle_s_or_saveexec_b64(pat, ALL_LANES_ACTIVE_64) - self.assertEqual(saved, pat) - self.assertEqual(new_exec, ALL_LANES_ACTIVE_64) - self.assertEqual(scc, 1) - - def test_superset_invariant(self) -> None: - """New EXEC must always be a superset of original EXEC bits.""" - rng = random.Random(0x5A1E_0864) - for _ in range(100): - exec_in = rng.getrandbits(64) - src_val = rng.getrandbits(64) - saved, new_exec, scc = oracle_s_or_saveexec_b64(exec_in, src_val) - self.assertEqual(saved, exec_in) - # Invariant: all bits initially active in EXEC remain active - self.assertEqual(new_exec & exec_in, exec_in) - # Invariant: all bits active in SSRC0 become active - self.assertEqual(new_exec & src_val, src_val) - # Invariant: active lane count never decreases - self.assertGreaterEqual(popcount64(new_exec), popcount64(exec_in)) - - def test_idempotence(self) -> None: - """When src == exec_in, new EXEC equals exec_in.""" - for pattern in [0x0, 0x1, 0x8000_0000_0000_0000, 0xDEAD_BEEF_CAFE_BABE, MASK64]: - saved, new_exec, scc = oracle_s_or_saveexec_b64(pattern, pattern) - self.assertEqual(saved, pattern) - self.assertEqual(new_exec, pattern) - self.assertEqual(scc, 1 if pattern != 0 else 0) - - def test_word_splitting_lo_hi(self) -> None: - """Ensure 64-bit operation matches independent 32-bit (lo, hi) word operations.""" - rng = random.Random(0x3232_6464) - for _ in range(50): - exec_in = rng.getrandbits(64) - src_val = rng.getrandbits(64) - saved, new_exec, scc = oracle_s_or_saveexec_b64(exec_in, src_val) - exec_lo, exec_hi = split_u64_to_u32s(exec_in) - src_lo, src_hi = split_u64_to_u32s(src_val) - expected_new_lo = exec_lo | src_lo - expected_new_hi = exec_hi | src_hi - new_lo, new_hi = split_u64_to_u32s(new_exec) - self.assertEqual(new_lo, expected_new_lo) - self.assertEqual(new_hi, expected_new_hi) - self.assertEqual(combine_u32s_to_u64(new_lo, new_hi), new_exec) - - def test_scc_flag_truth_table(self) -> None: - """SCC flag is 1 if and only if new EXEC has at least one active bit.""" - # 1. Both zero -> SCC == 0 - saved, new_exec, scc = oracle_s_or_saveexec_b64(0, 0) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - - # 2. Exec non-zero, src zero -> SCC == 1 - saved, new_exec, scc = oracle_s_or_saveexec_b64(1, 0) - self.assertEqual(scc, 1) - - # 3. Exec zero, src non-zero -> SCC == 1 - saved, new_exec, scc = oracle_s_or_saveexec_b64(0, 1 << 63) - self.assertEqual(scc, 1) - - # 4. Both non-zero -> SCC == 1 - saved, new_exec, scc = oracle_s_or_saveexec_b64(EVEN_LANES_64, ODD_LANES_64) - self.assertEqual(new_exec, MASK64) - self.assertEqual(scc, 1) - - def test_walking_ones_oracle(self) -> None: - """Test single-lane activations across all 64 lane positions.""" - for lane in range(64): - single_bit = 1 << lane - saved, new_exec, scc = oracle_s_or_saveexec_b64(0, single_bit) - self.assertEqual(saved, 0) - self.assertEqual(new_exec, single_bit) - self.assertEqual(scc, 1) - self.assertEqual(popcount64(new_exec), 1) - - - -# ============================================================================== -# Phase 2: Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - SGPR = auto() - EXEC = auto() - VCC = auto() - TTMP = auto() - SPECIAL = auto() - - -@dataclass(frozen=True) -class RegPair64: - """Architectural 64-bit scalar register pair (e.g. s[0:1], exec, vcc).""" - index: int - reg_type: RegType = RegType.SGPR - custom_name: Optional[str] = None - - def __post_init__(self) -> None: - if self.reg_type == RegType.SGPR: - if not (0 <= self.index <= 104): - raise ValueError(f"SGPR index {self.index} out of bounds [0, 104]") - if self.index % 2 != 0: - raise ValueError(f"64-bit SGPR pair base index must be even-aligned, got {self.index}") - elif self.reg_type == RegType.TTMP: - if not (0 <= self.index <= 14): - raise ValueError(f"TTMP index {self.index} out of bounds [0, 14]") - if self.index % 2 != 0: - raise ValueError(f"64-bit TTMP pair base index must be even-aligned, got {self.index}") - - @property - def lo_reg(self) -> int: - return self.index - - @property - def hi_reg(self) -> int: - return self.index + 1 - - @property - def is_aligned(self) -> bool: - return (self.index % 2) == 0 - - @property - def is_exec(self) -> bool: - return self.reg_type == RegType.EXEC - - @property - def is_vcc(self) -> bool: - return self.reg_type == RegType.VCC - - @property - def name(self) -> str: - if self.custom_name is not None: - return self.custom_name - if self.reg_type == RegType.SGPR: - return f"s[{self.index}:{self.index + 1}]" - elif self.reg_type == RegType.EXEC: - return "exec" - elif self.reg_type == RegType.VCC: - return "vcc" - elif self.reg_type == RegType.TTMP: - return f"ttmp[{self.index}:{self.index + 1}]" - return f"reg64_{self.index}" - - -@dataclass(frozen=True) -class Literal64: - """64-bit scalar literal or inline integer constant.""" - bits: int - - def __post_init__(self) -> None: - object.__setattr__(self, "bits", u64(self.bits)) - - @classmethod - def from_int(cls, val: int) -> Literal64: - return cls(u64(val)) - - @property - def is_inline_constant(self) -> bool: - # AMD RDNA2 inline constants: -16 to 64 or float constants like 0.0, 1.0, -1.0 - return self.bits == 0 or self.bits == MASK64 or (1 <= self.bits <= 64) - - @property - def name(self) -> str: - if self.bits == 0: - return "0" - elif self.bits == MASK64: - return "-1" - elif 1 <= self.bits <= 64: - return str(self.bits) - return f"0x{self.bits:016X}" - - -@dataclass(frozen=True) -class SaluOperand: - """Typed SALU expression operand (Register Pair or 64-bit Literal).""" - source: Union[RegPair64, Literal64] - - @property - def is_reg(self) -> bool: - return isinstance(self.source, RegPair64) - - @property - def is_literal(self) -> bool: - return isinstance(self.source, Literal64) - - def disassemble(self) -> str: - return self.source.name - - -@dataclass(frozen=True) -class SOrSaveExecB64Instruction: - """Symbolic AST node for S_OR_SAVEEXEC_B64.""" - dst: RegPair64 - src: SaluOperand - - def disassemble(self) -> str: - return f"s_or_saveexec_b64 {self.dst.name}, {self.src.disassemble()}" - - def validate(self) -> None: - if not self.dst.is_aligned and self.dst.reg_type in (RegType.SGPR, RegType.TTMP): - raise ValueError(f"Unaligned destination register pair: {self.dst.name}") - if self.src.is_reg: - src_reg = self.src.source # type: ignore[union-attr] - if not src_reg.is_aligned and src_reg.reg_type in (RegType.SGPR, RegType.TTMP): - raise ValueError(f"Unaligned source register pair: {src_reg.name}") - - @classmethod - def parse(cls, line: str) -> SOrSaveExecB64Instruction: - """Parse assembly text into typed AST instruction node.""" - cleaned = line.strip() - if ";" in cleaned: - cleaned = cleaned.split(";", 1)[0].strip() - if not cleaned: - raise ValueError("Empty instruction line") - - parts = cleaned.split(None, 1) - mnemonic = parts[0].lower() - if mnemonic != "s_or_saveexec_b64": - raise ValueError(f"Unexpected mnemonic {mnemonic}, expected s_or_saveexec_b64") - if len(parts) < 2: - raise ValueError(f"Missing operands in: {line}") - - raw_ops = [op.strip() for op in parts[1].split(",")] - if len(raw_ops) != 2: - raise ValueError(f"Instruction requires exactly 2 operands, got {len(raw_ops)} in: {line}") - - dst_str, src_str = raw_ops[0], raw_ops[1] - - # Parse destination register - dst_reg = cls._parse_reg(dst_str) - - # Parse source operand (reg or literal) - src_op = cls._parse_operand(src_str) - - inst = cls(dst=dst_reg, src=src_op) - inst.validate() - return inst - - @classmethod - def _parse_reg(cls, token: str) -> RegPair64: - tok = token.lower() - if tok == "exec": - return RegPair64(index=126, reg_type=RegType.EXEC, custom_name="exec") - if tok == "vcc": - return RegPair64(index=106, reg_type=RegType.VCC, custom_name="vcc") - if tok.startswith("s[") and tok.endswith("]"): - inner = tok[2:-1] - if ":" not in inner: - raise ValueError(f"64-bit SGPR must specify range s[lo:hi], got {token}") - lo_str, hi_str = inner.split(":", 1) - lo, hi = int(lo_str), int(hi_str) - if hi != lo + 1: - raise ValueError(f"SGPR range must span 2 dwords s[lo:lo+1], got {token}") - return RegPair64(index=lo, reg_type=RegType.SGPR) - if tok.startswith("ttmp[") and tok.endswith("]"): - inner = tok[5:-1] - lo_str, hi_str = inner.split(":", 1) - lo, hi = int(lo_str), int(hi_str) - if hi != lo + 1: - raise ValueError(f"TTMP range must span 2 dwords, got {token}") - return RegPair64(index=lo, reg_type=RegType.TTMP) - raise ValueError(f"Unrecognized register syntax: {token}") - - @classmethod - def _parse_operand(cls, token: str) -> SaluOperand: - tok = token.strip().lower() - try: - reg = cls._parse_reg(tok) - return SaluOperand(source=reg) - except ValueError: - pass - - # Parse as integer literal - if tok.startswith("0x") or tok.startswith("-0x"): - val = int(tok, 16) - else: - val = int(tok, 10) - return SaluOperand(source=Literal64.from_int(val)) - - -class TestSymbolicAST(unittest.TestCase): - """Verifies typed AST node creation, parsing, validation, and disassembly.""" - - def test_reg_pair_creation_and_properties(self) -> None: - r_sgpr = RegPair64(index=4, reg_type=RegType.SGPR) - self.assertEqual(r_sgpr.name, "s[4:5]") - self.assertEqual(r_sgpr.lo_reg, 4) - self.assertEqual(r_sgpr.hi_reg, 5) - self.assertTrue(r_sgpr.is_aligned) - self.assertFalse(r_sgpr.is_exec) - self.assertFalse(r_sgpr.is_vcc) - - r_exec = RegPair64(index=126, reg_type=RegType.EXEC, custom_name="exec") - self.assertEqual(r_exec.name, "exec") - self.assertTrue(r_exec.is_exec) - - r_vcc = RegPair64(index=106, reg_type=RegType.VCC, custom_name="vcc") - self.assertEqual(r_vcc.name, "vcc") - self.assertTrue(r_vcc.is_vcc) - - def test_reg_pair_alignment_validation(self) -> None: - """Odd base index for 64-bit pair raises ValueError.""" - with self.assertRaises(ValueError): - RegPair64(index=5, reg_type=RegType.SGPR) - with self.assertRaises(ValueError): - RegPair64(index=106, reg_type=RegType.SGPR) # Out of SGPR bounds [0, 104] - - def test_literal64_formatting(self) -> None: - lit_zero = Literal64.from_int(0) - self.assertEqual(lit_zero.name, "0") - self.assertTrue(lit_zero.is_inline_constant) - - lit_neg1 = Literal64.from_int(-1) - self.assertEqual(lit_neg1.name, "-1") - self.assertTrue(lit_neg1.is_inline_constant) - - lit_val = Literal64.from_int(0x1234_5678_9ABC_DEF0) - self.assertEqual(lit_val.name, "0x123456789ABCDEF0") - self.assertFalse(lit_val.is_inline_constant) - - def test_ast_disassembly_roundtrip(self) -> None: - dst = RegPair64(index=10, reg_type=RegType.SGPR) - src = SaluOperand(source=RegPair64(index=12, reg_type=RegType.SGPR)) - inst = SOrSaveExecB64Instruction(dst=dst, src=src) - dis = inst.disassemble() - self.assertEqual(dis, "s_or_saveexec_b64 s[10:11], s[12:13]") - - reparsed = SOrSaveExecB64Instruction.parse(dis) - self.assertEqual(reparsed, inst) - - def test_ast_parse_various_operands(self) -> None: - lines = [ - ("s_or_saveexec_b64 s[0:1], s[2:3]", "s[0:1]", "s[2:3]"), - ("s_or_saveexec_b64 s[4:5], vcc", "s[4:5]", "vcc"), - ("s_or_saveexec_b64 s[8:9], exec", "s[8:9]", "exec"), - ("s_or_saveexec_b64 s[12:13], 0", "s[12:13]", "0"), - ("s_or_saveexec_b64 s[14:15], -1", "s[14:15]", "-1"), - ("s_or_saveexec_b64 s[16:17], 0x5555555555555555", "s[16:17]", "0x5555555555555555"), - ] - for line, exp_dst, exp_src in lines: - inst = SOrSaveExecB64Instruction.parse(line) - self.assertEqual(inst.dst.name, exp_dst) - self.assertEqual(inst.src.disassemble(), exp_src) - - def test_invalid_syntax_rejection_in_ast(self) -> None: - invalid_cases = [ - "s_and_saveexec_b64 s[0:1], s[2:3]", - "s_or_saveexec_b64 s[0:1]", - "s_or_saveexec_b64 s[0:1], s[2:3], s[4:5]", - "s_or_saveexec_b64 s[1:2], s[4:5]", - "s_or_saveexec_b64 v[0:1], s[2:3]", - ] - for inv in invalid_cases: - with self.assertRaises(ValueError): - SOrSaveExecB64Instruction.parse(inv) - - - -# ============================================================================== -# Phase 3: Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural state of the AMD RDNA2 Scalar ALU machine.""" - sgprs: List[int] = field(default_factory=lambda: [0] * 106) - exec_mask: int = ALL_LANES_ACTIVE_64 - vcc: int = 0 - scc: int = 0 - pc: int = 0 - - def read_reg_pair(self, reg: RegPair64) -> int: - """Read 64-bit value from SGPR pair, EXEC, or VCC.""" - if reg.is_exec: - return u64(self.exec_mask) - elif reg.is_vcc: - return u64(self.vcc) - elif reg.reg_type == RegType.SGPR: - lo = self.sgprs[reg.lo_reg] - hi = self.sgprs[reg.hi_reg] - return combine_u32s_to_u64(lo, hi) - raise ValueError(f"Unsupported register read: {reg.name}") - - def write_reg_pair(self, reg: RegPair64, val: int) -> None: - """Write 64-bit value to SGPR pair, EXEC, or VCC.""" - v = u64(val) - if reg.is_exec: - self.exec_mask = v - elif reg.is_vcc: - self.vcc = v - elif reg.reg_type == RegType.SGPR: - lo, hi = split_u64_to_u32s(v) - self.sgprs[reg.lo_reg] = lo - self.sgprs[reg.hi_reg] = hi - else: - raise ValueError(f"Unsupported register write: {reg.name}") - - def read_operand(self, op: SaluOperand) -> int: - """Read 64-bit value from a typed SALU operand.""" - if op.is_literal: - return u64(op.source.bits) # type: ignore[union-attr] - elif op.is_reg: - return self.read_reg_pair(op.source) # type: ignore[arg-type] - raise ValueError("Invalid operand type") - - -class ScalarInterpreter: - """Deterministic step-by-step scalar instruction interpreter.""" - - def __init__(self, initial_state: Optional[ScalarMachineState] = None) -> None: - self.state = initial_state if initial_state is not None else ScalarMachineState() - self.history: List[Tuple[int, int, int]] = [] - - def step(self, inst: SOrSaveExecB64Instruction) -> Tuple[int, int, int]: - """Execute a single S_OR_SAVEEXEC_B64 instruction deterministically. - - Hardware execution order: - 1. Latch source operand value - 2. Latch current EXEC - 3. Compute saved_sdst = EXEC - 4. Compute new_exec = src_val | EXEC - 5. Update SDEST with saved_sdst - 6. Update EXEC with new_exec - 7. Update SCC = (new_exec != 0) - """ - src_val = self.state.read_operand(inst.src) - current_exec = self.state.exec_mask - - saved_sdst, new_exec, scc = oracle_s_or_saveexec_b64(current_exec, src_val) - - # Latch destination register write - self.state.write_reg_pair(inst.dst, saved_sdst) - - # Update architectural EXEC and SCC - self.state.exec_mask = new_exec - self.state.scc = scc - self.state.pc += 4 - - record = (saved_sdst, new_exec, scc) - self.history.append(record) - return record - - def run_program(self, instructions: Sequence[SOrSaveExecB64Instruction]) -> List[Tuple[int, int, int]]: - """Run a sequence of instructions to completion.""" - results = [] - for inst in instructions: - results.append(self.step(inst)) - return results - - -class TestScalarInterpreter(unittest.TestCase): - """Verifies deterministic execution in the architectural scalar interpreter.""" - - def test_single_step_execution(self) -> None: - state = ScalarMachineState(exec_mask=0x0000_0000_FFFF_FFFF) - interp = ScalarInterpreter(state) - - # s_or_saveexec_b64 s[4:5], 0xFFFF_0000_0000_0000 - inst = SOrSaveExecB64Instruction( - dst=RegPair64(4, RegType.SGPR), - src=SaluOperand(Literal64.from_int(0xFFFF_0000_0000_0000)), - ) - saved, new_exec, scc = interp.step(inst) - - self.assertEqual(saved, 0x0000_0000_FFFF_FFFF) - self.assertEqual(new_exec, 0xFFFF_0000_FFFF_FFFF) - self.assertEqual(scc, 1) - - # Check architectural state - self.assertEqual(state.exec_mask, 0xFFFF_0000_FFFF_FFFF) - self.assertEqual(state.scc, 1) - self.assertEqual(state.read_reg_pair(RegPair64(4, RegType.SGPR)), 0x0000_0000_FFFF_FFFF) - - def test_sequential_saveexec_chaining(self) -> None: - """Test accumulation of active lanes across chained calls.""" - state = ScalarMachineState(exec_mask=0x1) - interp = ScalarInterpreter(state) - - # Chain of 4 instructions setting bits 1, 2, 3, 4 - prog = [ - SOrSaveExecB64Instruction(RegPair64(0, RegType.SGPR), SaluOperand(Literal64.from_int(0x2))), - SOrSaveExecB64Instruction(RegPair64(2, RegType.SGPR), SaluOperand(Literal64.from_int(0x4))), - SOrSaveExecB64Instruction(RegPair64(4, RegType.SGPR), SaluOperand(Literal64.from_int(0x8))), - SOrSaveExecB64Instruction(RegPair64(6, RegType.SGPR), SaluOperand(Literal64.from_int(0x10))), - ] - history = interp.run_program(prog) - - self.assertEqual(history[0], (0x1, 0x3, 1)) - self.assertEqual(history[1], (0x3, 0x7, 1)) - self.assertEqual(history[2], (0x7, 0xF, 1)) - self.assertEqual(history[3], (0xF, 0x1F, 1)) - - # Check that saved registers contain exact previous states - self.assertEqual(state.read_reg_pair(RegPair64(0, RegType.SGPR)), 0x1) - self.assertEqual(state.read_reg_pair(RegPair64(2, RegType.SGPR)), 0x3) - self.assertEqual(state.read_reg_pair(RegPair64(4, RegType.SGPR)), 0x7) - self.assertEqual(state.read_reg_pair(RegPair64(6, RegType.SGPR)), 0xF) - self.assertEqual(state.exec_mask, 0x1F) - - def test_zero_to_active_transition(self) -> None: - """Starting with EXEC=0 and SCC=0, transition to active.""" - state = ScalarMachineState(exec_mask=0, scc=0) - interp = ScalarInterpreter(state) - - inst = SOrSaveExecB64Instruction( - dst=RegPair64(0, RegType.SGPR), - src=SaluOperand(Literal64.from_int(0x8000_0000_0000_0000)), - ) - saved, new_exec, scc = interp.step(inst) - - self.assertEqual(saved, 0) - self.assertEqual(new_exec, 0x8000_0000_0000_0000) - self.assertEqual(scc, 1) - self.assertEqual(state.scc, 1) - - def test_vcc_source_operand(self) -> None: - """Read mask from VCC into EXEC while saving old EXEC.""" - state = ScalarMachineState(exec_mask=0x00FF_00FF_00FF_00FF, vcc=0xFF00_FF00_FF00_FF00) - interp = ScalarInterpreter(state) - - inst = SOrSaveExecB64Instruction( - dst=RegPair64(8, RegType.SGPR), - src=SaluOperand(RegPair64(106, RegType.VCC, custom_name="vcc")), - ) - saved, new_exec, scc = interp.step(inst) - - self.assertEqual(saved, 0x00FF_00FF_00FF_00FF) - self.assertEqual(new_exec, 0xFFFF_FFFF_FFFF_FFFF) - self.assertEqual(scc, 1) - - - -# ============================================================================== -# Phase 4: SIMD Multi-Lane Divergence and 32/64-bit EXEC Masking -# ============================================================================== - -@dataclass -class SIMDWaveState: - """SIMD wavefront state modeling per-lane execution masking and vector registers.""" - wave_size: int = 64 - scalar_state: ScalarMachineState = field(default_factory=ScalarMachineState) - vgprs: List[List[int]] = field(default_factory=lambda: [[0] * 256 for _ in range(64)]) - - def __post_init__(self) -> None: - if self.wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size {self.wave_size}, must be 32 or 64") - if len(self.vgprs) != self.wave_size: - self.vgprs = [[0] * 256 for _ in range(self.wave_size)] - - @property - def active_mask(self) -> int: - limit = (1 << self.wave_size) - 1 - return self.scalar_state.exec_mask & limit - - def is_lane_active(self, lane: int) -> bool: - if not (0 <= lane < self.wave_size): - return False - return bool((self.active_mask >> lane) & 1) - - def active_lanes(self) -> List[int]: - return [i for i in range(self.wave_size) if self.is_lane_active(i)] - - def inactive_lanes(self) -> List[int]: - return [i for i in range(self.wave_size) if not self.is_lane_active(i)] - - def execute_vector_mov(self, dst_vgpr: int, val: int) -> None: - """v_mov_b32: writes value only to lanes currently enabled by EXEC.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_vgpr] = u32(val) - - def execute_vector_add(self, dst_vgpr: int, src0_vgpr: int, src1_vgpr: int) -> None: - """v_add_u32: adds src0 and src1 only for active lanes.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - a = self.vgprs[lane][src0_vgpr] - b = self.vgprs[lane][src1_vgpr] - self.vgprs[lane][dst_vgpr] = u32(a + b) - - -class SIMDInterpreter: - """Coordinates scalar control flow with SIMD vector lane divergence.""" - - def __init__(self, wave_state: Optional[SIMDWaveState] = None) -> None: - self.wave = wave_state if wave_state is not None else SIMDWaveState() - self.scalar_interp = ScalarInterpreter(self.wave.scalar_state) - - def step_scalar(self, inst: SOrSaveExecB64Instruction) -> Tuple[int, int, int]: - return self.scalar_interp.step(inst) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Verifies SIMD multi-lane divergence and EXEC masking under s_or_saveexec_b64.""" - - def test_active_inactive_lane_masking(self) -> None: - """Vector ops write only to active lanes; inactive lanes preserve old values.""" - wave = SIMDWaveState(wave_size=64) - wave.scalar_state.exec_mask = EVEN_LANES_64 # Even lanes active (32 lanes active) - - # Initialize v0 with 0xAAAA across all lanes - for lane in range(64): - wave.vgprs[lane][0] = 0xAAAA - - # Execute vector mov with 0x5555 - wave.execute_vector_mov(dst_vgpr=0, val=0x5555) - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(wave.vgprs[lane][0], 0x5555, f"Even lane {lane} should be updated") - else: - self.assertEqual(wave.vgprs[lane][0], 0xAAAA, f"Odd lane {lane} should remain untouched") - - def test_lane_activation_expansion_via_or(self) -> None: - """s_or_saveexec_b64 expands active lanes and saves old execution mask.""" - wave = SIMDWaveState(wave_size=64) - simd = SIMDInterpreter(wave) - - # Initially, only lower 32 lanes active - wave.scalar_state.exec_mask = LOWER_HALF_ACTIVE_64 - self.assertEqual(len(wave.active_lanes()), 32) - - # Vector write in lower half - wave.execute_vector_mov(dst_vgpr=1, val=0x1111) - - # Expand EXEC to include upper 32 lanes via s_or_saveexec_b64 s[4:5], UPPER_HALF - inst = SOrSaveExecB64Instruction( - dst=RegPair64(4, RegType.SGPR), - src=SaluOperand(Literal64.from_int(UPPER_HALF_ACTIVE_64)), - ) - saved, new_exec, scc = simd.step_scalar(inst) - - self.assertEqual(saved, LOWER_HALF_ACTIVE_64) - self.assertEqual(new_exec, ALL_LANES_ACTIVE_64) - self.assertEqual(scc, 1) - self.assertEqual(len(wave.active_lanes()), 64) - - # Vector write in all 64 lanes - wave.execute_vector_mov(dst_vgpr=2, val=0x2222) - for lane in range(64): - self.assertEqual(wave.vgprs[lane][2], 0x2222) - - def test_divergent_control_flow_merge(self) -> None: - """Simulate divergent execution join: Path A (lanes 0-15) merges with Path B (lanes 16-31).""" - wave = SIMDWaveState(wave_size=64) - simd = SIMDInterpreter(wave) - - mask_a = 0x0000_0000_0000_FFFF # Lanes 0..15 - mask_b = 0x0000_0000_FFFF_0000 # Lanes 16..31 - - wave.scalar_state.exec_mask = mask_a - wave.execute_vector_mov(dst_vgpr=5, val=100) - - # Merge Path B lanes into EXEC - inst = SOrSaveExecB64Instruction( - dst=RegPair64(0, RegType.SGPR), - src=SaluOperand(Literal64.from_int(mask_b)), - ) - saved, new_exec, scc = simd.step_scalar(inst) - - self.assertEqual(saved, mask_a) - self.assertEqual(new_exec, mask_a | mask_b) - self.assertEqual(scc, 1) - self.assertEqual(len(wave.active_lanes()), 32) - - def test_wavefront_quadrant_activation(self) -> None: - """Step-by-step activation of 16-lane quadrants.""" - wave = SIMDWaveState(wave_size=64) - simd = SIMDInterpreter(wave) - wave.scalar_state.exec_mask = 0 - - q0 = 0x0000_0000_0000_FFFF - q1 = 0x0000_0000_FFFF_0000 - q2 = 0x0000_FFFF_0000_0000 - q3 = 0xFFFF_0000_0000_0000 - - quadrants = [q0, q1, q2, q3] - expected_counts = [16, 32, 48, 64] - - for i, (q, count) in enumerate(zip(quadrants, expected_counts)): - inst = SOrSaveExecB64Instruction( - dst=RegPair64(i * 2, RegType.SGPR), - src=SaluOperand(Literal64.from_int(q)), - ) - simd.step_scalar(inst) - self.assertEqual(len(wave.active_lanes()), count) - - self.assertEqual(wave.active_mask, ALL_LANES_ACTIVE_64) - - def test_wave32_and_wave64_execution_boundaries(self) -> None: - """Verify active mask semantics when wave_size=32 versus wave_size=64.""" - wave32 = SIMDWaveState(wave_size=32) - wave32.scalar_state.exec_mask = ALL_LANES_ACTIVE_64 - # In Wave32 mode, active mask only considers lower 32 bits - self.assertEqual(wave32.active_mask, 0xFFFF_FFFF) - self.assertEqual(len(wave32.active_lanes()), 32) - self.assertFalse(wave32.is_lane_active(32)) - - wave64 = SIMDWaveState(wave_size=64) - wave64.scalar_state.exec_mask = ALL_LANES_ACTIVE_64 - self.assertEqual(wave64.active_mask, ALL_LANES_ACTIVE_64) - self.assertEqual(len(wave64.active_lanes()), 64) - self.assertTrue(wave64.is_lane_active(32)) - self.assertTrue(wave64.is_lane_active(63)) - - - -# ============================================================================== -# Phase 5: Register Aliasing and In-Place Operand Preservation -# ============================================================================== - -class TestRegisterAliasing(unittest.TestCase): - """Verifies architectural register aliasing, latching, and unwritten register preservation.""" - - def test_dst_equals_src_aliasing(self) -> None: - """When dst == src (e.g. s_or_saveexec_b64 s[4:5], s[4:5]): - - Hardware semantics: - - src operand value is read (val_src) - - old EXEC is latched (old_exec) - - new EXEC = val_src | old_exec - - dst receives old_exec - """ - state = ScalarMachineState(exec_mask=0x1111_2222_3333_4444) - interp = ScalarInterpreter(state) - - # Set s[4:5] to 0x5555_6666_7777_8888 - reg_s4 = RegPair64(4, RegType.SGPR) - state.write_reg_pair(reg_s4, 0x5555_6666_7777_8888) - - # Execute aliased instruction - inst = SOrSaveExecB64Instruction( - dst=reg_s4, - src=SaluOperand(reg_s4), - ) - saved, new_exec, scc = interp.step(inst) - - # Saved sdst must be old EXEC - self.assertEqual(saved, 0x1111_2222_3333_4444) - self.assertEqual(state.read_reg_pair(reg_s4), 0x1111_2222_3333_4444) - - # New EXEC must be val_src | old_exec - expected_exec = 0x5555_6666_7777_8888 | 0x1111_2222_3333_4444 - self.assertEqual(new_exec, expected_exec) - self.assertEqual(state.exec_mask, expected_exec) - self.assertEqual(scc, 1) - - def test_dst_is_exec_aliasing(self) -> None: - """When dst is EXEC (s_or_saveexec_b64 exec, s[2:3]): - - Hardware semantics: - - SDEST is EXEC, but EXEC is subsequently updated with src | EXEC. - - Final EXEC is src | old_exec. - """ - state = ScalarMachineState(exec_mask=0x0000_FFFF_0000_FFFF) - interp = ScalarInterpreter(state) - - reg_s2 = RegPair64(2, RegType.SGPR) - state.write_reg_pair(reg_s2, 0xFFFF_0000_FFFF_0000) - - reg_exec = RegPair64(126, RegType.EXEC, custom_name="exec") - inst = SOrSaveExecB64Instruction( - dst=reg_exec, - src=SaluOperand(reg_s2), - ) - saved, new_exec, scc = interp.step(inst) - - self.assertEqual(saved, 0x0000_FFFF_0000_FFFF) - self.assertEqual(new_exec, ALL_LANES_ACTIVE_64) - self.assertEqual(state.exec_mask, ALL_LANES_ACTIVE_64) - self.assertEqual(scc, 1) - - def test_src_is_exec_aliasing(self) -> None: - """When src is EXEC (s_or_saveexec_b64 s[6:7], exec): - - Hardware semantics: - - SDEST receives old EXEC - - New EXEC = EXEC | EXEC = EXEC - - EXEC remains unchanged, SCC = (EXEC != 0) - """ - initial_exec = 0x1234_5678_9ABC_DEF0 - state = ScalarMachineState(exec_mask=initial_exec) - interp = ScalarInterpreter(state) - - reg_s6 = RegPair64(6, RegType.SGPR) - reg_exec = RegPair64(126, RegType.EXEC, custom_name="exec") - - inst = SOrSaveExecB64Instruction( - dst=reg_s6, - src=SaluOperand(reg_exec), - ) - saved, new_exec, scc = interp.step(inst) - - self.assertEqual(saved, initial_exec) - self.assertEqual(new_exec, initial_exec) - self.assertEqual(state.read_reg_pair(reg_s6), initial_exec) - self.assertEqual(state.exec_mask, initial_exec) - self.assertEqual(scc, 1) - - def test_dst_and_src_both_exec_aliasing(self) -> None: - """When dst and src are both EXEC (s_or_saveexec_b64 exec, exec):""" - initial_exec = 0xAAAA_5555_AAAA_5555 - state = ScalarMachineState(exec_mask=initial_exec) - interp = ScalarInterpreter(state) - - reg_exec = RegPair64(126, RegType.EXEC, custom_name="exec") - inst = SOrSaveExecB64Instruction( - dst=reg_exec, - src=SaluOperand(reg_exec), - ) - saved, new_exec, scc = interp.step(inst) - - self.assertEqual(saved, initial_exec) - self.assertEqual(new_exec, initial_exec) - self.assertEqual(state.exec_mask, initial_exec) - self.assertEqual(scc, 1) - - def test_unwritten_registers_preserved(self) -> None: - """Verify that registers not targeted by dst remain completely unchanged.""" - state = ScalarMachineState() - rng = random.Random(0xDEAD_CAFE) - - # Populate all 106 SGPRs with random values - for i in range(106): - state.sgprs[i] = rng.getrandbits(32) - - snapshot_sgprs = list(state.sgprs) - target_pair = RegPair64(20, RegType.SGPR) - - interp = ScalarInterpreter(state) - inst = SOrSaveExecB64Instruction( - dst=target_pair, - src=SaluOperand(Literal64.from_int(0x1234)), - ) - interp.step(inst) - - # Check that only s20 and s21 changed; all other 104 SGPRs must be bit-for-bit identical - for i in range(106): - if i in (20, 21): - continue - self.assertEqual(state.sgprs[i], snapshot_sgprs[i], f"SGPR s{i} was unexpectedly modified") - - - -# ============================================================================== -# Phase 6: Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass -class ScalarStatusFlags: - """Architectural STATUS register flags for AMD RDNA2 SALU.""" - scc: int = 0 - priv: int = 0 - trap_en: int = 0 - spi_prio: int = 0 - carry_borrow: int = 0 - - def update_from_salu_or(self, new_exec: int) -> None: - """Update SCC from resulting EXEC mask. - - Logical bitwise operations in RDNA2 SALU do not generate carry or borrow. - All other status flags must remain untouched. - """ - self.scc = 1 if (u64(new_exec) != 0) else 0 - self.carry_borrow = 0 - - def evaluate_cbranch_scc0(self) -> bool: - """s_cbranch_scc0: taken if SCC == 0 (all lanes inactive).""" - return self.scc == 0 - - def evaluate_cbranch_scc1(self) -> bool: - """s_cbranch_scc1: taken if SCC == 1 (at least one lane active).""" - return self.scc == 1 - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Verifies SCC condition flag generation, carry/borrow neutrality, and cbranch semantics.""" - - def test_scc_zero_flag_behavior(self) -> None: - """EXEC == 0 results in SCC == 0.""" - flags = ScalarStatusFlags() - flags.update_from_salu_or(0) - self.assertEqual(flags.scc, 0) - self.assertTrue(flags.evaluate_cbranch_scc0()) - self.assertFalse(flags.evaluate_cbranch_scc1()) - - def test_scc_nonzero_flag_behavior(self) -> None: - """Any bit set in EXEC[63:0] results in SCC == 1.""" - flags = ScalarStatusFlags() - for lane in range(64): - flags.update_from_salu_or(1 << lane) - self.assertEqual(flags.scc, 1, f"Lane {lane} set should produce SCC=1") - self.assertFalse(flags.evaluate_cbranch_scc0()) - self.assertTrue(flags.evaluate_cbranch_scc1()) - - def test_no_carry_borrow_generation(self) -> None: - """s_or_saveexec_b64 is a bitwise logical op and must never generate carry or borrow.""" - flags = ScalarStatusFlags(carry_borrow=1) - # Even with all bits set (0xFFFF_FFFF_FFFF_FFFF | 0xFFFF_FFFF_FFFF_FFFF), no carry is generated - flags.update_from_salu_or(ALL_LANES_ACTIVE_64) - self.assertEqual(flags.carry_borrow, 0) - self.assertEqual(flags.scc, 1) - - def test_status_flags_preservation(self) -> None: - """Verify non-SCC status register bits (priv, trap_en, spi_prio) are preserved.""" - flags = ScalarStatusFlags(priv=1, trap_en=1, spi_prio=3) - flags.update_from_salu_or(0x1234) - self.assertEqual(flags.scc, 1) - self.assertEqual(flags.priv, 1) - self.assertEqual(flags.trap_en, 1) - self.assertEqual(flags.spi_prio, 3) - - def test_scc_and_execz_duality(self) -> None: - """scc == 0 is mathematically identical to exec_mask == 0 after s_or_saveexec_b64.""" - test_masks = [ - 0x0, - 0x1, - 0x8000_0000_0000_0000, - 0x0000_FFFF_0000_0000, - ALL_LANES_ACTIVE_64, - ] - flags = ScalarStatusFlags() - for mask in test_masks: - flags.update_from_salu_or(mask) - is_exec_zero = (mask == 0) - self.assertEqual(flags.scc == 0, is_exec_zero) - self.assertEqual(flags.scc == 1, not is_exec_zero) - - - -# ============================================================================== -# Phase 7: IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# ============================================================================== - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Verifies IEEE 754 bitcasts, subnormals, NaNs, and extreme bit pattern handling in SALU.""" - - def test_ieee754_zero_and_neg_zero_masks(self) -> None: - """+0.0 is all zeros (identity); -0.0 has only MSB (sign bit, lane 63) set.""" - pos_zero_bits = f64_to_bits(0.0) - neg_zero_bits = f64_to_bits(-0.0) - - self.assertEqual(pos_zero_bits, 0x0000_0000_0000_0000) - self.assertEqual(neg_zero_bits, 0x8000_0000_0000_0000) - - # OR with +0.0 leaves mask unchanged - saved, new_exec, scc = oracle_s_or_saveexec_b64(0x1234_5678, pos_zero_bits) - self.assertEqual(new_exec, 0x1234_5678) - - # OR with -0.0 activates lane 63 - saved, new_exec, scc = oracle_s_or_saveexec_b64(0, neg_zero_bits) - self.assertEqual(new_exec, 0x8000_0000_0000_0000) - self.assertEqual(scc, 1) - - def test_ieee754_infinities_and_nans(self) -> None: - """Infinities and NaNs are treated strictly as bit patterns; no quietening occurs in SALU.""" - pos_inf_bits = f64_to_bits(float("inf")) - neg_inf_bits = f64_to_bits(float("-inf")) - qnan_bits = CANONICAL_QNAN64 - snan_bits = 0x7FF0_0000_0000_0001 # SNaN (fraction != 0, quiet bit 51 is 0) - - self.assertEqual(pos_inf_bits, 0x7FF0_0000_0000_0000) - self.assertEqual(neg_inf_bits, 0xFFF0_0000_0000_0000) - - # Verify SALU preserves SNaN bits without converting to QNaN - saved, new_exec, scc = oracle_s_or_saveexec_b64(0, snan_bits) - self.assertEqual(new_exec, snan_bits) - self.assertEqual(new_exec & 0x0008_0000_0000_0000, 0, "Quiet bit should NOT be spontaneously set by SALU") - self.assertEqual(scc, 1) - - # Combining +inf with neg_zero sets sign bit and exponent bits - saved, new_exec, scc = oracle_s_or_saveexec_b64(pos_inf_bits, 0x8000_0000_0000_0000) - self.assertEqual(new_exec, neg_inf_bits) - self.assertEqual(scc, 1) - - def test_ieee754_subnormals_bit_patterns(self) -> None: - """Subnormal bit patterns (exponent=0, fraction!=0) are preserved bit-for-bit.""" - min_subnormal = 0x0000_0000_0000_0001 - max_subnormal = 0x000F_FFFF_FFFF_FFFF - - saved, new_exec, scc = oracle_s_or_saveexec_b64(min_subnormal, max_subnormal) - self.assertEqual(saved, min_subnormal) - self.assertEqual(new_exec, max_subnormal) - self.assertEqual(scc, 1) - - def test_walking_zeros_dense_masks(self) -> None: - """Test walking zero (single inactive lane) across all 64 lane positions.""" - for lane in range(64): - dense_mask = u64(~(1 << lane)) - # When combined with all zeros, new_exec is dense_mask - saved, new_exec, scc = oracle_s_or_saveexec_b64(0, dense_mask) - self.assertEqual(new_exec, dense_mask) - self.assertEqual(popcount64(new_exec), 63) - self.assertEqual(scc, 1) - - # When combined with the missing lane, completes to all lanes active - saved2, new_exec2, scc2 = oracle_s_or_saveexec_b64(new_exec, 1 << lane) - self.assertEqual(new_exec2, ALL_LANES_ACTIVE_64) - self.assertEqual(popcount64(new_exec2), 64) - self.assertEqual(scc2, 1) - - def test_alternating_and_checkerboard_merges(self) -> None: - """Alternating lane masks (0x5555... and 0xAAAA...) merge to all ones.""" - saved, new_exec, scc = oracle_s_or_saveexec_b64(EVEN_LANES_64, ODD_LANES_64) - self.assertEqual(saved, EVEN_LANES_64) - self.assertEqual(new_exec, ALL_LANES_ACTIVE_64) - self.assertEqual(scc, 1) - self.assertEqual(popcount64(new_exec), 64) - - def test_sparse_random_bit_masks(self) -> None: - """Fuzz with sparse masks having only 1, 2, or 3 random bits set.""" - rng = random.Random(0x7547_7547) - for _ in range(50): - lanes = rng.sample(range(64), k=3) - mask_a = (1 << lanes[0]) | (1 << lanes[1]) - mask_b = 1 << lanes[2] - saved, new_exec, scc = oracle_s_or_saveexec_b64(mask_a, mask_b) - self.assertEqual(saved, mask_a) - self.assertEqual(new_exec, mask_a | mask_b) - self.assertEqual(popcount64(new_exec), 3) - self.assertEqual(scc, 1) - - - -# ============================================================================== -# Phase 8: Negative Controls, Syntax Rejection, and Mutation Detection -# ============================================================================== - -def mutant_and_instead_of_or(exec_in: int, src_val: int) -> Tuple[int, int, int]: - """Mutant 1: Emits bitwise AND instead of OR.""" - saved_sdst = u64(exec_in) - new_exec = u64(src_val & exec_in) - scc = 1 if new_exec != 0 else 0 - return saved_sdst, new_exec, scc - - -def mutant_xor_instead_of_or(exec_in: int, src_val: int) -> Tuple[int, int, int]: - """Mutant 2: Emits bitwise XOR instead of OR.""" - saved_sdst = u64(exec_in) - new_exec = u64(src_val ^ exec_in) - scc = 1 if new_exec != 0 else 0 - return saved_sdst, new_exec, scc - - -def mutant_save_new_exec(exec_in: int, src_val: int) -> Tuple[int, int, int]: - """Mutant 3: Saves updated EXEC into SDEST instead of previous EXEC.""" - new_exec = u64(src_val | exec_in) - saved_sdst = new_exec - scc = 1 if new_exec != 0 else 0 - return saved_sdst, new_exec, scc - - -def mutant_inverted_scc(exec_in: int, src_val: int) -> Tuple[int, int, int]: - """Mutant 4: Inverts SCC condition flag (sets 1 on zero, 0 on non-zero).""" - saved_sdst = u64(exec_in) - new_exec = u64(src_val | exec_in) - scc = 1 if new_exec == 0 else 0 - return saved_sdst, new_exec, scc - - -def mutant_scc_from_old_exec(exec_in: int, src_val: int) -> Tuple[int, int, int]: - """Mutant 5: Computes SCC from old EXEC instead of resulting EXEC.""" - saved_sdst = u64(exec_in) - new_exec = u64(src_val | exec_in) - scc = 1 if saved_sdst != 0 else 0 - return saved_sdst, new_exec, scc - - -def mutant_truncate_32bit(exec_in: int, src_val: int) -> Tuple[int, int, int]: - """Mutant 6: Incorrectly truncates EXEC mask to 32 bits on Wave64.""" - saved_sdst = u64(exec_in) - new_exec = u32(src_val | exec_in) - scc = 1 if new_exec != 0 else 0 - return saved_sdst, new_exec, scc - - -def mutant_src_negation(exec_in: int, src_val: int) -> Tuple[int, int, int]: - """Mutant 7: Confuses s_or with s_orn2 (ORs with inverted source).""" - saved_sdst = u64(exec_in) - new_exec = u64((~src_val & MASK64) | exec_in) - scc = 1 if new_exec != 0 else 0 - return saved_sdst, new_exec, scc - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Verifies syntax rejection of invalid assembly and catches subtle behavioral mutations.""" - - def test_rejection_of_invalid_mnemonics(self) -> None: - """Reject invalid mnemonics and opcodes.""" - invalid_mnemonics = [ - "s_or_saveexec_b32 s[0:1], s[2:3]", - "v_or_saveexec_b64 s[0:1], s[2:3]", - "s_and_saveexec_b64 s[0:1], s[2:3]", - "s_or_b64 s[0:1], s[2:3]", - "s_saveexec_b64 s[0:1], s[2:3]", - ] - for line in invalid_mnemonics: - with self.assertRaises(ValueError): - SOrSaveExecB64Instruction.parse(line) - - def test_rejection_of_vgpr_and_odd_sgpr_operands(self) -> None: - """Reject VGPR destinations and unaligned odd SGPR base indices.""" - invalid_registers = [ - "s_or_saveexec_b64 v[0:1], s[2:3]", - "s_or_saveexec_b64 v0, s[2:3]", - "s_or_saveexec_b64 s[1:2], s[4:5]", - "s_or_saveexec_b64 s[3:4], s[4:5]", - "s_or_saveexec_b64 s[105:106], s[4:5]", - ] - for line in invalid_registers: - with self.assertRaises(ValueError): - SOrSaveExecB64Instruction.parse(line) - - def test_rejection_of_truncated_and_excess_operands(self) -> None: - """Reject instruction lines with wrong operand counts or malformed delimiters.""" - malformed = [ - "s_or_saveexec_b64", - "s_or_saveexec_b64 s[0:1]", - "s_or_saveexec_b64 s[0:1], s[2:3], s[4:5]", - "s_or_saveexec_b64 s[0:1] s[2:3]", - "s_or_saveexec_b64 s[0:1],", - ] - for line in malformed: - with self.assertRaises(ValueError): - SOrSaveExecB64Instruction.parse(line) - - def test_mutation_detection_and_instead_of_or(self) -> None: - """Mutant 1 (AND instead of OR) must be detected.""" - exec_in = 0x0000_0000_FFFF_0000 - src_val = 0x0000_0000_0000_FFFF - ref = oracle_s_or_saveexec_b64(exec_in, src_val) - mut = mutant_and_instead_of_or(exec_in, src_val) - self.assertNotEqual(ref, mut) - self.assertEqual(ref[1], 0x0000_0000_FFFF_FFFF) - self.assertEqual(mut[1], 0x0) - - def test_mutation_detection_xor_instead_of_or(self) -> None: - """Mutant 2 (XOR instead of OR) must be detected on overlapping bits.""" - exec_in = 0xFFFF_FFFF_FFFF_FFFF - src_val = 0xFFFF_FFFF_FFFF_FFFF - ref = oracle_s_or_saveexec_b64(exec_in, src_val) - mut = mutant_xor_instead_of_or(exec_in, src_val) - self.assertNotEqual(ref, mut) - self.assertEqual(ref[1], ALL_LANES_ACTIVE_64) - self.assertEqual(mut[1], 0x0) - - def test_mutation_detection_save_new_exec(self) -> None: - """Mutant 3 (saving new EXEC instead of previous EXEC) must be detected.""" - exec_in = 0x1 - src_val = 0x2 - ref = oracle_s_or_saveexec_b64(exec_in, src_val) - mut = mutant_save_new_exec(exec_in, src_val) - self.assertNotEqual(ref, mut) - self.assertEqual(ref[0], 0x1) # Saved is old EXEC - self.assertEqual(mut[0], 0x3) # Mutant saved new EXEC - - def test_mutation_detection_inverted_scc(self) -> None: - """Mutant 4 (inverted SCC) must be detected.""" - exec_in = 0x0 - src_val = 0x1 - ref = oracle_s_or_saveexec_b64(exec_in, src_val) - mut = mutant_inverted_scc(exec_in, src_val) - self.assertNotEqual(ref, mut) - self.assertEqual(ref[2], 1) - self.assertEqual(mut[2], 0) - - def test_mutation_detection_scc_from_old_exec(self) -> None: - """Mutant 5 (computing SCC before the OR operation) must be detected.""" - exec_in = 0x0 # Old exec is 0 - src_val = 0x100 # New exec will be 0x100 != 0 - ref = oracle_s_or_saveexec_b64(exec_in, src_val) - mut = mutant_scc_from_old_exec(exec_in, src_val) - self.assertNotEqual(ref, mut) - self.assertEqual(ref[2], 1) - self.assertEqual(mut[2], 0) - - def test_mutation_detection_truncate_32bit(self) -> None: - """Mutant 6 (truncating mask to 32 bits) must be detected on upper 32 lanes.""" - exec_in = 0x0 - src_val = 0x8000_0000_0000_0000 - ref = oracle_s_or_saveexec_b64(exec_in, src_val) - mut = mutant_truncate_32bit(exec_in, src_val) - self.assertNotEqual(ref, mut) - self.assertEqual(ref[1], 0x8000_0000_0000_0000) - self.assertEqual(mut[1], 0x0) - - def test_mutation_detection_src_negation(self) -> None: - """Mutant 7 (confusing with s_orn2) must be detected.""" - exec_in = 0x0 - src_val = 0x0 - ref = oracle_s_or_saveexec_b64(exec_in, src_val) - mut = mutant_src_negation(exec_in, src_val) - self.assertNotEqual(ref, mut) - self.assertEqual(ref[1], 0x0) - self.assertEqual(mut[1], ALL_LANES_ACTIVE_64) + def test_or_every_lane(self): + saveexec_run.check(self, "or") if __name__ == "__main__": unittest.main() - - - - - - - diff --git a/tests/semantic/test_salu_orn2_saveexec_b64.py b/tests/semantic/test_salu_orn2_saveexec_b64.py index 9293fa556..59df808d9 100644 --- a/tests/semantic/test_salu_orn2_saveexec_b64.py +++ b/tests/semantic/test_salu_orn2_saveexec_b64.py @@ -1,1227 +1,33 @@ -from __future__ import annotations +"""s_orn2_saveexec_b64 through the translator, on every lane of a wave64. +RDNA2 ISA, SOP1: + s_orn2_saveexec_b64: D = EXEC; EXEC = S0 | ~EXEC; SCC = (EXEC != 0). + +Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in +tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an +SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of +this name ran a self-built interpreter and never called the translator. +""" +import os +import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from typing import Dict, List, Optional, Tuple, Union -# RDNA2 Architectural Bitmasks & Constants -MASK32: int = 0xFFFF_FFFF -MASK64: int = 0xFFFF_FFFF_FFFF_FFFF -EXEC_ALL_ONES: int = 0xFFFF_FFFF_FFFF_FFFF -EXEC_ALL_ZEROS: int = 0x0000_0000_0000_0000 -SCC_SET: int = 1 -SCC_CLEARED: int = 0 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import saveexec_run # noqa: E402 (support puts tools/ on sys.path) -def u64_to_u32_pair(val: int) -> Tuple[int, int]: - """Split a 64-bit scalar value into (lo, hi) 32-bit dwords.""" - return val & MASK32, (val >> 32) & MASK32 +class Saveexec(unittest.TestCase): + def test_orn2_by_hand(self): + # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = S0 | ~EXEC written out by hand. + lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) + s0, e = lanes(0, 32), lanes(16, 48) + want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), + "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), + "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["orn2"] + self.assertEqual(saveexec_run.model("orn2", s0, e), (want, e, 1)) - -def u32_pair_to_u64(lo: int, hi: int) -> int: - """Combine two 32-bit dwords into a 64-bit scalar register value.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def oracle_s_orn2_saveexec_b64(src0: int, exec_in: int) -> Tuple[int, int, int]: - """Reference mathematical oracle for RDNA2 s_orn2_saveexec_b64. - - Instruction Definition: - SOP1 / Wave64 Execution Flow Control: - S_ORN2_SAVEEXEC_B64 SDST, SSRC0 - - Architectural Operation: - SDST = EXEC; - EXEC = SSRC0 | ~EXEC; - SCC = (EXEC != 0); - - Parameters: - src0: 64-bit scalar source operand (SGPR pair, literal constant, or inline constant). - exec_in: 64-bit current EXEC mask register value before execution. - - Returns: - Tuple of (saved_exec, new_exec, scc): - saved_exec: the pre-instruction EXEC mask destined for SDST. - new_exec: the updated EXEC mask after applying OR with bitwise NOT of previous EXEC. - scc: scalar condition code flag (1 if new_exec is non-zero, else 0). - """ - saved_exec = exec_in & MASK64 - not_exec = (~exec_in) & MASK64 - new_exec = (src0 | not_exec) & MASK64 - scc = SCC_SET if new_exec != 0 else SCC_CLEARED - return saved_exec, new_exec, scc - - -@dataclass -class ArchitecturalModel: - """Architectural register model capturing the hardware execution state.""" - - sgprs: Dict[int, int] = field(default_factory=dict) - exec_mask: int = EXEC_ALL_ONES - scc: int = SCC_CLEARED - - def get_sgpr32(self, idx: int) -> int: - return self.sgprs.get(idx, 0) & MASK32 - - def set_sgpr32(self, idx: int, val: int) -> None: - self.sgprs[idx] = val & MASK32 - - def get_sgpr64(self, idx: int) -> int: - lo = self.get_sgpr32(idx) - hi = self.get_sgpr32(idx + 1) - return u32_pair_to_u64(lo, hi) - - def set_sgpr64(self, idx: int, val: int) -> None: - lo, hi = u64_to_u32_pair(val) - self.set_sgpr32(idx, lo) - self.set_sgpr32(idx + 1, hi) - - def step_orn2_saveexec(self, dst_idx: Optional[int], src0_val: int) -> Tuple[int, int, int]: - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(src0_val, self.exec_mask) - if dst_idx is not None: - self.set_sgpr64(dst_idx, saved) - self.exec_mask = new_exec - self.scc = scc - return saved, new_exec, scc - - -# ----------------------------------------------------------------------------- -# Commit 2: Symbolic AST Opcode Definitions & Typed Expressions -# ----------------------------------------------------------------------------- - -class RegType(Enum): - SGPR = auto() - EXEC = auto() - SCC = auto() - NULL = auto() - LITERAL = auto() - - -class RegWidth(Enum): - B32 = 32 - B64 = 64 - - -@dataclass(frozen=True) -class RegRef: - name: str - reg_type: RegType - index: int = 0 - width: RegWidth = RegWidth.B64 - - def format_asm(self) -> str: - if self.reg_type == RegType.SGPR: - if self.width == RegWidth.B64: - return f"s[{self.index}:{self.index + 1}]" - return f"s{self.index}" - elif self.reg_type == RegType.EXEC: - return "exec" if self.width == RegWidth.B64 else ("exec_lo" if self.index == 0 else "exec_hi") - elif self.reg_type == RegType.NULL: - return "null" - elif self.reg_type == RegType.SCC: - return "scc" - return self.name - - -@dataclass -class TypedExpr: - width: RegWidth = RegWidth.B64 - - def evaluate(self, env: Dict[str, int]) -> int: - raise NotImplementedError - - -@dataclass -class RegExpr(TypedExpr): - reg: RegRef = field(default_factory=lambda: RegRef("s[0:1]", RegType.SGPR, 0, RegWidth.B64)) - - def evaluate(self, env: Dict[str, int]) -> int: - return env.get(self.reg.name, 0) & (MASK64 if self.width == RegWidth.B64 else MASK32) - - -@dataclass -class LiteralExpr(TypedExpr): - val: int = 0 - - def evaluate(self, env: Dict[str, int]) -> int: - return self.val & (MASK64 if self.width == RegWidth.B64 else MASK32) - - -@dataclass -class BitwiseNotExpr(TypedExpr): - operand: TypedExpr = field(default_factory=TypedExpr) - - def evaluate(self, env: Dict[str, int]) -> int: - mask = MASK64 if self.width == RegWidth.B64 else MASK32 - return (~self.operand.evaluate(env)) & mask - - -@dataclass -class BitwiseOrExpr(TypedExpr): - lhs: TypedExpr = field(default_factory=TypedExpr) - rhs: TypedExpr = field(default_factory=TypedExpr) - - def evaluate(self, env: Dict[str, int]) -> int: - mask = MASK64 if self.width == RegWidth.B64 else MASK32 - return (self.lhs.evaluate(env) | self.rhs.evaluate(env)) & mask - - -@dataclass -class SOrn2SaveExecB64ASTNode: - """Symbolic AST node representing s_orn2_saveexec_b64 instruction.""" - - sdst: RegRef - ssrc0: TypedExpr - exec_ref: RegRef = field(default_factory=lambda: RegRef("exec", RegType.EXEC, 0, RegWidth.B64)) - scc_ref: RegRef = field(default_factory=lambda: RegRef("scc", RegType.SCC, 0, RegWidth.B32)) - - def type_check(self) -> bool: - if self.sdst.reg_type not in (RegType.SGPR, RegType.NULL, RegType.EXEC): - return False - if self.sdst.width != RegWidth.B64 and self.sdst.reg_type != RegType.NULL: - return False - if self.ssrc0.width != RegWidth.B64: - return False - if self.exec_ref.reg_type != RegType.EXEC or self.exec_ref.width != RegWidth.B64: - return False - return True - - def to_assembly(self) -> str: - dst_str = self.sdst.format_asm() - if isinstance(self.ssrc0, RegExpr): - src_str = self.ssrc0.reg.format_asm() - elif isinstance(self.ssrc0, LiteralExpr): - src_str = f"0x{self.ssrc0.val:X}" - else: - src_str = str(self.ssrc0) - return f"s_orn2_saveexec_b64 {dst_str}, {src_str}" - - def build_symbolic_exec_expr(self) -> BitwiseOrExpr: - """Construct the symbolic expression tree: ssrc0 | ~EXEC.""" - not_exec = BitwiseNotExpr(width=RegWidth.B64, operand=RegExpr(width=RegWidth.B64, reg=self.exec_ref)) - return BitwiseOrExpr(width=RegWidth.B64, lhs=self.ssrc0, rhs=not_exec) - - def eval_symbolic(self, env: Dict[str, int]) -> Dict[str, int]: - saved_exec = env.get(self.exec_ref.name, EXEC_ALL_ONES) & MASK64 - expr = self.build_symbolic_exec_expr() - new_exec = expr.evaluate(env) - scc = SCC_SET if new_exec != 0 else SCC_CLEARED - - out_env = dict(env) - if self.sdst.reg_type == RegType.SGPR: - out_env[self.sdst.name] = saved_exec - out_env[self.exec_ref.name] = new_exec - out_env[self.scc_ref.name] = scc - return out_env - - -# ----------------------------------------------------------------------------- -# Commit 3: Deterministic Scalar Instruction Interpreter -# ----------------------------------------------------------------------------- - -@dataclass -class ScalarMachineState: - """Deterministic hardware state representing the RDNA2 Scalar ALU.""" - - sgpr: List[int] = field(default_factory=lambda: [0] * 104) - exec_mask: int = EXEC_ALL_ONES - scc: int = SCC_CLEARED - - def read_sgpr32(self, idx: int) -> int: - if not (0 <= idx < 104): - raise IndexError(f"SGPR index out of range: {idx}") - return self.sgpr[idx] & MASK32 - - def write_sgpr32(self, idx: int, val: int) -> None: - if not (0 <= idx < 104): - raise IndexError(f"SGPR index out of range: {idx}") - self.sgpr[idx] = val & MASK32 - - def read_sgpr64(self, idx: int) -> int: - if idx % 2 != 0: - raise ValueError(f"64-bit SGPR access must be even-aligned: s{idx}") - lo = self.read_sgpr32(idx) - hi = self.read_sgpr32(idx + 1) - return u32_pair_to_u64(lo, hi) - - def write_sgpr64(self, idx: int, val: int) -> None: - if idx % 2 != 0: - raise ValueError(f"64-bit SGPR access must be even-aligned: s{idx}") - lo, hi = u64_to_u32_pair(val) - self.write_sgpr32(idx, lo) - self.write_sgpr32(idx + 1, hi) - - def read_exec(self) -> int: - return self.exec_mask & MASK64 - - def write_exec(self, val: int) -> None: - self.exec_mask = val & MASK64 - - def read_scc(self) -> int: - return self.scc & 1 - - def write_scc(self, val: int) -> None: - self.scc = 1 if val else 0 - - -@dataclass -class ScalarInstruction: - """Decoded scalar instruction.""" - - opcode: str - dst: str - src0: Union[int, str] - - -class ScalarInterpreter: - """Deterministic interpreter executing SALU instructions.""" - - @staticmethod - def parse_src64(operand: Union[int, str], state: ScalarMachineState) -> int: - if isinstance(operand, int): - return operand & MASK64 - op = operand.strip().lower() - if op == "exec": - return state.read_exec() - if op == "null": - return 0 - if op.startswith("s[") and op.endswith("]"): - inner = op[2:-1] - parts = inner.split(":") - idx = int(parts[0]) - return state.read_sgpr64(idx) - if op.startswith("s") and not op.startswith("s["): - idx = int(op[1:]) - return state.read_sgpr64(idx) - if op.startswith("0x"): - return int(op, 16) & MASK64 - return int(op) & MASK64 - - def step(self, instr: ScalarInstruction, state: ScalarMachineState) -> Tuple[int, int, int]: - if instr.opcode != "s_orn2_saveexec_b64": - raise ValueError(f"Unsupported opcode in ScalarInterpreter: {instr.opcode}") - - src0_val = self.parse_src64(instr.src0, state) - old_exec = state.read_exec() - - saved_exec, new_exec, scc = oracle_s_orn2_saveexec_b64(src0_val, old_exec) - - dst = instr.dst.strip().lower() - if dst == "null": - pass - elif dst == "exec": - pass - elif dst.startswith("s[") and dst.endswith("]"): - parts = dst[2:-1].split(":") - dst_idx = int(parts[0]) - state.write_sgpr64(dst_idx, saved_exec) - elif dst.startswith("s") and not dst.startswith("s["): - dst_idx = int(dst[1:]) - state.write_sgpr64(dst_idx, saved_exec) - else: - raise ValueError(f"Invalid destination register: {instr.dst}") - - state.write_exec(new_exec) - state.write_scc(scc) - - return saved_exec, new_exec, scc - - -# ----------------------------------------------------------------------------- -# Commit 4: SIMD Multi-Lane Divergence and 32/64-Bit EXEC Masking -# ----------------------------------------------------------------------------- - -class WaveMode(Enum): - WAVE32 = 32 - WAVE64 = 64 - - -@dataclass -class SIMDMultiLaneState: - """Multi-lane SIMD wave state capturing lane divergence under EXEC masks.""" - - mode: WaveMode = WaveMode.WAVE64 - exec_mask: int = EXEC_ALL_ONES - vgprs: List[List[int]] = field(default_factory=list) - - def __post_init__(self) -> None: - num_lanes = self.mode.value - if not self.vgprs: - self.vgprs = [[0] * 32 for _ in range(num_lanes)] - - def is_lane_active(self, lane_id: int) -> bool: - if not (0 <= lane_id < self.mode.value): - return False - return bool((self.exec_mask >> lane_id) & 1) - - def active_lane_count(self) -> int: - mask = MASK32 if self.mode == WaveMode.WAVE32 else MASK64 - return bin(self.exec_mask & mask).count("1") - - def read_vgpr(self, lane_id: int, vgpr_idx: int) -> int: - return self.vgprs[lane_id][vgpr_idx] & MASK32 - - def write_vgpr_masked(self, vgpr_idx: int, values_per_lane: List[int]) -> int: - """Vector ALU write: only active lanes are modified. Inactive lanes preserve contents.""" - updated = 0 - for lane in range(self.mode.value): - if self.is_lane_active(lane): - self.vgprs[lane][vgpr_idx] = values_per_lane[lane] & MASK32 - updated += 1 - return updated - - -class SIMDMultiLaneController: - """Coordinates SALU saveexec flow control with VALU multi-lane execution.""" - - def __init__(self, wave: SIMDMultiLaneState, scalar: ScalarMachineState) -> None: - self.wave = wave - self.scalar = scalar - self.interp = ScalarInterpreter() - - def execute_orn2_saveexec(self, dst_sgpr: str, src0: Union[int, str]) -> Tuple[int, int, int]: - self.scalar.write_exec(self.wave.exec_mask) - instr = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst=dst_sgpr, src0=src0) - saved_exec, new_exec, scc = self.interp.step(instr, self.scalar) - if self.wave.mode == WaveMode.WAVE32: - self.wave.exec_mask = new_exec & MASK32 - else: - self.wave.exec_mask = new_exec & MASK64 - return saved_exec, new_exec, scc - - def restore_exec(self, saved_sgpr: str) -> None: - restored = self.interp.parse_src64(saved_sgpr, self.scalar) - self.scalar.write_exec(restored) - if self.wave.mode == WaveMode.WAVE32: - self.wave.exec_mask = restored & MASK32 - else: - self.wave.exec_mask = restored & MASK64 - - -# ----------------------------------------------------------------------------- -# Test Suites -# ----------------------------------------------------------------------------- - -class TestReferenceOracleAndArchitecturalModel(unittest.TestCase): - """Commit 1: Reference mathematical oracle and architectural model tests.""" - - def test_truth_table_bit_by_bit(self) -> None: - """Exhaustively verify 1-bit combinations of (src0, exec_in).""" - cases = [ - (0, 0, 0, 1, 1), - (0, 1, 1, 0, 0), - (1, 0, 0, 1, 1), - (1, 1, 1, 1, 1), - ] - for s0_bit, ex_bit, exp_saved, exp_new, exp_scc in cases: - with self.subTest(s0_bit=s0_bit, ex_bit=ex_bit): - s0 = MASK64 if s0_bit else 0 - ex = MASK64 if ex_bit else 0 - want_saved = MASK64 if exp_saved else 0 - want_new = MASK64 if exp_new else 0 - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(s0, ex) - self.assertEqual(saved, want_saved) - self.assertEqual(new_exec, want_new) - self.assertEqual(scc, exp_scc) - - def test_all_zeros_and_all_ones(self) -> None: - """Verify boundary extremes: all zeros and all ones in both operands.""" - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(EXEC_ALL_ZEROS, EXEC_ALL_ZEROS) - self.assertEqual(saved, EXEC_ALL_ZEROS) - self.assertEqual(new_exec, EXEC_ALL_ONES) - self.assertEqual(scc, SCC_SET) - - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(EXEC_ALL_ZEROS, EXEC_ALL_ONES) - self.assertEqual(saved, EXEC_ALL_ONES) - self.assertEqual(new_exec, EXEC_ALL_ZEROS) - self.assertEqual(scc, SCC_CLEARED) - - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(EXEC_ALL_ONES, EXEC_ALL_ZEROS) - self.assertEqual(saved, EXEC_ALL_ZEROS) - self.assertEqual(new_exec, EXEC_ALL_ONES) - self.assertEqual(scc, SCC_SET) - - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(EXEC_ALL_ONES, EXEC_ALL_ONES) - self.assertEqual(saved, EXEC_ALL_ONES) - self.assertEqual(new_exec, EXEC_ALL_ONES) - self.assertEqual(scc, SCC_SET) - - def test_alternating_bit_patterns(self) -> None: - """Test alternating checkerboard patterns 0x5555... and 0xAAAA...""" - p5 = 0x5555_5555_5555_5555 - pA = 0xAAAA_AAAA_AAAA_AAAA - - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(p5, p5) - self.assertEqual(saved, p5) - self.assertEqual(new_exec, EXEC_ALL_ONES) - self.assertEqual(scc, SCC_SET) - - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(p5, pA) - self.assertEqual(saved, pA) - self.assertEqual(new_exec, p5) - self.assertEqual(scc, SCC_SET) - - def test_walking_ones_and_zeros(self) -> None: - """Verify walking ones across all 64 bit lanes.""" - for i in range(64): - bit = 1 << i - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(bit, EXEC_ALL_ZEROS) - self.assertEqual(saved, EXEC_ALL_ZEROS) - self.assertEqual(new_exec, EXEC_ALL_ONES) - self.assertEqual(scc, SCC_SET) - - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(0, bit) - self.assertEqual(saved, bit) - self.assertEqual(new_exec, (~bit) & MASK64) - self.assertEqual(scc, SCC_SET) - - def test_scc_zero_uniqueness(self) -> None: - """Prove that SCC == 0 occurs if and only if src0 == 0 and exec_in == ALL_ONES.""" - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(0, EXEC_ALL_ONES) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, SCC_CLEARED) - - for i in range(64): - _, new_exec, scc = oracle_s_orn2_saveexec_b64(1 << i, EXEC_ALL_ONES) - self.assertNotEqual(new_exec, 0) - self.assertEqual(scc, SCC_SET) - - for i in range(64): - exec_val = EXEC_ALL_ONES ^ (1 << i) - _, new_exec, scc = oracle_s_orn2_saveexec_b64(0, exec_val) - self.assertNotEqual(new_exec, 0) - self.assertEqual(scc, SCC_SET) - - def test_architectural_model_execution(self) -> None: - """Verify architectural model state transitions.""" - model = ArchitecturalModel(exec_mask=0x1234_5678_9ABC_DEF0) - saved, new_ex, scc = model.step_orn2_saveexec(dst_idx=4, src0_val=0xF000_0000_0000_000F) - - self.assertEqual(saved, 0x1234_5678_9ABC_DEF0) - self.assertEqual(model.get_sgpr64(4), 0x1234_5678_9ABC_DEF0) - - expected_new = (0xF000_0000_0000_000F | (~0x1234_5678_9ABC_DEF0 & MASK64)) & MASK64 - self.assertEqual(model.exec_mask, expected_new) - self.assertEqual(model.scc, SCC_SET if expected_new != 0 else SCC_CLEARED) - - -class TestSymbolicASTDefinitions(unittest.TestCase): - """Commit 2: Symbolic AST opcode definitions and typed expressions tests.""" - - def test_ast_type_checking(self) -> None: - """Verify AST type check enforcement on registers and expression widths.""" - dst_valid = RegRef("s[4:5]", RegType.SGPR, 4, RegWidth.B64) - src_valid = RegExpr(width=RegWidth.B64, reg=RegRef("s[6:7]", RegType.SGPR, 6, RegWidth.B64)) - node = SOrn2SaveExecB64ASTNode(sdst=dst_valid, ssrc0=src_valid) - self.assertTrue(node.type_check()) - - dst_invalid = RegRef("s4", RegType.SGPR, 4, RegWidth.B32) - node_bad_dst = SOrn2SaveExecB64ASTNode(sdst=dst_invalid, ssrc0=src_valid) - self.assertFalse(node_bad_dst.type_check()) - - src_invalid = LiteralExpr(width=RegWidth.B32, val=0x1234) - node_bad_src = SOrn2SaveExecB64ASTNode(sdst=dst_valid, ssrc0=src_invalid) - self.assertFalse(node_bad_src.type_check()) - - dst_null = RegRef("null", RegType.NULL, 0, RegWidth.B64) - node_null = SOrn2SaveExecB64ASTNode(sdst=dst_null, ssrc0=src_valid) - self.assertTrue(node_null.type_check()) - - def test_ast_to_assembly(self) -> None: - """Verify AST string formatting into valid disassembly syntax.""" - dst = RegRef("s[8:9]", RegType.SGPR, 8, RegWidth.B64) - src_reg = RegExpr(width=RegWidth.B64, reg=RegRef("s[10:11]", RegType.SGPR, 10, RegWidth.B64)) - node_reg = SOrn2SaveExecB64ASTNode(sdst=dst, ssrc0=src_reg) - self.assertEqual(node_reg.to_assembly(), "s_orn2_saveexec_b64 s[8:9], s[10:11]") - - src_lit = LiteralExpr(width=RegWidth.B64, val=0xDEAD_BEEF_CAFE_BABE) - node_lit = SOrn2SaveExecB64ASTNode(sdst=dst, ssrc0=src_lit) - self.assertEqual(node_lit.to_assembly(), "s_orn2_saveexec_b64 s[8:9], 0xDEADBEEFCAFEBABE") - - def test_ast_symbolic_expression_tree(self) -> None: - """Validate symbolic expression evaluation matches mathematical oracle.""" - node = SOrn2SaveExecB64ASTNode( - sdst=RegRef("s[0:1]", RegType.SGPR, 0, RegWidth.B64), - ssrc0=RegExpr(width=RegWidth.B64, reg=RegRef("s[2:3]", RegType.SGPR, 2, RegWidth.B64)), - ) - expr_tree = node.build_symbolic_exec_expr() - - env = { - "s[2:3]": 0x0F0F_0F0F_0F0F_0F0F, - "exec": 0x3333_3333_3333_3333, - } - res = expr_tree.evaluate(env) - _, expected_exec, _ = oracle_s_orn2_saveexec_b64(env["s[2:3]"], env["exec"]) - self.assertEqual(res, expected_exec) - - def test_ast_eval_symbolic_environment(self) -> None: - """Check symbolic AST environment update behavior.""" - node = SOrn2SaveExecB64ASTNode( - sdst=RegRef("s[12:13]", RegType.SGPR, 12, RegWidth.B64), - ssrc0=LiteralExpr(width=RegWidth.B64, val=0x00FF_00FF_00FF_00FF), - ) - initial_env = { - "exec": 0xAAAA_5555_AAAA_5555, - "scc": 0, - } - final_env = node.eval_symbolic(initial_env) - self.assertEqual(final_env["s[12:13]"], 0xAAAA_5555_AAAA_5555) - expected_exec = (0x00FF_00FF_00FF_00FF | (~0xAAAA_5555_AAAA_5555 & MASK64)) & MASK64 - self.assertEqual(final_env["exec"], expected_exec) - self.assertEqual(final_env["scc"], SCC_SET if expected_exec != 0 else SCC_CLEARED) - - -class TestDeterministicScalarInterpreter(unittest.TestCase): - """Commit 3: Deterministic scalar instruction interpreter tests.""" - - def setUp(self) -> None: - self.state = ScalarMachineState() - self.interp = ScalarInterpreter() - - def test_interpreter_basic_execution(self) -> None: - """Test step execution with SGPR operands.""" - self.state.write_sgpr64(4, 0x1111_2222_3333_4444) - self.state.write_exec(0x5555_6666_7777_8888) - - instr = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[0:1]", src0="s[4:5]") - saved, new_exec, scc = self.interp.step(instr, self.state) - - self.assertEqual(saved, 0x5555_6666_7777_8888) - self.assertEqual(self.state.read_sgpr64(0), 0x5555_6666_7777_8888) - expected_exec = (0x1111_2222_3333_4444 | (~0x5555_6666_7777_8888 & MASK64)) & MASK64 - self.assertEqual(new_exec, expected_exec) - self.assertEqual(self.state.read_exec(), expected_exec) - self.assertEqual(self.state.read_scc(), SCC_SET if expected_exec != 0 else SCC_CLEARED) - - def test_interpreter_null_destination(self) -> None: - """Verify writing to null destination discards saved exec without altering SGPRs.""" - self.state.write_sgpr64(0, 0xCAFE_BABE_DEAD_BEEF) - self.state.write_exec(0xFFFF_0000_FFFF_0000) - - instr = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="null", src0=0x0000_FFFF_0000_FFFF) - saved, new_exec, scc = self.interp.step(instr, self.state) - - self.assertEqual(saved, 0xFFFF_0000_FFFF_0000) - self.assertEqual(self.state.read_sgpr64(0), 0xCAFE_BABE_DEAD_BEEF) - self.assertEqual(self.state.read_exec(), 0x0000_FFFF_0000_FFFF) - self.assertEqual(self.state.read_scc(), SCC_SET) - - def test_interpreter_inline_constants(self) -> None: - """Verify behavior with inline constants 0, -1, 1.""" - self.state.write_exec(EXEC_ALL_ONES) - instr0 = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[2:3]", src0=0) - _, new_exec, scc = self.interp.step(instr0, self.state) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, SCC_CLEARED) - self.assertEqual(self.state.read_scc(), SCC_CLEARED) - - instr_neg1 = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[4:5]", src0=-1) - _, new_exec, scc = self.interp.step(instr_neg1, self.state) - self.assertEqual(new_exec, EXEC_ALL_ONES) - self.assertEqual(scc, SCC_SET) - self.assertEqual(self.state.read_scc(), SCC_SET) - - def test_interpreter_sequential_program(self) -> None: - """Verify a multi-step sequence simulating control flow branching.""" - self.state.write_exec(0xFFFF_FFFF_0000_0000) - self.state.write_sgpr64(6, 0x0000_0000_FFFF_0000) - - instr1 = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[8:9]", src0="s[6:7]") - self.interp.step(instr1, self.state) - self.assertEqual(self.state.read_sgpr64(8), 0xFFFF_FFFF_0000_0000) - self.assertEqual(self.state.read_exec(), 0x0000_0000_FFFF_FFFF) - - instr2 = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[10:11]", src0=0) - self.interp.step(instr2, self.state) - self.assertEqual(self.state.read_sgpr64(10), 0x0000_0000_FFFF_FFFF) - self.assertEqual(self.state.read_exec(), 0xFFFF_FFFF_0000_0000) - - def test_interpreter_alignment_enforcement(self) -> None: - """Verify unaligned 64-bit SGPR accesses raise ValueError.""" - with self.assertRaises(ValueError): - self.state.read_sgpr64(1) - with self.assertRaises(ValueError): - self.state.write_sgpr64(3, 123) - - -class TestSIMDMultiLaneDivergenceAndExecMasking(unittest.TestCase): - """Commit 4: SIMD multi-lane divergence and 32/64-bit EXEC masking tests.""" - - def test_wave64_multi_lane_divergence(self) -> None: - """Verify that vector ALU updates strictly follow the EXEC mask derived from s_orn2_saveexec_b64.""" - wave = SIMDMultiLaneState(mode=WaveMode.WAVE64, exec_mask=0x5555_5555_5555_5555) # Even lanes active - scalar = ScalarMachineState() - controller = SIMDMultiLaneController(wave, scalar) - - # Vector write under initial exec: only even lanes should receive 100 + lane - values_initial = [100 + i for i in range(64)] - updated_lanes = wave.write_vgpr_masked(0, values_initial) - self.assertEqual(updated_lanes, 32) - for i in range(64): - if i % 2 == 0: - self.assertEqual(wave.read_vgpr(i, 0), 100 + i) - else: - self.assertEqual(wave.read_vgpr(i, 0), 0) - - # Apply s_orn2_saveexec_b64 with src0 mask setting low 16 lanes - # Old exec = 0x5555_5555_5555_5555 - # ~Old exec = 0xAAAA_AAAA_AAAA_AAAA - # src0 = 0x0000_0000_0000_FFFF - # New exec = 0x0000_0000_0000_FFFF | 0xAAAA_AAAA_AAAA_AAAA - # = 0xAAAA_AAAA_AAAA_FFFF - src0_mask = 0x0000_0000_0000_FFFF - saved, new_exec, scc = controller.execute_orn2_saveexec("s[16:17]", src0_mask) - - self.assertEqual(saved, 0x5555_5555_5555_5555) - self.assertEqual(scalar.read_sgpr64(16), 0x5555_5555_5555_5555) - self.assertEqual(new_exec, 0xAAAA_AAAA_AAAA_FFFF) - self.assertEqual(wave.exec_mask, 0xAAAA_AAAA_AAAA_FFFF) - self.assertEqual(scc, SCC_SET) - - # Vector write under new exec - values_second = [500 + i for i in range(64)] - wave.write_vgpr_masked(1, values_second) - for i in range(64): - expected_active = bool((0xAAAA_AAAA_AAAA_FFFF >> i) & 1) - if expected_active: - self.assertEqual(wave.read_vgpr(i, 1), 500 + i) - else: - self.assertEqual(wave.read_vgpr(i, 1), 0) - - def test_wave32_divergence_masking(self) -> None: - """Verify Wave32 restricts execution to lanes 0..31 and limits active count.""" - wave = SIMDMultiLaneState(mode=WaveMode.WAVE32, exec_mask=0xFFFF_FFFF) - scalar = ScalarMachineState() - controller = SIMDMultiLaneController(wave, scalar) - - self.assertEqual(wave.active_lane_count(), 32) - - # Saveexec with src0 = 0 -> in 64-bit opcode, exec_in has high 32 bits as 0, so ~exec has high 32 bits as 1! - # Thus new_exec = 0xFFFF_FFFF_0000_0000. Wave32 active lanes (low 32 bits) are 0, but 64-bit SCC is 1! - controller.execute_orn2_saveexec("s[20:21]", 0) - self.assertEqual(wave.active_lane_count(), 0) - self.assertEqual(scalar.read_scc(), SCC_SET) - - # Write attempt under empty exec: 0 lanes updated - values = [999] * 32 - updated = wave.write_vgpr_masked(0, values) - self.assertEqual(updated, 0) - - def test_reconvergence_after_saveexec(self) -> None: - """Simulate shader flow control: saveexec -> diverge -> restore original mask.""" - initial_exec = 0x1234_5678_9ABC_DEF0 - wave = SIMDMultiLaneState(mode=WaveMode.WAVE64, exec_mask=initial_exec) - scalar = ScalarMachineState() - controller = SIMDMultiLaneController(wave, scalar) - - # Saveexec - controller.execute_orn2_saveexec("s[30:31]", 0x0000_FFFF_0000_FFFF) - self.assertNotEqual(wave.exec_mask, initial_exec) - - # Restore - controller.restore_exec("s[30:31]") - self.assertEqual(wave.exec_mask, initial_exec) - self.assertEqual(scalar.read_exec(), initial_exec) - - -# ----------------------------------------------------------------------------- -# Commit 5: Register Aliasing and In-Place Operand Preservation -# ----------------------------------------------------------------------------- - -class TestRegisterAliasingAndInPlacePreservation(unittest.TestCase): - """Commit 5: Register aliasing, overlapping operands, and in-place preservation tests.""" - - def setUp(self) -> None: - self.state = ScalarMachineState() - self.interp = ScalarInterpreter() - - def test_exact_src0_dst_aliasing_order_of_evaluation(self) -> None: - """Verify sdst == ssrc0: src0 must be captured before sdst is written with saved exec.""" - val_src = 0x0000_FFFF_0000_FFFF - old_exec = 0x5555_5555_5555_5555 - self.state.write_sgpr64(4, val_src) - self.state.write_exec(old_exec) - - instr = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[4:5]", src0="s[4:5]") - saved, new_exec, scc = self.interp.step(instr, self.state) - - # Saved EXEC returned and placed into s[4:5] - self.assertEqual(saved, old_exec) - self.assertEqual(self.state.read_sgpr64(4), old_exec) - - # New EXEC must be computed from val_src, NOT from old_exec! - expected_new_exec = (val_src | (~old_exec & MASK64)) & MASK64 - self.assertNotEqual(expected_new_exec, EXEC_ALL_ONES) - self.assertEqual(new_exec, expected_new_exec) - self.assertEqual(self.state.read_exec(), expected_new_exec) - - def test_src0_is_exec_tautological_ones(self) -> None: - """Verify ssrc0 == exec: EXEC | ~EXEC is mathematically always ALL_ONES.""" - arbitrary_execs = [ - 0x0000_0000_0000_0000, - 0xFFFF_FFFF_FFFF_FFFF, - 0x1234_5678_9ABC_DEF0, - 0xAAAA_5555_AAAA_5555, - 0x8000_0000_0000_0001, - ] - for ex in arbitrary_execs: - with self.subTest(ex=hex(ex)): - self.state.write_exec(ex) - instr = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[6:7]", src0="exec") - saved, new_exec, scc = self.interp.step(instr, self.state) - self.assertEqual(saved, ex) - self.assertEqual(self.state.read_sgpr64(6), ex) - self.assertEqual(new_exec, EXEC_ALL_ONES) - self.assertEqual(self.state.read_exec(), EXEC_ALL_ONES) - self.assertEqual(scc, SCC_SET) - - def test_dst_is_exec_overwriting(self) -> None: - """Verify sdst == exec: new EXEC calculation takes precedence.""" - self.state.write_sgpr64(8, 0x1111_1111_1111_1111) - self.state.write_exec(0x2222_2222_2222_2222) - - instr = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="exec", src0="s[8:9]") - saved, new_exec, scc = self.interp.step(instr, self.state) - - self.assertEqual(saved, 0x2222_2222_2222_2222) - expected_exec = (0x1111_1111_1111_1111 | (~0x2222_2222_2222_2222 & MASK64)) & MASK64 - self.assertEqual(new_exec, expected_exec) - self.assertEqual(self.state.read_exec(), expected_exec) - - def test_adjacent_register_non_interference(self) -> None: - """Verify non-targeted SGPR registers retain their exact contents without bleeding.""" - sentinels = {} - for idx in range(0, 32, 2): - val = (0xABCD_0000_0000_0000 | (idx << 32) | (idx * 7919)) & MASK64 - sentinels[idx] = val - self.state.write_sgpr64(idx, val) - - self.state.write_exec(0xF0F0_F0F0_F0F0_F0F0) - - # Target only s[14:15] with s[8:9] - instr = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[14:15]", src0="s[8:9]") - self.interp.step(instr, self.state) - - # Check s[14:15] updated with saved exec - self.assertEqual(self.state.read_sgpr64(14), 0xF0F0_F0F0_F0F0_F0F0) - - # Check all other SGPRs unaltered - for idx, expected_val in sentinels.items(): - if idx == 14: - continue - self.assertEqual(self.state.read_sgpr64(idx), expected_val, f"SGPR s[{idx}:{idx+1}] corrupted!") - - def test_null_destination_with_aliased_source(self) -> None: - """Verify sdst=null with ssrc0 being an SGPR preserves ssrc0 completely.""" - self.state.write_sgpr64(18, 0x9999_8888_7777_6666) - self.state.write_exec(0x1234_1234_1234_1234) - - instr = ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="null", src0="s[18:19]") - saved, new_exec, scc = self.interp.step(instr, self.state) - - self.assertEqual(saved, 0x1234_1234_1234_1234) - self.assertEqual(self.state.read_sgpr64(18), 0x9999_8888_7777_6666) - expected_exec = (0x9999_8888_7777_6666 | (~0x1234_1234_1234_1234 & MASK64)) & MASK64 - self.assertEqual(self.state.read_exec(), expected_exec) - - -# ----------------------------------------------------------------------------- -# Commit 6: Condition Codes, Status Flags, and Carry/Borrow Generation -# ----------------------------------------------------------------------------- - -@dataclass -class FlowControlStatusFlags: - """Detailed status metrics evaluating execution mask state transitions.""" - - all_lanes_active: bool - no_lanes_active: bool - partial_lanes_active: bool - divergence_altered: bool - lanes_enabled_count: int - lanes_disabled_count: int - - -def evaluate_saveexec_status_flags(old_exec: int, new_exec: int) -> FlowControlStatusFlags: - """Calculate lane transition dynamics and convergence status.""" - all_active = (new_exec == MASK64) - no_active = (new_exec == 0) - partial_active = (0 < new_exec < MASK64) - divergence_altered = (new_exec != old_exec) - lanes_enabled = bin(new_exec & (~old_exec & MASK64)).count("1") - lanes_disabled = bin((~new_exec & MASK64) & old_exec).count("1") - return FlowControlStatusFlags( - all_lanes_active=all_active, - no_lanes_active=no_active, - partial_lanes_active=partial_active, - divergence_altered=divergence_altered, - lanes_enabled_count=lanes_enabled, - lanes_disabled_count=lanes_disabled, - ) - - -def scalar_addc_u32(s0: int, s1: int, carry_in: int) -> Tuple[int, int]: - """Simulate RDNA2 s_addc_u32 consuming SCC carry bit. Returns (sum32, carry_out).""" - total = (s0 & MASK32) + (s1 & MASK32) + (carry_in & 1) - return total & MASK32, 1 if total > MASK32 else 0 - - -def scalar_subb_u32(s0: int, s1: int, borrow_in: int) -> Tuple[int, int]: - """Simulate RDNA2 s_subb_u32 consuming SCC borrow bit. Returns (diff32, borrow_out).""" - diff = (s0 & MASK32) - (s1 & MASK32) - (borrow_in & 1) - return diff & MASK32, 1 if diff < 0 else 0 - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Commit 6: Condition codes, status flags, and carry/borrow generation tests.""" - - def test_scc_exhaustive_zero_conditions(self) -> None: - """Verify that SCC is 0 ONLY when src0 is 0 and exec is all-ones, 1 otherwise.""" - _, new_exec, scc = oracle_s_orn2_saveexec_b64(0, EXEC_ALL_ONES) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, SCC_CLEARED) - - for bit in range(64): - _, new_exec, scc = oracle_s_orn2_saveexec_b64(1 << bit, EXEC_ALL_ONES) - self.assertNotEqual(new_exec, 0) - self.assertEqual(scc, SCC_SET) - - for bit in range(64): - _, new_exec, scc = oracle_s_orn2_saveexec_b64(0, EXEC_ALL_ONES ^ (1 << bit)) - self.assertNotEqual(new_exec, 0) - self.assertEqual(scc, SCC_SET) - - def test_status_flags_metrics(self) -> None: - """Verify status metrics across transitions: full, empty, partial divergence.""" - old_exec = 0x0000_0000_FFFF_FFFF - src0 = 0xFFFF_0000_0000_0000 - _, new_exec, _ = oracle_s_orn2_saveexec_b64(src0, old_exec) - flags = evaluate_saveexec_status_flags(old_exec, new_exec) - self.assertFalse(flags.all_lanes_active) - self.assertFalse(flags.no_lanes_active) - self.assertTrue(flags.partial_lanes_active) - self.assertTrue(flags.divergence_altered) - self.assertEqual(flags.lanes_enabled_count, 32) - self.assertEqual(flags.lanes_disabled_count, 32) - - _, new_exec_all, _ = oracle_s_orn2_saveexec_b64(EXEC_ALL_ONES, old_exec) - flags_all = evaluate_saveexec_status_flags(old_exec, new_exec_all) - self.assertTrue(flags_all.all_lanes_active) - self.assertFalse(flags_all.no_lanes_active) - self.assertEqual(flags_all.lanes_enabled_count, 32) - self.assertEqual(flags_all.lanes_disabled_count, 0) - - _, new_exec_none, _ = oracle_s_orn2_saveexec_b64(0, EXEC_ALL_ONES) - flags_none = evaluate_saveexec_status_flags(EXEC_ALL_ONES, new_exec_none) - self.assertFalse(flags_none.all_lanes_active) - self.assertTrue(flags_none.no_lanes_active) - self.assertEqual(flags_none.lanes_enabled_count, 0) - self.assertEqual(flags_none.lanes_disabled_count, 64) - - def test_scc_forwarding_to_scalar_addc(self) -> None: - """Test carry generation chain: s_orn2_saveexec_b64 -> SCC -> s_addc_u32.""" - state = ScalarMachineState() - interp = ScalarInterpreter() - - state.write_exec(0) - interp.step(ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[0:1]", src0=0), state) - self.assertEqual(state.read_scc(), 1) - - sum_val, carry_out = scalar_addc_u32(0xFFFF_FFFF, 0, state.read_scc()) - self.assertEqual(sum_val, 0) - self.assertEqual(carry_out, 1) - - state.write_exec(EXEC_ALL_ONES) - interp.step(ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[0:1]", src0=0), state) - self.assertEqual(state.read_scc(), 0) - - sum_val2, carry_out2 = scalar_addc_u32(0xFFFF_FFFF, 0, state.read_scc()) - self.assertEqual(sum_val2, 0xFFFF_FFFF) - self.assertEqual(carry_out2, 0) - - def test_scc_forwarding_to_scalar_subb(self) -> None: - """Test borrow generation chain: s_orn2_saveexec_b64 -> SCC -> s_subb_u32.""" - state = ScalarMachineState() - interp = ScalarInterpreter() - - state.write_exec(0) - interp.step(ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[0:1]", src0=0), state) - self.assertEqual(state.read_scc(), 1) - - diff, borrow_out = scalar_subb_u32(0, 0, state.read_scc()) - self.assertEqual(diff, 0xFFFF_FFFF) - self.assertEqual(borrow_out, 1) - - state.write_exec(EXEC_ALL_ONES) - interp.step(ScalarInstruction(opcode="s_orn2_saveexec_b64", dst="s[0:1]", src0=0), state) - self.assertEqual(state.read_scc(), 0) - - diff2, borrow_out2 = scalar_subb_u32(0, 0, state.read_scc()) - self.assertEqual(diff2, 0) - self.assertEqual(borrow_out2, 0) - - -# ----------------------------------------------------------------------------- -# Commit 7: IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# ----------------------------------------------------------------------------- - -# IEEE 754 Binary64 architectural constants -IEEE_F64_POS_ZERO: int = 0x0000_0000_0000_0000 -IEEE_F64_NEG_ZERO: int = 0x8000_0000_0000_0000 -IEEE_F64_POS_INF: int = 0x7FF0_0000_0000_0000 -IEEE_F64_NEG_INF: int = 0xFFF0_0000_0000_0000 -IEEE_F64_QNAN: int = 0x7FF8_0000_0000_0000 -IEEE_F64_SNAN: int = 0x7FF0_0000_0000_0001 -IEEE_F64_MIN_SUBNORMAL: int = 0x0000_0000_0000_0001 -IEEE_F64_MAX_SUBNORMAL: int = 0x000F_FFFF_FFFF_FFFF -IEEE_F64_MIN_NORMAL: int = 0x0010_0000_0000_0000 -IEEE_F64_MAX_NORMAL: int = 0x7FEF_FFFF_FFFF_FFFF - -IEEE_F64_BOUNDARY_PATTERNS = [ - ("POS_ZERO", IEEE_F64_POS_ZERO), - ("NEG_ZERO", IEEE_F64_NEG_ZERO), - ("POS_INF", IEEE_F64_POS_INF), - ("NEG_INF", IEEE_F64_NEG_INF), - ("QNAN", IEEE_F64_QNAN), - ("SNAN", IEEE_F64_SNAN), - ("MIN_SUBNORMAL", IEEE_F64_MIN_SUBNORMAL), - ("MAX_SUBNORMAL", IEEE_F64_MAX_SUBNORMAL), - ("MIN_NORMAL", IEEE_F64_MIN_NORMAL), - ("MAX_NORMAL", IEEE_F64_MAX_NORMAL), -] - - -class TestIEEE754BoundaryExtremesAndBitPatterns(unittest.TestCase): - """Commit 7: IEEE 754 boundary extremes, subnormals, and NaN bit preservation tests.""" - - def test_subnormal_no_flush_preservation(self) -> None: - """Verify subnormal bit patterns are preserved strictly without hardware denormal flushing.""" - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(IEEE_F64_MIN_SUBNORMAL, EXEC_ALL_ONES) - self.assertEqual(saved, EXEC_ALL_ONES) - self.assertEqual(new_exec, IEEE_F64_MIN_SUBNORMAL) - self.assertEqual(scc, SCC_SET) - - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(IEEE_F64_MAX_SUBNORMAL, EXEC_ALL_ONES) - self.assertEqual(saved, EXEC_ALL_ONES) - self.assertEqual(new_exec, IEEE_F64_MAX_SUBNORMAL) - self.assertEqual(scc, SCC_SET) - - def test_nan_payload_bit_preservation(self) -> None: - """Verify that signaling and diagnostic NaN payloads are never modified or quietened.""" - custom_snan = 0x7FF0_0000_DEAD_BEEF - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(custom_snan, EXEC_ALL_ONES) - self.assertEqual(new_exec, custom_snan) - self.assertEqual(new_exec & 0xFFFF_FFFF, 0xDEAD_BEEF) - - def test_signed_zero_complementation(self) -> None: - """Verify distinct behavior between +0.0 and -0.0 under bitwise complementation.""" - _, new_exec_pos, scc_pos = oracle_s_orn2_saveexec_b64(0, IEEE_F64_POS_ZERO) - self.assertEqual(new_exec_pos, EXEC_ALL_ONES) - self.assertEqual(scc_pos, SCC_SET) - - _, new_exec_neg, scc_neg = oracle_s_orn2_saveexec_b64(0, IEEE_F64_NEG_ZERO) - self.assertEqual(new_exec_neg, 0x7FFF_FFFF_FFFF_FFFF) - self.assertEqual(scc_neg, SCC_SET) - self.assertEqual((new_exec_neg >> 63) & 1, 0) - self.assertEqual(new_exec_neg & 0x7FFF_FFFF_FFFF_FFFF, 0x7FFF_FFFF_FFFF_FFFF) - - def test_infinity_exponent_mask_interaction(self) -> None: - """Verify interaction between +/- infinity exponent bit patterns.""" - _, new_exec, scc = oracle_s_orn2_saveexec_b64(0, IEEE_F64_POS_INF) - expected = (~IEEE_F64_POS_INF) & MASK64 - self.assertEqual(new_exec, expected) - self.assertEqual((new_exec >> 52) & 0x7FF, 0) - self.assertEqual(scc, SCC_SET) - - def test_all_ieee754_extremes_cross_product(self) -> None: - """Exhaustively verify 10x10 combinations of IEEE 754 boundary extremes as src0 and exec.""" - for s0_name, s0_val in IEEE_F64_BOUNDARY_PATTERNS: - for ex_name, ex_val in IEEE_F64_BOUNDARY_PATTERNS: - with self.subTest(src0=s0_name, exec_in=ex_name): - saved, new_exec, scc = oracle_s_orn2_saveexec_b64(s0_val, ex_val) - self.assertEqual(saved, ex_val) - expected = (s0_val | (~ex_val & MASK64)) & MASK64 - self.assertEqual(new_exec, expected) - self.assertEqual(scc, SCC_SET if expected != 0 else SCC_CLEARED) - - -# ----------------------------------------------------------------------------- -# Commit 8: Negative Controls, Syntax Rejection, and Mutation Detection -# ----------------------------------------------------------------------------- - -def mutant_or_instead_of_orn2(src0: int, exec_in: int) -> Tuple[int, int, int]: - """Defect: computes OR instead of ORN2 (fails to invert second operand).""" - saved = exec_in & MASK64 - new_exec = (src0 | exec_in) & MASK64 - scc = SCC_SET if new_exec != 0 else SCC_CLEARED - return saved, new_exec, scc - - -def mutant_orn1_instead_of_orn2(src0: int, exec_in: int) -> Tuple[int, int, int]: - """Defect: inverts first operand instead of second operand (~src0 | exec).""" - saved = exec_in & MASK64 - new_exec = ((~src0 & MASK64) | exec_in) & MASK64 - scc = SCC_SET if new_exec != 0 else SCC_CLEARED - return saved, new_exec, scc - - -def mutant_andn2_instead_of_orn2(src0: int, exec_in: int) -> Tuple[int, int, int]: - """Defect: performs ANDN2 instead of ORN2 (AND instead of OR).""" - saved = exec_in & MASK64 - new_exec = (src0 & (~exec_in & MASK64)) & MASK64 - scc = SCC_SET if new_exec != 0 else SCC_CLEARED - return saved, new_exec, scc - - -def mutant_drop_saved_exec(src0: int, exec_in: int) -> Tuple[int, int, int]: - """Defect: corrupts or zeroes the saved EXEC return value.""" - saved = 0 - new_exec = (src0 | (~exec_in & MASK64)) & MASK64 - scc = SCC_SET if new_exec != 0 else SCC_CLEARED - return saved, new_exec, scc - - -def mutant_inverted_scc_condition(src0: int, exec_in: int) -> Tuple[int, int, int]: - """Defect: inverts SCC condition flag logic.""" - saved = exec_in & MASK64 - new_exec = (src0 | (~exec_in & MASK64)) & MASK64 - scc = SCC_CLEARED if new_exec != 0 else SCC_SET - return saved, new_exec, scc - - -def mutant_32bit_truncation(src0: int, exec_in: int) -> Tuple[int, int, int]: - """Defect: truncates calculations to 32 bits, dropping high dword.""" - saved = exec_in & MASK32 - new_exec = ((src0 & MASK32) | (~exec_in & MASK32)) & MASK32 - scc = SCC_SET if new_exec != 0 else SCC_CLEARED - return saved, new_exec, scc - - -def validate_instruction_syntax(raw_asm: str) -> None: - """Strict syntax parser and checker for s_orn2_saveexec_b64.""" - line = raw_asm.strip() - if not line: - raise ValueError("Empty assembly line") - parts = line.split(None, 1) - opcode = parts[0] - if opcode != "s_orn2_saveexec_b64": - raise ValueError(f"Unrecognized opcode: {opcode}") - if len(parts) < 2: - raise ValueError(f"Missing operands for {opcode}") - - operands = [op.strip() for op in parts[1].split(",")] - if len(operands) != 2: - raise ValueError(f"Expected exactly 2 operands, got {len(operands)}") - - dst = operands[0] - - # Validate destination - if dst == "null" or dst == "exec": - pass - elif dst.startswith("v"): - raise ValueError(f"Vector register {dst} invalid for scalar ALU destination") - elif dst.startswith("s[") and dst.endswith("]"): - inner = dst[2:-1] - range_parts = inner.split(":") - if len(range_parts) != 2: - raise ValueError(f"Malformed SGPR range: {dst}") - lo, hi = int(range_parts[0]), int(range_parts[1]) - if hi != lo + 1: - raise ValueError(f"64-bit SGPR pair must span exactly 2 dwords: {dst}") - if lo % 2 != 0: - raise ValueError(f"64-bit SGPR destination must be even-aligned: {dst}") - if not (0 <= lo <= 102): - raise ValueError(f"SGPR index out of architectural bounds [0..102]: {dst}") - else: - raise ValueError(f"Invalid scalar destination operand: {dst}") - - -class TestNegativeControlsAndMutationDetection(unittest.TestCase): - """Commit 8: Negative controls, syntax rejection, and mutation detection tests.""" - - def test_mutation_or_instead_of_orn2_caught(self) -> None: - """Verify OR mutant produces incorrect result on test vector.""" - src0 = 0x0000_0000_0000_0000 - exec_in = 0x0000_0000_0000_0000 - _, correct_exec, _ = oracle_s_orn2_saveexec_b64(src0, exec_in) - _, mutant_exec, _ = mutant_or_instead_of_orn2(src0, exec_in) - self.assertEqual(correct_exec, EXEC_ALL_ONES) - self.assertEqual(mutant_exec, 0) - self.assertNotEqual(correct_exec, mutant_exec) - - def test_mutation_inverted_operand_order_caught(self) -> None: - """Verify ORN1 mutant (~src0 | exec) is caught due to non-commutativity.""" - src0 = 0xFFFF_FFFF_0000_0000 - exec_in = 0x0000_0000_0000_0000 - _, correct_exec, _ = oracle_s_orn2_saveexec_b64(src0, exec_in) - _, mutant_exec, _ = mutant_orn1_instead_of_orn2(src0, exec_in) - self.assertEqual(correct_exec, EXEC_ALL_ONES) - self.assertEqual(mutant_exec, 0x0000_0000_FFFF_FFFF) - self.assertNotEqual(correct_exec, mutant_exec) - - def test_mutation_andn2_caught(self) -> None: - """Verify ANDN2 mutant is distinguished from ORN2.""" - src0 = 0x5555_5555_5555_5555 - exec_in = 0x5555_5555_5555_5555 - _, correct_exec, _ = oracle_s_orn2_saveexec_b64(src0, exec_in) - _, mutant_exec, _ = mutant_andn2_instead_of_orn2(src0, exec_in) - self.assertEqual(correct_exec, EXEC_ALL_ONES) - self.assertEqual(mutant_exec, 0) - self.assertNotEqual(correct_exec, mutant_exec) - - def test_mutation_dropped_save_caught(self) -> None: - """Verify mutant dropping saved EXEC is caught.""" - exec_in = 0x1234_5678_9ABC_DEF0 - saved_corr, _, _ = oracle_s_orn2_saveexec_b64(0, exec_in) - saved_mut, _, _ = mutant_drop_saved_exec(0, exec_in) - self.assertEqual(saved_corr, exec_in) - self.assertEqual(saved_mut, 0) - self.assertNotEqual(saved_corr, saved_mut) - - def test_mutation_inverted_scc_caught(self) -> None: - """Verify mutant inverting SCC flag is caught on zero and non-zero cases.""" - _, _, scc_corr = oracle_s_orn2_saveexec_b64(0, EXEC_ALL_ONES) - _, _, scc_mut = mutant_inverted_scc_condition(0, EXEC_ALL_ONES) - self.assertEqual(scc_corr, SCC_CLEARED) - self.assertEqual(scc_mut, SCC_SET) - self.assertNotEqual(scc_corr, scc_mut) - - def test_mutation_32bit_truncation_caught(self) -> None: - """Verify 32-bit truncation mutant is caught when upper 32 lanes differ.""" - src0 = 0xAAAA_0000_0000_0000 - exec_in = 0xFFFF_FFFF_FFFF_FFFF - _, correct_exec, _ = oracle_s_orn2_saveexec_b64(src0, exec_in) - _, mutant_exec, _ = mutant_32bit_truncation(src0, exec_in) - self.assertEqual(correct_exec, 0xAAAA_0000_0000_0000) - self.assertEqual(mutant_exec, 0) - self.assertNotEqual(correct_exec, mutant_exec) - - def test_syntax_rejection_unaligned_sgpr(self) -> None: - """Verify rejection of unaligned SGPR pair destination.""" - with self.assertRaises(ValueError) as ctx: - validate_instruction_syntax("s_orn2_saveexec_b64 s[1:2], s[4:5]") - self.assertIn("even-aligned", str(ctx.exception)) - - def test_syntax_rejection_out_of_bounds_sgpr(self) -> None: - """Verify rejection of out-of-bounds SGPR destination.""" - with self.assertRaises(ValueError) as ctx: - validate_instruction_syntax("s_orn2_saveexec_b64 s[104:105], s[0:1]") - self.assertIn("bounds", str(ctx.exception)) - - def test_syntax_rejection_vgpr_as_scalar_dst(self) -> None: - """Verify rejection of VGPR used in scalar saveexec destination.""" - with self.assertRaises(ValueError) as ctx: - validate_instruction_syntax("s_orn2_saveexec_b64 v[0:1], s[0:1]") - self.assertIn("Vector register", str(ctx.exception)) - - def test_syntax_rejection_malformed_syntax(self) -> None: - """Verify rejection of invalid opcode and missing operands.""" - with self.assertRaises(ValueError): - validate_instruction_syntax("s_orn2_saveexec_b32 s[0:1], s[2:3]") - with self.assertRaises(ValueError): - validate_instruction_syntax("s_orn2_saveexec_b64 s[0:1]") - with self.assertRaises(ValueError): - validate_instruction_syntax("") + def test_orn2_every_lane(self): + saveexec_run.check(self, "orn2") if __name__ == "__main__": diff --git a/tests/semantic/test_salu_pack_b32.py b/tests/semantic/test_salu_pack_b32.py index 08a79464a..77295eb58 100644 --- a/tests/semantic/test_salu_pack_b32.py +++ b/tests/semantic/test_salu_pack_b32.py @@ -310,10 +310,6 @@ class TestSaluPackB32PermutationsAndRouting(unittest.TestCase): self.assertEqual(scc_out, scc_in) -if __name__ == "__main__": - unittest.main() - - class TestSaluPackB32BoundariesAliasingAndNegativeControls(unittest.TestCase): """Tests boundary extremes (zeros, ones, sign bits), register aliasing, and negative controls.""" @@ -369,3 +365,7 @@ class TestSaluPackB32BoundariesAliasingAndNegativeControls(unittest.TestCase): ] with self.assertRaises(Exception): run_assembly_lines(bad_lines) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_salu_xnor_saveexec_b64.py b/tests/semantic/test_salu_xnor_saveexec_b64.py index 211be5039..3282883ea 100644 --- a/tests/semantic/test_salu_xnor_saveexec_b64.py +++ b/tests/semantic/test_salu_xnor_saveexec_b64.py @@ -1,1230 +1,33 @@ -"""Semantic reference tests and architectural model for AMD RDNA2 s_xnor_saveexec_b64. +"""s_xnor_saveexec_b64 through the translator, on every lane of a wave64. -AMD RDNA2 (GFX10/GFX1030) Scalar Arithmetic Logic Unit (SALU) Architecture: - In AMD RDNA2 ISA, scalar instructions operate across 32-bit Scalar General-Purpose - Registers (SGPRs), the 64-bit Execution Mask (EXEC / exec_lo, exec_hi), the Scalar - Condition Code (SCC), and special system registers (VCC, M0). +RDNA2 ISA, SOP1: + s_xnor_saveexec_b64: D = EXEC; EXEC = ~(S0 ^ EXEC); SCC = (EXEC != 0). - Instruction: - s_xnor_saveexec_b64 sdst, ssrc0 - - Architectural Operation: - 1. The incoming 64-bit EXEC register is saved to the destination scalar register: - SDST = EXEC - 2. The new 64-bit EXEC mask is calculated as the bitwise equivalence (XNOR) of - the source operand SSRC0 and the prior EXEC mask: - NEW_EXEC = ~(SSRC0 ^ EXEC) & 0xFFFFFFFFFFFFFFFF - 3. The EXEC register is updated with the new mask: - EXEC = NEW_EXEC - 4. The Scalar Condition Code (SCC) is updated based on whether the new EXEC mask - has any active lanes enabled: - SCC = 1 if (NEW_EXEC != 0) else 0 - - Bitwise XNOR Truth Table: - A | B | A XNOR B - --+---+--------- - 0 | 0 | 1 - 0 | 1 | 0 - 1 | 0 | 0 - 1 | 1 | 1 - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. +Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in +tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an +SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of +this name ran a self-built interpreter and never called the translator. """ -from __future__ import annotations - -from dataclasses import dataclass, field -from enum import Enum, auto import os -import random -import struct import sys import unittest -from typing import List, Optional, Tuple, Union -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF -SIGN_BIT64: int = 0x8000000000000000 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import saveexec_run # noqa: E402 (support puts tools/ on sys.path) -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 +class Saveexec(unittest.TestCase): + def test_xnor_by_hand(self): + # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = ~(S0 ^ EXEC) written out by hand. + lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) + s0, e = lanes(0, 32), lanes(16, 48) + want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), + "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), + "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["xnor"] + self.assertEqual(saveexec_run.model("xnor", s0, e), (want, e, 1)) - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def split_dwords(val64: int) -> Tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def popcount64(val: int) -> int: - """Count the number of set bits in an unsigned 64-bit integer.""" - return bin(val & MASK64).count("1") - - -def ref_xnor64(a: int, b: int) -> int: - """Reference mathematical oracle for 64-bit bitwise XNOR: ~(a ^ b).""" - return (~(a ^ b)) & MASK64 - - -def ref_scc(val64: int) -> int: - """RDNA2 SALU condition flag: SCC is 1 if 64-bit value is non-zero, else 0.""" - return 1 if (val64 & MASK64) != 0 else 0 - - -def oracle_s_xnor_saveexec_b64(src0: int, exec_current: int) -> Tuple[int, int, int]: - """Reference architectural oracle for s_xnor_saveexec_b64. - - Returns: - (saved_exec, new_exec, scc) - """ - saved_exec = exec_current & MASK64 - new_exec = ref_xnor64(src0, exec_current) - scc = ref_scc(new_exec) - return saved_exec, new_exec, scc - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - """Register file domain for RDNA2 ISA.""" - SGPR = auto() - VGPR = auto() - SPECIAL = auto() - - -class SpecialReg(Enum): - """Architectural special registers relevant to SALU execution.""" - EXEC = auto() - VCC = auto() - SCC = auto() - NULL = auto() - - -@dataclass(frozen=True) -class RegPair: - """Represents a 64-bit aligned register pair, e.g. s[4:5] or v[0:1].""" - index: int - reg_type: RegType = RegType.SGPR - - def __post_init__(self) -> None: - if self.reg_type not in (RegType.SGPR, RegType.VGPR): - raise ValueError(f"Invalid reg_type: {self.reg_type}") - if self.index < 0: - raise ValueError(f"Register index must be non-negative, got {self.index}") - if self.index % 2 != 0: - raise ValueError(f"64-bit register pair must be even-aligned, got {self.index}") - - @property - def lo_reg(self) -> int: - return self.index - - @property - def hi_reg(self) -> int: - return self.index + 1 - - @property - def name(self) -> str: - prefix = "s" if self.reg_type == RegType.SGPR else "v" - return f"{prefix}[{self.index}:{self.index + 1}]" - - -@dataclass(frozen=True) -class SpecialRegOperand: - """Represents an architectural special register operand like exec or vcc.""" - reg: SpecialReg - - @property - def name(self) -> str: - return self.reg.name.lower() - - -@dataclass(frozen=True) -class Literal64: - """Represents a 64-bit constant literal scalar operand.""" - bits: int - - def __post_init__(self) -> None: - if not (0 <= self.bits <= MASK64): - raise ValueError(f"Literal64 out of 64-bit unsigned bounds: {self.bits}") - - @property - def name(self) -> str: - return f"0x{self.bits:016x}" - - -@dataclass(frozen=True) -class SALUSourceOperand: - """Typed source operand for scalar arithmetic instructions.""" - source: Union[RegPair, SpecialRegOperand, Literal64] - - def disassemble(self) -> str: - return self.source.name - - -@dataclass(frozen=True) -class SXnorSaveexecB64Instruction: - """Symbolic AST node representing the s_xnor_saveexec_b64 instruction.""" - dst: Union[RegPair, SpecialRegOperand] - src0: SALUSourceOperand - - def __post_init__(self) -> None: - if isinstance(self.dst, RegPair): - if self.dst.reg_type != RegType.SGPR: - raise TypeError(f"SALU destination must be SGPR pair, got {self.dst.reg_type}") - elif isinstance(self.dst, SpecialRegOperand): - if self.dst.reg not in (SpecialReg.EXEC, SpecialReg.VCC): - raise TypeError(f"Invalid special register destination: {self.dst.reg}") - else: - raise TypeError(f"Unsupported destination operand type: {type(self.dst)}") - - def disassemble(self) -> str: - dst_str = self.dst.name if hasattr(self.dst, "name") else str(self.dst) - return f"s_xnor_saveexec_b64 {dst_str}, {self.src0.disassemble()}" - - -def parse_salu_instruction(line: str) -> SXnorSaveexecB64Instruction: - """Parse a single assembly line into an SXnorSaveexecB64Instruction AST node.""" - line = line.strip() - if not line.startswith("s_xnor_saveexec_b64"): - raise ValueError(f"Not an s_xnor_saveexec_b64 instruction: {line}") - payload = line[len("s_xnor_saveexec_b64"):].strip() - parts = [p.strip() for p in payload.split(",")] - if len(parts) != 2: - raise ValueError(f"Expected 2 operands (dst, src0), got: {line}") - dst_part, src0_part = parts - - # Parse destination - if dst_part.lower() == "exec": - dst: Union[RegPair, SpecialRegOperand] = SpecialRegOperand(SpecialReg.EXEC) - elif dst_part.lower() == "vcc": - dst = SpecialRegOperand(SpecialReg.VCC) - elif dst_part.startswith("s[") and dst_part.endswith("]"): - idx_str = dst_part[2:-1] - lo, hi = map(int, idx_str.split(":")) - if hi != lo + 1: - raise ValueError(f"Invalid 64-bit pair range: {dst_part}") - dst = RegPair(index=lo, reg_type=RegType.SGPR) - else: - raise ValueError(f"Unrecognized destination operand: {dst_part}") - - # Parse src0 - if src0_part.lower() == "exec": - src_op = SALUSourceOperand(SpecialRegOperand(SpecialReg.EXEC)) - elif src0_part.lower() == "vcc": - src_op = SALUSourceOperand(SpecialRegOperand(SpecialReg.VCC)) - elif src0_part.startswith("s[") and src0_part.endswith("]"): - idx_str = src0_part[2:-1] - lo, hi = map(int, idx_str.split(":")) - if hi != lo + 1: - raise ValueError(f"Invalid 64-bit pair range: {src0_part}") - src_op = SALUSourceOperand(RegPair(index=lo, reg_type=RegType.SGPR)) - elif src0_part.startswith("0x") or src0_part.isdigit() or (src0_part.startswith("-") and src0_part[1:].isdigit()): - val = int(src0_part, 0) & MASK64 - src_op = SALUSourceOperand(Literal64(bits=val)) - else: - raise ValueError(f"Unrecognized src0 operand: {src0_part}") - - return SXnorSaveexecB64Instruction(dst=dst, src0=src_op) - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register state for RDNA2 SALU execution.""" - sgprs: List[int] = field(default_factory=lambda: [0] * 128) - exec_mask: int = MASK64 - scc: int = 0 - vcc: int = 0 - - def get_sgpr64(self, index: int) -> int: - """Read 64-bit value from aligned SGPR pair s[index:index+1].""" - if index < 0 or index + 1 >= len(self.sgprs): - raise IndexError(f"SGPR index out of range: {index}") - return join_dwords(self.sgprs[index], self.sgprs[index + 1]) - - def set_sgpr64(self, index: int, val: int) -> None: - """Write 64-bit value into aligned SGPR pair s[index:index+1].""" - if index < 0 or index + 1 >= len(self.sgprs): - raise IndexError(f"SGPR index out of range: {index}") - lo, hi = split_dwords(val) - self.sgprs[index] = lo - self.sgprs[index + 1] = hi - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for s_xnor_saveexec_b64.""" - - def resolve_source(self, op: SALUSourceOperand, state: ScalarMachineState) -> int: - """Resolve a 64-bit source operand against machine state.""" - if isinstance(op.source, RegPair): - return state.get_sgpr64(op.source.index) - elif isinstance(op.source, SpecialRegOperand): - if op.source.reg == SpecialReg.EXEC: - return state.exec_mask & MASK64 - elif op.source.reg == SpecialReg.VCC: - return state.vcc & MASK64 - elif op.source.reg == SpecialReg.NULL: - return 0 - else: - raise ValueError(f"Unsupported source special register: {op.source.reg}") - elif isinstance(op.source, Literal64): - return op.source.bits & MASK64 - else: - raise TypeError(f"Unknown source operand type: {type(op.source)}") - - def step(self, instr: SXnorSaveexecB64Instruction, state: ScalarMachineState) -> Tuple[int, int, int]: - """Execute one s_xnor_saveexec_b64 instruction deterministically.""" - # 1. Atomic read phase - src0_val = self.resolve_source(instr.src0, state) - incoming_exec = state.exec_mask & MASK64 - - # 2. Mathematical evaluation - saved_exec, new_exec, scc = oracle_s_xnor_saveexec_b64(src0_val, incoming_exec) - - # 3. Write-back phase - # Destination register write - if isinstance(instr.dst, RegPair): - state.set_sgpr64(instr.dst.index, saved_exec) - elif isinstance(instr.dst, SpecialRegOperand): - if instr.dst.reg == SpecialReg.VCC: - state.vcc = saved_exec - elif instr.dst.reg == SpecialReg.EXEC: - # If destination is EXEC, EXEC will be overwritten by new_exec in final state - pass - - # EXEC and SCC update - state.exec_mask = new_exec - state.scc = scc - - return saved_exec, new_exec, scc - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - num_lanes: int - exec_mask: int = MASK64 - scc: int = 0 - vcc: int = 0 - sgprs: List[int] = field(default_factory=lambda: [0] * 128) - vgprs: List[List[int]] = field(default_factory=list) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.num_lanes == 32: - self.exec_mask &= MASK32 - - def is_lane_active(self, lane_id: int) -> bool: - """Check if a specific SIMD lane is active according to the EXEC mask.""" - if 0 <= lane_id < self.num_lanes: - return bool(self.exec_mask & (1 << lane_id)) - return False - - def active_lane_count(self) -> int: - """Return the number of currently active SIMD lanes.""" - mask = (1 << self.num_lanes) - 1 - return popcount64(self.exec_mask & mask) - - def get_sgpr64(self, index: int) -> int: - return join_dwords(self.sgprs[index], self.sgprs[index + 1]) - - def set_sgpr64(self, index: int, val: int) -> None: - lo, hi = split_dwords(val) - self.sgprs[index] = lo - self.sgprs[index + 1] = hi - - -class SIMDInterpreter: - """SIMD wavefront execution engine modeling multi-lane divergence and masking.""" - - def __init__(self) -> None: - self.scalar_interp = ScalarInterpreter() - - def step_salu(self, instr: SXnorSaveexecB64Instruction, state: SIMDState) -> Tuple[int, int, int]: - """Execute a SALU instruction on the wavefront, updating shared EXEC/SCC/SGPRs.""" - scalar_state = ScalarMachineState( - sgprs=list(state.sgprs), - exec_mask=state.exec_mask, - scc=state.scc, - vcc=state.vcc, - ) - saved_exec, new_exec, scc = self.scalar_interp.step(instr, scalar_state) - - # Sync back to SIMD state - state.sgprs = list(scalar_state.sgprs) - if state.num_lanes == 32: - state.exec_mask = new_exec & MASK32 - else: - state.exec_mask = new_exec & MASK64 - state.scc = scc - state.vcc = scalar_state.vcc - - return saved_exec, state.exec_mask, scc - - def execute_valu_add(self, dst_vgpr: int, src0_vgpr: int, src1_vgpr: int, state: SIMDState) -> None: - """Execute a VALU vector add (v_add_u32) across all lanes under the current EXEC mask.""" - for lane in range(state.num_lanes): - if state.is_lane_active(lane): - a = state.vgprs[lane][src0_vgpr] - b = state.vgprs[lane][src1_vgpr] - state.vgprs[lane][dst_vgpr] = u32(a + b) - # Inactive lanes strictly preserve their previous destination VGPR content - - -class TestSXnorSaveexecB64ModelAndOracle(unittest.TestCase): - """Reference mathematical oracle and architectural model tests.""" - - def test_truth_table_all_bits(self) -> None: - """Verify the 1-bit truth table of XNOR across all 4 input combinations.""" - cases = [ - (0, 0, 1), - (0, 1, 0), - (1, 0, 0), - (1, 1, 1), - ] - for b0, b1, expected in cases: - with self.subTest(b0=b0, b1=b1): - s0 = MASK64 if b0 else 0 - s1 = MASK64 if b1 else 0 - want = MASK64 if expected else 0 - got = ref_xnor64(s0, s1) - self.assertEqual(got, want) - self.assertEqual(ref_scc(got), 1 if expected else 0) - - def test_commutativity_symmetry(self) -> None: - """Verify that 64-bit XNOR is strictly commutative.""" - rng = random.Random(0x1337) - for _ in range(50): - a = rng.getrandbits(64) - b = rng.getrandbits(64) - self.assertEqual(ref_xnor64(a, b), ref_xnor64(b, a)) - - def test_algebraic_identities(self) -> None: - """Verify core boolean algebraic identities of the 64-bit XNOR operator.""" - rng = random.Random(0xCAFE) - for _ in range(50): - x = rng.getrandbits(64) - # Identity: x XNOR 0xFFFFFFFFFFFFFFFF == x - self.assertEqual(ref_xnor64(x, MASK64), x) - # Negation: x XNOR 0 == ~x - self.assertEqual(ref_xnor64(x, 0), (~x) & MASK64) - # Self-equivalence: x XNOR x == 0xFFFFFFFFFFFFFFFF - self.assertEqual(ref_xnor64(x, x), MASK64) - # Contradiction: x XNOR (~x) == 0 - self.assertEqual(ref_xnor64(x, (~x) & MASK64), 0) - # Involution with XOR: (x XNOR y) XNOR 0 == x ^ y - y = rng.getrandbits(64) - self.assertEqual(ref_xnor64(ref_xnor64(x, y), 0), (x ^ y) & MASK64) - - def test_de_morgan_and_boolean_expansion(self) -> None: - """Verify equivalence to canonical SOP form: (A & B) | (~A & ~B).""" - rng = random.Random(0xBEEF) - for _ in range(50): - a = rng.getrandbits(64) - b = rng.getrandbits(64) - expanded = ((a & b) | ((~a & MASK64) & (~b & MASK64))) & MASK64 - self.assertEqual(ref_xnor64(a, b), expanded) - - def test_scc_flag_truth(self) -> None: - """Verify SCC condition code behavior on exact zero and non-zero boundaries.""" - self.assertEqual(ref_scc(0), 0) - self.assertEqual(ref_scc(1), 1) - self.assertEqual(ref_scc(MASK64), 1) - self.assertEqual(ref_scc(SIGN_BIT64), 1) - for i in range(64): - self.assertEqual(ref_scc(1 << i), 1) - - def test_saveexec_architectural_contract(self) -> None: - """Verify the three-part architectural return contract of s_xnor_saveexec_b64.""" - test_cases = [ - (0x0000000000000000, 0x0000000000000000, 0x0000000000000000, MASK64, 1), - (MASK64, MASK64, MASK64, MASK64, 1), - (0x0000000000000000, MASK64, MASK64, 0x0000000000000000, 0), - (MASK64, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0), - (0xAAAAAAAAAAAAAAAA, 0x5555555555555555, 0x5555555555555555, 0x0000000000000000, 0), - (0xAAAAAAAAAAAAAAAA, 0xAAAAAAAAAAAAAAAA, 0xAAAAAAAAAAAAAAAA, MASK64, 1), - (0x1234567890ABCDEF, 0xFEDCBA0987654321, 0xFEDCBA0987654321, - (~(0x1234567890ABCDEF ^ 0xFEDCBA0987654321)) & MASK64, 1), - ] - for src0, exec_curr, want_saved, want_new, want_scc in test_cases: - with self.subTest(src0=hex(src0), exec_curr=hex(exec_curr)): - saved, new_exec, scc = oracle_s_xnor_saveexec_b64(src0, exec_curr) - self.assertEqual(saved, want_saved) - self.assertEqual(new_exec, want_new) - self.assertEqual(scc, want_scc) - - def test_walking_bits(self) -> None: - """Verify single walking bit across all 64 lane positions.""" - for i in range(64): - bit = 1 << i - # When src0 == bit and exec == bit: bit matches bit -> XNOR bit is 1, all others 1 - saved, new_exec, scc = oracle_s_xnor_saveexec_b64(bit, bit) - self.assertEqual(saved, bit) - self.assertEqual(new_exec, MASK64) - self.assertEqual(scc, 1) - - # When src0 == bit and exec == ~bit: bit position differs -> XNOR bit is 0, all others 0 -> new_exec == 0 - saved, new_exec, scc = oracle_s_xnor_saveexec_b64(bit, (~bit) & MASK64) - self.assertEqual(saved, (~bit) & MASK64) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - - def test_fuzz_random_vectors(self) -> None: - """Fuzz testing with 200 random 64-bit bitmasks.""" - rng = random.Random(0x9999) - for _ in range(200): - src = rng.getrandbits(64) - curr = rng.getrandbits(64) - saved, new_exec, scc = oracle_s_xnor_saveexec_b64(src, curr) - self.assertEqual(saved, curr) - expected_new = (~(src ^ curr)) & MASK64 - self.assertEqual(new_exec, expected_new) - self.assertEqual(scc, 1 if expected_new != 0 else 0) - - -class TestSymbolicAST(unittest.TestCase): - """Symbolic AST opcode definitions, expression typing, and parser tests.""" - - def test_ast_construction_sgpr_operands(self) -> None: - """Construct AST node with SGPR pair operands.""" - dst = RegPair(index=4, reg_type=RegType.SGPR) - src0 = SALUSourceOperand(RegPair(index=2, reg_type=RegType.SGPR)) - instr = SXnorSaveexecB64Instruction(dst=dst, src0=src0) - self.assertEqual(instr.dst, dst) - self.assertEqual(instr.src0, src0) - self.assertEqual(instr.disassemble(), "s_xnor_saveexec_b64 s[4:5], s[2:3]") - - def test_ast_construction_literal_operand(self) -> None: - """Construct AST node with a 64-bit literal constant.""" - dst = RegPair(index=0, reg_type=RegType.SGPR) - lit = Literal64(bits=0x123456789ABCDEF0) - instr = SXnorSaveexecB64Instruction(dst=dst, src0=SALUSourceOperand(lit)) - self.assertEqual(instr.disassemble(), "s_xnor_saveexec_b64 s[0:1], 0x123456789abcdef0") - - def test_ast_construction_special_registers(self) -> None: - """Construct AST node using special registers exec and vcc.""" - dst = SpecialRegOperand(SpecialReg.EXEC) - src = SALUSourceOperand(SpecialRegOperand(SpecialReg.EXEC)) - instr = SXnorSaveexecB64Instruction(dst=dst, src0=src) - self.assertEqual(instr.disassemble(), "s_xnor_saveexec_b64 exec, exec") - - def test_ast_immutability(self) -> None: - """Ensure AST nodes are immutable frozen dataclasses.""" - dst = RegPair(index=8, reg_type=RegType.SGPR) - src = SALUSourceOperand(RegPair(index=6, reg_type=RegType.SGPR)) - instr = SXnorSaveexecB64Instruction(dst=dst, src0=src) - with self.assertRaises(Exception): - instr.dst = RegPair(index=10, reg_type=RegType.SGPR) # type: ignore - - def test_regpair_alignment_enforcement(self) -> None: - """Verify that odd SGPR indices are rejected for 64-bit register pairs.""" - with self.assertRaises(ValueError): - RegPair(index=1, reg_type=RegType.SGPR) - with self.assertRaises(ValueError): - RegPair(index=3, reg_type=RegType.SGPR) - p = RegPair(index=2, reg_type=RegType.SGPR) - self.assertEqual(p.lo_reg, 2) - self.assertEqual(p.hi_reg, 3) - - def test_invalid_destination_rejection(self) -> None: - """Verify that non-SGPR destinations raise TypeError.""" - vgpr_dst = RegPair(index=0, reg_type=RegType.VGPR) - src = SALUSourceOperand(RegPair(index=2, reg_type=RegType.SGPR)) - with self.assertRaises(TypeError): - SXnorSaveexecB64Instruction(dst=vgpr_dst, src0=src) - - def test_parser_roundtrip(self) -> None: - """Verify that assembly parser parses and disassembles correctly.""" - lines = [ - "s_xnor_saveexec_b64 s[4:5], s[2:3]", - "s_xnor_saveexec_b64 s[0:1], exec", - "s_xnor_saveexec_b64 exec, s[8:9]", - "s_xnor_saveexec_b64 s[10:11], 0x0000000000000000", - "s_xnor_saveexec_b64 s[12:13], 0xffffffffffffffff", - ] - for line in lines: - with self.subTest(line=line): - ast_node = parse_salu_instruction(line) - self.assertEqual(ast_node.disassemble(), line) - - def test_parser_syntax_errors(self) -> None: - """Verify parser rejections on malformed instructions.""" - bad_lines = [ - "v_add_f64 s[4:5], s[2:3]", - "s_xnor_saveexec_b64 s[4:5]", - "s_xnor_saveexec_b64 s[1:2], s[2:3]", - "s_xnor_saveexec_b64 s[4:5], s[2:3], s[0:1]", - "s_xnor_saveexec_b64 s[4:6], s[2:3]", - ] - for bad in bad_lines: - with self.subTest(bad=bad): - with self.assertRaises((ValueError, TypeError)): - parse_salu_instruction(bad) - - -class TestScalarInterpreter(unittest.TestCase): - """Deterministic scalar instruction interpreter tests.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_single_step_execution(self) -> None: - """Verify basic scalar instruction execution and register updates.""" - # Setup initial state - self.state.exec_mask = 0xFFFFFFFF00000000 - self.state.set_sgpr64(2, 0xAAAAAAAAAAAAAAAA) - self.state.scc = 0 - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[4:5], s[2:3]") - saved, new_exec, scc = self.interp.step(instr, self.state) - - # Saved EXEC should be previous EXEC - self.assertEqual(saved, 0xFFFFFFFF00000000) - self.assertEqual(self.state.get_sgpr64(4), 0xFFFFFFFF00000000) - - # New EXEC should be ~(0xAAAAAAAAAAAAAAAA ^ 0xFFFFFFFF00000000) - expected_new = (~(0xAAAAAAAAAAAAAAAA ^ 0xFFFFFFFF00000000)) & MASK64 - self.assertEqual(new_exec, expected_new) - self.assertEqual(self.state.exec_mask, expected_new) - - # SCC should be non-zero (1) - self.assertEqual(scc, 1) - self.assertEqual(self.state.scc, 1) - - def test_zero_result_scc_cleared(self) -> None: - """Verify SCC is 0 when new EXEC becomes all zeros.""" - # When ssrc0 == ~EXEC, ~(ssrc0 ^ EXEC) == ~(~EXEC ^ EXEC) == ~(-1) == 0 - incoming = 0x1234567890ABCDEF - self.state.exec_mask = incoming - self.state.set_sgpr64(0, (~incoming) & MASK64) - self.state.scc = 1 # Pre-set SCC to 1 to verify transition to 0 - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[6:7], s[0:1]") - saved, new_exec, scc = self.interp.step(instr, self.state) - - self.assertEqual(saved, incoming) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - self.assertEqual(self.state.exec_mask, 0) - self.assertEqual(self.state.scc, 0) - - def test_literal_operand_execution(self) -> None: - """Verify execution with 64-bit literal constant.""" - self.state.exec_mask = MASK64 - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[8:9], 0x5555555555555555") - saved, new_exec, scc = self.interp.step(instr, self.state) - - self.assertEqual(saved, MASK64) - self.assertEqual(self.state.get_sgpr64(8), MASK64) - self.assertEqual(new_exec, 0x5555555555555555) - self.assertEqual(self.state.exec_mask, 0x5555555555555555) - self.assertEqual(scc, 1) - - def test_special_reg_vcc_source(self) -> None: - """Verify reading from VCC special register.""" - self.state.vcc = 0x0123456789ABCDEF - self.state.exec_mask = MASK64 - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[10:11], vcc") - saved, new_exec, scc = self.interp.step(instr, self.state) - - self.assertEqual(saved, MASK64) - self.assertEqual(new_exec, 0x0123456789ABCDEF) - self.assertEqual(self.state.exec_mask, 0x0123456789ABCDEF) - self.assertEqual(scc, 1) - - def test_sequential_instruction_chaining(self) -> None: - """Verify a chain of saveexec instructions accurately passes EXEC state.""" - self.state.exec_mask = 0x00000000FFFFFFFF - self.state.set_sgpr64(0, 0x00000000FFFFFFFF) - self.state.set_sgpr64(2, 0xFFFFFFFFFFFFFFFF) - - # Step 1: s[4:5] = EXEC (0x00000000FFFFFFFF); EXEC = ~(s[0:1] ^ EXEC) = ~0 = MASK64 - instr1 = parse_salu_instruction("s_xnor_saveexec_b64 s[4:5], s[0:1]") - s1, e1, c1 = self.interp.step(instr1, self.state) - self.assertEqual(s1, 0x00000000FFFFFFFF) - self.assertEqual(e1, MASK64) - self.assertEqual(c1, 1) - - # Step 2: s[6:7] = EXEC (MASK64); EXEC = ~(s[2:3] ^ EXEC) = ~(MASK64 ^ MASK64) = MASK64 - instr2 = parse_salu_instruction("s_xnor_saveexec_b64 s[6:7], s[2:3]") - s2, e2, c2 = self.interp.step(instr2, self.state) - self.assertEqual(s2, MASK64) - self.assertEqual(e2, MASK64) - self.assertEqual(c2, 1) - - def test_determinism_repeatability(self) -> None: - """Ensure repeating same step on identical state produces identical output.""" - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[0:1], s[2:3]") - for _ in range(5): - st = ScalarMachineState() - st.exec_mask = 0x1122334455667788 - st.set_sgpr64(2, 0x8877665544332211) - saved, new_exec, scc = self.interp.step(instr, st) - self.assertEqual(saved, 0x1122334455667788) - self.assertEqual(new_exec, (~(0x8877665544332211 ^ 0x1122334455667788)) & MASK64) - self.assertEqual(scc, 1) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """SIMD multi-lane divergence and 32/64-bit EXEC masking tests.""" - - def setUp(self) -> None: - self.simd = SIMDInterpreter() - - def test_divergent_mask_generation(self) -> None: - """Verify generating divergent active/inactive lane patterns.""" - state = SIMDState(num_lanes=64, exec_mask=MASK64) - # S0 = alternating pattern: 0x5555555555555555 (even lanes 1, odd lanes 0) - # Initial EXEC = MASK64 - # NEW_EXEC = ~(0x5555... ^ MASK64) = 0x5555555555555555 - state.set_sgpr64(0, 0x5555555555555555) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - saved, new_exec, scc = self.simd.step_salu(instr, state) - - self.assertEqual(saved, MASK64) - self.assertEqual(new_exec, 0x5555555555555555) - self.assertEqual(state.active_lane_count(), 32) - for lane in range(64): - expected_active = (lane % 2 == 0) - self.assertEqual(state.is_lane_active(lane), expected_active) - - def test_valu_preservation_under_divergent_mask(self) -> None: - """Verify that inactive lanes strictly preserve their VGPR state during VALU ops.""" - state = SIMDState(num_lanes=64, exec_mask=MASK64) - - # Pre-populate VGPRs for all lanes: - # v0 = lane index - # v1 = 100 - # v2 = 0xDEADBEEF (destination sentinel) - for lane in range(64): - state.vgprs[lane][0] = lane - state.vgprs[lane][1] = 100 - state.vgprs[lane][2] = 0xDEADBEEF - - # EXEC: activate only lanes 0..15 (lower 16 lanes) - # Using S0 = 0x000000000000FFFF with EXEC = MASK64 -> NEW_EXEC = 0x000000000000FFFF - state.set_sgpr64(4, 0x000000000000FFFF) - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[6:7], s[4:5]") - self.simd.step_salu(instr, state) - - self.assertEqual(state.active_lane_count(), 16) - - # Run vector add: v2 = v0 + v1 - self.simd.execute_valu_add(dst_vgpr=2, src0_vgpr=0, src1_vgpr=1, state=state) - - # Check lane outcomes: lanes 0..15 must have lane + 100, lanes 16..63 must still be 0xDEADBEEF - for lane in range(64): - if lane < 16: - self.assertEqual(state.vgprs[lane][2], lane + 100, f"Active lane {lane} failed") - else: - self.assertEqual(state.vgprs[lane][2], 0xDEADBEEF, f"Inactive lane {lane} overwritten") - - def test_reactivation_of_disabled_lanes(self) -> None: - """Verify re-activation of previously disabled lanes through XNOR logic. - - In RDNA2 control flow, XNOR with 0 turns inactive (0) lanes ON because 0 XNOR 0 == 1. - """ - # Start with all lanes disabled except lane 0 - state = SIMDState(num_lanes=64, exec_mask=0x0000000000000001) - self.assertEqual(state.active_lane_count(), 1) - - # S0 = 0 -> NEW_EXEC = ~(0 ^ EXEC) = ~EXEC - # Lane 0 (was 1) becomes 0; lanes 1..63 (were 0) become 1! - state.set_sgpr64(0, 0) - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - saved, new_exec, scc = self.simd.step_salu(instr, state) - - self.assertEqual(saved, 0x0000000000000001) - self.assertEqual(new_exec, MASK64 ^ 1) - self.assertEqual(state.active_lane_count(), 63) - self.assertFalse(state.is_lane_active(0)) - for lane in range(1, 64): - self.assertTrue(state.is_lane_active(lane)) - - def test_wave32_mode_masking(self) -> None: - """Verify Wave32 execution mode restricts active mask to 32 lanes.""" - state = SIMDState(num_lanes=32, exec_mask=MASK32) - self.assertEqual(state.active_lane_count(), 32) - - # XNOR with half mask in Wave32 - state.set_sgpr64(0, 0x0000FFFF) - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - saved, new_exec, scc = self.simd.step_salu(instr, state) - - self.assertEqual(saved, MASK32) - self.assertEqual(new_exec, 0x0000FFFF) - self.assertEqual(state.active_lane_count(), 16) - self.assertFalse(state.is_lane_active(32)) - - def test_total_divergence_all_lanes_disabled(self) -> None: - """Verify total divergence where all lanes are disabled produces 0 active count.""" - state = SIMDState(num_lanes=64, exec_mask=0xAAAAAAAAAAAAAAAA) - # S0 is bitwise NOT of EXEC -> NEW_EXEC == 0 - state.set_sgpr64(0, 0x5555555555555555) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - saved, new_exec, scc = self.simd.step_salu(instr, state) - - self.assertEqual(saved, 0xAAAAAAAAAAAAAAAA) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - self.assertEqual(state.active_lane_count(), 0) - for lane in range(64): - self.assertFalse(state.is_lane_active(lane)) - - -class TestRegisterAliasing(unittest.TestCase): - """Register aliasing and in-place operand preservation tests.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - - def test_dst_equals_src0_in_place(self) -> None: - """Verify atomic read-before-write when destination SGPR equals source SGPR.""" - state = ScalarMachineState() - # Initial: s[4:5] = 0xAAAAAAAAAAAAAAAA, EXEC = 0x5555555555555555 - state.set_sgpr64(4, 0xAAAAAAAAAAAAAAAA) - state.exec_mask = 0x5555555555555555 - - # s_xnor_saveexec_b64 s[4:5], s[4:5] - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[4:5], s[4:5]") - saved, new_exec, scc = self.interp.step(instr, state) - - # Saved EXEC should be old EXEC (0x5555555555555555) - self.assertEqual(saved, 0x5555555555555555) - self.assertEqual(state.get_sgpr64(4), 0x5555555555555555) - - # New EXEC must be computed from original s[4:5] before it was overwritten - # ~(0xAAAAAAAAAAAAAAAA ^ 0x5555555555555555) = ~(0xFFFFFFFFFFFFFFFF) = 0 - self.assertEqual(new_exec, 0) - self.assertEqual(state.exec_mask, 0) - self.assertEqual(scc, 0) - - def test_src0_equals_exec_special(self) -> None: - """Verify self-XNOR behavior when SSRC0 is the EXEC register itself.""" - state = ScalarMachineState() - state.exec_mask = 0x123456789ABCDEF0 - state.set_sgpr64(2, 0) - - # s_xnor_saveexec_b64 s[2:3], exec - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], exec") - saved, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(saved, 0x123456789ABCDEF0) - self.assertEqual(state.get_sgpr64(2), 0x123456789ABCDEF0) - # ~(EXEC ^ EXEC) == ~(0) == MASK64 - self.assertEqual(new_exec, MASK64) - self.assertEqual(state.exec_mask, MASK64) - self.assertEqual(scc, 1) - - def test_dst_equals_exec(self) -> None: - """Verify behavior when destination operand is explicitly the EXEC register.""" - state = ScalarMachineState() - state.exec_mask = 0x0F0F0F0F0F0F0F0F - state.set_sgpr64(2, 0x0000000000000000) - - # s_xnor_saveexec_b64 exec, s[2:3] - instr = parse_salu_instruction("s_xnor_saveexec_b64 exec, s[2:3]") - saved, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(saved, 0x0F0F0F0F0F0F0F0F) - expected_new = (~(0x0000000000000000 ^ 0x0F0F0F0F0F0F0F0F)) & MASK64 - self.assertEqual(new_exec, expected_new) - self.assertEqual(state.exec_mask, expected_new) - - def test_dst_and_src0_both_exec(self) -> None: - """Verify execution when both SDST and SSRC0 are the EXEC register.""" - state = ScalarMachineState() - state.exec_mask = 0xDEADBEEFCAFE0000 - - instr = parse_salu_instruction("s_xnor_saveexec_b64 exec, exec") - saved, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(saved, 0xDEADBEEFCAFE0000) - self.assertEqual(new_exec, MASK64) - self.assertEqual(state.exec_mask, MASK64) - self.assertEqual(scc, 1) - - def test_adjacent_register_non_interference(self) -> None: - """Verify writing a 64-bit pair leaves immediately adjacent SGPRs unchanged.""" - state = ScalarMachineState() - state.set_sgpr64(2, 0x1111111111111111) - state.set_sgpr64(4, 0x2222222222222222) - state.set_sgpr64(6, 0x3333333333333333) - state.exec_mask = 0xAAAAAAAAAAAAAAAA - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[4:5], s[2:3]") - self.interp.step(instr, state) - - # s[2:3] (src0) and s[6:7] (neighbor) must remain completely untouched - self.assertEqual(state.get_sgpr64(2), 0x1111111111111111) - self.assertEqual(state.get_sgpr64(6), 0x3333333333333333) - # s[4:5] should hold old EXEC - self.assertEqual(state.get_sgpr64(4), 0xAAAAAAAAAAAAAAAA) - - def test_unrelated_sgprs_preserved(self) -> None: - """Verify full SGPR file preservation across instruction execution.""" - state = ScalarMachineState() - for i in range(128): - state.sgprs[i] = 0xA000 + i - - state.exec_mask = 0x1234567887654321 - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[10:11], s[20:21]") - self.interp.step(instr, state) - - # Verify only s10 and s11 changed - for i in range(128): - if i in (10, 11): - continue - self.assertEqual(state.sgprs[i], 0xA000 + i, f"SGPR s{i} was unexpectedly corrupted") - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Condition codes, status flags, and carry/borrow generation tests.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - - def test_scc_all_64_single_bit_positions(self) -> None: - """Verify SCC is 1 when exactly one bit in NEW_EXEC is set for each of the 64 bit positions.""" - for bit_idx in range(64): - with self.subTest(bit_idx=bit_idx): - state = ScalarMachineState() - # We want NEW_EXEC == (1 << bit_idx) - # NEW_EXEC = ~(S0 ^ EXEC) - # If we choose EXEC = 0, NEW_EXEC = ~(S0 ^ 0) = ~S0 - # Thus ~S0 = (1 << bit_idx) => S0 = ~(1 << bit_idx) & MASK64 - target_bit = (1 << bit_idx) - s0 = (~target_bit) & MASK64 - - state.exec_mask = 0 - state.set_sgpr64(0, s0) - state.scc = 0 - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - saved, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(saved, 0) - self.assertEqual(new_exec, target_bit) - self.assertEqual(scc, 1) - self.assertEqual(state.scc, 1) - - def test_scc_zero_flag_state(self) -> None: - """Verify SCC is strictly 0 when NEW_EXEC is exactly 0.""" - state = ScalarMachineState() - # EXEC = 0xFFFFFFFF0000FFFF - # S0 = ~EXEC => S0 ^ EXEC = MASK64 => ~(S0 ^ EXEC) = 0 - exec_val = 0xFFFFFFFF0000FFFF - state.exec_mask = exec_val - state.set_sgpr64(0, (~exec_val) & MASK64) - state.scc = 1 # Verify transition from 1 to 0 - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[4:5], s[0:1]") - saved, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(saved, exec_val) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - self.assertEqual(state.scc, 0) - - def test_scc_state_transitions(self) -> None: - """Verify all 4 state transitions of SCC: 0->0, 0->1, 1->0, 1->1.""" - transitions = [ - (0, 0, 0), # init_scc=0, target_new_exec=0 -> expected_scc=0 - (0, MASK64, 1), # init_scc=0, target_new_exec!=0 -> expected_scc=1 - (1, 0, 0), # init_scc=1, target_new_exec=0 -> expected_scc=0 - (1, 0x1, 1), # init_scc=1, target_new_exec!=0 -> expected_scc=1 - ] - for init_scc, target_exec, expected_scc in transitions: - with self.subTest(init_scc=init_scc, expected_scc=expected_scc): - state = ScalarMachineState() - state.exec_mask = 0 - state.scc = init_scc - # S0 = ~target_exec => NEW_EXEC = ~(S0 ^ 0) = target_exec - state.set_sgpr64(0, (~target_exec) & MASK64) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - _, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(new_exec, target_exec) - self.assertEqual(scc, expected_scc) - self.assertEqual(state.scc, expected_scc) - - def test_scc_consumer_cselect_b64(self) -> None: - """Verify interaction between s_xnor_saveexec_b64 and conditional selection (s_cselect_b64).""" - # Emulate: s_xnor_saveexec_b64 followed by s_cselect_b64 D, S0, S1 (D = SCC ? S0 : S1) - true_val = 0xAAAAAAAAAAAAAAAA - false_val = 0x5555555555555555 - - for make_nonzero in (True, False): - with self.subTest(make_nonzero=make_nonzero): - state = ScalarMachineState() - state.exec_mask = MASK64 - state.set_sgpr64(0, MASK64 if make_nonzero else 0) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[4:5], s[0:1]") - _, new_exec, scc = self.interp.step(instr, state) - - if make_nonzero: - self.assertEqual(scc, 1) - selected = true_val if state.scc else false_val - self.assertEqual(selected, true_val) - else: - self.assertEqual(scc, 0) - selected = true_val if state.scc else false_val - self.assertEqual(selected, false_val) - - def test_no_carry_borrow_generation(self) -> None: - """Confirm bitwise logical saveexec does not emit spurious arithmetic carry/borrow.""" - # Logical instructions in RDNA2 update only SCC as non-zero detector, not carry/borrow - state = ScalarMachineState() - # Even on maximum overflow-like bit patterns (all 1s), only SCC is affected - state.exec_mask = MASK64 - state.set_sgpr64(0, MASK64) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - _, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(new_exec, MASK64) - self.assertEqual(scc, 1) - # VCC (vector carry mask) remains unchanged - self.assertEqual(state.vcc, 0) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """IEEE 754 boundary extremes, subnormals, and NaN handling tests. - - Verifies bit-exact semantics when IEEE 754 binary64 bit-patterns are processed - by the SALU without floating-point trapping, denormal flushing, or NaN quietening. - """ - - # IEEE 754 double-precision bit constants - POS_ZERO: int = 0x0000000000000000 - NEG_ZERO: int = 0x8000000000000000 - POS_INF: int = 0x7FF0000000000000 - NEG_INF: int = 0xFFF0000000000000 - QNAN_CANONICAL: int = 0x7FF8000000000000 - SNAN_PATTERN: int = 0x7FF0000000000001 - SUBNORMAL_MIN: int = 0x0000000000000001 - SUBNORMAL_MAX: int = 0x000FFFFFFFFFFFFF - NORMAL_MIN: int = 0x0010000000000000 - NORMAL_MAX: int = 0x7FEFFFFFFFFFFFFF - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - - def test_signed_zero_representation_distinction(self) -> None: - """Verify +0.0 and -0.0 differ in sign bit and are not conflated by SALU XNOR. - - While IEEE 754 treats +0.0 == -0.0, SALU bitwise operations distinguish the sign bit: - 0x0000000000000000 XNOR 0x8000000000000000 -> 0x7FFFFFFFFFFFFFFF. - """ - state = ScalarMachineState() - state.exec_mask = self.POS_ZERO - state.set_sgpr64(0, self.NEG_ZERO) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - saved, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(saved, self.POS_ZERO) - self.assertEqual(new_exec, 0x7FFFFFFFFFFFFFFF) - self.assertEqual(scc, 1) - - def test_nan_preservation_and_no_quietening(self) -> None: - """Verify Signaling NaN is not quietened and payload bits are strictly inverted. - - In VALU, SNAN would trigger invalid operation or be converted to QNAN. - In SALU, bits are preserved bitwise without NaN quietening. - """ - state = ScalarMachineState() - state.exec_mask = MASK64 - state.set_sgpr64(0, self.SNAN_PATTERN) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - _, new_exec, scc = self.interp.step(instr, state) - - # XNOR with MASK64 is identity, preserving SNAN without setting the quiet bit - self.assertEqual(new_exec, self.SNAN_PATTERN) - self.assertEqual(scc, 1) - - def test_nan_self_xnor_equivalence(self) -> None: - """Verify NaN XNOR NaN yields all 1s (unlike IEEE 754 where NaN == NaN is False).""" - state = ScalarMachineState() - state.exec_mask = self.QNAN_CANONICAL - state.set_sgpr64(0, self.QNAN_CANONICAL) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - _, new_exec, scc = self.interp.step(instr, state) - - self.assertEqual(new_exec, MASK64) - self.assertEqual(scc, 1) - - def test_subnormal_no_flush_to_zero(self) -> None: - """Verify subnormal/denormal representations are not flushed to zero.""" - state = ScalarMachineState() - state.exec_mask = MASK64 - state.set_sgpr64(0, self.SUBNORMAL_MIN) - - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - _, new_exec, scc = self.interp.step(instr, state) - - # Must not flush to zero - self.assertEqual(new_exec, self.SUBNORMAL_MIN) - self.assertNotEqual(new_exec, 0) - self.assertEqual(scc, 1) - - def test_infinity_combinations(self) -> None: - """Verify XNOR with positive and negative infinity representations.""" - # Same signed infinities -> all 1s - saved, new_exec, scc = oracle_s_xnor_saveexec_b64(self.POS_INF, self.POS_INF) - self.assertEqual(new_exec, MASK64) - self.assertEqual(scc, 1) - - # Opposite signed infinities -> differ only in sign bit (bit 63) - saved, new_exec, scc = oracle_s_xnor_saveexec_b64(self.POS_INF, self.NEG_INF) - self.assertEqual(new_exec, 0x7FFFFFFFFFFFFFFF) - self.assertEqual(scc, 1) - - def test_struct_pack_double_roundtrip_verification(self) -> None: - """Verify bit patterns round-trip faithfully through Python struct IEEE 754 packing.""" - test_floats = [1.0, -1.0, 0.5, -0.5, 2.0, 1e-300, 1e300] - for f in test_floats: - with self.subTest(f=f): - bits = struct.unpack(" None: - """Verify parser rejects invalid assembly syntaxes and illegal operand structures.""" - invalid_instructions = [ - "s_xnor_saveexec_b64", # Missing all operands - "s_xnor_saveexec_b64 s[4:5]", # Missing src0 operand - "s_xnor_saveexec_b64 s[4:5], s[2:3], s[0:1]", # Extra third operand - "s_xnor_saveexec_b64 v[4:5], s[2:3]", # VGPR destination invalid for SALU - "s_xnor_saveexec_b64 s[1:2], s[2:3]", # Odd-aligned destination register pair - "s_xnor_saveexec_b64 s[4:5], s[3:4]", # Odd-aligned source register pair - "s_xnor_saveexec_b64 s[4:7], s[2:3]", # 4-dword span instead of 2-dword - "s_xnor_saveexec_b64 m0, s[2:3]", # Invalid scalar destination special register - "s_xor_saveexec_b64 s[4:5], s[2:3]", # Wrong opcode mnemonic - "s_xnor_saveexec_b32 s[4:5], s[2:3]", # 32-bit opcode mismatch - ] - for bad in invalid_instructions: - with self.subTest(bad=bad): - with self.assertRaises((ValueError, TypeError)): - parse_salu_instruction(bad) - - def test_mutation_detection_xor_instead_of_xnor(self) -> None: - """Mutation 1: Detect mutant calculating XOR rather than XNOR.""" - class MutantXorInterpreter(ScalarInterpreter): - def step(self, instr: SXnorSaveexecB64Instruction, state: ScalarMachineState) -> Tuple[int, int, int]: - src0_val = self.resolve_source(instr.src0, state) - curr_exec = state.exec_mask & MASK64 - # Mutant bug: computes XOR instead of XNOR - new_exec = (src0_val ^ curr_exec) & MASK64 - saved = curr_exec - state.exec_mask = new_exec - state.scc = ref_scc(new_exec) - return saved, new_exec, state.scc - - mutant = MutantXorInterpreter() - st = ScalarMachineState(exec_mask=0) - st.set_sgpr64(0, 0) - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - _, new_exec, _ = mutant.step(instr, st) - # Expected XNOR(0, 0) == MASK64, Mutant XOR(0, 0) == 0 - self.assertNotEqual(new_exec, MASK64) - self.assertEqual(new_exec, 0) - - def test_mutation_detection_wrexec_instead_of_saveexec(self) -> None: - """Mutation 2: Detect mutant saving new_exec into dst instead of old EXEC (wrexec bug).""" - class MutantWrexecInterpreter(ScalarInterpreter): - def step(self, instr: SXnorSaveexecB64Instruction, state: ScalarMachineState) -> Tuple[int, int, int]: - src0_val = self.resolve_source(instr.src0, state) - curr_exec = state.exec_mask & MASK64 - saved, new_exec, scc = oracle_s_xnor_saveexec_b64(src0_val, curr_exec) - # Mutant bug: saves new_exec to destination instead of saved - if isinstance(instr.dst, RegPair): - state.set_sgpr64(instr.dst.index, new_exec) - state.exec_mask = new_exec - state.scc = scc - return new_exec, new_exec, scc - - mutant = MutantWrexecInterpreter() - st = ScalarMachineState(exec_mask=0x1111111111111111) - st.set_sgpr64(0, 0x2222222222222222) - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - saved, _, _ = mutant.step(instr, st) - self.assertNotEqual(st.get_sgpr64(2), 0x1111111111111111) - - def test_mutation_detection_inverted_scc_flag(self) -> None: - """Mutation 3: Detect mutant inverting SCC flag logic.""" - class MutantSccInterpreter(ScalarInterpreter): - def step(self, instr: SXnorSaveexecB64Instruction, state: ScalarMachineState) -> Tuple[int, int, int]: - saved, new_exec, scc = super().step(instr, state) - # Mutant bug: inverts SCC condition - bad_scc = 0 if scc == 1 else 1 - state.scc = bad_scc - return saved, new_exec, bad_scc - - mutant = MutantSccInterpreter() - st = ScalarMachineState(exec_mask=MASK64) - st.set_sgpr64(0, MASK64) - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - _, _, scc = mutant.step(instr, st) - # Correct SCC is 1, mutant sets 0 - self.assertEqual(scc, 0) - self.assertNotEqual(scc, 1) - - def test_mutation_detection_32bit_truncation(self) -> None: - """Mutation 4: Detect mutant erroneously truncating 64-bit operation to 32 bits.""" - class Mutant32BitTruncation(ScalarInterpreter): - def step(self, instr: SXnorSaveexecB64Instruction, state: ScalarMachineState) -> Tuple[int, int, int]: - saved, new_exec, scc = super().step(instr, state) - truncated_exec = new_exec & MASK32 - state.exec_mask = truncated_exec - return saved, truncated_exec, scc - - mutant = Mutant32BitTruncation() - st = ScalarMachineState(exec_mask=MASK64) - st.set_sgpr64(0, MASK64) - instr = parse_salu_instruction("s_xnor_saveexec_b64 s[2:3], s[0:1]") - _, new_exec, _ = mutant.step(instr, st) - # Mutant lost upper 32 bits - self.assertEqual(new_exec, MASK32) - self.assertNotEqual(new_exec, MASK64) + def test_xnor_every_lane(self): + saveexec_run.check(self, "xnor") if __name__ == "__main__": diff --git a/tests/semantic/test_salu_xor_saveexec_b64.py b/tests/semantic/test_salu_xor_saveexec_b64.py index b094f0018..70f8dcb9f 100644 --- a/tests/semantic/test_salu_xor_saveexec_b64.py +++ b/tests/semantic/test_salu_xor_saveexec_b64.py @@ -1,1225 +1,33 @@ -from __future__ import annotations +"""s_xor_saveexec_b64 through the translator, on every lane of a wave64. -import math -import struct +RDNA2 ISA, SOP1: + s_xor_saveexec_b64: D = EXEC; EXEC = S0 ^ EXEC; SCC = (EXEC != 0). + +Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in +tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an +SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of +this name ran a self-built interpreter and never called the translator. +""" +import os +import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from typing import List, Optional, Tuple, Union -# ============================================================================== -# Architectural Constants and Masks -# ============================================================================== +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import saveexec_run # noqa: E402 (support puts tools/ on sys.path) -MASK32: int = 0xFFFF_FFFF -MASK64: int = 0xFFFF_FFFF_FFFF_FFFF -# IEEE 754 double-precision bit manipulation constants -SIGN_BIT_64: int = 0x8000_0000_0000_0000 -EXP_MASK_64: int = 0x7FF0_0000_0000_0000 -FRAC_MASK_64: int = 0x000F_FFFF_FFFF_FFFF -QNAN_BIT_64: int = 0x0008_0000_0000_0000 -CANONICAL_QNAN_64: int = 0x7FF8_0000_0000_0000 -SIGNALING_NAN_64: int = 0x7FF0_0000_0000_0001 -POS_INFINITY_64: int = 0x7FF0_0000_0000_0000 -NEG_INFINITY_64: int = 0xFFF0_0000_0000_0000 -POS_ZERO_64: int = 0x0000_0000_0000_0000 -NEG_ZERO_64: int = 0x8000_0000_0000_0000 +class Saveexec(unittest.TestCase): + def test_xor_by_hand(self): + # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = S0 ^ EXEC written out by hand. + lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) + s0, e = lanes(0, 32), lanes(16, 48) + want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), + "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), + "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["xor"] + self.assertEqual(saveexec_run.model("xor", s0, e), (want, e, 1)) -# Wavefront lane mask constants -ALL_LANES_W32: int = 0x0000_0000_FFFF_FFFF -ALL_LANES_W64: int = 0xFFFF_FFFF_FFFF_FFFF -EVEN_LANES_W64: int = 0x5555_5555_5555_5555 -ODD_LANES_W64: int = 0xAAAA_AAAA_AAAA_AAAA -LOWER_HALF_W64: int = 0x0000_0000_FFFF_FFFF -UPPER_HALF_W64: int = 0xFFFF_FFFF_0000_0000 - - -# ============================================================================== -# Bit-Level Conversion and Classification Helpers -# ============================================================================== - -def u64_to_words(val: int) -> Tuple[int, int]: - """Split a 64-bit unsigned integer into (low_dword, high_dword).""" - return (val & MASK32), ((val >> 32) & MASK32) - - -def words_to_u64(lo: int, hi: int) -> int: - """Combine (low_dword, high_dword) into a 64-bit unsigned integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def u64_to_f64(bits: int) -> float: - """Reinterpret 64-bit integer bits as IEEE 754 binary64 float.""" - return struct.unpack(" int: - """Reinterpret IEEE 754 binary64 float as 64-bit integer bits.""" - return struct.unpack(" bool: - """Return True if 64-bit bits represent IEEE 754 NaN.""" - return ((bits & EXP_MASK_64) == EXP_MASK_64) and ((bits & FRAC_MASK_64) != 0) - - -def is_snan_bits(bits: int) -> bool: - """Return True if 64-bit bits represent IEEE 754 Signaling NaN.""" - return is_nan_bits(bits) and not bool(bits & QNAN_BIT_64) - - -def is_qnan_bits(bits: int) -> bool: - """Return True if 64-bit bits represent IEEE 754 Quiet NaN.""" - return is_nan_bits(bits) and bool(bits & QNAN_BIT_64) - - -def is_inf_bits(bits: int) -> bool: - """Return True if 64-bit bits represent IEEE 754 positive or negative infinity.""" - return ((bits & EXP_MASK_64) == EXP_MASK_64) and ((bits & FRAC_MASK_64) == 0) - - -def is_subnormal_bits(bits: int) -> bool: - """Return True if 64-bit bits represent IEEE 754 subnormal float.""" - return ((bits & EXP_MASK_64) == 0) and ((bits & FRAC_MASK_64) != 0) - - -# ============================================================================== -# Reference Mathematical Oracle -# ============================================================================== - -def oracle_s_xor_saveexec_b64(exec_mask: int, src0: int) -> Tuple[int, int, int]: - """Reference mathematical oracle for RDNA2 s_xor_saveexec_b64 instruction. - - Architectural Operation: - saved_exec = EXEC; - EXEC = EXEC ^ src0; - SCC = (EXEC != 0); - - Parameters: - exec_mask: The 64-bit architectural EXEC mask prior to instruction execution. - src0: The 64-bit source operand (SGPR pair, literal constant, or special register). - - Returns: - A tuple of (saved_exec, new_exec, scc): - - saved_exec: 64-bit unsigned integer copied to sdst. - - new_exec: 64-bit unsigned integer written to EXEC. - - scc: 1 if new_exec != 0, else 0. - """ - saved_exec = exec_mask & MASK64 - new_exec = (saved_exec ^ (src0 & MASK64)) & MASK64 - scc = 1 if new_exec != 0 else 0 - return saved_exec, new_exec, scc - - -# ============================================================================== -# Architectural State Model -# ============================================================================== - -@dataclass -class SALUArchitecturalState: - """Architectural state for AMD RDNA2 Scalar ALU (SALU) execution. - - Holds the scalar register file (106 SGPRs standard in RDNA2), - special registers (EXEC, VCC, SCC, M0), and status flags. - """ - sgprs: List[int] = field(default_factory=lambda: [0] * 106) - exec_mask: int = field(default=MASK64) - vcc: int = field(default=0) - scc: int = field(default=0) - m0: int = field(default=0) - - def read_sgpr_u32(self, index: int) -> int: - if not (0 <= index < len(self.sgprs)): - raise IndexError(f"SGPR index {index} out of range [0, {len(self.sgprs) - 1}]") - return self.sgprs[index] & MASK32 - - def write_sgpr_u32(self, index: int, val: int) -> None: - if not (0 <= index < len(self.sgprs)): - raise IndexError(f"SGPR index {index} out of range [0, {len(self.sgprs) - 1}]") - self.sgprs[index] = val & MASK32 - - def read_sgpr_u64(self, index: int) -> int: - if not (0 <= index < len(self.sgprs) - 1): - raise IndexError(f"SGPR pair base index {index} out of range [0, {len(self.sgprs) - 2}]") - lo = self.read_sgpr_u32(index) - hi = self.read_sgpr_u32(index + 1) - return words_to_u64(lo, hi) - - def write_sgpr_u64(self, index: int, val: int) -> None: - if not (0 <= index < len(self.sgprs) - 1): - raise IndexError(f"SGPR pair base index {index} out of range [0, {len(self.sgprs) - 2}]") - lo, hi = u64_to_words(val) - self.write_sgpr_u32(index, lo) - self.write_sgpr_u32(index + 1, hi) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegKind(Enum): - SGPR = auto() - VGPR = auto() - SPECIAL = auto() - - -@dataclass(frozen=True) -class Register: - """Architectural register representation with kind, base index, and count.""" - kind: RegKind - index: int - count: int = 1 - - def __post_init__(self) -> None: - if self.kind == RegKind.SGPR: - if not (0 <= self.index <= 105): - raise ValueError(f"SGPR index {self.index} out of range [0, 105]") - if self.index + self.count > 106: - raise ValueError(f"SGPR register span {self.index} + {self.count} exceeds SGPR limit 106") - elif self.kind == RegKind.VGPR: - if not (0 <= self.index <= 255): - raise ValueError(f"VGPR index {self.index} out of range [0, 255]") - if self.index + self.count > 256: - raise ValueError(f"VGPR register span {self.index} + {self.count} exceeds VGPR limit 256") - if self.count not in (1, 2): - raise ValueError(f"Register count must be 1 (32-bit) or 2 (64-bit), got {self.count}") - - @property - def name(self) -> str: - prefix = "s" if self.kind == RegKind.SGPR else "v" - if self.count == 1: - return f"{prefix}{self.index}" - return f"{prefix}[{self.index}:{self.index + self.count - 1}]" - - -@dataclass(frozen=True) -class LiteralConstant64: - """64-bit scalar immediate or inline literal constant.""" - val: int - - @property - def name(self) -> str: - return f"0x{self.val & MASK64:016x}" - - -class SALUOpcode(Enum): - S_XOR_SAVEEXEC_B64 = auto() - - -@dataclass(frozen=True) -class SXorSaveExecB64AST: - """Symbolic AST node representing RDNA2 s_xor_saveexec_b64 instruction.""" - dst: Register - src0: Union[Register, LiteralConstant64] - opcode: SALUOpcode = SALUOpcode.S_XOR_SAVEEXEC_B64 - - def __post_init__(self) -> None: - if self.dst.kind != RegKind.SGPR: - raise TypeError(f"Destination of s_xor_saveexec_b64 must be SGPR, got {self.dst.kind}") - if self.dst.count != 2: - raise ValueError(f"Destination of s_xor_saveexec_b64 must be 64-bit register pair (count=2), got count={self.dst.count}") - if isinstance(self.src0, Register): - if self.src0.kind != RegKind.SGPR: - raise TypeError(f"Register source of s_xor_saveexec_b64 must be SGPR, got {self.src0.kind}") - if self.src0.count != 2: - raise ValueError(f"Register source of s_xor_saveexec_b64 must be 64-bit register pair (count=2), got count={self.src0.count}") - - def disassemble(self) -> str: - return f"s_xor_saveexec_b64 {self.dst.name}, {self.src0.name}" - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass(frozen=True) -class ExecutionResult: - """Result of executing a single SALU instruction.""" - saved_exec: int - new_exec: int - scc: int - - -class ScalarSALUInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 SALU instructions.""" - - def resolve_src64(self, src: Union[Register, LiteralConstant64], state: SALUArchitecturalState) -> int: - if isinstance(src, Register): - return state.read_sgpr_u64(src.index) - elif isinstance(src, LiteralConstant64): - return src.val & MASK64 - else: - raise TypeError(f"Unsupported source operand type: {type(src)}") - - def step(self, instr: SXorSaveExecB64AST, state: SALUArchitecturalState) -> ExecutionResult: - # 1. Atomic read phase - src0_val = self.resolve_src64(instr.src0, state) - current_exec = state.exec_mask - - # 2. Computation phase via mathematical oracle - saved_exec, new_exec, scc = oracle_s_xor_saveexec_b64(current_exec, src0_val) - - # 3. Atomic write-back phase - state.write_sgpr_u64(instr.dst.index, saved_exec) - state.exec_mask = new_exec - state.scc = scc - - return ExecutionResult(saved_exec=saved_exec, new_exec=new_exec, scc=scc) - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDWavefrontState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - wave_size: int - salu_state: SALUArchitecturalState = field(default_factory=SALUArchitecturalState) - vgprs: List[List[int]] = field(default_factory=list) - - def __post_init__(self) -> None: - if self.wave_size not in (32, 64): - raise ValueError(f"wave_size must be 32 or 64, got {self.wave_size}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.wave_size)] - if self.wave_size == 32: - self.salu_state.exec_mask &= ALL_LANES_W32 - - def is_lane_active(self, lane: int) -> bool: - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size - 1}]") - return bool((self.salu_state.exec_mask & (1 << lane)) != 0) - - def active_lane_indices(self) -> List[int]: - return [lane for lane in range(self.wave_size) if self.is_lane_active(lane)] - - def read_vgpr(self, lane: int, vgpr_idx: int) -> int: - return self.vgprs[lane][vgpr_idx] & MASK32 - - def write_vgpr(self, lane: int, vgpr_idx: int, val: int) -> None: - self.vgprs[lane][vgpr_idx] = val & MASK32 - - -class SIMDInstructionExecutor: - """Executes SALU control-flow and masked VALU operations across wavefront lanes.""" - - def __init__(self, salu_interp: Optional[ScalarSALUInterpreter] = None) -> None: - self.salu_interp = salu_interp or ScalarSALUInterpreter() - - def step_salu(self, instr: SXorSaveExecB64AST, state: SIMDWavefrontState) -> ExecutionResult: - res = self.salu_interp.step(instr, state.salu_state) - if state.wave_size == 32: - state.salu_state.exec_mask &= ALL_LANES_W32 - return res - - def step_valu_add_u32(self, dst_v: int, src_v: int, addend: int, state: SIMDWavefrontState) -> List[Optional[int]]: - """Masked VALU instruction: lane writes only if active under EXEC.""" - written_vals: List[Optional[int]] = [None] * state.wave_size - for lane in range(state.wave_size): - if state.is_lane_active(lane): - in_val = state.read_vgpr(lane, src_v) - out_val = (in_val + addend) & MASK32 - state.write_vgpr(lane, dst_v, out_val) - written_vals[lane] = out_val - return written_vals - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Independence -# ============================================================================== - -@dataclass(frozen=True) -class SALUStatusFlags: - """Condition codes and architectural status flags evaluated after SALU instruction.""" - scc: int - execz: bool - execnz: bool - active_lane_count: int - parity_even: bool - carry_borrow_unaltered: bool = True - - -def evaluate_salu_status_flags( - new_exec: int, - vcc_before: int, - vcc_after: int, -) -> SALUStatusFlags: - """Evaluate SALU status flags and verify carry/borrow preservation.""" - scc = 1 if (new_exec & MASK64) != 0 else 0 - execz = (new_exec & MASK64) == 0 - execnz = (new_exec & MASK64) != 0 - active_lanes = bin(new_exec & MASK64).count("1") - parity_even = (active_lanes % 2 == 0) - carry_unaltered = (vcc_before == vcc_after) - - return SALUStatusFlags( - scc=scc, - execz=execz, - execnz=execnz, - active_lane_count=active_lanes, - parity_even=parity_even, - carry_borrow_unaltered=carry_unaltered, - ) - - - - - -# ============================================================================== -# Unit Tests: Phase 1 Oracle and Architectural Model -# ============================================================================== - -class TestSXorSaveExecB64Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_identity_zero_xor(self) -> None: - """XOR with 0 preserves EXEC, returns old EXEC, and SCC reflects (EXEC != 0).""" - exec_val = 0x1234_5678_9ABC_DEF0 - saved, new_exec, scc = oracle_s_xor_saveexec_b64(exec_val, 0) - self.assertEqual(saved, exec_val) - self.assertEqual(new_exec, exec_val) - self.assertEqual(scc, 1) - - def test_identity_zero_exec_zero_src(self) -> None: - """XOR 0 with 0 yields new_exec=0 and SCC=0.""" - saved, new_exec, scc = oracle_s_xor_saveexec_b64(0, 0) - self.assertEqual(saved, 0) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - - def test_invert_all_lanes_with_all_ones(self) -> None: - """XOR with ~0 inverts all 64 bits of EXEC.""" - saved, new_exec, scc = oracle_s_xor_saveexec_b64(ALL_LANES_W64, ALL_LANES_W64) - self.assertEqual(saved, ALL_LANES_W64) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - - saved2, new_exec2, scc2 = oracle_s_xor_saveexec_b64(0, ALL_LANES_W64) - self.assertEqual(saved2, 0) - self.assertEqual(new_exec2, ALL_LANES_W64) - self.assertEqual(scc2, 1) - - def test_toggle_alternating_lanes(self) -> None: - """XOR with odd lane mask toggles between even and odd active lanes.""" - saved, new_exec, scc = oracle_s_xor_saveexec_b64(ALL_LANES_W64, ODD_LANES_W64) - self.assertEqual(saved, ALL_LANES_W64) - self.assertEqual(new_exec, EVEN_LANES_W64) - self.assertEqual(scc, 1) - - saved2, new_exec2, scc2 = oracle_s_xor_saveexec_b64(new_exec, ALL_LANES_W64) - self.assertEqual(saved2, EVEN_LANES_W64) - self.assertEqual(new_exec2, ODD_LANES_W64) - self.assertEqual(scc2, 1) - - def test_toggle_wave64_halves(self) -> None: - """XOR lower half with upper half transitions wave halves.""" - saved, new_exec, scc = oracle_s_xor_saveexec_b64(LOWER_HALF_W64, ALL_LANES_W64) - self.assertEqual(saved, LOWER_HALF_W64) - self.assertEqual(new_exec, UPPER_HALF_W64) - self.assertEqual(scc, 1) - - def test_scc_boundary_single_bit_set(self) -> None: - """Single active bit (LSB or MSB) produces SCC=1.""" - saved_lsb, new_lsb, scc_lsb = oracle_s_xor_saveexec_b64(0, 1) - self.assertEqual(new_lsb, 1) - self.assertEqual(scc_lsb, 1) - - msb_mask = 1 << 63 - saved_msb, new_msb, scc_msb = oracle_s_xor_saveexec_b64(0, msb_mask) - self.assertEqual(new_msb, msb_mask) - self.assertEqual(scc_msb, 1) - - def test_word_packing_and_architectural_state(self) -> None: - """Test SGPR 64-bit pair read/write and word decomposition.""" - state = SALUArchitecturalState() - test_val = 0xCAFE_BABE_DEAD_BEEF - state.write_sgpr_u64(4, test_val) - self.assertEqual(state.read_sgpr_u64(4), test_val) - self.assertEqual(state.read_sgpr_u32(4), 0xDEAD_BEEF) - self.assertEqual(state.read_sgpr_u32(5), 0xCAFE_BABE) - - lo, hi = u64_to_words(test_val) - self.assertEqual(words_to_u64(lo, hi), test_val) - - def test_self_cancellation_identity(self) -> None: - """XOR of any value with itself produces 0 (EXEC ^ EXEC == 0).""" - arbitrary_patterns = [ - 0x1, - 0x8000_0000_0000_0000, - 0x5555_5555_AAAA_AAAA, - 0x0123_4567_89AB_CDEF, - ALL_LANES_W64, - ] - for pat in arbitrary_patterns: - saved, new_exec, scc = oracle_s_xor_saveexec_b64(pat, pat) - self.assertEqual(saved, pat) - self.assertEqual(new_exec, 0) - self.assertEqual(scc, 0) - - -class TestSXorSaveExecB64AST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_ast_valid_sgpr_operands(self) -> None: - dst = Register(RegKind.SGPR, 4, count=2) - src = Register(RegKind.SGPR, 6, count=2) - ast = SXorSaveExecB64AST(dst=dst, src0=src) - self.assertEqual(ast.opcode, SALUOpcode.S_XOR_SAVEEXEC_B64) - self.assertEqual(ast.dst.name, "s[4:5]") - self.assertEqual(ast.src0.name, "s[6:7]") - self.assertEqual(ast.disassemble(), "s_xor_saveexec_b64 s[4:5], s[6:7]") - - def test_ast_valid_literal_operand(self) -> None: - dst = Register(RegKind.SGPR, 0, count=2) - lit = LiteralConstant64(0x1234_5678_9ABC_DEF0) - ast = SXorSaveExecB64AST(dst=dst, src0=lit) - self.assertEqual(ast.disassemble(), "s_xor_saveexec_b64 s[0:1], 0x123456789abcdef0") - - def test_ast_dataclass_equality(self) -> None: - ast1 = SXorSaveExecB64AST(Register(RegKind.SGPR, 8, count=2), LiteralConstant64(0x5555)) - ast2 = SXorSaveExecB64AST(Register(RegKind.SGPR, 8, count=2), LiteralConstant64(0x5555)) - self.assertEqual(ast1, ast2) - self.assertEqual(hash(ast1), hash(ast2)) - - def test_rejection_of_vgpr_dst(self) -> None: - with self.assertRaises(TypeError): - SXorSaveExecB64AST( - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.SGPR, 2, count=2), - ) - - def test_rejection_of_vgpr_src(self) -> None: - with self.assertRaises(TypeError): - SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - ) - - def test_rejection_of_single_32bit_dst_or_src(self) -> None: - with self.assertRaises(ValueError): - SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=1), - src0=Register(RegKind.SGPR, 2, count=2), - ) - with self.assertRaises(ValueError): - SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=Register(RegKind.SGPR, 2, count=1), - ) - - def test_rejection_of_out_of_range_sgpr(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.SGPR, -1, count=2) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 106, count=2) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 105, count=2) # 105+2 = 107 > 106 - - -class TestScalarSALUInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar instruction interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarSALUInterpreter() - self.state = SALUArchitecturalState() - - def test_scalar_execution_step(self) -> None: - self.state.exec_mask = 0xFFFF_0000_FFFF_0000 - self.state.write_sgpr_u64(2, 0x0000_FFFF_FFFF_0000) - instr = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 4, count=2), - src0=Register(RegKind.SGPR, 2, count=2), - ) - res = self.interp.step(instr, self.state) - self.assertEqual(res.saved_exec, 0xFFFF_0000_FFFF_0000) - self.assertEqual(res.new_exec, 0xFFFF_FFFF_0000_0000) - self.assertEqual(res.scc, 1) - - # Architectural state verification - self.assertEqual(self.state.read_sgpr_u64(4), 0xFFFF_0000_FFFF_0000) - self.assertEqual(self.state.exec_mask, 0xFFFF_FFFF_0000_0000) - self.assertEqual(self.state.scc, 1) - - def test_scalar_step_with_literal_constant(self) -> None: - self.state.exec_mask = 0xAAAA_AAAA_AAAA_AAAA - lit = LiteralConstant64(0x5555_5555_5555_5555) - instr = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=lit, - ) - res = self.interp.step(instr, self.state) - self.assertEqual(res.saved_exec, 0xAAAA_AAAA_AAAA_AAAA) - self.assertEqual(res.new_exec, 0xFFFF_FFFF_FFFF_FFFF) - self.assertEqual(res.scc, 1) - self.assertEqual(self.state.read_sgpr_u64(0), 0xAAAA_AAAA_AAAA_AAAA) - self.assertEqual(self.state.exec_mask, ALL_LANES_W64) - - def test_sequential_saveexec_chaining(self) -> None: - """Chain multiple saveexec instructions toggling masks.""" - # Initial: EXEC = all ones - self.state.exec_mask = ALL_LANES_W64 - # Step 1: invert lower half -> s[0:1] receives all ones, EXEC becomes upper half - inst1 = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=LiteralConstant64(LOWER_HALF_W64), - ) - res1 = self.interp.step(inst1, self.state) - self.assertEqual(res1.saved_exec, ALL_LANES_W64) - self.assertEqual(self.state.exec_mask, UPPER_HALF_W64) - self.assertEqual(self.state.read_sgpr_u64(0), ALL_LANES_W64) - - # Step 2: invert all ones -> s[2:3] receives upper half, EXEC becomes lower half - inst2 = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 2, count=2), - src0=LiteralConstant64(ALL_LANES_W64), - ) - res2 = self.interp.step(inst2, self.state) - self.assertEqual(res2.saved_exec, UPPER_HALF_W64) - self.assertEqual(self.state.exec_mask, LOWER_HALF_W64) - self.assertEqual(self.state.read_sgpr_u64(2), UPPER_HALF_W64) - - def test_deterministic_replay(self) -> None: - """Verify strict determinism across multiple interpreter runs.""" - results = [] - for _ in range(50): - st = SALUArchitecturalState() - st.exec_mask = 0x0123_4567_89AB_CDEF - st.write_sgpr_u64(10, 0xFEDC_BA98_7654_3210) - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 20, count=2), - src0=Register(RegKind.SGPR, 10, count=2), - ) - r = self.interp.step(inst, st) - results.append((r.saved_exec, r.new_exec, r.scc, st.read_sgpr_u64(20))) - self.assertTrue(all(item == results[0] for item in results)) - - def test_scc_cleared_on_zero_result(self) -> None: - self.state.exec_mask = 0x1111_2222_3333_4444 - self.state.write_sgpr_u64(0, 0x1111_2222_3333_4444) - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 4, count=2), - src0=Register(RegKind.SGPR, 0, count=2), - ) - res = self.interp.step(inst, self.state) - self.assertEqual(res.new_exec, 0) - self.assertEqual(res.scc, 0) - self.assertEqual(self.state.scc, 0) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD execution, lane divergence, and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.executor = SIMDInstructionExecutor() - - def test_wave64_divergence_toggle(self) -> None: - """Start with even lanes active, XOR with all ones, verify only odd lanes execute VALU.""" - state = SIMDWavefrontState(wave_size=64) - state.salu_state.exec_mask = EVEN_LANES_W64 - - # Initialise v0 with 100 for all lanes, v1 with sentinel 0xDEAD - for lane in range(64): - state.write_vgpr(lane, 0, 100) - state.write_vgpr(lane, 1, 0xDEAD) - - # Toggle active lanes with ~0 - toggle_inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=LiteralConstant64(ALL_LANES_W64), - ) - salu_res = self.executor.step_salu(toggle_inst, state) - self.assertEqual(salu_res.saved_exec, EVEN_LANES_W64) - self.assertEqual(salu_res.new_exec, ODD_LANES_W64) - self.assertEqual(state.salu_state.exec_mask, ODD_LANES_W64) - - # Execute masked VALU add: v1 = v0 + 50 - written = self.executor.step_valu_add_u32(dst_v=1, src_v=0, addend=50, state=state) - - for lane in range(64): - if lane % 2 == 1: - # Odd lanes were activated by XOR - self.assertEqual(written[lane], 150) - self.assertEqual(state.read_vgpr(lane, 1), 150) - else: - # Even lanes were deactivated by XOR - self.assertIsNone(written[lane]) - self.assertEqual(state.read_vgpr(lane, 1), 0xDEAD) - - def test_wave32_upper_half_masking(self) -> None: - """In Wave32 mode, execution mask is strictly bounded to lower 32 lanes.""" - state = SIMDWavefrontState(wave_size=32) - state.salu_state.exec_mask = 0x0000_0000_FFFF_0000 - - # Attempt XOR with 64-bit mask that touches upper half - toggle_inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 4, count=2), - src0=LiteralConstant64(ALL_LANES_W64), - ) - self.executor.step_salu(toggle_inst, state) - - # In Wave32, upper 32 bits of active exec mask must remain 0 - self.assertEqual(state.salu_state.exec_mask & UPPER_HALF_W64, 0) - self.assertEqual(state.salu_state.exec_mask, 0x0000_0000_0000_FFFF) - self.assertEqual(len(state.active_lane_indices()), 16) - - def test_wave64_if_else_reconvergence_flow(self) -> None: - """Emulate complete compiler if-else divergence and reconvergence workflow.""" - state = SIMDWavefrontState(wave_size=64) - outer_mask = ALL_LANES_W64 - state.salu_state.exec_mask = outer_mask - - # Subgroup condition: lower 32 lanes satisfy 'if' condition - cond_mask = LOWER_HALF_W64 - - # Save outer mask in s[10:11], set EXEC to if-branch - # In compiler: s_and_saveexec_b64 s[10:11], cond_mask - state.salu_state.write_sgpr_u64(10, outer_mask) - state.salu_state.exec_mask = cond_mask - - # At the end of 'if', transition to 'else' via s_xor_saveexec_b64 s[12:13], s[10:11] - # EXEC = EXEC ^ s[10:11] = LOWER_HALF ^ ALL_LANES = UPPER_HALF! - else_transition = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 12, count=2), - src0=Register(RegKind.SGPR, 10, count=2), - ) - res = self.executor.step_salu(else_transition, state) - self.assertEqual(res.saved_exec, LOWER_HALF_W64) - self.assertEqual(state.salu_state.exec_mask, UPPER_HALF_W64) - self.assertEqual(state.active_lane_indices(), list(range(32, 64))) - - def test_wave_total_sleep_all_lanes_disabled(self) -> None: - """When EXEC XOR with itself yields 0, all lanes are disabled and VALU writes do nothing.""" - state = SIMDWavefrontState(wave_size=64) - state.salu_state.exec_mask = 0x1234_5678_9ABC_DEF0 - state.salu_state.write_sgpr_u64(6, 0x1234_5678_9ABC_DEF0) - - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=Register(RegKind.SGPR, 6, count=2), - ) - self.executor.step_salu(inst, state) - self.assertEqual(state.salu_state.exec_mask, 0) - self.assertEqual(state.salu_state.scc, 0) - self.assertEqual(len(state.active_lane_indices()), 0) - - # VALU write - written = self.executor.step_valu_add_u32(dst_v=0, src_v=0, addend=1, state=state) - self.assertTrue(all(w is None for w in written)) - - def test_popcount_consistency_with_exec(self) -> None: - """Popcount of active lanes strictly matches active bits in exec_mask.""" - test_masks = [ - 0x0, - 0x1, - 0x8000_0000_0000_0000, - EVEN_LANES_W64, - ODD_LANES_W64, - LOWER_HALF_W64, - UPPER_HALF_W64, - ALL_LANES_W64, - ] - for m in test_masks: - state = SIMDWavefrontState(wave_size=64) - state.salu_state.exec_mask = m - expected_pop = bin(m).count("1") - self.assertEqual(len(state.active_lane_indices()), expected_pop) - - -class TestRegisterAliasingAndPreservation(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.interp = ScalarSALUInterpreter() - self.simd_executor = SIMDInstructionExecutor(self.interp) - - def test_dst_identical_to_src0(self) -> None: - """When dst == src0, dst receives old EXEC; EXEC receives old_exec ^ old_src.""" - state = SALUArchitecturalState() - init_exec = 0xAAAA_AAAA_5555_5555 - init_src = 0x1234_5678_9ABC_DEF0 - state.exec_mask = init_exec - state.write_sgpr_u64(4, init_src) - - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 4, count=2), - src0=Register(RegKind.SGPR, 4, count=2), - ) - res = self.interp.step(inst, state) - - # Result verification - self.assertEqual(res.saved_exec, init_exec) - self.assertEqual(res.new_exec, init_exec ^ init_src) - - # Architectural state verification: s[4:5] must hold saved_exec, NOT new_exec! - self.assertEqual(state.read_sgpr_u64(4), init_exec) - self.assertEqual(state.exec_mask, init_exec ^ init_src) - - def test_dst_partial_overlap_low(self) -> None: - """dst s[4:5] overlaps low register of src0 s[3:4] at s[4].""" - state = SALUArchitecturalState() - val_s3 = 0x1111_1111 - val_s4 = 0x2222_2222 - val_s5 = 0x3333_3333 - state.write_sgpr_u32(3, val_s3) - state.write_sgpr_u32(4, val_s4) - state.write_sgpr_u32(5, val_s5) - - init_exec = 0xF0F0_F0F0_0F0F_0F0F - state.exec_mask = init_exec - - # src0 is s[3:4] -> lo=s3, hi=s4 - src0_val = words_to_u64(val_s3, val_s4) - - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 4, count=2), - src0=Register(RegKind.SGPR, 3, count=2), - ) - res = self.interp.step(inst, state) - - self.assertEqual(res.saved_exec, init_exec) - self.assertEqual(res.new_exec, init_exec ^ src0_val) - - # Check register preservation: s[3] must remain val_s3 - self.assertEqual(state.read_sgpr_u32(3), val_s3) - # s[4:5] must hold init_exec (lo in s4, hi in s5) - self.assertEqual(state.read_sgpr_u64(4), init_exec) - - def test_dst_partial_overlap_high(self) -> None: - """dst s[4:5] overlaps high register of src0 s[5:6] at s[5].""" - state = SALUArchitecturalState() - val_s4 = 0x4444_4444 - val_s5 = 0x5555_5555 - val_s6 = 0x6666_6666 - state.write_sgpr_u32(4, val_s4) - state.write_sgpr_u32(5, val_s5) - state.write_sgpr_u32(6, val_s6) - - init_exec = 0x00FF_00FF_FF00_FF00 - state.exec_mask = init_exec - - src0_val = words_to_u64(val_s5, val_s6) - - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 4, count=2), - src0=Register(RegKind.SGPR, 5, count=2), - ) - res = self.interp.step(inst, state) - - self.assertEqual(res.saved_exec, init_exec) - self.assertEqual(res.new_exec, init_exec ^ src0_val) - - # Check register preservation: s[6] must remain val_s6 - self.assertEqual(state.read_sgpr_u32(6), val_s6) - # s[4:5] holds init_exec - self.assertEqual(state.read_sgpr_u64(4), init_exec) - - def test_inplace_mask_inversion_loop(self) -> None: - """Sequential loop with dst == src0 repeatedly toggling and saving.""" - state = SALUArchitecturalState() - state.exec_mask = ALL_LANES_W64 - # Register s[0:1] holds inversion mask - invert_mask = EVEN_LANES_W64 - state.write_sgpr_u64(0, invert_mask) - - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=Register(RegKind.SGPR, 0, count=2), - ) - - # Iteration 1: - # EXEC was ALL_LANES, src was EVEN_LANES - # saved -> ALL_LANES (written to s[0:1]) - # new EXEC -> ALL_LANES ^ EVEN_LANES = ODD_LANES - res1 = self.interp.step(inst, state) - self.assertEqual(res1.saved_exec, ALL_LANES_W64) - self.assertEqual(state.read_sgpr_u64(0), ALL_LANES_W64) - self.assertEqual(state.exec_mask, ODD_LANES_W64) - - # Iteration 2: - # EXEC is ODD_LANES, src is ALL_LANES (from s[0:1]) - # saved -> ODD_LANES (written to s[0:1]) - # new EXEC -> ODD_LANES ^ ALL_LANES = EVEN_LANES - res2 = self.interp.step(inst, state) - self.assertEqual(res2.saved_exec, ODD_LANES_W64) - self.assertEqual(state.read_sgpr_u64(0), ODD_LANES_W64) - self.assertEqual(state.exec_mask, EVEN_LANES_W64) - - def test_unrelated_sgpr_preservation(self) -> None: - """Verify that all 104 un-targeted SGPRs remain strictly unaltered.""" - state = SALUArchitecturalState() - # Seed all 106 SGPRs with distinct canary values - for i in range(106): - state.write_sgpr_u32(i, 0xA000_0000 | (i * 0x101)) - - snapshot_before = list(state.sgprs) - - # Modify s[20:21] using s[30:31] - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 20, count=2), - src0=Register(RegKind.SGPR, 30, count=2), - ) - self.interp.step(inst, state) - - # Verify untouched registers - for i in range(106): - if i not in (20, 21): - self.assertEqual( - state.read_sgpr_u32(i), - snapshot_before[i], - f"SGPR {i} was unexpectedly corrupted!", - ) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for status flags, condition codes, and carry/borrow independence.""" - - def setUp(self) -> None: - self.interp = ScalarSALUInterpreter() - - def test_scc_matches_execnz_truth_table(self) -> None: - """SCC is strictly 1 iff EXEC != 0 across exhaustive edge cases.""" - edge_cases = [ - (0, 0, 0), # 0 ^ 0 -> 0 (SCC=0) - (ALL_LANES_W64, ALL_LANES_W64, 0),# all_ones ^ all_ones -> 0 (SCC=0) - (0, 1, 1), # 0 ^ 1 -> 1 (SCC=1) - (0, 1 << 63, 1), # 0 ^ (1<<63) -> MSB (SCC=1) - (EVEN_LANES_W64, ODD_LANES_W64, 1), - (ALL_LANES_W64, 0, 1), - ] - for init_exec, src_val, expected_scc in edge_cases: - with self.subTest(init_exec=hex(init_exec), src_val=hex(src_val)): - state = SALUArchitecturalState() - state.exec_mask = init_exec - state.write_sgpr_u64(0, src_val) - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 2, count=2), - src0=Register(RegKind.SGPR, 0, count=2), - ) - res = self.interp.step(inst, state) - flags = evaluate_salu_status_flags(res.new_exec, 0, 0) - - self.assertEqual(res.scc, expected_scc) - self.assertEqual(flags.scc, expected_scc) - self.assertEqual(flags.execnz, (expected_scc == 1)) - self.assertEqual(flags.execz, (expected_scc == 0)) - - def test_vcc_carry_borrow_independence(self) -> None: - """Logic SALU instructions must leave VCC (carry/borrow) completely unaltered.""" - state = SALUArchitecturalState() - canary_vcc = 0xDEAD_BEEF_CAFE_BABE - state.vcc = canary_vcc - state.exec_mask = ALL_LANES_W64 - - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 4, count=2), - src0=LiteralConstant64(EVEN_LANES_W64), - ) - res = self.interp.step(inst, state) - flags = evaluate_salu_status_flags(res.new_exec, canary_vcc, state.vcc) - - self.assertTrue(flags.carry_borrow_unaltered) - self.assertEqual(state.vcc, canary_vcc) - - def test_execz_execnz_complementary_duality(self) -> None: - """execz and execnz must be strict logical complements.""" - test_values = [0, 1, 0xFF, ALL_LANES_W32, ALL_LANES_W64, 1 << 62] - for val in test_values: - flags = evaluate_salu_status_flags(val, 0, 0) - self.assertNotEqual(flags.execz, flags.execnz) - self.assertTrue(flags.execz or flags.execnz) - - def test_active_lane_count_and_parity(self) -> None: - """Active lane count matches popcount and parity is correct.""" - # Even parity: 0 active lanes - flags0 = evaluate_salu_status_flags(0, 0, 0) - self.assertEqual(flags0.active_lane_count, 0) - self.assertTrue(flags0.parity_even) - - # Odd parity: 1 active lane - flags1 = evaluate_salu_status_flags(1, 0, 0) - self.assertEqual(flags1.active_lane_count, 1) - self.assertFalse(flags1.parity_even) - - # Even parity: 64 active lanes - flags64 = evaluate_salu_status_flags(ALL_LANES_W64, 0, 0) - self.assertEqual(flags64.active_lane_count, 64) - self.assertTrue(flags64.parity_even) - - # Odd parity: 63 active lanes - flags63 = evaluate_salu_status_flags(ALL_LANES_W64 ^ 1, 0, 0) - self.assertEqual(flags63.active_lane_count, 63) - self.assertFalse(flags63.parity_even) - - def test_branch_condition_emulation(self) -> None: - """Emulate scalar conditional branches (s_cbranch_scc0 / s_cbranch_scc1 / s_cbranch_execz).""" - def should_branch_scc0(scc: int) -> bool: - return scc == 0 - - def should_branch_scc1(scc: int) -> bool: - return scc == 1 - - def should_branch_execz(exec_mask: int) -> bool: - return exec_mask == 0 - - # When EXEC becomes 0 - _, exec0, scc0 = oracle_s_xor_saveexec_b64(0x1234, 0x1234) - self.assertTrue(should_branch_scc0(scc0)) - self.assertFalse(should_branch_scc1(scc0)) - self.assertTrue(should_branch_execz(exec0)) - - # When EXEC is non-zero - _, exec1, scc1 = oracle_s_xor_saveexec_b64(0x1234, 0x5678) - self.assertFalse(should_branch_scc0(scc1)) - self.assertTrue(should_branch_scc1(scc1)) - self.assertFalse(should_branch_execz(exec1)) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling in 64-bit masks.""" - - def test_float_sign_bit_inversion(self) -> None: - """XOR with SIGN_BIT_64 negates IEEE 754 doubles across normal, zero, and infinite values.""" - test_floats = [1.0, -1.0, 42.5, -0.001953125, math.pi] - for f in test_floats: - bits = f64_to_u64(f) - saved, new_exec, scc = oracle_s_xor_saveexec_b64(bits, SIGN_BIT_64) - self.assertEqual(saved, bits) - self.assertEqual(new_exec, f64_to_u64(-f)) - self.assertEqual(u64_to_f64(new_exec), -f) - self.assertEqual(scc, 1) - - def test_signed_zero_inversion(self) -> None: - """XOR of +0.0 with SIGN_BIT_64 yields -0.0 and vice-versa.""" - saved_pz, new_nz, scc_nz = oracle_s_xor_saveexec_b64(POS_ZERO_64, SIGN_BIT_64) - self.assertEqual(new_nz, NEG_ZERO_64) - self.assertEqual(math.copysign(1.0, u64_to_f64(new_nz)), -1.0) - self.assertEqual(scc_nz, 1) - - saved_nz, new_pz, scc_pz = oracle_s_xor_saveexec_b64(NEG_ZERO_64, SIGN_BIT_64) - self.assertEqual(new_pz, POS_ZERO_64) - self.assertEqual(math.copysign(1.0, u64_to_f64(new_pz)), 1.0) - self.assertEqual(scc_pz, 0) # +0.0 is integer 0, so SCC=0! - - def test_canonical_and_signaling_nan_toggling(self) -> None: - """Toggling the quiet bit (bit 51) transitions between Signaling and Quiet NaN.""" - snan = SIGNALING_NAN_64 - self.assertTrue(is_snan_bits(snan)) - self.assertFalse(is_qnan_bits(snan)) - - # Toggle QNAN bit - saved, qnan, scc = oracle_s_xor_saveexec_b64(snan, QNAN_BIT_64) - self.assertTrue(is_qnan_bits(qnan)) - self.assertFalse(is_snan_bits(qnan)) - self.assertTrue(math.isnan(u64_to_f64(qnan))) - self.assertEqual(scc, 1) - - # Toggle back to snan - saved2, snan2, scc2 = oracle_s_xor_saveexec_b64(qnan, QNAN_BIT_64) - self.assertEqual(snan2, snan) - self.assertTrue(is_snan_bits(snan2)) - - def test_subnormal_boundary_masking(self) -> None: - """Subnormal floating point bit boundaries handled as 64-bit masks.""" - min_subnormal = 0x0000_0000_0000_0001 - max_subnormal = 0x000F_FFFF_FFFF_FFFF - min_normal = 0x0010_0000_0000_0000 - - self.assertTrue(is_subnormal_bits(min_subnormal)) - self.assertTrue(is_subnormal_bits(max_subnormal)) - self.assertFalse(is_subnormal_bits(min_normal)) - - # XOR max_subnormal with (max_subnormal ^ min_normal) transitions to min_normal - transition_mask = max_subnormal ^ min_normal - saved, new_exec, scc = oracle_s_xor_saveexec_b64(max_subnormal, transition_mask) - self.assertEqual(new_exec, min_normal) - self.assertFalse(is_subnormal_bits(new_exec)) - self.assertEqual(scc, 1) - - def test_infinity_arithmetic_boundaries(self) -> None: - """XOR of +inf and -inf yields SIGN_BIT_64 (-0.0 bit representation).""" - self.assertTrue(is_inf_bits(POS_INFINITY_64)) - self.assertTrue(is_inf_bits(NEG_INFINITY_64)) - - saved, new_exec, scc = oracle_s_xor_saveexec_b64(POS_INFINITY_64, NEG_INFINITY_64) - self.assertEqual(saved, POS_INFINITY_64) - self.assertEqual(new_exec, SIGN_BIT_64) # 0x8000_0000_0000_0000 - self.assertEqual(scc, 1) - - def test_nan_payload_preservation(self) -> None: - """Custom payload bits within NaN fraction field preserved under XOR.""" - custom_payload = 0x000A_BCDE_1234_5678 - nan_with_payload = EXP_MASK_64 | custom_payload - self.assertTrue(is_nan_bits(nan_with_payload)) - - saved, new_exec, scc = oracle_s_xor_saveexec_b64(nan_with_payload, 0) - self.assertEqual(new_exec, nan_with_payload) - self.assertTrue(is_nan_bits(new_exec)) - self.assertEqual(new_exec & FRAC_MASK_64, custom_payload) - - -class TestSXorSaveExecB64NegativeControls(unittest.TestCase): - """Negative control tests: syntax rejection, invalid encodings, and boundary defenses.""" - - def test_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.SGPR, -1, count=2) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 106, count=2) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 105, count=2) # spans to 107 - with self.assertRaises(ValueError): - Register(RegKind.VGPR, -1, count=2) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 256, count=2) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 255, count=2) # spans to 257 - - def test_invalid_register_counts(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 0, count=0) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 0, count=3) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 0, count=4) - - def test_invalid_register_kind_for_salu(self) -> None: - with self.assertRaises(TypeError): - SXorSaveExecB64AST( - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.SGPR, 2, count=2), - ) - with self.assertRaises(TypeError): - SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - ) - - def test_architectural_state_out_of_bounds_access(self) -> None: - state = SALUArchitecturalState() - with self.assertRaises(IndexError): - state.read_sgpr_u32(106) - with self.assertRaises(IndexError): - state.write_sgpr_u32(-1, 0) - with self.assertRaises(IndexError): - state.read_sgpr_u64(105) - with self.assertRaises(IndexError): - state.write_sgpr_u64(105, 0) - - def test_simd_invalid_wave_size(self) -> None: - with self.assertRaises(ValueError): - SIMDWavefrontState(wave_size=16) - with self.assertRaises(ValueError): - SIMDWavefrontState(wave_size=128) - - def test_simd_invalid_lane_index(self) -> None: - state = SIMDWavefrontState(wave_size=32) - with self.assertRaises(IndexError): - state.is_lane_active(32) - with self.assertRaises(IndexError): - state.is_lane_active(-1) - - -class TestSXorSaveExecB64MutationDetection(unittest.TestCase): - """Mutation tests: verify that intentional sabotages/mutations of the oracle are caught.""" - - def test_mutation_xor_to_or_sabotage(self) -> None: - # Sabotage: replace XOR with OR - def mutated_oracle(exec_val: int, src_val: int) -> Tuple[int, int, int]: - saved = exec_val & MASK64 - new_exec = (saved | src_val) & MASK64 - scc = 1 if new_exec != 0 else 0 - return saved, new_exec, scc - - # Oracle test: ALL_LANES ^ ALL_LANES must equal 0, but OR yields ALL_LANES - with self.assertRaises(AssertionError): - saved, new_exec, scc = mutated_oracle(ALL_LANES_W64, ALL_LANES_W64) - self.assertEqual(new_exec, 0) - - def test_mutation_xor_to_and_sabotage(self) -> None: - # Sabotage: replace XOR with AND - def mutated_oracle(exec_val: int, src_val: int) -> Tuple[int, int, int]: - saved = exec_val & MASK64 - new_exec = (saved & src_val) & MASK64 - scc = 1 if new_exec != 0 else 0 - return saved, new_exec, scc - - # Oracle test: 0 ^ ALL_LANES must equal ALL_LANES, but AND yields 0 - with self.assertRaises(AssertionError): - saved, new_exec, scc = mutated_oracle(0, ALL_LANES_W64) - self.assertEqual(new_exec, ALL_LANES_W64) - - def test_mutation_saveexec_write_order_sabotage(self) -> None: - # Sabotage: write new_exec to sdst instead of saved (old) exec - interp = ScalarSALUInterpreter() - state = SALUArchitecturalState() - state.exec_mask = ALL_LANES_W64 - - # Proper execution saves ALL_LANES_W64 to s[0:1] and sets EXEC to 0 - inst = SXorSaveExecB64AST( - dst=Register(RegKind.SGPR, 0, count=2), - src0=LiteralConstant64(ALL_LANES_W64), - ) - res = interp.step(inst, state) - self.assertEqual(res.saved_exec, ALL_LANES_W64) - self.assertEqual(state.read_sgpr_u64(0), ALL_LANES_W64) - - # Mutated state: if dst received new_exec (0), asserting it holds ALL_LANES_W64 would fail - mutated_dst_val = 0 - with self.assertRaises(AssertionError): - self.assertEqual(mutated_dst_val, ALL_LANES_W64) - - def test_mutation_scc_inversion_sabotage(self) -> None: - # Sabotage: inverted SCC logic (SCC = 1 when EXEC == 0) - def mutated_oracle(exec_val: int, src_val: int) -> Tuple[int, int, int]: - saved = exec_val & MASK64 - new_exec = (saved ^ src_val) & MASK64 - scc = 1 if new_exec == 0 else 0 # Inverted! - return saved, new_exec, scc - - with self.assertRaises(AssertionError): - _, _, scc = mutated_oracle(0, 0) - self.assertEqual(scc, 0) - - def test_mutation_scc_from_old_exec_sabotage(self) -> None: - # Sabotage: SCC computed from old EXEC instead of new EXEC - def mutated_oracle(exec_val: int, src_val: int) -> Tuple[int, int, int]: - saved = exec_val & MASK64 - new_exec = (saved ^ src_val) & MASK64 - scc = 1 if saved != 0 else 0 # Bug: derived from old exec - return saved, new_exec, scc - - # When old exec is ALL_LANES but new exec is 0: SCC must be 0, not 1 - with self.assertRaises(AssertionError): - _, _, scc = mutated_oracle(ALL_LANES_W64, ALL_LANES_W64) - self.assertEqual(scc, 0) - - def test_mutation_mask_32bit_truncation_sabotage(self) -> None: - # Sabotage: 64-bit mask truncated to 32-bit - def mutated_step(exec_val: int, src_val: int) -> int: - return (exec_val ^ src_val) & MASK32 # Lost upper 32 bits! - - with self.assertRaises(AssertionError): - res = mutated_step(ALL_LANES_W64, 0) - self.assertEqual(res, ALL_LANES_W64) - - def test_mutation_aliasing_read_after_write_sabotage(self) -> None: - # Sabotage: non-atomic sequential execution reading src0 after updating dst - state = SALUArchitecturalState() - init_exec = 0xAAAA_AAAA_5555_5555 - init_src = 0x1234_5678_9ABC_DEF0 - state.exec_mask = init_exec - state.write_sgpr_u64(4, init_src) - - # Buggy sequence: - # 1. state.write_sgpr_u64(4, state.exec_mask) -> s[4:5] is now init_exec! - # 2. src0 = state.read_sgpr_u64(4) -> reads init_exec instead of init_src! - # 3. state.exec_mask = state.exec_mask ^ src0 -> init_exec ^ init_exec = 0! - mutated_new_exec = 0 # would result in 0 - expected_new_exec = init_exec ^ init_src - with self.assertRaises(AssertionError): - self.assertEqual(mutated_new_exec, expected_new_exec) + def test_xor_every_lane(self): + saveexec_run.check(self, "xor") if __name__ == "__main__": diff --git a/tests/semantic/test_sample_c.py b/tests/semantic/test_sample_c.py new file mode 100644 index 000000000..0b5759ac5 --- /dev/null +++ b/tests/semantic/test_sample_c.py @@ -0,0 +1,108 @@ +"""image_sample_c and image_sample_c_b (and their _o forms): depth-compare samples with implicit LOD / bias. + +Standard library only (spirv-val is used when it is on PATH); no GPU, no LLVM, no game files. + +The GPU fixtures are runtime/test/shaders/ps_sample_c.asm and ps_sample_c_b.asm (vk_texture_test dref_c, dref_c_b). Here: +the shape of the SPIR-V in a pixel shader (OpImageSampleDrefImplicitLod, a Bias operand for _c_b, the Offset for _o), +LOD 0 for _c outside the pixel stage, the refusal of _c_b there, d16 and a16 forms, and that the module validates. +""" +import os +import re +import shutil +import struct +import subprocess +import tempfile +import unittest + +import support + +DESC = "s[8:15], s[16:19]" +CS_FSSM = bytearray(0x148) +struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 32, 1, 1) +CS_FSSM = bytes(CS_FSSM) +PRO = ["v_mov_b32 v4, 1.0", "v_mov_b32 v5, 0.5", "v_mov_b32 v6, 0.25", "v_mov_b32 v7, 0.75", "v_mov_b32 v8, 0"] + + +def translate(name, line): + fssm = CS_FSSM if name.startswith("cs_") else None + return support.translate_lines(name, PRO + [line, "exp mrt0 v9, v9, v9, v9 done vm", "s_endpgm"] + if name.startswith("ps_") else PRO + [line, "s_endpgm"], fssm=fssm) + + +def samples(spv): + return [ln.strip() for ln in spv.splitlines() if "= OpImageSample" in ln] + + +class SampleC(unittest.TestCase): + def test_c_is_dref_implicit_lod_in_a_pixel_shader(self): + spv = translate("ps_samplec", f"image_sample_c v9, v[4:6], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") + (line,) = samples(spv) + self.assertRegex(line, r"= OpImageSampleDrefImplicitLod %float %\w+ %\w+ %\w+$") + + def test_c_b_has_a_bias_operand(self): + spv = translate("ps_samplecb", f"image_sample_c_b v9, v[4:7], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") + (line,) = samples(spv) + self.assertRegex(line, r"= OpImageSampleDrefImplicitLod %float %\w+ %\w+ %\w+ Bias %\w+$") + + def test_offset_forms_carry_the_offset(self): + for op, regs in (("image_sample_c_o", "v[4:7]"), ("image_sample_c_b_o", "v[4:8]")): + with self.subTest(op=op): + spv = translate("ps_sampleco", f"{op} v9, {regs}, {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") + (line,) = samples(spv) + self.assertIn("OpImageSampleDrefImplicitLod", line) + self.assertIn("Offset", line) + + def test_d16_result_is_an_f16_in_the_low_half(self): + spv = translate("ps_sampled16", f"image_sample_c v9, v[4:6], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D d16") + self.assertIn("OpImageSampleDrefImplicitLod", spv) + self.assertNotIn("PackHalf2x16", spv) + + def test_c_outside_a_pixel_shader_samples_lod_zero(self): + for name, fssm in (("vs_samplec", None), ("cs_samplec", CS_FSSM)): + with self.subTest(shader=name): + spv = translate(name, f"image_sample_c v9, v[4:6], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") + (line,) = samples(spv) + self.assertRegex(line, r"= OpImageSampleDrefExplicitLod %float %\w+ %\w+ %\w+ Lod %f0$") + + def test_c_b_outside_a_pixel_shader_is_refused(self): + with self.assertRaises(support.rdna2spirv.Unsupported): + translate("vs_samplecb", f"image_sample_c_b v9, v[4:7], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") + + def test_the_bias_comes_before_the_compare(self): + # GFX10 address order after the offset: bias, z-compare, coordinates (the compare in v5, the bias in v4). + spv = translate("ps_sampleorder", f"image_sample_c_b v9, v[4:7], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") + (line,) = samples(spv) + ref, bias = re.search(r"%\w+ %\w+ (%\w+) Bias (%\w+)$", line).groups() + + def loaded_from(value): + """The VGPR index a value was loaded from: the OpLoad of %vgpr[k] behind it, through bitcasts.""" + for _ in range(6): + m = re.search(rf"^\s*{re.escape(value)} = (\w+) (?:%\w+ )?(%\w+)", spv, re.M) + if not m: + return None + op, src = m.groups() + if op == "OpLoad": + m2 = re.search(rf"^\s*{re.escape(src)} = OpAccessChain %\S+ %vgpr (%\w+)", spv, re.M) + consts = {k: int(v) for k, v in re.findall(r"^\s*(%\w+) = OpConstant %uint (\d+)", spv, re.M)} + return consts.get(m2.group(1)) if m2 else None + value = src + return None + self.assertEqual((loaded_from(bias), loaded_from(ref)), (4, 5)) + + @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val on PATH") + def test_modules_validate(self): + for op, regs in (("image_sample_c", "v[4:6]"), ("image_sample_c_b", "v[4:7]"), ("image_sample_c_o", "v[4:7]"), + ("image_sample_c_b_o", "v[4:8]")): + with self.subTest(op=op): + spv = translate("ps_sampleval", f"{op} v9, {regs}, {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") + with tempfile.TemporaryDirectory() as tmp: + a, b = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") + with open(a, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + subprocess.run(["spirv-as", "--target-env", "vulkan1.2", a, "-o", b], check=True) + # a texel offset that comes from a register needs VK_KHR_maintenance8 (design.md, Texel offsets) + subprocess.run(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", b], check=True) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/tests/semantic/test_sample_cl.py b/tests/semantic/test_sample_cl.py new file mode 100644 index 000000000..70faa09d1 --- /dev/null +++ b/tests/semantic/test_sample_cl.py @@ -0,0 +1,131 @@ +"""image_sample_cl, _b_cl, _c_cl, _c_b_cl (and their _o forms): implicit-LOD samples with a min-LOD clamp. + +Standard library only (spirv-val is used when it is on PATH); no GPU, no LLVM, no game files. + +GPU tests: ps_texture_cl and ps_texture_b_cl (two-mip texture, check.py GRADIENT_TESTS / CLAMP_TESTS). Here the shape +of the SPIR-V: the clamp is the component after the coordinates and becomes MinLod (with Bias, with the compare, after +Offset), outside the pixel stage the LOD is max(0, clamp), a16 packs the clamp with the coordinates, and the module +declares MinLod and validates. +""" +import os +import re +import shutil +import struct +import subprocess +import tempfile +import unittest + +import support + +DESC = "s[8:15], s[16:19]" +D2 = "dim:SQ_RSRC_IMG_2D" +PRO = ["v_mov_b32 v4, 1.0", "v_mov_b32 v5, 0.5", "v_mov_b32 v6, 0.25", "v_mov_b32 v7, 0.75", "v_mov_b32 v8, 0.125", + "v_mov_b32 v9, 0"] +CS_FSSM = bytearray(0x148) +struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 32, 1, 1) +CS_FSSM = bytes(CS_FSSM) + + +def translate(name, line): + fssm = CS_FSSM if name.startswith("cs_") else None + body = PRO + [line] + (["exp mrt0 v9, v9, v9, v9 done vm"] if name.startswith("ps_") else []) + ["s_endpgm"] + return support.translate_lines(name, body, fssm=fssm) + + +def samples(spv): + return [ln.strip() for ln in spv.splitlines() if "= OpImageSample" in ln] + + +def source_vgpr(spv, value): + """The VGPR index the id `value` was loaded from (through bitcasts), or None.""" + consts = {k: int(v) for k, v in re.findall(r"^\s*(%\w+) = OpConstant %uint (\d+)", spv, re.M)} + for _ in range(8): + m = re.search(rf"^\s*{re.escape(value)} = (\w+) (?:%\w+ )?(%\w+)", spv, re.M) + if not m: + return None + op, src = m.groups() + if op == "OpLoad": + m2 = re.search(rf"^\s*{re.escape(src)} = OpAccessChain %\S+ %vgpr (%\w+)", spv, re.M) + return consts.get(m2.group(1)) if m2 else None + value = src + return None + + +class SampleCl(unittest.TestCase): + def one(self, name, line): + (s,) = samples(translate(name, line)) + return s + + def test_cl_is_implicit_lod_with_min_lod(self): + s = self.one("ps_cl", f"image_sample_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2}") + self.assertRegex(s, r"= OpImageSampleImplicitLod %v4float %\w+ %\w+ MinLod %\w+$") + + def test_the_clamp_is_the_component_after_the_coordinates(self): + spv = translate("ps_cl", f"image_sample_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2}") + (s,) = samples(spv) + self.assertEqual(source_vgpr(spv, s.split()[-1]), 6) + + def test_b_cl_has_bias_and_min_lod(self): + spv = translate("ps_bcl", f"image_sample_b_cl v[0:3], v[4:7], {DESC} dmask:0xf {D2}") + (s,) = samples(spv) + self.assertRegex(s, r"= OpImageSampleImplicitLod %v4float %\w+ %\w+ Bias\|MinLod %\w+ %\w+$") + bias, minlod = s.split()[-2:] + self.assertEqual((source_vgpr(spv, bias), source_vgpr(spv, minlod)), (4, 7)) + + def test_dref_forms(self): + s = self.one("ps_ccl", f"image_sample_c_cl v9, v[4:7], {DESC} dmask:0x1 {D2}") + self.assertRegex(s, r"= OpImageSampleDrefImplicitLod %float %\w+ %\w+ %\w+ MinLod %\w+$") + s = self.one("ps_cbcl", f"image_sample_c_b_cl v9, v[4:8], {DESC} dmask:0x1 {D2}") + self.assertRegex(s, r"= OpImageSampleDrefImplicitLod %float %\w+ %\w+ %\w+ Bias\|MinLod %\w+ %\w+$") + + def test_offset_comes_before_the_min_lod(self): + s = self.one("ps_clo", f"image_sample_cl_o v[0:3], v[4:7], {DESC} dmask:0xf {D2}") + self.assertRegex(s, r"= OpImageSampleImplicitLod %v4float %\w+ %\w+ Offset\|MinLod %\w+ %\w+$") + + def test_a16_packs_the_clamp_with_the_coordinates(self): + # u, v in one VGPR, the clamp in the low half of the next; no whole-VGPR extra for _cl itself + s = self.one("ps_clo16", f"image_sample_cl v[0:3], v[4:5], {DESC} dmask:0xf {D2} a16") + self.assertIn("MinLod", s) + s = self.one("ps_bclo16", f"image_sample_b_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2} a16") + self.assertIn("Bias|MinLod", s) + + def test_without_derivatives_the_lod_is_the_clamp_or_zero(self): + for name, fssm in (("vs_cl", None), ("cs_cl", CS_FSSM)): + with self.subTest(shader=name): + spv = translate(name, f"image_sample_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2}") + (s,) = samples(spv) + self.assertRegex(s, r"= OpImageSampleExplicitLod %v4float %\w+ %\w+ Lod %\w+$") + self.assertIn("FMax %f0", spv) + self.assertNotIn("MinLod", s) + + def test_module_declares_min_lod(self): + self.assertIn("OpCapability MinLod", translate("ps_cl", f"image_sample_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2}")) + self.assertNotIn("OpCapability MinLod", translate("ps_noc", f"image_sample v[0:3], v[4:5], {DESC} dmask:0xf {D2}")) + + def test_forms_with_no_clamp_variant_stay_refused(self): + for op, regs in (("image_sample_l_cl", "v[4:7]"), ("image_sample_lz_cl", "v[4:6]")): + with self.subTest(op=op), self.assertRaises(support.rdna2spirv.Unsupported): + translate("ps_x", f"{op} v[0:3], {regs}, {DESC} dmask:0xf {D2}") + + @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val on PATH") + def test_modules_validate(self): + cases = [("image_sample_cl", "v[0:3]", "v[4:6]", 0xf), ("image_sample_b_cl", "v[0:3]", "v[4:7]", 0xf), + ("image_sample_c_cl", "v9", "v[4:7]", 1), ("image_sample_c_b_cl", "v9", "v[4:8]", 1), + ("image_sample_cl_o", "v[0:3]", "v[4:7]", 0xf)] + for op, dst, regs, dmask in cases: + for name in ("ps_val", "vs_val"): + if name == "vs_val" and "_b_" in op: + continue # no bias without derivatives + with self.subTest(op=op, shader=name): + spv = translate(name, f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2}") + with tempfile.TemporaryDirectory() as tmp: + a, b = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") + with open(a, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + subprocess.run(["spirv-as", "--target-env", "vulkan1.2", a, "-o", b], check=True) + subprocess.run(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", b], + check=True) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/tests/semantic/test_scalar_alu_and_smem_folding.py b/tests/semantic/test_scalar_alu_and_smem_folding.py index bb34022e5..f17476663 100644 --- a/tests/semantic/test_scalar_alu_and_smem_folding.py +++ b/tests/semantic/test_scalar_alu_and_smem_folding.py @@ -188,6 +188,33 @@ class ScalarAluAndSmemFoldingTests(unittest.TestCase): # Only base lo is masked with %cfffffffc; offset s2 is not dynamically masked self.assertEqual(text.count("%cfffffffc"), 1) + def test_s_buffer_load_constant_negative_sgpr_offset_does_not_wrap(self): + # SHADER-328: s8 = -4 with offset:20 is 0xFFFFFFFC + 20 in 64 bits (RDNA2 reads 0, measured in #1686), not + # 16 after a 32-bit wrap. The constant must give what the run-time path gives: out of bounds, 0. + g = rdna2spirv.Gen("ps") + g.sgpr_imm.update({0: 0x1000, 1: 0, 2: 64, 3: 0x31000FAC, 8: 0xFFFFFFFC}) # raw V#, limit 64 bytes + ins = parse_line("s_buffer_load_dword s10, s[0:3], s8 offset:20") + g.scalar_load(ins["op"], ins["args"], ins["mods"]) + text = "\n".join(g.body) + self.assertNotIn("OpAccessChain %_ptr_PSB_uint", text) # no read: the dword is out of bounds + self.assertTrue(any(ln.strip().startswith("OpStore %t") and ln.strip().endswith(g.cu(0)) for ln in g.body)) + + # The same offsets inside the limit still read memory. + g = rdna2spirv.Gen("ps") + g.sgpr_imm.update({0: 0x1000, 1: 0, 2: 64, 3: 0x31000FAC, 8: 4}) + ins = parse_line("s_buffer_load_dword s10, s[0:3], s8 offset:20") + g.scalar_load(ins["op"], ins["args"], ins["mods"]) + self.assertIn("OpAccessChain %_ptr_PSB_uint", "\n".join(g.body)) + + def test_s_load_constant_sgpr_offset_is_not_sign_extended(self): + # The run-time path adds zext(sOFF & ~3) to the 21-bit immediate; a constant sOFF of 2^20 must not pass + # through the immediate's 21-bit sign extension (it would become -2^20). + g = rdna2spirv.Gen("ps") + g.sgpr_imm[2] = 0x100000 + ins = parse_line("s_load_dword s0, s[4:5], s2 offset:0x10") + g.scalar_load(ins["op"], ins["args"], ins["mods"]) + self.assertIn("%cl100010", "\n".join(g.body)) + if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_scalar_bitcmp.py b/tests/semantic/test_scalar_bitcmp.py index daa6f09b4..3c632af5f 100644 --- a/tests/semantic/test_scalar_bitcmp.py +++ b/tests/semantic/test_scalar_bitcmp.py @@ -364,6 +364,90 @@ class TestRdna2SpirvBitcmpEmission(unittest.TestCase): self.assertIn("FindILsb", emitted) self.assertIn("OpIAdd %uint", emitted) + def test_s_ff0_s_ff1_b64_negative_inline_and_literal_immediates(self): + """s_ff0_i32_b64 / s_ff1_i32_b64 sign-extend negative inline constants (-1..-16) and zero-extend literals.""" + import shutil + import struct + import subprocess + import tempfile + import warnings + if HERE not in sys.path: + sys.path.insert(0, HERE) + import spirv_mini_interp as si + + stub_dxbc = b"DXBC" + bytes(24) + struct.pack(" no 0 bit + ("s_ff0_i32_b64 s10, -2", 0), # 0xFFFFFFFF_FFFFFFFE -> bit 0 is 0 + ("s_ff0_i32_b64 s10, -16", 0), # 0xFFFFFFFF_FFFFFFF0 -> bit 0 is 0 + ("s_ff0_i32_b64 s10, 0xffffffff", 32), # 0x00000000_FFFFFFFF -> bit 32 is first 0 + ("s_ff0_i32_b64 s10, 0", 0), # 0x00000000_00000000 -> bit 0 is 0 + ("s_ff0_i32_b64 s10, 0x5", 1), # 0b101 -> bit 1 is 0 + ("s_ff1_i32_b64 s10, -1", 0), # 0xFFFFFFFF_FFFFFFFF -> bit 0 is 1 + ("s_ff1_i32_b64 s10, -16", 4), # 0xFFFFFFFF_FFFFFFF0 -> bit 4 is 1 + ("s_ff1_i32_b64 s10, 0", 0xFFFFFFFF), # no 1 bit + ("s_ff1_i32_b64 s10, 0x80000000", 31), # literal bit 31 + ("s_ff0_i32_b64 s10, null", 0), # null -> 0 + ("s_ff1_i32_b64 s10, null", 0xFFFFFFFF), # null -> 0 + ] + asm_lines = [] + for idx, (insn, _) in enumerate(cases): + asm_lines += [ + insn, + "v_mov_b32_e32 v1, s10", + f"v_mov_b32_e32 v2, {idx * 4}", + "buffer_store_dword v1, v2, s[0:3], 0 offen", + ] + asm_lines.append("s_endpgm") + with tempfile.TemporaryDirectory() as tmp: + os.mkdir(os.path.join(tmp, "disasm")) + os.mkdir(os.path.join(tmp, "fssm")) + src = os.path.join(tmp, "disasm", "cs_ff_b64_imm.s") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write("; cs_ff_b64_imm\n" + "".join(f"\t{ln}\n" for ln in asm_lines)) + with open(os.path.join(tmp, "cs_ff_b64_imm.dxbc"), "wb") as f: + f.write(stub_dxbc) + with open(os.path.join(tmp, "fssm", "cs_ff_b64_imm.fssm"), "wb") as f: + f.write(bytes(0x138) + struct.pack("<4I", 0x8090, 64, 1, 1)) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(src) + spirv_as = shutil.which("spirv-as") + spirv_val = shutil.which("spirv-val") + if spirv_as and spirv_val: + spvasm = os.path.join(tmp, "m.spvasm") + spvbin = os.path.join(tmp, "m.spv") + with open(spvasm, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", spvasm, "-o", spvbin], + capture_output=True, text=True) + self.assertEqual(r1.returncode, 0, r1.stderr) + r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", spvbin], + capture_output=True, text=True) + self.assertEqual(r2.returncode, 0, r2.stderr) + mem = si.run_workgroup( + spv, 64, 64, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=vsharp + [0] * 28, memory={}, + ) + for idx, (insn, want) in enumerate(cases): + with self.subTest(insn=insn): + self.assertEqual(mem[idx * 4], want) + + def test_s_ff1_i32_b64_high_word_immediate(self): + """Synthetic 64-bit immediate with only high-word bits set uses hi via src64_data.""" + g = rdna2spirv.Gen("ps") + g.insn({ + "op": "s_ff1_i32_b64", + "args": [{"k": "sgpr", "r": 0}, {"k": "imm", "v": 0x0000000100000000}], + "mods": [], + }) + emitted = "\n".join(g.body) + self.assertIn("OpBitcast %int %c0", emitted) + self.assertIn("OpBitcast %int %c1", emitted) + if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_scalar_mem_smem.py b/tests/semantic/test_scalar_mem_smem.py index ad6eb3138..c52222a2e 100644 --- a/tests/semantic/test_scalar_mem_smem.py +++ b/tests/semantic/test_scalar_mem_smem.py @@ -773,6 +773,43 @@ class SmemHardwareRuleTests(unittest.TestCase): self.both("s_buffer_load_dword s12, s[24:27], s40", soff, [None], [], extra={"nr": 0x100}) self.both("s_buffer_load_dword s12, s[24:27], s40", 8, [8], [8], extra={"nr": 0x100}) + # Measured on gfx1036 (RDNA2, Ryzen 9 9950X3D iGPU, AMD Windows driver 32.0.21045.16010) through tools/hw_oracle, + # wave32 = wave64, every read inside a seeded region so only the bound decides: the edges docs/design.md listed + # as not measured. + def test_x16_is_bounded_per_dword(self): + # x16 at 0, NR 0x14 -> d0..d4 data, d5..d15 0; NR 0x40 -> all 16 data + line = "s_buffer_load_dwordx16 s[40:55], s[24:27], 0x0" + self.check_wide(line, {"nr": 0x14}, [4 * i if i < 5 else None for i in range(16)]) + self.check_wide(line, {"nr": 0x40}, [4 * i for i in range(16)]) + # x16 with imm 8 or soffset 8, NR 0x20 -> d0..d5 data (bytes 8..0x1f), d6..d15 0 + self.check_wide("s_buffer_load_dwordx16 s[40:55], s[24:27], 0x8", {"nr": 0x20}, + [8 + 4 * i if i < 6 else None for i in range(16)]) + self.check_wide("s_buffer_load_dwordx16 s[40:55], s[24:27], s20", {"nr": 0x20, 20: 8}, + [8 + 4 * i if i < 6 else None for i in range(16)]) + + def test_num_records_times_stride_does_not_wrap_at_4gib(self): + # stride 0x1000 x NR 0x100000 and 0x2000 x 0x80000 = 2^32, stride 8 x NR 0x20000001 = 2^32 + 8: all four + # dwords are data. A 32-bit product (0, 0, 8) would give 0 for every dword, or for d2 and d3. + for stride, nr in ((0x1000, 0x100000), (0x2000, 0x80000), (8, 0x20000001)): + self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0x0", {"nr": nr, "stride": stride}, + [0x0, 0x4, 0x8, 0xC], [0x0, 0x4, 0x8, 0xC]) + # control from the same run: stride 8 x NR 1 = 8 bytes -> d0, d1 data, d2, d3 0 + self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0x0", {"nr": 1, "stride": 8}, + [0x0, 0x4, None, None], [0x0, 0x4]) + + def test_num_records_at_or_above_2_31_is_unsigned(self): + for nr in (0x80000000, 0xFFFFFFFF): + self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0x0", {"nr": nr}, + [0x0, 0x4, 0x8, 0xC], [0x0, 0x4, 0x8, 0xC]) + + def check_wide(self, line, sgpr, want): + """check() for a destination starting at s40 (a 16-dword load does not fit below the V# in s[24:27]).""" + ev, got_reads, mem = self.run_line(line, sgpr) + values = [0 if w is None else mem.data(w) for w in want] + self.assertEqual([f"{ev.sgpr.get(40 + i, 0):#010x}" for i in range(len(want))], + [f"{v:#010x}" for v in values], line) + self.assertEqual([hex(r) for r in got_reads], [hex(w) for w in want if w is not None], line) + # s_load: 64-bit pointer, no bound def test_s_load_truncates_pointer_and_offsets(self): # p0-k1[0]: ptr & 3 = 1, imm 1 -> data@+0; p0-k1[6]: soffset 3 + imm 3 -> data@+0; p0-k1[8]: 8 + 4 -> +0xc diff --git a/tests/semantic/test_spirv_wave_interp.py b/tests/semantic/test_spirv_wave_interp.py index ddae1b9ec..b247ae135 100644 --- a/tests/semantic/test_spirv_wave_interp.py +++ b/tests/semantic/test_spirv_wave_interp.py @@ -208,6 +208,54 @@ OpStore %out %v outs(body) +class WideIntegers(unittest.TestCase): + """OpBitCount and the GLSL.std.450 signed integer operations on a 64-bit type.""" + HEAD64 = (HEAD.replace("OpMemoryModel", '%glsl = OpExtInstImport "GLSL.std.450"\nOpMemoryModel') + .replace("%c0 = OpConstant %uint 0", + "%ulong = OpTypeInt 64 0\n" + "%cl_1 = OpConstant %ulong 1\n" + "%cl_2p31 = OpConstant %ulong 2147483648\n" + "%cl_2p32 = OpConstant %ulong 4294967296\n" + "%cl_2p32_5 = OpConstant %ulong 4294967301\n" + "%cl_hi = OpConstant %ulong 18446744069414584320\n" # 0xFFFFFFFF00000000 = -2**32 + "%cl_m1 = OpConstant %ulong 18446744073709551615\n" + "%c0 = OpConstant %uint 0")) + + def lane0(self, body): + return run_wave(self.HEAD64 + body + "%v = OpCompositeConstruct %v4uint %res %c0 %c0 %c0\n" + "OpStore %out %v\n" + TAIL, wave=32)["outputs"][0]["%out"][0] + + def test_bit_count_counts_every_bit_of_a_64bit_operand(self): + for src, want in (("%cl_hi", 32), ("%cl_m1", 64), ("%cl_2p32_5", 3), ("%cl_1", 1), ("%c3", 2)): + with self.subTest(src=src): + self.assertEqual(self.lane0(f"%res = OpBitCount %uint {src}\n"), want) + + def test_signed_min_max_clamp_abs_use_the_width_of_a_64bit_type(self): + # 2**31 is positive in a 64-bit integer and 0xFFFFFFFF00000000 is -2**32; a 32-bit reading takes them + # as -2**31 and 0. + for inst, want in (("SMin %cl_2p31 %cl_1", "%cl_1"), ("SMax %cl_2p31 %cl_1", "%cl_2p31"), + ("SMin %cl_hi %cl_1", "%cl_hi"), ("SMax %cl_hi %cl_m1", "%cl_m1"), + ("SClamp %cl_2p31 %cl_1 %cl_2p32", "%cl_2p31"), ("SClamp %cl_hi %cl_m1 %cl_1", "%cl_m1"), + ("SAbs %cl_hi", "%cl_2p32"), ("SAbs %cl_2p32_5", "%cl_2p32_5"), ("SAbs %cl_m1", "%cl_1")): + with self.subTest(inst=inst): + self.assertEqual(self.lane0(f"%r = OpExtInst %ulong %glsl {inst}\n" + f"%eq = OpIEqual %bool %r {want}\n" + "%res = OpSelect %uint %eq %c1 %c0\n"), 1) + + def test_32bit_signed_operations_are_unchanged(self): + self.assertEqual(self.lane0("%m1 = OpISub %uint %c0 %c1\n%res = OpExtInst %uint %glsl SMin %m1 %c1\n"), + 0xFFFFFFFF) + self.assertEqual(self.lane0("%m1 = OpISub %uint %c0 %c1\n%res = OpExtInst %uint %glsl SAbs %m1\n"), 1) + self.assertEqual(self.lane0("%res = OpExtInst %uint %glsl FindUMsb %c8\n"), 3) + + def test_find_bit_of_a_64bit_operand_is_rejected(self): + # GLSL.std.450 limits FindILsb, FindSMsb and FindUMsb to 32-bit components. + for name in ("FindILsb", "FindSMsb", "FindUMsb"): + with self.subTest(name=name): + with self.assertRaises(UnsupportedConstruct): + self.lane0(f"%r = OpExtInst %ulong %glsl {name} %cl_2p32\n%res = OpUConvert %uint %r\n") + + class Strictness(unittest.TestCase): def test_float_arithmetic_is_rejected(self): body = """%f = OpBitcast %uint %c1 @@ -227,5 +275,136 @@ OpReturn outs(body) + + +class WaveInterpExtensions(unittest.TestCase): + def test_location_inputs_float_ops_and_convert(self): + mod = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" %out %in0 %l +OpDecorate %out Location 0 +OpDecorate %in0 Location 0 +OpDecorate %l BuiltIn SubgroupLocalInvocationId +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%v4uint = OpTypeVector %uint 4 +%_ptr_Output = OpTypePointer Output %v4uint +%_ptr_Input = OpTypePointer Input %v4float +%_ptr_Input_f = OpTypePointer Input %float +%_ptr_Builtin = OpTypePointer Input %uint +%out = OpVariable %_ptr_Output Output +%in0 = OpVariable %_ptr_Input Input +%l = OpVariable %_ptr_Builtin Input +%c0 = OpConstant %uint 0 +%c1 = OpConstant %uint 1 +%f64 = OpConstant %float 64.0 +%main = OpFunction %void None %fn +%entry = OpLabel +%px = OpAccessChain %_ptr_Input_f %in0 %c0 +%py = OpAccessChain %_ptr_Input_f %in0 %c1 +%fx = OpLoad %float %px +%fy = OpLoad %float %py +%sx = OpFMul %float %fx %f64 +%sy = OpFMul %float %fy %f64 +%ux = OpConvertFToU %uint %sx +%uy = OpConvertFToU %uint %sy +%sum = OpFAdd %float %fx %fy +%us = OpConvertFToU %uint %sum +%v = OpCompositeConstruct %v4uint %ux %uy %us %c0 +OpStore %out %v +OpReturn +OpFunctionEnd +""" + res = run_wave(mod, wave=32, inputs={0: lambda lane: ((lane + 0.5) / 64.0, 1.5 / 64.0, 0.0, 0.0)}) + for lane in range(32): + self.assertEqual(res["outputs"][lane]["%out"], (lane, 1, 0, 0)) + + def test_physical_storage_buffer_atomic_and_store(self): + mod = """OpCapability Shader +OpCapability Int64 +OpCapability PhysicalStorageBufferAddresses +OpMemoryModel PhysicalStorageBuffer64 GLSL450 +OpEntryPoint GLCompute %main "main" %out %l +OpDecorate %out Location 0 +OpDecorate %l BuiltIn SubgroupLocalInvocationId +OpDecorate %arr ArrayStride 4 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%ulong = OpTypeInt 64 0 +%v4uint = OpTypeVector %uint 4 +%arr = OpTypeRuntimeArray %uint +%_ptr_Output = OpTypePointer Output %v4uint +%_ptr_Builtin = OpTypePointer Input %uint +%_ptr_PSB_arr = OpTypePointer PhysicalStorageBuffer %arr +%_ptr_PSB_u = OpTypePointer PhysicalStorageBuffer %uint +%out = OpVariable %_ptr_Output Output +%l = OpVariable %_ptr_Builtin Input +%c0 = OpConstant %uint 0 +%c1 = OpConstant %uint 1 +%c0_64 = OpConstant %ulong 0 +%c64_64 = OpConstant %ulong 64 +%c4_64 = OpConstant %ulong 4 +%main = OpFunction %void None %fn +%entry = OpLabel +%lane = OpLoad %uint %l +%base = OpConvertUToPtr %_ptr_PSB_arr %c0_64 +%p0 = OpAccessChain %_ptr_PSB_u %base %c0 +%slot = OpAtomicIAdd %uint %p0 %c1 %c0 %c1 +%slot64 = OpUConvert %ulong %slot +%off = OpIMul %ulong %slot64 %c4_64 +%addr = OpIAdd %ulong %c64_64 %off +%sptr_arr = OpConvertUToPtr %_ptr_PSB_arr %addr +%sptr = OpAccessChain %_ptr_PSB_u %sptr_arr %c0 +OpStore %sptr %lane Aligned 4 +%v = OpCompositeConstruct %v4uint %slot %c0 %c0 %c0 +OpStore %out %v +OpReturn +OpFunctionEnd +""" + mem = {0: 0} + res = run_wave(mod, wave=32, memory=mem) + self.assertEqual(mem[0], 32) + self.assertEqual({mem[64 + 4 * i] for i in range(32)}, set(range(32))) + + def test_quad_swap_and_broadcast(self): + mod = """OpCapability Shader +OpCapability GroupNonUniformQuad +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" %out %l +OpDecorate %out Location 0 +OpDecorate %l BuiltIn SubgroupLocalInvocationId +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%v4uint = OpTypeVector %uint 4 +%_ptr_Output = OpTypePointer Output %v4uint +%_ptr_Builtin = OpTypePointer Input %uint +%out = OpVariable %_ptr_Output Output +%l = OpVariable %_ptr_Builtin Input +%c0 = OpConstant %uint 0 +%c1 = OpConstant %uint 1 +%c2 = OpConstant %uint 2 +%c3 = OpConstant %uint 3 +%main = OpFunction %void None %fn +%entry = OpLabel +%lane = OpLoad %uint %l +%sh = OpGroupNonUniformQuadSwap %uint %c3 %lane %c0 +%sv = OpGroupNonUniformQuadSwap %uint %c3 %lane %c1 +%sd = OpGroupNonUniformQuadSwap %uint %c3 %lane %c2 +%sb = OpGroupNonUniformQuadBroadcast %uint %c3 %lane %c0 +%v = OpCompositeConstruct %v4uint %sh %sv %sd %sb +OpStore %out %v +OpReturn +OpFunctionEnd +""" + res = run_wave(mod, wave=32) + for lane in range(32): + self.assertEqual(res["outputs"][lane]["%out"], (lane ^ 1, lane ^ 2, lane ^ 3, lane & ~3)) + + if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_valu_add_f16.py b/tests/semantic/test_valu_add_f16.py index ca3147358..b6dc6507d 100644 --- a/tests/semantic/test_valu_add_f16.py +++ b/tests/semantic/test_valu_add_f16.py @@ -1,1319 +1,146 @@ -from __future__ import annotations +"""v_add_f16 (RDNA2 VOP2 / VOP3): D.f16 = S0.f16 + S1.f16, binary16 with round to nearest even. -import math -import struct +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in +tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the _e32 form (the high half of the +destination is kept), the _e64 form with op_sel, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. +Standard library only: no GPU, no LLVM, no game data. +""" +import os +import random +import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from fractions import Fraction -from typing import List, Optional, Tuple, Union -# IEEE 754 binary16 (half precision) architectural constants -SIGN_MASK: int = 0x8000 -EXP_MASK: int = 0x7C00 -FRAC_MASK: int = 0x03FF -QNAN_BIT: int = 0x0200 -CANONICAL_QNAN: int = 0x7E00 +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import OLD, ref_add, same_f16, scale # noqa: E402 -POS_ZERO: int = 0x0000 -NEG_ZERO: int = 0x8000 -POS_INF: int = 0x7C00 -NEG_INF: int = 0xFC00 - -ONE_F16: int = 0x3C00 -MAX_NORMAL_F16: int = 0x7BFF -MIN_NORMAL_F16: int = 0x0400 -MAX_SUBNORMAL_F16: int = 0x03FF -MIN_SUBNORMAL_F16: int = 0x0001 +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF -def f16_to_bits(val: float) -> int: - """Convert a Python float to 16-bit integer bits (IEEE 754 binary16).""" - return struct.unpack(" float: - """Convert 16-bit integer bits to a Python float (IEEE 754 binary16).""" - return struct.unpack(" Tuple[int, int, int]: - """Unpack bits into (sign, exponent, fraction) components.""" - sign = (bits & SIGN_MASK) >> 15 - exponent = (bits & EXP_MASK) >> 10 - fraction = bits & FRAC_MASK - return sign, exponent, fraction - - -def pack_f16_pair(lo: int, hi: int) -> int: - """Pack two 16-bit values into a 32-bit register word.""" - return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) - - -def unpack_f16_pair(val32: int) -> Tuple[int, int]: - """Unpack a 32-bit register word into two 16-bit half words (lo, hi).""" - return val32 & 0xFFFF, (val32 >> 16) & 0xFFFF - - -def is_nan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 binary16 NaN.""" - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & FRAC_MASK) != 0) - - -def is_qnan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Quiet NaN.""" - return is_nan(bits) and bool(bits & QNAN_BIT) - - -def is_snan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Signaling NaN.""" - return is_nan(bits) and not bool(bits & QNAN_BIT) - - -def is_inf(bits: int) -> bool: - """Return True if bits represent IEEE 754 positive or negative infinity.""" - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & FRAC_MASK) == 0) - - -def is_subnormal(bits: int) -> bool: - """Return True if bits represent a subnormal (denormal) half-precision float.""" - return ((bits & EXP_MASK) == 0) and ((bits & FRAC_MASK) != 0) - - -def is_zero(bits: int) -> bool: - """Return True if bits represent positive or negative zero.""" - return (bits & ~SIGN_MASK) == 0 - - -def apply_f16_modifiers(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Apply VOP3 input modifiers: abs clears sign bit; neg toggles sign bit.""" - res = bits & 0xFFFF - if abs_mod: - res &= ~SIGN_MASK - if neg_mod: - res ^= SIGN_MASK - return res - - -def oracle_v_add_f16( - src0_bits: int, - src1_bits: int, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_add_f16 half-precision addition. - - Computes D = src0 + src1 conforming to IEEE 754-2008 half precision (binary16) - with Round-to-Nearest-Even (RNE), applying input modifiers and clamp. + `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its + upper half, so reading the wrong half of a source shows. v0 starts as `old`. """ - s0 = apply_f16_modifiers(src0_bits, abs0, neg0) - s1 = apply_f16_modifiers(src1_bits, abs1, neg1) - - # 1. NaN handling - if is_nan(s0) or is_nan(s1): - if clamp: - # Clamping NaN in RDNA2 produces +0.0 - return POS_ZERO - # Prefer quietening signaling NaN or propagating quiet NaN - nan_bits = s0 if is_nan(s0) else s1 - return nan_bits | QNAN_BIT - - # 2. Infinity handling - s0_inf = is_inf(s0) - s1_inf = is_inf(s1) - if s0_inf and s1_inf: - s0_sign = (s0 & SIGN_MASK) - s1_sign = (s1 & SIGN_MASK) - if s0_sign != s1_sign: - # +inf + -inf -> Invalid operation -> Canonical Quiet NaN - return POS_ZERO if clamp else CANONICAL_QNAN - # Same signed infinities - if clamp: - return ONE_F16 if s0 == POS_INF else POS_ZERO - return s0 - if s0_inf: - if clamp: - return ONE_F16 if s0 == POS_INF else POS_ZERO - return s0 - if s1_inf: - if clamp: - return ONE_F16 if s1 == POS_INF else POS_ZERO - return s1 - - # 3. Signed zero handling - if is_zero(s0) and is_zero(s1): - s0_is_neg = (s0 == NEG_ZERO) - s1_is_neg = (s1 == NEG_ZERO) - if s0_is_neg and s1_is_neg: - res = NEG_ZERO - else: - res = POS_ZERO - if clamp and res == NEG_ZERO: - return POS_ZERO - return res - - # 4. Finite arithmetic - f0 = bits_to_f16(s0) - f1 = bits_to_f16(s1) - f_sum = f0 + f1 - - # Exact signed zero cancellation: (+x) + (-x) -> +0.0 - if f_sum == 0.0: - return POS_ZERO - - try: - raw_res = f16_to_bits(f_sum) - except OverflowError: - raw_res = POS_INF if f_sum > 0 else NEG_INF - - # 5. Clamp modifier handling [0.0, 1.0] - if clamp: - if is_inf(raw_res): - return ONE_F16 if raw_res == POS_INF else POS_ZERO - res_f = bits_to_f16(raw_res) - if res_f < 0.0 or raw_res == NEG_ZERO: - return POS_ZERO - elif res_f > 1.0: - return ONE_F16 - - return raw_res - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - VGPR = auto() - SGPR = auto() - - -class SubWord(Enum): - LO = auto() - HI = auto() - - -@dataclass(frozen=True) -class Reg16: - """Represents an architectural 16-bit register operand (e.g. v0.l, v0.h, s2.l).""" - index: int - reg_type: RegType = RegType.VGPR - sub_word: SubWord = SubWord.LO - - def __post_init__(self) -> None: - if not (0 <= self.index <= 255): - raise ValueError(f"Register index {self.index} out of range [0, 255]") - - @property - def is_hi(self) -> bool: - return self.sub_word == SubWord.HI - - @property - def name(self) -> str: - prefix = "v" if self.reg_type == RegType.VGPR else "s" - suffix = "h" if self.is_hi else "l" - return f"{prefix}{self.index}.{suffix}" - - -@dataclass(frozen=True) -class Literal16: - """Represents a 16-bit inline float constant or literal.""" - bits: int - - @classmethod - def from_float(cls, val: float) -> Literal16: - return cls(f16_to_bits(val)) - - @property - def float_value(self) -> float: - return bits_to_f16(self.bits) - - @property - def name(self) -> str: - if self.bits == POS_ZERO: - return "0.0" - if self.bits == NEG_ZERO: - return "-0.0" - f = self.float_value - if math.isnan(f): - return "nan" - if math.isinf(f): - return "inf" if f > 0 else "-inf" - return f"{f:g}" - - -@dataclass(frozen=True) -class VOP3Operand16: - """Typed expression operand with optional input modifiers (abs, neg).""" - source: Union[Reg16, Literal16] - abs_mod: bool = False - neg_mod: bool = False - - def disassemble(self) -> str: - s = self.source.name - if self.abs_mod: - s = f"|{s}|" - if self.neg_mod: - s = f"-{s}" - return s - - -@dataclass(frozen=True) -class VAddF16Instruction: - """Symbolic AST node representing a RDNA2 v_add_f16 instruction.""" - dst: Reg16 - src0: VOP3Operand16 - src1: VOP3Operand16 - clamp: bool = False - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination of VALU instruction must be VGPR, got {self.dst.reg_type}") - - def disassemble(self) -> str: - s = f"v_add_f16 {self.dst.name}, {self.src0.disassemble()}, {self.src1.disassemble()}" - if self.clamp: - s += " clamp" - return s - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register file for a single wavefront lane.""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def get_reg16(self, reg: Reg16) -> int: - file = self.vgprs if reg.reg_type == RegType.VGPR else self.sgprs - word = file[reg.index] - return (word >> 16) & 0xFFFF if reg.is_hi else word & 0xFFFF - - def set_reg16(self, reg: Reg16, val16: int) -> None: - file = self.vgprs if reg.reg_type == RegType.VGPR else self.sgprs - old = file[reg.index] - if reg.is_hi: - file[reg.index] = (old & 0x0000FFFF) | ((val16 & 0xFFFF) << 16) - else: - file[reg.index] = (old & 0xFFFF0000) | (val16 & 0xFFFF) - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_add_f16.""" - - def resolve_operand(self, op: VOP3Operand16, state: ScalarMachineState) -> int: - if isinstance(op.source, Reg16): - return state.get_reg16(op.source) - elif isinstance(op.source, Literal16): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VAddF16Instruction, state: ScalarMachineState) -> int: - # Atomic read phase - s0_raw = self.resolve_operand(instr.src0, state) - s1_raw = self.resolve_operand(instr.src1, state) - - # Computation phase - result_bits = oracle_v_add_f16( - src0_bits=s0_raw, - src1_bits=s1_raw, - abs0=instr.src0.abs_mod, - neg0=instr.src0.neg_mod, - abs1=instr.src1.abs_mod, - neg1=instr.src1.neg_mod, - clamp=instr.clamp, - ) - - # Write-back phase - state.set_reg16(instr.dst, result_bits) - return result_bits - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - num_lanes: int - exec_mask: Optional[int] = None - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - - def get_reg16(self, lane: int, reg: Reg16) -> int: - if reg.reg_type == RegType.VGPR: - word = self.vgprs[lane][reg.index] - else: - word = self.sgprs[reg.index] - return (word >> 16) & 0xFFFF if reg.is_hi else word & 0xFFFF - - def set_reg16(self, lane: int, reg: Reg16, val16: int) -> None: - if reg.reg_type == RegType.VGPR: - old = self.vgprs[lane][reg.index] - if reg.is_hi: - self.vgprs[lane][reg.index] = (old & 0x0000FFFF) | ((val16 & 0xFFFF) << 16) - else: - self.vgprs[lane][reg.index] = (old & 0xFFFF0000) | (val16 & 0xFFFF) - else: - old = self.sgprs[reg.index] - if reg.is_hi: - self.sgprs[reg.index] = (old & 0x0000FFFF) | ((val16 & 0xFFFF) << 16) - else: - self.sgprs[reg.index] = (old & 0xFFFF0000) | (val16 & 0xFFFF) - - -class SIMDInterpreter: - """SIMD instruction interpreter handling multi-lane divergence and EXEC masking.""" - - def resolve_lane_operand(self, op: VOP3Operand16, state: SIMDState, lane: int) -> int: - if isinstance(op.source, Reg16): - return state.get_reg16(lane, op.source) - elif isinstance(op.source, Literal16): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VAddF16Instruction, state: SIMDState) -> List[Optional[int]]: - results: List[Optional[int]] = [None] * state.num_lanes - # Atomic read phase across all lanes - s0_vals = [ - self.resolve_lane_operand(instr.src0, state, lane) - for lane in range(state.num_lanes) - ] - s1_vals = [ - self.resolve_lane_operand(instr.src1, state, lane) - for lane in range(state.num_lanes) - ] - - # Execution phase - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - res = oracle_v_add_f16( - src0_bits=s0_vals[lane], - src1_bits=s1_vals[lane], - abs0=instr.src0.abs_mod, - neg0=instr.src0.neg_mod, - abs1=instr.src1.abs_mod, - neg1=instr.src1.neg_mod, - clamp=instr.clamp, - ) - state.set_reg16(lane, instr.dst, res) - results[lane] = res - - return results - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry Generation -# ============================================================================== - -@dataclass(frozen=True) -class FPStatusFlags: - """Architectural floating-point condition codes and IEEE 754 status flags.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -def evaluate_v_add_f16_flags( - src0_bits: int, - src1_bits: int, - res_bits: int, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> FPStatusFlags: - """Evaluate IEEE 754 architectural flags and condition codes for v_add_f16.""" - s0 = apply_f16_modifiers(src0_bits, abs0, neg0) - s1 = apply_f16_modifiers(src1_bits, abs1, neg1) - - s0_nan = is_nan(s0) - s1_nan = is_nan(s1) - s0_snan = is_snan(s0) - s1_snan = is_snan(s1) - s0_inf = is_inf(s0) - s1_inf = is_inf(s1) - - invalid = False - if s0_snan or s1_snan: - invalid = True - elif s0_inf and s1_inf and ((s0 & SIGN_MASK) != (s1 & SIGN_MASK)): - invalid = True - - nan_flag = is_nan(res_bits) - inf_flag = is_inf(res_bits) - zero_flag = is_zero(res_bits) - neg_flag = bool(res_bits & SIGN_MASK) - denorm_flag = is_subnormal(res_bits) - - overflow = False - if not (s0_nan or s1_nan or s0_inf or s1_inf) and inf_flag: - overflow = True - - underflow = False - if denorm_flag: - underflow = True - - inexact = False - if overflow: - inexact = True - elif not (s0_nan or s1_nan or s0_inf or s1_inf or nan_flag or inf_flag): - f0 = bits_to_f16(s0) - f1 = bits_to_f16(s1) - res_f = bits_to_f16(res_bits) - if not clamp: - if Fraction(f0) + Fraction(f1) != Fraction(res_f): - inexact = True - else: - clamped_math = min(1.0, max(0.0, float(Fraction(f0) + Fraction(f1)))) - if Fraction(clamped_math) != Fraction(res_f): - inexact = True - - return FPStatusFlags( - invalid=invalid, - overflow=overflow, - underflow=underflow, - inexact=inexact, - zero=zero_flag, - negative=neg_flag, - denormal=denorm_flag, - infinite=inf_flag, - nan=nan_flag, - ) - - -def compute_f16_mantissa_carry(s0_bits: int, s1_bits: int) -> Tuple[int, int]: - """Demonstrate IEEE 754 11-bit mantissa carry generation during half-precision addition.""" - _, exp0, frac0 = split_f16_bits(s0_bits) - _, exp1, frac1 = split_f16_bits(s1_bits) - m0 = (1 << 10) | frac0 if exp0 != 0 else frac0 - m1 = (1 << 10) | frac1 if exp1 != 0 else frac1 - if exp0 > exp1: - m1 >>= (exp0 - exp1) - elif exp1 > exp0: - m0 >>= (exp1 - exp0) - mant_sum = m0 + m1 - carry_out = 1 if mant_sum >= (1 << 11) else 0 - return mant_sum, carry_out - - -# ============================================================================== -# Unit Tests -# ============================================================================== - -class TestF16ModelAndOracle(unittest.TestCase): - """Unit tests for binary16 bit model, predicates, and reference oracle.""" - - def test_round_trip_conversion(self) -> None: - values = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 65504.0, -65504.0, 3.140625] - for val in values: - with self.subTest(val=val): - bits = f16_to_bits(val) - recovered = bits_to_f16(bits) - self.assertEqual(val, recovered) - self.assertEqual(math.copysign(1.0, val), math.copysign(1.0, recovered)) - - def test_word_packing_vgpr_pair(self) -> None: - lo = 0x3C00 # 1.0 - hi = 0x4000 # 2.0 - packed = pack_f16_pair(lo, hi) - self.assertEqual(packed, 0x40003C00) - unpacked_lo, unpacked_hi = unpack_f16_pair(packed) - self.assertEqual(unpacked_lo, lo) - self.assertEqual(unpacked_hi, hi) - - def test_classification_predicates(self) -> None: - self.assertTrue(f16_to_bits(0.0) == POS_ZERO) - self.assertTrue(f16_to_bits(-0.0) == NEG_ZERO) - self.assertTrue(is_zero(POS_ZERO)) - self.assertTrue(is_zero(NEG_ZERO)) - self.assertFalse(is_zero(f16_to_bits(1.0))) - - self.assertTrue(is_inf(POS_INF)) - self.assertTrue(is_inf(NEG_INF)) - self.assertFalse(is_inf(POS_ZERO)) - - snan_bits = 0x7C01 - qnan_bits = CANONICAL_QNAN - self.assertTrue(is_nan(snan_bits)) - self.assertTrue(is_snan(snan_bits)) - self.assertFalse(is_qnan(snan_bits)) - - self.assertTrue(is_nan(qnan_bits)) - self.assertTrue(is_qnan(qnan_bits)) - self.assertFalse(is_snan(qnan_bits)) - - subnorm_bits = 0x0001 - self.assertTrue(is_subnormal(subnorm_bits)) - self.assertFalse(is_subnormal(POS_ZERO)) - self.assertFalse(is_subnormal(f16_to_bits(1.0))) - - def test_exact_finite_addition(self) -> None: - c = oracle_v_add_f16(f16_to_bits(1.5), f16_to_bits(2.25)) - self.assertEqual(bits_to_f16(c), 3.75) - - c2 = oracle_v_add_f16(f16_to_bits(100.0), f16_to_bits(-25.5)) - self.assertEqual(bits_to_f16(c2), 74.5) - - def test_signed_zero_rules(self) -> None: - # IEEE 754: (+0) + (+0) = +0 - self.assertEqual(oracle_v_add_f16(POS_ZERO, POS_ZERO), POS_ZERO) - # (-0) + (-0) = -0 - self.assertEqual(oracle_v_add_f16(NEG_ZERO, NEG_ZERO), NEG_ZERO) - # (+0) + (-0) = +0 - self.assertEqual(oracle_v_add_f16(POS_ZERO, NEG_ZERO), POS_ZERO) - # (-0) + (+0) = +0 - self.assertEqual(oracle_v_add_f16(NEG_ZERO, POS_ZERO), POS_ZERO) - # x + (-x) = +0 - self.assertEqual(oracle_v_add_f16(f16_to_bits(42.0), f16_to_bits(-42.0)), POS_ZERO) - - def test_input_modifiers_abs_neg(self) -> None: - val_pos = f16_to_bits(10.0) - val_neg = f16_to_bits(-10.0) - - # abs on negative: |-10.0| + 5.0 = 15.0 - res = oracle_v_add_f16(val_neg, f16_to_bits(5.0), abs0=True) - self.assertEqual(bits_to_f16(res), 15.0) - - # neg on positive: -(10.0) + 5.0 = -5.0 - res = oracle_v_add_f16(val_pos, f16_to_bits(5.0), neg0=True) - self.assertEqual(bits_to_f16(res), -5.0) - - # abs and neg together: -|10.0| + 5.0 = -5.0; -|-10.0| + 5.0 = -5.0 - res1 = oracle_v_add_f16(val_pos, f16_to_bits(5.0), abs0=True, neg0=True) - res2 = oracle_v_add_f16(val_neg, f16_to_bits(5.0), abs0=True, neg0=True) - self.assertEqual(bits_to_f16(res1), -5.0) - self.assertEqual(bits_to_f16(res2), -5.0) - - def test_clamp_modifier(self) -> None: - # Clamped result > 1.0 becomes 1.0 - res_hi = oracle_v_add_f16(f16_to_bits(0.75), f16_to_bits(0.5), clamp=True) - self.assertEqual(res_hi, ONE_F16) - - # Clamped result < 0.0 becomes +0.0 - res_lo = oracle_v_add_f16(f16_to_bits(-1.5), f16_to_bits(0.5), clamp=True) - self.assertEqual(res_lo, POS_ZERO) - - # Clamped result within [0.0, 1.0] is unmodified - res_mid = oracle_v_add_f16(f16_to_bits(0.25), f16_to_bits(0.5), clamp=True) - self.assertEqual(bits_to_f16(res_mid), 0.75) - - def test_infinity_addition(self) -> None: - self.assertEqual(oracle_v_add_f16(POS_INF, f16_to_bits(1.0)), POS_INF) - self.assertEqual(oracle_v_add_f16(NEG_INF, f16_to_bits(1.0)), NEG_INF) - self.assertEqual(oracle_v_add_f16(POS_INF, POS_INF), POS_INF) - self.assertEqual(oracle_v_add_f16(NEG_INF, NEG_INF), NEG_INF) - # (+inf) + (-inf) -> Canonical NaN - self.assertEqual(oracle_v_add_f16(POS_INF, NEG_INF), CANONICAL_QNAN) - - def test_nan_quietening_and_propagation(self) -> None: - snan = 0x7C05 - res = oracle_v_add_f16(snan, f16_to_bits(1.0)) - self.assertTrue(is_qnan(res)) - self.assertEqual(res, snan | QNAN_BIT) - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_reg16_validation_and_naming(self) -> None: - v0_l = Reg16(0, RegType.VGPR, SubWord.LO) - self.assertEqual(v0_l.name, "v0.l") - self.assertFalse(v0_l.is_hi) - - v0_h = Reg16(0, RegType.VGPR, SubWord.HI) - self.assertEqual(v0_h.name, "v0.h") - self.assertTrue(v0_h.is_hi) - - s8_l = Reg16(8, RegType.SGPR, SubWord.LO) - self.assertEqual(s8_l.name, "s8.l") - self.assertFalse(s8_l.is_hi) - - with self.assertRaises(ValueError): - Reg16(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg16(-1, RegType.VGPR) - - def test_operand_disassembly(self) -> None: - v = Reg16(2, RegType.VGPR, SubWord.LO) - op_plain = VOP3Operand16(v) - self.assertEqual(op_plain.disassemble(), "v2.l") - - op_abs = VOP3Operand16(v, abs_mod=True) - self.assertEqual(op_abs.disassemble(), "|v2.l|") - - op_neg = VOP3Operand16(v, neg_mod=True) - self.assertEqual(op_neg.disassemble(), "-v2.l") - - op_neg_abs = VOP3Operand16(v, abs_mod=True, neg_mod=True) - self.assertEqual(op_neg_abs.disassemble(), "-|v2.l|") - - lit = Literal16.from_float(1.5) - op_lit = VOP3Operand16(lit) - self.assertEqual(op_lit.disassemble(), "1.5") - - def test_v_add_f16_ast_construction_and_validation(self) -> None: - dst = Reg16(0, RegType.VGPR, SubWord.LO) - src0 = VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.HI), neg_mod=True, abs_mod=True) - src1 = VOP3Operand16(Reg16(4, RegType.SGPR, SubWord.LO)) - instr = VAddF16Instruction(dst=dst, src0=src0, src1=src1, clamp=True) - - self.assertEqual(instr.disassemble(), "v_add_f16 v0.l, -|v2.h|, s4.l clamp") - - # Invalid destination type (SGPR) - with self.assertRaises(TypeError): - VAddF16Instruction(dst=Reg16(0, RegType.SGPR), src0=src0, src1=src1) - - def test_structural_equality(self) -> None: - i1 = VAddF16Instruction( - Reg16(0, RegType.VGPR), - VOP3Operand16(Reg16(2, RegType.VGPR)), - VOP3Operand16(Literal16.from_float(0.0)), - ) - i2 = VAddF16Instruction( - Reg16(0, RegType.VGPR), - VOP3Operand16(Reg16(2, RegType.VGPR)), - VOP3Operand16(Literal16.from_float(0.0)), - ) - self.assertEqual(i1, i2) - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_scalar_vgpr_vgpr_addition(self) -> None: - self.state.set_reg16(Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(12.5)) - self.state.set_reg16(Reg16(4, RegType.VGPR, SubWord.LO), f16_to_bits(7.5)) - instr = VAddF16Instruction( - dst=Reg16(0, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(4, RegType.VGPR, SubWord.LO)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f16(res_bits), 20.0) - self.assertEqual(self.state.get_reg16(Reg16(0, RegType.VGPR, SubWord.LO)), res_bits) - - def test_scalar_vgpr_sgpr_addition(self) -> None: - self.state.set_reg16(Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(10.0)) - self.state.set_reg16(Reg16(8, RegType.SGPR, SubWord.LO), f16_to_bits(2.5)) - instr = VAddF16Instruction( - dst=Reg16(4, RegType.VGPR, SubWord.HI), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(8, RegType.SGPR, SubWord.LO)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f16(res_bits), 12.5) - self.assertEqual(self.state.get_reg16(Reg16(4, RegType.VGPR, SubWord.HI)), res_bits) - - def test_scalar_vgpr_literal_addition(self) -> None: - self.state.set_reg16(Reg16(6, RegType.VGPR, SubWord.LO), f16_to_bits(3.0)) - instr = VAddF16Instruction( - dst=Reg16(6, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(6, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Literal16.from_float(0.5)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f16(res_bits), 3.5) - self.assertEqual(self.state.get_reg16(Reg16(6, RegType.VGPR, SubWord.LO)), res_bits) - - def test_scalar_with_modifiers_and_clamp(self) -> None: - self.state.set_reg16(Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(-0.8)) - self.state.set_reg16(Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(1.5)) - # -|-0.8| + 1.5 = -0.8 + 1.5 = 0.7 (within [0, 1] so clamp doesn't alter 0.7) - instr = VAddF16Instruction( - dst=Reg16(4, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO), abs_mod=True, neg_mod=True), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - clamp=True, - ) - res_bits = self.interp.step(instr, self.state) - self.assertAlmostEqual(bits_to_f16(res_bits), 0.7, places=3) - - def test_scalar_subword_preservation(self) -> None: - # Prepopulate v1 with distinct lo and hi half words - self.state.vgprs[1] = pack_f16_pair(0x1111, 0x2222) - instr_lo = VAddF16Instruction( - dst=Reg16(1, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Literal16.from_float(1.0)), - src1=VOP3Operand16(Literal16.from_float(2.0)), - ) - self.interp.step(instr_lo, self.state) - # Low half updated to 3.0 (0x4200), high half preserved (0x2222) - self.assertEqual(self.state.get_reg16(Reg16(1, RegType.VGPR, SubWord.LO)), 0x4200) - self.assertEqual(self.state.get_reg16(Reg16(1, RegType.VGPR, SubWord.HI)), 0x2222) - - instr_hi = VAddF16Instruction( - dst=Reg16(1, RegType.VGPR, SubWord.HI), - src0=VOP3Operand16(Literal16.from_float(0.5)), - src1=VOP3Operand16(Literal16.from_float(0.5)), - ) - self.interp.step(instr_hi, self.state) - # High half updated to 1.0 (0x3C00), low half preserved (0x4200) - self.assertEqual(self.state.get_reg16(Reg16(1, RegType.VGPR, SubWord.LO)), 0x4200) - self.assertEqual(self.state.get_reg16(Reg16(1, RegType.VGPR, SubWord.HI)), 0x3C00) - - def test_scalar_determinism(self) -> None: - runs = [] - for _ in range(50): - st = ScalarMachineState() - st.set_reg16(Reg16(0, RegType.VGPR, SubWord.LO), 0x4248) # ~3.14 - st.set_reg16(Reg16(2, RegType.VGPR, SubWord.LO), 0x4170) # ~2.718 - instr = VAddF16Instruction( - dst=Reg16(4, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - runs.append(self.interp.step(instr, st)) - self.assertTrue(all(r == runs[0] for r in runs)) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD execution, lane divergence, and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.interp = SIMDInterpreter() - - def test_wave32_full_exec(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(float(lane))) - state.set_reg16(lane, Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(10.0)) - instr = VAddF16Instruction( - dst=Reg16(4, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - self.assertIsNotNone(results[lane]) - expected = float(lane) + 10.0 - self.assertEqual(bits_to_f16(state.get_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO))), expected) - - def test_wave32_divergent_masking(self) -> None: - # Alternating mask: even lanes active (0x55555555) - sentinel = 0xBEEF - state = SIMDState(num_lanes=32, exec_mask=0x5555_5555) - for lane in range(32): - state.set_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(float(lane))) - state.set_reg16(lane, Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(5.0)) - state.set_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO), sentinel) - - instr = VAddF16Instruction( - dst=Reg16(4, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - if lane % 2 == 0: - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f16(state.get_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO))), float(lane) + 5.0) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO)), sentinel) - - def test_wave64_full_exec(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=0xFFFF_FFFF_FFFF_FFFF) - for lane in range(64): - state.set_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(float(lane) * 0.5)) - state.set_reg16(lane, Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(1.0)) - instr = VAddF16Instruction( - dst=Reg16(0, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - self.interp.step(instr, state) - for lane in range(64): - self.assertEqual(bits_to_f16(state.get_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO))), float(lane) * 0.5 + 1.0) - - def test_wave64_half_disabled(self) -> None: - # Lower 32 lanes active, upper 32 lanes inactive - sentinel = 0xCAFE - state = SIMDState(num_lanes=64, exec_mask=0x0000_0000_FFFF_FFFF) - for lane in range(64): - state.set_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(10.0)) - state.set_reg16(lane, Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(20.0)) - state.set_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO), sentinel) - - instr = VAddF16Instruction( - dst=Reg16(4, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - results = self.interp.step(instr, state) - for lane in range(64): - if lane < 32: - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f16(state.get_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO))), 30.0) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO)), sentinel) - - def test_wave_exec_all_zero(self) -> None: - sentinel = 0xAA55 - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) - for lane in range(32): - state.set_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO), sentinel) - instr = VAddF16Instruction( - dst=Reg16(0, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Literal16.from_float(1.0)), - src1=VOP3Operand16(Literal16.from_float(2.0)), - ) - results = self.interp.step(instr, state) - self.assertTrue(all(r is None for r in results)) - for lane in range(32): - self.assertEqual(state.get_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO)), sentinel) - - def test_simd_sgpr_uniform_broadcast(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - state.set_reg16(0, Reg16(10, RegType.SGPR, SubWord.LO), f16_to_bits(100.0)) - for lane in range(32): - state.set_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(float(lane))) - - instr = VAddF16Instruction( - dst=Reg16(2, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(10, RegType.SGPR, SubWord.LO)), - ) - self.interp.step(instr, state) - for lane in range(32): - self.assertEqual(bits_to_f16(state.get_reg16(lane, Reg16(2, RegType.VGPR, SubWord.LO))), 100.0 + float(lane)) - - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_dst_alias_src0(self) -> None: - state = ScalarMachineState() - state.set_reg16(Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(15.5)) - state.set_reg16(Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(4.5)) - instr = VAddF16Instruction( - dst=Reg16(0, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(state.get_reg16(Reg16(0, RegType.VGPR, SubWord.LO))), 20.0) - # src1 untouched - self.assertEqual(bits_to_f16(state.get_reg16(Reg16(2, RegType.VGPR, SubWord.LO))), 4.5) - - def test_dst_alias_src1(self) -> None: - state = ScalarMachineState() - state.set_reg16(Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(15.5)) - state.set_reg16(Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(4.5)) - instr = VAddF16Instruction( - dst=Reg16(2, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(state.get_reg16(Reg16(2, RegType.VGPR, SubWord.LO))), 20.0) - # src0 untouched - self.assertEqual(bits_to_f16(state.get_reg16(Reg16(0, RegType.VGPR, SubWord.LO))), 15.5) - - def test_dst_alias_both_srcs(self) -> None: - state = ScalarMachineState() - state.set_reg16(Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(16.0)) - instr = VAddF16Instruction( - dst=Reg16(0, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(state.get_reg16(Reg16(0, RegType.VGPR, SubWord.LO))), 32.0) - - def test_subword_cross_half_aliasing(self) -> None: - # Prepopulate v0 with lo=1.5, hi=2.5 - state = ScalarMachineState() - state.set_reg16(Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(1.5)) - state.set_reg16(Reg16(0, RegType.VGPR, SubWord.HI), f16_to_bits(2.5)) - - instr = VAddF16Instruction( - dst=Reg16(0, RegType.VGPR, SubWord.HI), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.HI)), - ) - self.scalar_interp.step(instr, state) - # hi updated to 4.0, lo untouched at 1.5 - self.assertEqual(bits_to_f16(state.get_reg16(Reg16(0, RegType.VGPR, SubWord.HI))), 4.0) - self.assertEqual(bits_to_f16(state.get_reg16(Reg16(0, RegType.VGPR, SubWord.LO))), 1.5) - - def test_inplace_iterative_accumulation(self) -> None: - state = ScalarMachineState() - state.set_reg16(Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(0.0)) - state.set_reg16(Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(0.5)) - instr = VAddF16Instruction( - dst=Reg16(0, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - for _ in range(100): - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(state.get_reg16(Reg16(0, RegType.VGPR, SubWord.LO))), 50.0) - - def test_simd_multi_lane_aliasing(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO), f16_to_bits(float(lane))) - state.set_reg16(lane, Reg16(2, RegType.VGPR, SubWord.LO), f16_to_bits(1.0)) - - instr = VAddF16Instruction( - dst=Reg16(0, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Reg16(0, RegType.VGPR, SubWord.LO)), - src1=VOP3Operand16(Reg16(2, RegType.VGPR, SubWord.LO)), - ) - self.simd_interp.step(instr, state) - for lane in range(32): - self.assertEqual(bits_to_f16(state.get_reg16(lane, Reg16(0, RegType.VGPR, SubWord.LO))), float(lane) + 1.0) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for status flags, condition codes, and carry generation.""" - - def test_exact_finite_flags(self) -> None: - s0 = f16_to_bits(1.0) - s1 = f16_to_bits(2.0) - res = oracle_v_add_f16(s0, s1) - flags = evaluate_v_add_f16_flags(s0, s1, res) - self.assertFalse(flags.invalid) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - self.assertFalse(flags.inexact) - self.assertFalse(flags.zero) - self.assertFalse(flags.negative) - self.assertFalse(flags.denormal) - self.assertFalse(flags.infinite) - self.assertFalse(flags.nan) - - def test_inexact_flag(self) -> None: - # In f16, 1.0 + 2^-11 has an inexact round - s0 = f16_to_bits(1.0) - s1 = f16_to_bits(2.0 ** -11) - res = oracle_v_add_f16(s0, s1) - flags = evaluate_v_add_f16_flags(s0, s1, res) - self.assertTrue(flags.inexact) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - - def test_overflow_flag(self) -> None: - half_max = 0x7BFF # 65504.0 - res = oracle_v_add_f16(half_max, half_max) - self.assertEqual(res, POS_INF) - flags = evaluate_v_add_f16_flags(half_max, half_max, res) - self.assertTrue(flags.overflow) - self.assertTrue(flags.infinite) - self.assertTrue(flags.inexact) - self.assertFalse(flags.invalid) - - def test_underflow_and_denorm_flags(self) -> None: - subnorm = 0x0001 - res = oracle_v_add_f16(subnorm, subnorm) - self.assertEqual(res, 0x0002) - flags = evaluate_v_add_f16_flags(subnorm, subnorm, res) - self.assertTrue(flags.denormal) - self.assertTrue(flags.underflow) - self.assertFalse(flags.overflow) - - def test_invalid_operation_flag(self) -> None: - # +inf + -inf is invalid - res = oracle_v_add_f16(POS_INF, NEG_INF) - flags = evaluate_v_add_f16_flags(POS_INF, NEG_INF, res) - self.assertTrue(flags.invalid) - self.assertTrue(flags.nan) - - # signaling NaN operand triggers invalid operation - snan = 0x7C01 - res2 = oracle_v_add_f16(snan, f16_to_bits(1.0)) - flags2 = evaluate_v_add_f16_flags(snan, f16_to_bits(1.0), res2) - self.assertTrue(flags2.invalid) - self.assertTrue(flags2.nan) - - def test_zero_and_negative_flags(self) -> None: - # +0 + +0 - res_pz = oracle_v_add_f16(POS_ZERO, POS_ZERO) - flags_pz = evaluate_v_add_f16_flags(POS_ZERO, POS_ZERO, res_pz) - self.assertTrue(flags_pz.zero) - self.assertFalse(flags_pz.negative) - - # -0 + -0 - res_nz = oracle_v_add_f16(NEG_ZERO, NEG_ZERO) - flags_nz = evaluate_v_add_f16_flags(NEG_ZERO, NEG_ZERO, res_nz) - self.assertTrue(flags_nz.zero) - self.assertTrue(flags_nz.negative) - - # -5.0 + -10.0 = -15.0 - s0 = f16_to_bits(-5.0) - s1 = f16_to_bits(-10.0) - res_neg = oracle_v_add_f16(s0, s1) - flags_neg = evaluate_v_add_f16_flags(s0, s1, res_neg) - self.assertFalse(flags_neg.zero) - self.assertTrue(flags_neg.negative) - - def test_mantissa_carry_generation(self) -> None: - # 1.0 + 1.0: mantissas are 1.000... + 1.000... = 2.000... -> carry out = 1 - _, carry1 = compute_f16_mantissa_carry(f16_to_bits(1.0), f16_to_bits(1.0)) - self.assertEqual(carry1, 1) - - # 1.0 + 0.25: mantissas sum < 2.0 -> carry out = 0 - _, carry0 = compute_f16_mantissa_carry(f16_to_bits(1.0), f16_to_bits(0.25)) - self.assertEqual(carry0, 0) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_addition_without_carry(self) -> None: - sub1 = 0x0001 - sub2 = 0x0002 - res = oracle_v_add_f16(sub1, sub2) - self.assertEqual(res, 0x0003) - self.assertTrue(is_subnormal(res)) - - def test_subnormal_to_normal_transition(self) -> None: - # Largest subnormal: 0x03FF - max_sub = 0x03FF - min_sub = 0x0001 - # Sum is 0x0400 = smallest normal (2^-14) - res = oracle_v_add_f16(max_sub, min_sub) - self.assertEqual(res, 0x0400) - self.assertFalse(is_subnormal(res)) - self.assertEqual(split_f16_bits(res)[1], 1) # exponent = 1 - self.assertEqual(split_f16_bits(res)[2], 0) # fraction = 0 - - def test_subnormal_cancellation(self) -> None: - sub = 0x0123 - neg_sub = sub | SIGN_MASK - res = oracle_v_add_f16(sub, neg_sub) - self.assertEqual(res, POS_ZERO) - - def test_nan_signaling_to_quiet_conversion(self) -> None: - snan = 0x7C05 # fraction non-zero, quiet bit 9 is 0 - self.assertTrue(is_snan(snan)) - res = oracle_v_add_f16(snan, f16_to_bits(1.0)) - self.assertTrue(is_qnan(res)) - self.assertEqual(res, snan | QNAN_BIT) - - def test_nan_payload_preservation(self) -> None: - payload = 0x02AB - qnan = EXP_MASK | payload - res = oracle_v_add_f16(qnan, f16_to_bits(10.0)) - self.assertEqual(res, qnan) - - def test_nan_with_modifiers(self) -> None: - qnan = 0x7E01 - # abs should clear sign bit - res_abs = oracle_v_add_f16(qnan | SIGN_MASK, f16_to_bits(0.0), abs0=True) - self.assertEqual(res_abs & SIGN_MASK, 0) - self.assertTrue(is_qnan(res_abs)) - - # neg should toggle sign bit - res_neg = oracle_v_add_f16(qnan, f16_to_bits(0.0), neg0=True) - self.assertEqual(res_neg & SIGN_MASK, SIGN_MASK) - - def test_nan_with_clamp(self) -> None: - qnan = CANONICAL_QNAN - res = oracle_v_add_f16(qnan, f16_to_bits(1.0), clamp=True) - self.assertEqual(res, POS_ZERO) - - def test_infinity_arithmetic_boundaries(self) -> None: - self.assertEqual(oracle_v_add_f16(POS_INF, f16_to_bits(100.0)), POS_INF) - self.assertEqual(oracle_v_add_f16(NEG_INF, f16_to_bits(100.0)), NEG_INF) - self.assertEqual(oracle_v_add_f16(POS_INF, NEG_INF), CANONICAL_QNAN) - self.assertEqual(oracle_v_add_f16(NEG_INF, POS_INF), CANONICAL_QNAN) - - # Infinity with clamp - self.assertEqual(oracle_v_add_f16(POS_INF, f16_to_bits(0.0), clamp=True), ONE_F16) - self.assertEqual(oracle_v_add_f16(NEG_INF, f16_to_bits(0.0), clamp=True), POS_ZERO) - - def test_round_to_nearest_even_ties(self) -> None: - # In IEEE 754 half precision (11 bits significand): - # 1.0 has bits 0x3C00 (even LSB = 0) - # 1.0 + 2^-10 has bits 0x3C01 (odd LSB = 1) - # 2^-11 is exactly halfway between representable numbers. - half_ulp = 2.0 ** -11 - one = 1.0 - one_plus_ulp = bits_to_f16(0x3C01) - - # Case 1: 1.0 (even LSB) + 2^-11: tie rounds to even (1.0) - res1 = oracle_v_add_f16(f16_to_bits(one), f16_to_bits(half_ulp)) - self.assertEqual(res1, f16_to_bits(one)) - - # Case 2: (1.0 + 2^-10) (odd LSB) + 2^-11: tie rounds to even (1.0 + 2 * 2^-10) - res2 = oracle_v_add_f16(f16_to_bits(one_plus_ulp), f16_to_bits(half_ulp)) - self.assertEqual(res2, 0x3C02) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Reg16(-1, RegType.VGPR) - with self.assertRaises(ValueError): - Reg16(256, RegType.VGPR) - - def test_syntax_rejection_valu_destination_must_be_vgpr(self) -> None: - dst_sgpr = Reg16(0, RegType.SGPR) - src = VOP3Operand16(Reg16(2, RegType.VGPR)) - with self.assertRaises(TypeError): - VAddF16Instruction(dst=dst_sgpr, src0=src, src1=src) - - def test_syntax_rejection_invalid_lane_count(self) -> None: - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDState(num_lanes=128) - - def test_negative_control_bit_flip_detection(self) -> None: - s0 = f16_to_bits(12.0) - s1 = f16_to_bits(18.0) - correct = oracle_v_add_f16(s0, s1) - self.assertEqual(bits_to_f16(correct), 30.0) - - # Perturb single mantissa bit - corrupted_mantissa = correct ^ 0x1 - self.assertNotEqual(correct, corrupted_mantissa) - - # Perturb single exponent bit - corrupted_exp = correct ^ (1 << 10) - self.assertNotEqual(correct, corrupted_exp) - - # Perturb sign bit - corrupted_sign = correct ^ SIGN_MASK - self.assertNotEqual(correct, corrupted_sign) - - def test_mutation_add_to_sub(self) -> None: - """Mutant: Replace addition with subtraction (s0 - s1).""" - def mutant_v_add_f16(s0_bits: int, s1_bits: int) -> int: - f0 = bits_to_f16(s0_bits) - f1 = bits_to_f16(s1_bits) - return f16_to_bits(f0 - f1) - - s0 = f16_to_bits(10.0) - s1 = f16_to_bits(3.0) - expected = oracle_v_add_f16(s0, s1) - mutant_res = mutant_v_add_f16(s0, s1) - self.assertNotEqual(expected, mutant_res) - - def test_mutation_ignore_abs_modifier(self) -> None: - """Mutant: Ignore abs modifier on negative operand.""" - def mutant_apply_mod(bits: int, abs_mod: bool, neg_mod: bool) -> int: - res = bits & 0xFFFF - if neg_mod: - res ^= SIGN_MASK - return res - - val = f16_to_bits(-10.0) - correct = apply_f16_modifiers(val, abs_mod=True, neg_mod=False) - mutant = mutant_apply_mod(val, abs_mod=True, neg_mod=False) - self.assertEqual(correct, f16_to_bits(10.0)) - self.assertNotEqual(correct, mutant) - - def test_mutation_ignore_neg_modifier(self) -> None: - """Mutant: Ignore neg modifier on positive operand.""" - def mutant_apply_mod(bits: int, abs_mod: bool, neg_mod: bool) -> int: - res = bits & 0xFFFF - if abs_mod: - res &= ~SIGN_MASK - return res - - val = f16_to_bits(10.0) - correct = apply_f16_modifiers(val, abs_mod=False, neg_mod=True) - mutant = mutant_apply_mod(val, abs_mod=False, neg_mod=True) - self.assertEqual(correct, f16_to_bits(-10.0)) - self.assertNotEqual(correct, mutant) - - def test_mutation_ignore_clamp_upper_bound(self) -> None: - """Mutant: Clamp modifier fails to clamp values exceeding 1.0.""" - s0 = f16_to_bits(0.75) - s1 = f16_to_bits(0.5) - # Expected clamp=True yields 1.0 - expected = oracle_v_add_f16(s0, s1, clamp=True) - self.assertEqual(expected, ONE_F16) - - # Mutant unclamped - unclamped = oracle_v_add_f16(s0, s1, clamp=False) - self.assertNotEqual(expected, unclamped) - - def test_mutation_ignore_exec_mask(self) -> None: - """Mutant: Inactive SIMD lanes are overwritten despite EXEC mask.""" - sentinel = 0xDEAD - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) # all inactive - for lane in range(32): - state.set_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO), sentinel) - - # Mutant interpreter that ignores exec_mask - class MutantSIMDInterpreter(SIMDInterpreter): - def step(self, instr: VAddF16Instruction, state: SIMDState) -> List[Optional[int]]: - results = [] - for lane in range(state.num_lanes): - res = oracle_v_add_f16(f16_to_bits(1.0), f16_to_bits(2.0)) - state.set_reg16(lane, instr.dst, res) - results.append(res) - return results - - mutant_interp = MutantSIMDInterpreter() - instr = VAddF16Instruction( - dst=Reg16(4, RegType.VGPR, SubWord.LO), - src0=VOP3Operand16(Literal16.from_float(1.0)), - src1=VOP3Operand16(Literal16.from_float(2.0)), - ) - mutant_interp.step(instr, state) - # Mutation detected: inactive lanes corrupted - corrupted_lanes = [ - lane for lane in range(32) - if state.get_reg16(lane, Reg16(4, RegType.VGPR, SubWord.LO)) != sentinel - ] - self.assertEqual(len(corrupted_lanes), 32) - - def test_mutation_subnormal_flush_to_zero(self) -> None: - """Mutant: Subnormals flushed to zero (FTZ mode).""" - sub = 0x0001 - correct = oracle_v_add_f16(sub, sub) - self.assertEqual(correct, 0x0002) - - # FTZ mutant flushes to 0.0 - ftz_mutant = POS_ZERO - self.assertNotEqual(correct, ftz_mutant) - - def test_mutation_skip_snan_quietening(self) -> None: - """Mutant: Signaling NaN is not quietened.""" - snan = 0x7C05 - res = oracle_v_add_f16(snan, f16_to_bits(1.0)) - self.assertTrue(is_qnan(res)) - self.assertNotEqual(res, snan) # snan without QNAN_BIT would be a bug + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + w = w if w > 0xFFFF else (hi << 16) | w + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_add_f16", prog))[0] + + +# (src0, src1, D), written by hand. +CASES = [ + (ONE, TWO, THREE), # 1 + 2 = 3 + (HALF, QUARTER, 0x3A00), # 0.5 + 0.25 = 0.75 + (THREE, 0xBC00, TWO), # 3 + -1 = 2 + (0x3E00, 0xBE00, 0x0000), # 1.5 + -1.5 = +0 (exact cancellation gives +0) + (0x8000, 0x8000, 0x8000), # -0 + -0 = -0 + (0x0000, 0x8000, 0x0000), # +0 + -0 = +0 + (MAXH, MAXH, INF), # 65504 * 2 overflows + (MAXH, 0x4C00, INF), # 65504 + 16 = 65520: tie between 65504 and 2^16, even is the overflow + (MIN_SUB, MIN_SUB, 0x0002), # 2^-24 + 2^-24 = 2^-23 + (MIN_NORMAL, 0x8001, MAX_SUB), # 2^-14 - 2^-24 = the largest subnormal + (ONE, 0x1000, ONE), # 1 + 2^-11: half an ulp above 1 ties to even, stays 1 + (ONE, 0x1001, 0x3C01), # a little over half an ulp rounds up + (0x6800, ONE, 0x6800), # 2048 + 1: tie, even mantissa is 2048 + (0x6801, ONE, 0x6802), # 2050 + 1 = 2051: tie, even mantissa is 2052 + (INF, ONE, INF), + (INF, NINF, QNAN), # inf + -inf = NaN + (QNAN, ONE, QNAN), +] + +SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, + MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0x1000, 0x6800, 0x6801, 0x4C00] + + +class AddF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for a, b, want in CASES: + self.assertTrue(same_f16(ref_add(a, b), want), (hex(a), hex(b), hex(ref_add(a, b)))) + + def test_e32_writes_low_half_and_keeps_high_half(self): + for a, b, want in CASES: + with self.subTest(a=hex(a), b=hex(b)): + got = run("v_add_f16 v0, v1, v2", {"v1": a, "v2": b}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_vop3_sgpr_and_literal_sources(self): + for a, b, want in CASES[:14]: + forms = [ + ("e64 vgpr", "v_add_f16_e64 v0, v1, v2", {"v1": a, "v2": b}), + ("e64 sgpr", "v_add_f16_e64 v0, s1, s2", {"s1": a, "s2": b}), + ("e32 sgpr src0", "v_add_f16 v0, s1, v2", {"s1": a, "v2": b}), + ("e32 literal src0", f"v_add_f16 v0, {a:#x}, v2", {"v2": b}), + ("e64 literal src1", f"v_add_f16_e64 v0, v1, {b:#x}", {"v1": a}), + ] + for form, line, seeds in forms: + with self.subTest(a=hex(a), b=hex(b), form=form): + got = run(line, seeds) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_inline_constants(self): + # (inline constant as src0, its binary16 value, v1 low half, D), by hand + for text, c, b, want in (("2.0", TWO, 0xB800, 0x3E00), ("-1.0", 0xBC00, HALF, 0xB800), ("0.5", HALF, QUARTER, 0x3A00), + ("4.0", 0x4400, 0xB800, 0x4300), ("1.0", ONE, ONE, TWO)): + with self.subTest(const=text): + self.assertEqual(run(f"v_add_f16 v0, {text}, v1", {"v1": b}) & 0xFFFF, want) + self.assertEqual(ref_add(c, b), want) + + def test_op_sel_selects_source_and_destination_halves(self): + # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25); D by hand for each (src0 half, src1 half). + s0, s1 = (THREE << 16) | ONE, (0xB400 << 16) | HALF + expect_lo = {(0, 0): 0x3E00, (1, 0): 0x4300, (0, 1): 0x3A00, (1, 1): 0x4180} # 1.5, 3.5, 0.75, 2.75 + for h0 in (0, 1): + for h1 in (0, 1): + for dh in (0, 1): + want = expect_lo[(h0, h1)] + expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) + with self.subTest(op_sel=(h0, h1, dh)): + got = run(f"v_add_f16_e64 v0, v1, v2 op_sel:[{h0},{h1},{dh}]", {"v1": s0, "v2": s1}) + self.assertEqual(got, expect) + + def test_neg_and_abs_source_modifiers(self): + # v1 = 1.0, v2 = -0.5; (operand text, D) by hand + for ops, want in (("v1, v2", HALF), ("-v1, v2", 0xBE00), ("v1, -v2", 0x3E00), ("|v1|, |v2|", 0x3E00), + ("-|v1|, v2", 0xBE00), ("v1, -|v2|", HALF)): + with self.subTest(ops=ops): + got = run(f"v_add_f16_e64 v0, {ops}", {"v1": ONE, "v2": 0xB800}) + self.assertEqual(got & 0xFFFF, want) + + def test_output_modifiers_and_clamp(self): + # unmodified result: 1.5 + 0.5 = 2.0; mul/div scale it, clamp limits it to [0, 1] (negatives and NaN become +0) + for suffix, want in ((" mul:2", 0x4400), (" mul:4", 0x4800), (" div:2", ONE), (" clamp", ONE)): + with self.subTest(mod=suffix): + got = run("v_add_f16_e64 v0, v1, v2" + suffix, {"v1": 0x3E00, "v2": HALF}) + self.assertEqual(got & 0xFFFF, want) + for (a, b), suffix, want in (((HALF, QUARTER), " clamp", 0x3A00), ((0xBC00, QUARTER), " clamp", 0x0000), + ((ONE, HALF), " div:2 clamp", 0x3A00), ((HALF, QUARTER), " mul:2 clamp", ONE)): + with self.subTest(a=hex(a), b=hex(b), mod=suffix): + self.assertEqual(run("v_add_f16_e64 v0, v1, v2" + suffix, {"v1": a, "v2": b}) & 0xFFFF, want) + for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): + got = run("v_add_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4900, "v2": 0xC100}) # 10 and -2.5 + self.assertEqual(got & 0xFFFF, scale(ref_add(0x4900, 0xC100), f)) + + def test_random_operands(self): + rng = random.Random(0xADD16) + pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] + for _ in range(120): + a = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) + b = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) + with self.subTest(a=hex(a), b=hex(b)): + got = run("v_add_f16 v0, v1, v2", {"v1": a, "v2": b}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, ref_add(a, b)), (hex(got), hex(ref_add(a, b)))) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_alignbyte_b32.py b/tests/semantic/test_valu_alignbyte_b32.py index 5ce957212..2a19410e9 100644 --- a/tests/semantic/test_valu_alignbyte_b32.py +++ b/tests/semantic/test_valu_alignbyte_b32.py @@ -1,1416 +1,83 @@ -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_alignbyte_b32. +"""v_alignbyte_b32 (RDNA2 VOP3): D = low 32 bits of ({S0, S1} >> (8 * (S2 & 3))), S0 the high dword. -Models AMD RDNA2 / GFX10 Vector Arithmetic Logic Unit (VALU) architectural semantics -for the byte alignment / funnel shift instruction: - v_alignbyte_b32 dst, src0, src1, src2 - -RDNA2 VALU Instruction Specification: - v_alignbyte_b32 D.u, S0.u, S1.u, S2.u - Operands: - - D: 32-bit VGPR destination - - S0: 32-bit register (VGPR/SGPR) or immediate, providing high 32 bits (bytes 4..7) - - S1: 32-bit register (VGPR/SGPR) or immediate, providing low 32 bits (bytes 0..3) - - S2: 32-bit register (VGPR/SGPR) or inline constant shift amount (in bytes) - - Mathematical Operation: - concat = ((S0 & 0xFFFFFFFF) << 32) | (S1 & 0xFFFFFFFF) - shift_bytes = S2 & 3 - D = (concat >> (shift_bytes * 8)) & 0xFFFFFFFF - - Byte Selection Mapping: - Let S1 = [B0, B1, B2, B3] and S0 = [B4, B5, B6, B7] (in little-endian byte order). - - shift_bytes == 0: D = [B0, B1, B2, B3] = S1 - - shift_bytes == 1: D = [B1, B2, B3, B4] = (S1 >> 8) | ((S0 & 0xFF) << 24) - - shift_bytes == 2: D = [B2, B3, B4, B5] = (S1 >> 16) | ((S0 & 0xFFFF) << 16) - - shift_bytes == 3: D = [B3, B4, B5, B6] = (S1 >> 24) | ((S0 & 0xFFFFFF) << 8) - - Key Architectural Properties: - 1. Only the low 2 bits of S2 (S2 & 3) determine the byte shift count. - Shift counts >= 4, negative numbers, and high bits are strictly masked modulo 4. - 2. Byte B7 (the highest byte of S0) is never part of the destination for any valid shift. - 3. Common compiler idioms: - - S0 == S1: 32-bit byte-rotate right: rotr32(S1, (S2 & 3) * 8). - - S0 == 0: logical shift right of S1 by (S2 & 3) * 8 bits. - - S1 == 0: logical shift left of S0 low bytes to high positions. - 4. Bitwise integrity: All bit patterns within bytes are preserved exactly with zero mutation. - -Standard library Python only; zero third-party dependencies; zero game data. -Python 3.9+ compatible (from __future__ import annotations). +Each case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +words are written by hand and also recomputed by a plain-Python reference. Standard library only: no GPU, no LLVM, +no game data. """ -from __future__ import annotations - -import dataclasses -import enum import os -import struct +import random import sys import unittest -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF -SIGN_BIT32: int = 0x80000000 - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned word as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & SIGN_BIT32) else val - - -def get_byte(val32: int, byte_idx: int) -> int: - """Extract byte at index byte_idx (0..3) from 32-bit word.""" - return (val32 >> ((byte_idx & 3) * 8)) & 0xFF - - -def set_byte(val32: int, byte_idx: int, byte_val: int) -> int: - """Insert byte_val at byte_idx (0..3) in 32-bit word.""" - shift = (byte_idx & 3) * 8 - mask = ~(0xFF << shift) & MASK32 - return (val32 & mask) | ((byte_val & 0xFF) << shift) - - -def pack_bytes(b0: int, b1: int, b2: int, b3: int) -> int: - """Pack four 8-bit bytes into a 32-bit unsigned little-endian integer.""" - return ((b3 & 0xFF) << 24) | ((b2 & 0xFF) << 16) | ((b1 & 0xFF) << 8) | (b0 & 0xFF) - - -def unpack_bytes(val32: int) -> tuple[int, int, int, int]: - """Unpack a 32-bit unsigned integer into four 8-bit bytes (b0, b1, b2, b3).""" - val = val32 & MASK32 - return val & 0xFF, (val >> 8) & 0xFF, (val >> 16) & 0xFF, (val >> 24) & 0xFF - - -def ref_alignbyte_b32(src0: int, src1: int, src2: int) -> int: - """Reference mathematical oracle for RDNA2 v_alignbyte_b32. - - Concatenates {src0, src1} into a 64-bit word with src0 as the high dword and - src1 as the low dword, then right shifts logically by (src2 & 3) bytes (0, 8, 16, or 24 bits) - and extracts the low 32 bits. - """ - s0 = src0 & MASK32 - s1 = src1 & MASK32 - shift_bytes = src2 & 3 - concat = (s0 << 32) | s1 - res = (concat >> (shift_bytes * 8)) & MASK32 - return res - - -def ref_alignbyte_by_bytes(src0: int, src1: int, shift: int) -> int: - """Alternative architectural byte-indexed oracle for verification and cross-checking.""" - b_lo = unpack_bytes(src1) - b_hi = unpack_bytes(src0) - eight_bytes = b_lo + b_hi # 8 bytes: [0..7] - s = shift & 3 - return pack_bytes( - eight_bytes[s], - eight_bytes[s + 1], - eight_bytes[s + 2], - eight_bytes[s + 3], - ) - - -class TestValuAlignbyteB32Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_shift_zero_returns_src1(self) -> None: - src0 = 0xDEADBEEF - src1 = 0xCAFEBABE - self.assertEqual(ref_alignbyte_b32(src0, src1, 0), src1) - self.assertEqual(ref_alignbyte_by_bytes(src0, src1, 0), src1) - - def test_shift_one_byte(self) -> None: - # S1: bytes [0x11, 0x22, 0x33, 0x44] -> 0x44332211 - # S0: bytes [0x55, 0x66, 0x77, 0x88] -> 0x88776655 - # Expected: bytes [0x22, 0x33, 0x44, 0x55] -> 0x55443322 - src1 = 0x44332211 - src0 = 0x88776655 - expected = 0x55443322 - self.assertEqual(ref_alignbyte_b32(src0, src1, 1), expected) - self.assertEqual(ref_alignbyte_by_bytes(src0, src1, 1), expected) - - def test_shift_two_bytes(self) -> None: - src1 = 0x44332211 - src0 = 0x88776655 - expected = 0x66554433 - self.assertEqual(ref_alignbyte_b32(src0, src1, 2), expected) - self.assertEqual(ref_alignbyte_by_bytes(src0, src1, 2), expected) - - def test_shift_three_bytes(self) -> None: - src1 = 0x44332211 - src0 = 0x88776655 - expected = 0x77665544 - self.assertEqual(ref_alignbyte_b32(src0, src1, 3), expected) - self.assertEqual(ref_alignbyte_by_bytes(src0, src1, 3), expected) - - def test_shift_masking_modulo_four(self) -> None: - src1 = 0x12345678 - src0 = 0x9ABCDEF0 - # src2 values with same low 2 bits must yield identical results - for base_shift in (0, 1, 2, 3): - ref = ref_alignbyte_b32(src0, src1, base_shift) - for mult in (4, 8, 12, 16, 32, 64, 100, 256, 1024, 0xFFFFFFFC): - test_shift = mult + base_shift - self.assertEqual(ref_alignbyte_b32(src0, src1, test_shift), ref) - - def test_negative_shift_masking(self) -> None: - src1 = 0xAABBCCDD - src0 = 0x11223344 - # -1 in two's complement has low 2 bits 0b11 == 3 - self.assertEqual(ref_alignbyte_b32(src0, src1, -1), ref_alignbyte_b32(src0, src1, 3)) - # -2 has low 2 bits 0b10 == 2 - self.assertEqual(ref_alignbyte_b32(src0, src1, -2), ref_alignbyte_b32(src0, src1, 2)) - # -3 has low 2 bits 0b01 == 1 - self.assertEqual(ref_alignbyte_b32(src0, src1, -3), ref_alignbyte_b32(src0, src1, 1)) - # -4 has low 2 bits 0b00 == 0 - self.assertEqual(ref_alignbyte_b32(src0, src1, -4), ref_alignbyte_b32(src0, src1, 0)) - - def test_rotate_idiom_src0_equals_src1(self) -> None: - # When src0 == src1, alignbyte is 32-bit rotate right by (shift & 3) bytes - val = 0x12345678 - # shift 0: 0x12345678 - self.assertEqual(ref_alignbyte_b32(val, val, 0), val) - # shift 1: byte 0x78 moves to high byte -> 0x78123456 - self.assertEqual(ref_alignbyte_b32(val, val, 1), 0x78123456) - # shift 2: bytes 0x5678 move to high -> 0x56781234 - self.assertEqual(ref_alignbyte_b32(val, val, 2), 0x56781234) - # shift 3: bytes 0x345678 move to high -> 0x34567812 - self.assertEqual(ref_alignbyte_b32(val, val, 3), 0x34567812) - - def test_zero_src0_logical_shift_right(self) -> None: - val = 0x89ABCDEF - self.assertEqual(ref_alignbyte_b32(0, val, 0), val) - self.assertEqual(ref_alignbyte_b32(0, val, 1), val >> 8) - self.assertEqual(ref_alignbyte_b32(0, val, 2), val >> 16) - self.assertEqual(ref_alignbyte_b32(0, val, 3), val >> 24) - - def test_zero_src1_logical_shift_left(self) -> None: - val = 0x89ABCDEF - self.assertEqual(ref_alignbyte_b32(val, 0, 0), 0) - self.assertEqual(ref_alignbyte_b32(val, 0, 1), (val & 0xFF) << 24) - self.assertEqual(ref_alignbyte_b32(val, 0, 2), (val & 0xFFFF) << 16) - self.assertEqual(ref_alignbyte_b32(val, 0, 3), (val & 0xFFFFFF) << 8) - - def test_highest_byte_of_src0_never_included(self) -> None: - # Highest byte of S0 is 0xFF, rest zeros - src0 = 0xFF000000 - src1 = 0x00000000 - for s in range(8): - # 0xFF should NEVER appear in result - res = ref_alignbyte_b32(src0, src1, s) - self.assertEqual(res, 0) - - def test_pack_unpack_bytes_roundtrip(self) -> None: - val = 0xDEADBEEF - b0, b1, b2, b3 = unpack_bytes(val) - self.assertEqual(b0, 0xEF) - self.assertEqual(b1, 0xBE) - self.assertEqual(b2, 0xAD) - self.assertEqual(b3, 0xDE) - self.assertEqual(pack_bytes(b0, b1, b2, b3), val) - - -# --------------------------------------------------------------------------- -# Symbolic AST Opcode Definitions and Typed Expressions -# --------------------------------------------------------------------------- - -class RegKind(enum.Enum): - """Register file domain.""" - VGPR = "v" - SGPR = "s" - - -@dataclasses.dataclass(frozen=True) -class Register: - """Symbolic register operand representing a 32-bit vector or scalar register.""" - kind: RegKind - index: int - count: int = 1 - - def __post_init__(self) -> None: - if self.kind == RegKind.VGPR and not (0 <= self.index < 256): - raise ValueError(f"VGPR index out of range [0, 255]: {self.index}") - if self.kind == RegKind.SGPR and not (0 <= self.index < 106): - raise ValueError(f"SGPR index out of range [0, 105]: {self.index}") - if self.count != 1: - raise ValueError(f"Unsupported register count for 32-bit VALU instruction: {self.count}") - - @property - def is_vgpr(self) -> bool: - return self.kind == RegKind.VGPR - - @property - def is_sgpr(self) -> bool: - return self.kind == RegKind.SGPR - - def format_asm(self) -> str: - return f"{self.kind.value}{self.index}" - - -@dataclasses.dataclass(frozen=True) -class Immediate: - """Symbolic 32-bit immediate operand.""" - bits: int - - def __init__(self, val: int) -> None: - object.__setattr__(self, "bits", val & MASK32) - - def format_asm(self) -> str: - if 0 <= self.bits <= 64: - return str(self.bits) - return f"{self.bits:#010x}" - - -class Opcode(enum.Enum): - """VALU 32-bit alignment opcode.""" - V_ALIGNBYTE_B32 = "v_alignbyte_b32" - - -class Encoding(enum.Enum): - """Instruction encoding format.""" - VOP3 = "e64" - VOP3A = "vop3a" - - -@dataclasses.dataclass(frozen=True) -class Instruction: - """Symbolic AST node representing a VALU byte alignment instruction.""" - opcode: Opcode - dst: Register - src0: Register | Immediate - src1: Register | Immediate - src2: Register | Immediate - encoding: Encoding = Encoding.VOP3 - - def __post_init__(self) -> None: - if not self.dst.is_vgpr: - raise ValueError(f"VALU instruction destination must be a VGPR: {self.dst}") - if self.dst.count != 1: - raise ValueError(f"VALU 32-bit instruction destination must have count=1: {self.dst}") - - def to_assembly(self) -> str: - s0_str = self.src0.format_asm() - s1_str = self.src1.format_asm() - s2_str = self.src2.format_asm() - dst_str = self.dst.format_asm() - return f"{self.opcode.value} {dst_str}, {s0_str}, {s1_str}, {s2_str}" - - -@dataclasses.dataclass -class Program: - """Symbolic sequence of VALU instructions.""" - instructions: list[Instruction] = dataclasses.field(default_factory=list) - - def append(self, inst: Instruction) -> None: - self.instructions.append(inst) - - def to_assembly(self) -> str: - return "\n".join(inst.to_assembly() for inst in self.instructions) - - -class TestValuAlignbyteB32AST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_register_construction_and_formatting(self) -> None: - v0 = Register(RegKind.VGPR, 0) - v7 = Register(RegKind.VGPR, 7) - s4 = Register(RegKind.SGPR, 4) - self.assertTrue(v0.is_vgpr) - self.assertFalse(v0.is_sgpr) - self.assertTrue(s4.is_sgpr) - self.assertEqual(v0.format_asm(), "v0") - self.assertEqual(v7.format_asm(), "v7") - self.assertEqual(s4.format_asm(), "s4") - - def test_immediate_construction(self) -> None: - imm2 = Immediate(2) - imm_hex = Immediate(0xDEADBEEF) - self.assertEqual(imm2.bits, 2) - self.assertEqual(imm2.format_asm(), "2") - self.assertEqual(imm_hex.bits, 0xDEADBEEF) - self.assertEqual(imm_hex.format_asm(), "0xdeadbeef") - - def test_instruction_formatting(self) -> None: - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(2), - ) - self.assertEqual(inst.to_assembly(), "v_alignbyte_b32 v0, v1, v2, 2") - - def test_instruction_with_sgpr_and_vgpr(self) -> None: - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 5), - src0=Register(RegKind.SGPR, 0), - src1=Register(RegKind.VGPR, 1), - src2=Register(RegKind.SGPR, 2), - ) - self.assertEqual(inst.to_assembly(), "v_alignbyte_b32 v5, s0, v1, s2") - - def test_instruction_validation_negative(self) -> None: - # Invalid destination kind (must be VGPR) - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.SGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(0), - ) - - # Invalid register count - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 0, count=2) - - # Out of bounds register index - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 256) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 106) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, -1) - - def test_program_assembly(self) -> None: - prog = Program() - prog.append(Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(1), - )) - prog.append(Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 3), - src0=Register(RegKind.VGPR, 0), - src1=Register(RegKind.VGPR, 4), - src2=Immediate(2), - )) - expected = ( - "v_alignbyte_b32 v0, v1, v2, 1\n" - "v_alignbyte_b32 v3, v0, v4, 2" - ) - self.assertEqual(prog.to_assembly(), expected) - - -# --------------------------------------------------------------------------- -# Condition Codes, Status Flags, and Carry/Borrow Isolation -# --------------------------------------------------------------------------- - -@dataclasses.dataclass(frozen=True) -class ConditionCodes: - """Architectural condition codes for 32-bit VALU operations.""" - zero: bool - sign: bool - byte0_zero: bool - byte1_zero: bool - byte2_zero: bool - byte3_zero: bool - parity: bool - - -@dataclasses.dataclass(frozen=True) -class VALUStatusFlags: - """Status flags and carry/borrow tracking for VALU instructions.""" - vcc_modified: bool = False - overflow: bool = False - carry: bool = False - - -def compute_alignbyte_condition_codes(result: int) -> ConditionCodes: - """Computes condition codes evaluating attributes of the 32-bit alignbyte result.""" - res = result & MASK32 - b0 = res & 0xFF - b1 = (res >> 8) & 0xFF - b2 = (res >> 16) & 0xFF - b3 = (res >> 24) & 0xFF - # Parity of low byte (True if even number of set bits) - parity = (bin(b0).count("1") % 2) == 0 - return ConditionCodes( - zero=(res == 0), - sign=bool(res & SIGN_BIT32), - byte0_zero=(b0 == 0), - byte1_zero=(b1 == 0), - byte2_zero=(b2 == 0), - byte3_zero=(b3 == 0), - parity=parity, - ) - - -def compute_alignbyte_status_flags() -> VALUStatusFlags: - """In RDNA2 ISA, VALU alignbyte is a purely logical funnel shift and never affects VCC.""" - return VALUStatusFlags(vcc_modified=False, overflow=False, carry=False) - - -# --------------------------------------------------------------------------- -# Deterministic Scalar Instruction Interpreter -# --------------------------------------------------------------------------- - -class ScalarVALUInterpreter: - """Deterministic scalar interpreter for GFX10/RDNA2 VALU v_alignbyte_b32.""" - - def __init__(self) -> None: - self.vgprs: list[int] = [0] * 256 - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - self.last_condition_codes: ConditionCodes | None = None - self.last_status_flags: VALUStatusFlags | None = None - self.trace: list[str] = [] - - def read_reg_u32(self, kind: RegKind, idx: int) -> int: - if kind == RegKind.VGPR: - if not (0 <= idx < 256): - raise IndexError(f"VGPR index out of bounds: {idx}") - return self.vgprs[idx] & MASK32 - if not (0 <= idx < 106): - raise IndexError(f"SGPR index out of bounds: {idx}") - return self.sgprs[idx] & MASK32 - - def write_reg_u32(self, kind: RegKind, idx: int, val: int) -> None: - val32 = val & MASK32 - if kind == RegKind.VGPR: - if not (0 <= idx < 256): - raise IndexError(f"VGPR index out of bounds: {idx}") - self.vgprs[idx] = val32 - else: - if not (0 <= idx < 106): - raise IndexError(f"SGPR index out of bounds: {idx}") - self.sgprs[idx] = val32 - - def read_operand(self, op: Register | Immediate) -> int: - if isinstance(op, Immediate): - return op.bits - if isinstance(op, Register): - return self.read_reg_u32(op.kind, op.index) - raise TypeError(f"Unsupported operand type: {type(op)}") - - def step(self, inst: Instruction) -> int: - """Executes a single VALU alignbyte instruction with strict read-before-write semantics.""" - # Latch all input operands before writing destination - s0_val = self.read_operand(inst.src0) - s1_val = self.read_operand(inst.src1) - s2_val = self.read_operand(inst.src2) - - if inst.opcode == Opcode.V_ALIGNBYTE_B32: - res = ref_alignbyte_b32(s0_val, s1_val, s2_val) - else: - raise NotImplementedError(f"Unsupported opcode in scalar interpreter: {inst.opcode}") - - self.write_reg_u32(inst.dst.kind, inst.dst.index, res) - self.last_condition_codes = compute_alignbyte_condition_codes(res) - self.last_status_flags = compute_alignbyte_status_flags() - self.trace.append(f"{inst.to_assembly()} => {res:#010x}") - return res - - def run_program(self, prog: Program) -> list[int]: - """Executes all instructions in a program sequentially.""" - return [self.step(inst) for inst in prog.instructions] - - -class TestValuAlignbyteB32ScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar VALU instruction interpreter.""" - - def test_scalar_register_read_write(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u32(RegKind.VGPR, 0, 0x12345678) - interp.write_reg_u32(RegKind.SGPR, 4, 0x9ABCDEF0) - - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), 0x12345678) - self.assertEqual(interp.read_reg_u32(RegKind.SGPR, 4), 0x9ABCDEF0) - - def test_scalar_execution_vgpr_sources(self) -> None: - interp = ScalarVALUInterpreter() - # S1 = v1 = 0x44332211, S0 = v0 = 0x88776655, S2 = v2 = 1 - interp.write_reg_u32(RegKind.VGPR, 0, 0x88776655) - interp.write_reg_u32(RegKind.VGPR, 1, 0x44332211) - interp.write_reg_u32(RegKind.VGPR, 2, 1) - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 3), - src0=Register(RegKind.VGPR, 0), - src1=Register(RegKind.VGPR, 1), - src2=Register(RegKind.VGPR, 2), - ) - res = interp.step(inst) - self.assertEqual(res, 0x55443322) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 3), 0x55443322) - - def test_scalar_execution_sgpr_sources(self) -> None: - interp = ScalarVALUInterpreter() - # S0 from SGPR s0, S1 from VGPR v1, shift from SGPR s2 - interp.write_reg_u32(RegKind.SGPR, 0, 0xAABBCCDD) - interp.write_reg_u32(RegKind.VGPR, 1, 0x11223344) - interp.write_reg_u32(RegKind.SGPR, 2, 2) - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.SGPR, 0), - src1=Register(RegKind.VGPR, 1), - src2=Register(RegKind.SGPR, 2), - ) - res = interp.step(inst) - # S1=0x11223344, S0=0xAABBCCDD, shift=2 -> [0x33, 0x44, 0xDD, 0xCC] -> 0xCCDD1122 ? - # S1 bytes: 44, 33, 22, 11; S0 bytes: DD, CC, BB, AA - # shift 2 bytes: bytes [2,3,4,5] -> [22, 11, DD, CC] -> 0xCCDD1122 - expected = ref_alignbyte_b32(0xAABBCCDD, 0x11223344, 2) - self.assertEqual(res, expected) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), expected) - - def test_scalar_immediate_operand(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u32(RegKind.VGPR, 1, 0x88776655) - interp.write_reg_u32(RegKind.VGPR, 2, 0x44332211) - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(3), - ) - res = interp.step(inst) - expected = ref_alignbyte_b32(0x88776655, 0x44332211, 3) - self.assertEqual(res, expected) - - def test_scalar_program_execution_chain(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u32(RegKind.VGPR, 1, 0x01020304) - interp.write_reg_u32(RegKind.VGPR, 2, 0x05060708) - - prog = Program() - # Step 1: v0 = alignbyte(v1, v2, 1) - prog.append(Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(1), - )) - # Step 2: v3 = alignbyte(v0, v1, 2) - prog.append(Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 3), - src0=Register(RegKind.VGPR, 0), - src1=Register(RegKind.VGPR, 1), - src2=Immediate(2), - )) - - results = interp.run_program(prog) - r0 = ref_alignbyte_b32(0x01020304, 0x05060708, 1) - r1 = ref_alignbyte_b32(r0, 0x01020304, 2) - self.assertEqual(results, [r0, r1]) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 3), r1) - self.assertEqual(len(interp.trace), 2) - - -# --------------------------------------------------------------------------- -# SIMD Wavefront Interpreter (Multi-Lane Divergence & 32/64-Bit EXEC Masking) -# --------------------------------------------------------------------------- - -class SIMDWavefrontInterpreter: - """Multi-lane SIMD interpreter modeling Wave32 and Wave64 execution on RDNA2.""" - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size} (must be 32 or 64)") - self.wave_size: int = wave_size - self.exec_mask: int = (1 << wave_size) - 1 - # Per-lane VGPR files: [wave_size][256] 32-bit registers - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - # Wavefront-shared SGPR file: [106] 32-bit registers - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - - def set_exec_mask(self, mask: int) -> None: - valid_mask = (1 << self.wave_size) - 1 - self.exec_mask = mask & valid_mask - - def read_lane_reg_u32(self, lane: int, kind: RegKind, idx: int) -> int: - if kind == RegKind.VGPR: - return self.vgprs[lane][idx] & MASK32 - return self.sgprs[idx] & MASK32 - - def write_lane_reg_u32(self, lane: int, kind: RegKind, idx: int, val: int) -> None: - val32 = val & MASK32 - if kind == RegKind.VGPR: - self.vgprs[lane][idx] = val32 - else: - self.sgprs[idx] = val32 - - def read_lane_operand(self, lane: int, op: Register | Immediate) -> int: - if isinstance(op, Immediate): - return op.bits - if isinstance(op, Register): - return self.read_lane_reg_u32(lane, op.kind, op.index) - raise TypeError(f"Unsupported operand type: {type(op)}") - - def step(self, inst: Instruction) -> list[int | None]: - """Executes a VALU instruction across all lanes in the wavefront governed by EXEC mask.""" - # 1. Latch inputs for all lanes (read-before-write semantics across wavefront) - latched_inputs: list[tuple[int, int, int]] = [] - for lane in range(self.wave_size): - s0_val = self.read_lane_operand(lane, inst.src0) - s1_val = self.read_lane_operand(lane, inst.src1) - s2_val = self.read_lane_operand(lane, inst.src2) - latched_inputs.append((s0_val, s1_val, s2_val)) - - # 2. Compute and write back strictly for active lanes - lane_results: list[int | None] = [] - for lane in range(self.wave_size): - is_active = bool((self.exec_mask >> lane) & 1) - if not is_active: - lane_results.append(None) - continue - - s0_val, s1_val, s2_val = latched_inputs[lane] - if inst.opcode == Opcode.V_ALIGNBYTE_B32: - res = ref_alignbyte_b32(s0_val, s1_val, s2_val) - else: - raise NotImplementedError(f"Unsupported opcode in SIMD interpreter: {inst.opcode}") - - self.write_lane_reg_u32(lane, inst.dst.kind, inst.dst.index, res) - lane_results.append(res) - - return lane_results - - -class TestValuAlignbyteB32SIMD(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_uniform_inputs(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(1), - ) - for lane in range(32): - simd.write_lane_reg_u32(lane, RegKind.VGPR, 1, 0x88776655) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 2, 0x44332211) - - results = simd.step(inst) - self.assertEqual(len(results), 32) - expected = ref_alignbyte_b32(0x88776655, 0x44332211, 1) - for lane in range(32): - self.assertEqual(results[lane], expected) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), expected) - - def test_wave64_multi_lane_divergence(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=64) - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Register(RegKind.VGPR, 3), - ) - expected: list[int] = [] - for lane in range(64): - s0 = (0x10000000 * (lane + 1)) & MASK32 - s1 = (0x01020304 + lane) & MASK32 - shift = lane % 4 - simd.write_lane_reg_u32(lane, RegKind.VGPR, 1, s0) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 2, s1) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 3, shift) - expected.append(ref_alignbyte_b32(s0, s1, shift)) - - results = simd.step(inst) - for lane in range(64): - self.assertEqual(results[lane], expected[lane]) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), expected[lane]) - - def test_wave32_exec_masking_partial(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - exec_mask = 0x55555555 # Even lanes active - simd.set_exec_mask(exec_mask) - - canary = 0xDEADBEEF - for lane in range(32): - simd.write_lane_reg_u32(lane, RegKind.VGPR, 0, canary) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 1, 0x88776655) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 2, 0x44332211) - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(2), - ) - results = simd.step(inst) - expected = ref_alignbyte_b32(0x88776655, 0x44332211, 2) - - for lane in range(32): - if (exec_mask >> lane) & 1: - self.assertEqual(results[lane], expected) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), expected) - else: - self.assertIsNone(results[lane]) - # Inactive lanes strictly retain canary - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), canary) - - def test_wave64_exec_masking_all_inactive(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=64) - simd.set_exec_mask(0) - - canary = 0xCAFEBABE - for lane in range(64): - simd.write_lane_reg_u32(lane, RegKind.VGPR, 0, canary) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 1, 0x11111111) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 2, 0x22222222) - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(1), - ) - results = simd.step(inst) - self.assertEqual(results, [None] * 64) - for lane in range(64): - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), canary) - - def test_simd_with_shared_sgpr_scalar_source(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - # Shift amount 3 in SGPR s4 - simd.write_lane_reg_u32(0, RegKind.SGPR, 4, 3) - - for lane in range(32): - simd.write_lane_reg_u32(lane, RegKind.VGPR, 1, 0x10203040 + lane) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 2, 0x50607080 + lane) - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Register(RegKind.SGPR, 4), - ) - results = simd.step(inst) - for lane in range(32): - s0 = 0x10203040 + lane - s1 = 0x50607080 + lane - expected = ref_alignbyte_b32(s0, s1, 3) - self.assertEqual(results[lane], expected) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), expected) - - -# --------------------------------------------------------------------------- -# Register Aliasing and In-Place Operand Preservation -# --------------------------------------------------------------------------- - -class TestValuAlignbyteB32RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_aliasing_dst_equals_src0(self) -> None: - interp = ScalarVALUInterpreter() - s0_val = 0x88776655 - s1_val = 0x44332211 - interp.write_reg_u32(RegKind.VGPR, 0, s0_val) - interp.write_reg_u32(RegKind.VGPR, 1, s1_val) - - # v0 = alignbyte(v0, v1, 2) - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 0), - src1=Register(RegKind.VGPR, 1), - src2=Immediate(2), - ) - res = interp.step(inst) - expected = ref_alignbyte_b32(s0_val, s1_val, 2) - self.assertEqual(res, expected) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), expected) - # v1 (src1) remains completely preserved - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), s1_val) - - def test_aliasing_dst_equals_src1(self) -> None: - interp = ScalarVALUInterpreter() - s0_val = 0x88776655 - s1_val = 0x44332211 - interp.write_reg_u32(RegKind.VGPR, 0, s0_val) - interp.write_reg_u32(RegKind.VGPR, 1, s1_val) - - # v1 = alignbyte(v0, v1, 1) - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 1), - src0=Register(RegKind.VGPR, 0), - src1=Register(RegKind.VGPR, 1), - src2=Immediate(1), - ) - res = interp.step(inst) - expected = ref_alignbyte_b32(s0_val, s1_val, 1) - self.assertEqual(res, expected) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), expected) - # v0 (src0) remains completely preserved - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), s0_val) - - def test_aliasing_dst_equals_src2_shift_amount(self) -> None: - interp = ScalarVALUInterpreter() - s0_val = 0x88776655 - s1_val = 0x44332211 - shift_reg = 3 - interp.write_reg_u32(RegKind.VGPR, 0, s0_val) - interp.write_reg_u32(RegKind.VGPR, 1, s1_val) - interp.write_reg_u32(RegKind.VGPR, 2, shift_reg) - - # v2 = alignbyte(v0, v1, v2) - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 2), - src0=Register(RegKind.VGPR, 0), - src1=Register(RegKind.VGPR, 1), - src2=Register(RegKind.VGPR, 2), - ) - res = interp.step(inst) - expected = ref_alignbyte_b32(s0_val, s1_val, shift_reg) - self.assertEqual(res, expected) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 2), expected) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), s0_val) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), s1_val) - - def test_aliasing_in_place_rotate_dst_src0_src1(self) -> None: - interp = ScalarVALUInterpreter() - val = 0x12345678 - interp.write_reg_u32(RegKind.VGPR, 5, val) - - # v5 = alignbyte(v5, v5, 1) -> 32-bit rotate right by 1 byte - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 5), - src0=Register(RegKind.VGPR, 5), - src1=Register(RegKind.VGPR, 5), - src2=Immediate(1), - ) - res = interp.step(inst) - expected = 0x78123456 - self.assertEqual(res, expected) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 5), expected) - - def test_aliasing_all_four_operands_identical(self) -> None: - interp = ScalarVALUInterpreter() - # Value 2 in v0: shift count is (2 & 3) == 2 bytes - interp.write_reg_u32(RegKind.VGPR, 0, 2) - - # v0 = alignbyte(v0, v0, v0) - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 0), - src1=Register(RegKind.VGPR, 0), - src2=Register(RegKind.VGPR, 0), - ) - res = interp.step(inst) - expected = ref_alignbyte_b32(2, 2, 2) - self.assertEqual(res, expected) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), expected) - - def test_unmodified_registers_preserved(self) -> None: - interp = ScalarVALUInterpreter() - # Seed registers 10..29 with canary patterns - for idx in range(10, 30): - interp.write_reg_u32(RegKind.VGPR, idx, 0xABC00000 + idx) - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Immediate(0x11111111), - src1=Immediate(0x22222222), - src2=Immediate(1), - ) - interp.step(inst) - - for idx in range(10, 30): - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, idx), 0xABC00000 + idx) - - def test_simd_aliasing_with_divergent_exec_mask(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - exec_mask = 0x0000000F # Only lanes 0..3 active - simd.set_exec_mask(exec_mask) - - # In all lanes: v0 = 0x88776655, v1 = 0x44332211 - for lane in range(32): - simd.write_lane_reg_u32(lane, RegKind.VGPR, 0, 0x88776655) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 1, 0x44332211) - - # v0 = alignbyte(v0, v1, 2) - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 0), - src1=Register(RegKind.VGPR, 1), - src2=Immediate(2), - ) - results = simd.step(inst) - expected = ref_alignbyte_b32(0x88776655, 0x44332211, 2) - - for lane in range(32): - if lane < 4: - self.assertEqual(results[lane], expected) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), expected) - else: - self.assertIsNone(results[lane]) - # Inactive lanes retain original v0 - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), 0x88776655) - - -class TestValuAlignbyteB32ConditionCodes(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow isolation.""" - - def test_condition_codes_zero_flag(self) -> None: - interp = ScalarVALUInterpreter() - inst_zero = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Immediate(0), - src1=Immediate(0), - src2=Immediate(0), - ) - res = interp.step(inst_zero) - self.assertEqual(res, 0) - cc = interp.last_condition_codes - self.assertIsNotNone(cc) - assert cc is not None - self.assertTrue(cc.zero) - self.assertFalse(cc.sign) - self.assertTrue(cc.byte0_zero) - self.assertTrue(cc.byte1_zero) - self.assertTrue(cc.byte2_zero) - self.assertTrue(cc.byte3_zero) - self.assertTrue(cc.parity) # 0 has 0 bits set, even parity - - def test_condition_codes_sign_flag(self) -> None: - interp = ScalarVALUInterpreter() - # High bit set: e.g. 0x80000000 - inst_sign = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Immediate(0x80000000), - src1=Immediate(0x00000000), - src2=Immediate(3), # shift 3 bytes -> byte 4 (low byte of src0) moves to high byte - ) - res = interp.step(inst_sign) - # Low byte of src0 is 0x00, so that wouldn't have bit 31 set. - # To get bit 31 set, we need byte 3 of result to have bit 7 set (0x80). - # Let's use S1=0x80000000 and shift 0 - inst_sign2 = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Immediate(0), - src1=Immediate(0x80000000), - src2=Immediate(0), - ) - res2 = interp.step(inst_sign2) - self.assertEqual(res2, 0x80000000) - cc = interp.last_condition_codes - self.assertIsNotNone(cc) - assert cc is not None - self.assertFalse(cc.zero) - self.assertTrue(cc.sign) - self.assertTrue(cc.byte0_zero) - self.assertFalse(cc.byte3_zero) - - def test_condition_codes_per_byte_zeros(self) -> None: - # Pattern 0x00FF00AA: byte 0 = 0xAA (non-zero), byte 1 = 0x00 (zero), - # byte 2 = 0xFF (non-zero), byte 3 = 0x00 (zero) - cc = compute_alignbyte_condition_codes(0x00FF00AA) - self.assertFalse(cc.zero) - self.assertFalse(cc.sign) - self.assertFalse(cc.byte0_zero) - self.assertTrue(cc.byte1_zero) - self.assertFalse(cc.byte2_zero) - self.assertTrue(cc.byte3_zero) - - def test_condition_codes_parity(self) -> None: - # 0x01 has 1 set bit (odd parity -> parity=False) - cc_odd = compute_alignbyte_condition_codes(0x01) - self.assertFalse(cc_odd.parity) - - # 0x03 has 2 set bits (even parity -> parity=True) - cc_even = compute_alignbyte_condition_codes(0x03) - self.assertTrue(cc_even.parity) - - def test_carry_borrow_vcc_isolation(self) -> None: - interp = ScalarVALUInterpreter() - canary_vcc = 0xFEEDFACECAFEBEEF - interp.vcc = canary_vcc - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Immediate(0xFFFFFFFF), - src1=Immediate(0xFFFFFFFF), - src2=Immediate(1), - ) - interp.step(inst) - # VCC is never modified or polluted by alignbyte - self.assertEqual(interp.vcc, canary_vcc) - - flags = interp.last_status_flags - self.assertIsNotNone(flags) - assert flags is not None - self.assertFalse(flags.vcc_modified) - self.assertFalse(flags.overflow) - self.assertFalse(flags.carry) - - # SIMD wavefront test: VCC invariant across wave - simd = SIMDWavefrontInterpreter(wave_size=64) - simd.vcc = canary_vcc - simd.step(inst) - self.assertEqual(simd.vcc, canary_vcc) - - -# --------------------------------------------------------------------------- -# IEEE 754 Single-Precision Floating-Point Architectural Constants & Boundaries -# --------------------------------------------------------------------------- - -POS_ZERO_F32: int = 0x00000000 -NEG_ZERO_F32: int = 0x80000000 -POS_ONE_F32: int = 0x3F800000 -NEG_ONE_F32: int = 0xBF800000 -POS_INF_F32: int = 0x7F800000 -NEG_INF_F32: int = 0xFF800000 -QNAN_F32: int = 0x7FC00000 -SNAN_F32: int = 0x7F800001 -QNAN_PAYLOAD_F32: int = 0x7FC01234 -SNAN_PAYLOAD_F32: int = 0x7F804321 -SUBNORM_MIN_F32: int = 0x00000001 -SUBNORM_MAX_F32: int = 0x007FFFFF -NEG_SUBNORM_MIN_F32: int = 0x80000001 -NEG_SUBNORM_MAX_F32: int = 0x807FFFFF -FLT_MIN_F32: int = 0x00800000 -FLT_MAX_F32: int = 0x7F7FFFFF - - -def f32_to_bits(val: float) -> int: - """Encode float to IEEE 754 single-precision 32-bit unsigned integer.""" - return struct.unpack(" float: - """Decode 32-bit unsigned integer to IEEE 754 single-precision float.""" - return struct.unpack(" bool: - """True if 32-bit integer represents an IEEE 754 single-precision NaN.""" - bits &= MASK32 - return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 - - -def is_subnormal_f32(bits: int) -> bool: - """True if 32-bit integer represents an IEEE 754 single-precision subnormal.""" - bits &= MASK32 - return (bits & 0x7F800000) == 0 and (bits & 0x007FFFFF) != 0 - - -class TestValuAlignbyteB32IEEE754Boundaries(unittest.TestCase): - """Exhaustive unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_unaligned_float_reconstruction_all_shifts(self) -> None: - """Verify unaligned IEEE 754 floats in byte streams are reconstructed bit-exactly.""" - floats_to_test = [ - POS_ZERO_F32, - NEG_ZERO_F32, - POS_ONE_F32, - NEG_ONE_F32, - POS_INF_F32, - NEG_INF_F32, - QNAN_F32, - SNAN_F32, - QNAN_PAYLOAD_F32, - SNAN_PAYLOAD_F32, - SUBNORM_MIN_F32, - SUBNORM_MAX_F32, - FLT_MIN_F32, - FLT_MAX_F32, - ] - - canary_pad = 0x5A # padding byte - - for flt_bits in floats_to_test: - flt_bytes = unpack_bytes(flt_bits) - for shift in (0, 1, 2, 3): - with self.subTest(flt=f"{flt_bits:#010x}", shift=shift): - # Create an 8-byte buffer where flt_bytes start at byte offset `shift` - buf = [canary_pad] * 8 - for i in range(4): - buf[shift + i] = flt_bytes[i] - - # S1 is bytes 0..3, S0 is bytes 4..7 - s1 = pack_bytes(buf[0], buf[1], buf[2], buf[3]) - s0 = pack_bytes(buf[4], buf[5], buf[6], buf[7]) - - # Align byte by `shift` extracts bytes `shift..shift+3` - extracted = ref_alignbyte_b32(s0, s1, shift) - self.assertEqual(extracted, flt_bits) - - # Float bitcast preservation - if not is_nan_f32(flt_bits): - orig_f = bits_to_f32(flt_bits) - extr_f = bits_to_f32(extracted) - if flt_bits in (POS_ZERO_F32, NEG_ZERO_F32): - # Ensure sign of zero is preserved - self.assertEqual(flt_bits & SIGN_BIT32, extracted & SIGN_BIT32) - else: - self.assertEqual(orig_f, extr_f) - else: - self.assertTrue(is_nan_f32(extracted)) - - def test_subnormals_bit_preservation_no_ftz(self) -> None: - """Verify that subnormal float bit patterns are NEVER flushed to zero during alignment.""" - subnormals = [ - SUBNORM_MIN_F32, - SUBNORM_MAX_F32, - NEG_SUBNORM_MIN_F32, - NEG_SUBNORM_MAX_F32, - 0x00000042, - 0x00012345, - 0x800055AA, - ] - for sub in subnormals: - self.assertTrue(is_subnormal_f32(sub)) - # Shift 0: returns sub directly - self.assertEqual(ref_alignbyte_b32(0, sub, 0), sub) - # Shift 2: pack across dwords - b0, b1, b2, b3 = unpack_bytes(sub) - s1 = pack_bytes(0, 0, b0, b1) - s0 = pack_bytes(b2, b3, 0, 0) - res = ref_alignbyte_b32(s0, s1, 2) - self.assertEqual(res, sub) - self.assertTrue(is_subnormal_f32(res)) - - def test_nan_payload_preservation_no_quietization(self) -> None: - """Verify signaling NaNs and quiet NaNs preserve their payloads without mutation.""" - nans = [ - QNAN_F32, - SNAN_F32, - QNAN_PAYLOAD_F32, - SNAN_PAYLOAD_F32, - 0x7F800002, # sNaN - 0x7FC00001, # qNaN - 0xFF800001, # negative sNaN - 0xFFC00001, # negative qNaN - ] - for nan in nans: - self.assertTrue(is_nan_f32(nan)) - # Across all shifts, bit pattern must be 100% invariant - for shift in (0, 1, 2, 3): - flt_bytes = unpack_bytes(nan) - buf = [0] * 8 - for i in range(4): - buf[shift + i] = flt_bytes[i] - s1 = pack_bytes(buf[0], buf[1], buf[2], buf[3]) - s0 = pack_bytes(buf[4], buf[5], buf[6], buf[7]) - res = ref_alignbyte_b32(s0, s1, shift) - self.assertEqual(res, nan) - self.assertEqual(res & 0x007FFFFF, nan & 0x007FFFFF) # payload intact - self.assertEqual(res & SIGN_BIT32, nan & SIGN_BIT32) # sign intact - - def test_signed_zeros_distinction(self) -> None: - """Verify +0.0 and -0.0 maintain their respective sign bits when aligned.""" - # Positive zero - self.assertEqual(ref_alignbyte_b32(0, POS_ZERO_F32, 0), POS_ZERO_F32) - self.assertEqual(ref_alignbyte_b32(0, POS_ZERO_F32, 0) & SIGN_BIT32, 0) - - # Negative zero - self.assertEqual(ref_alignbyte_b32(0, NEG_ZERO_F32, 0), NEG_ZERO_F32) - self.assertEqual(ref_alignbyte_b32(0, NEG_ZERO_F32, 0) & SIGN_BIT32, SIGN_BIT32) - - # Negative zero shifted by 1 byte: sign bit was bit 31 of S1 (byte 3). - # Shifting by 1 byte places byte 3 into byte 2 of result (bit 23). - res_shift1 = ref_alignbyte_b32(0, NEG_ZERO_F32, 1) - self.assertEqual(res_shift1, 0x00800000) - - def test_infinities_preservation(self) -> None: - """Verify positive and negative infinities remain bit-identical.""" - self.assertEqual(ref_alignbyte_b32(0, POS_INF_F32, 0), POS_INF_F32) - self.assertEqual(ref_alignbyte_b32(0, NEG_INF_F32, 0), NEG_INF_F32) - - def test_dual_packed_f16_half_swapping(self) -> None: - """Verify alignbyte can exchange high/low 16-bit halves (packed float16).""" - # Pack two f16 values: low=1.0 (0x3C00), high=2.0 (0x4000) -> 0x40003C00 - packed_f16 = 0x40003C00 - # Rotate by 2 bytes (shift 2 with S0 == S1) exchanges the two halves - swapped = ref_alignbyte_b32(packed_f16, packed_f16, 2) - self.assertEqual(swapped, 0x3C004000) - # Low half is now 2.0 (0x4000) and high half is 1.0 (0x3C00) - self.assertEqual(swapped & 0xFFFF, 0x4000) - self.assertEqual((swapped >> 16) & 0xFFFF, 0x3C00) - - -# --------------------------------------------------------------------------- -# Negative Controls, Syntax Rejection, and Mutation Detection -# --------------------------------------------------------------------------- - -class TestValuAlignbyteB32NegativeControls(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and invalid AST inputs.""" - - def test_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.VGPR, -1) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 256) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, -1) - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 106) - - def test_invalid_destination_kind(self) -> None: - # Destination cannot be an SGPR for VALU instruction - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.SGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(0), - ) - - def test_scalar_interpreter_out_of_bounds_access(self) -> None: - interp = ScalarVALUInterpreter() - with self.assertRaises(IndexError): - interp.read_reg_u32(RegKind.VGPR, 256) - with self.assertRaises(IndexError): - interp.write_reg_u32(RegKind.SGPR, 106, 0) - - def test_simd_interpreter_invalid_wave_size(self) -> None: - with self.assertRaises(ValueError): - SIMDWavefrontInterpreter(wave_size=16) - with self.assertRaises(ValueError): - SIMDWavefrontInterpreter(wave_size=128) - - def test_unsupported_operand_type(self) -> None: - interp = ScalarVALUInterpreter() - with self.assertRaises(TypeError): - interp.read_operand("v0") # type: ignore[arg-type] - - def test_unsupported_opcode_rejection(self) -> None: - # Create a mock instruction with unsupported opcode - class FakeOpcode(enum.Enum): - UNKNOWN = "v_unknown" - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Register(RegKind.VGPR, 1), - src1=Register(RegKind.VGPR, 2), - src2=Immediate(0), - ) - object.__setattr__(inst, "opcode", FakeOpcode.UNKNOWN) - - interp = ScalarVALUInterpreter() - with self.assertRaises(NotImplementedError): - interp.step(inst) - - -class TestValuAlignbyteB32MutationDetection(unittest.TestCase): - """Mutation tests: verifies that intentional sabotages/mutations of the oracle are caught.""" - - def test_mutation_inverted_shift_direction(self) -> None: - # Sabotage: left shift instead of right shift - def mutated_alignbyte(s0: int, s1: int, s2: int) -> int: - concat = ((s0 & MASK32) << 32) | (s1 & MASK32) - shift = (s2 & 3) * 8 - return (concat << shift) & MASK32 - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_alignbyte(0x88776655, 0x44332211, 1), 0x55443322) - - def test_mutation_inverted_operands_order(self) -> None: - # Sabotage: concatenating {S1, S0} instead of {S0, S1} - def mutated_alignbyte(s0: int, s1: int, s2: int) -> int: - concat = ((s1 & MASK32) << 32) | (s0 & MASK32) - shift = (s2 & 3) * 8 - return (concat >> shift) & MASK32 - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_alignbyte(0x88776655, 0x44332211, 1), 0x55443322) - - def test_mutation_shift_mask_omitted(self) -> None: - # Sabotage: omitting & 3 on shift count, so shift 4 shifts 32 bits - def mutated_alignbyte(s0: int, s1: int, s2: int) -> int: - concat = ((s0 & MASK32) << 32) | (s1 & MASK32) - shift = s2 * 8 # bug: missing & 3 - return (concat >> shift) & MASK32 - - # In RDNA2, shift 4 must behave identically to shift 0 (returning S1) - src0 = 0x88776655 - src1 = 0x44332211 - expected = ref_alignbyte_b32(src0, src1, 4) # returns src1 - with self.assertRaises(AssertionError): - self.assertEqual(mutated_alignbyte(src0, src1, 4), expected) - - def test_mutation_endianness_reversal(self) -> None: - # Sabotage: big-endian byte unpack - def mutated_pack_bytes(b0: int, b1: int, b2: int, b3: int) -> int: - return ((b0 & 0xFF) << 24) | ((b1 & 0xFF) << 16) | ((b2 & 0xFF) << 8) | (b3 & 0xFF) - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_pack_bytes(0x11, 0x22, 0x33, 0x44), 0x44332211) - - def test_mutation_exec_mask_leak(self) -> None: - # Sabotage: inactive SIMD lane modifies destination register - simd = SIMDWavefrontInterpreter(wave_size=32) - simd.set_exec_mask(0) # All lanes inactive - canary = 0xBAD0CAFE - simd.write_lane_reg_u32(0, RegKind.VGPR, 0, canary) - - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Immediate(1), - src1=Immediate(2), - src2=Immediate(0), - ) - simd.step(inst) - # Canary must be preserved - self.assertEqual(simd.read_lane_reg_u32(0, RegKind.VGPR, 0), canary) - - # Mutated behavior: unconditionally overwrite - simd.write_lane_reg_u32(0, RegKind.VGPR, 0, 0x12345678) - with self.assertRaises(AssertionError): - self.assertEqual(simd.read_lane_reg_u32(0, RegKind.VGPR, 0), canary) - - def test_mutation_vcc_clobber(self) -> None: - # Sabotage: alignbyte clobbering VCC - interp = ScalarVALUInterpreter() - canary_vcc = 0x1234567890ABCDEF - interp.vcc = canary_vcc - - # Proper step preserves VCC - inst = Instruction( - opcode=Opcode.V_ALIGNBYTE_B32, - dst=Register(RegKind.VGPR, 0), - src0=Immediate(1), - src1=Immediate(2), - src2=Immediate(0), - ) - interp.step(inst) - self.assertEqual(interp.vcc, canary_vcc) - - # Mutated step clobbers VCC - interp.vcc = 0 - with self.assertRaises(AssertionError): - self.assertEqual(interp.vcc, canary_vcc) +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) + +import support # noqa: E402 + +MASK32 = 0xFFFFFFFF + + +def ref_alignbyte(s0, s1, s2): + return ((((s0 & MASK32) << 32) | (s1 & MASK32)) >> (8 * (s2 & 3))) & MASK32 + + +def run(s0, s1, s2, form="vgpr"): + if form == "vgpr": + setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2 & MASK32:#x}"] + srcs = "v1, v2, v3" + elif form == "sgpr": + setup = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2 & MASK32:#x}"] + srcs = "s1, s2, s3" + else: # the shift as an inline constant + setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}"] + srcs = f"v1, v2, {s2}" + lines = setup + [f"v_alignbyte_b32 v0, {srcs}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_alignbyte", lines))[0] + + +# (name, S0, S1, S2, expected word), written by hand. +CASES = [ + ("shift 0 returns S1", 0xDEADBEEF, 0xCAFEBABE, 0, 0xCAFEBABE), + ("shift 1", 0x88776655, 0x44332211, 1, 0x55443322), + ("shift 2", 0x88776655, 0x44332211, 2, 0x66554433), + ("shift 3", 0x88776655, 0x44332211, 3, 0x77665544), + ("rotate idiom, shift 1", 0x12345678, 0x12345678, 1, 0x78123456), + ("rotate idiom, shift 2", 0x12345678, 0x12345678, 2, 0x56781234), + ("rotate idiom, shift 3", 0x12345678, 0x12345678, 3, 0x34567812), + ("S0 = 0 is a logical shift right", 0, 0x89ABCDEF, 1, 0x0089ABCD), + ("S1 = 0 is a shift left", 0x89ABCDEF, 0, 1, 0xEF000000), + ("S1 = 0, shift 3", 0x89ABCDEF, 0, 3, 0xABCDEF00), + ("top byte of S0 never reaches D", 0xFF000000, 0, 3, 0x00000000), + ("shift uses only the low two bits (4+1)", 0x9ABCDEF0, 0x12345678, 5, 0xF0123456), + ("shift uses only the low two bits (0xFFFFFFFC+2)", 0x9ABCDEF0, 0x12345678, 0xFFFFFFFE, 0xDEF01234), + ("negative shift -1 is 3", 0x11223344, 0xAABBCCDD, 0xFFFFFFFF, 0x223344AA), +] + + +class AlignByte(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for name, s0, s1, s2, want in CASES: + self.assertEqual(ref_alignbyte(s0, s1, s2), want, name) + + def test_translated_cases(self): + for name, s0, s1, s2, want in CASES: + with self.subTest(name): + self.assertEqual(run(s0, s1, s2), want) + + def test_sgpr_and_inline_constant_shift(self): + for name, s0, s1, s2, want in CASES[:11]: + with self.subTest(name, form="sgpr"): + self.assertEqual(run(s0, s1, s2, "sgpr"), want) + with self.subTest(name, form="inline"): + self.assertEqual(run(s0, s1, s2, "inline"), want) + + def test_random_operands(self): + rng = random.Random(0x616C676E) + for _ in range(60): + s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) + with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): + self.assertEqual(run(s0, s1, s2), ref_alignbyte(s0, s1, s2)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_dot4_int.py b/tests/semantic/test_valu_dot4_int.py index 6748256a6..5f7b73e40 100644 --- a/tests/semantic/test_valu_dot4_int.py +++ b/tests/semantic/test_valu_dot4_int.py @@ -1,1272 +1,112 @@ -from __future__ import annotations +"""v_dot4_u32_u8 and v_dot4_i32_i8 (RDNA2 VOP3P): D = S2 + sum of the four byte products of S0 and S1 (unsigned bytes +for u8, signed for i8), modulo 2^32; with `clamp` the result saturates to [0, 2^32-1] (u8) or [-2^31, 2^31-1] (i8). -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_dot4_int opcodes. - -This module provides an architectural reference model and semantic test suite for RDNA2 -VALU packed 8-bit integer dot product instructions: - - v_dot4_i32_i8 (VOP3/VOP3P): Signed 8-bit integer 4-vector dot product: - D.i32 = S2.i32 + sum(S0.i8[i] * S1.i8[i] for i in 0..3) mod 2^32 - - v_dot4_u32_u8 (VOP3/VOP3P): Unsigned 8-bit integer 4-vector dot product: - D.u32 = S2.u32 + sum(S0.u8[i] * S1.u8[i] for i in 0..3) mod 2^32 - - v_dot4acc_u32_u8: Accumulating unsigned 8-bit integer dot product with explicit accumulator: - D.u32 = S2.u32 + sum(S0.u8[i] * S1.u8[i] for i in 0..3) mod 2^32 - -ISA Specifications (RDNA2 / GFX10.3+): - - Each 32-bit dword S0 and S1 contains four packed 8-bit integers: - Byte 0: bits [7:0] - Byte 1: bits [15:8] - Byte 2: bits [23:16] - Byte 3: bits [31:24] - - In v_dot4_i32_i8, each byte is treated as signed 2's complement int8 in [-128, +127]. - Each component product S0.i8[i] * S1.i8[i] is in [-16256, +16384]. - The four products sum to [-65024, +65536], which is added to 32-bit accumulator S2 - and wrapped modulo 2^32 (or clamped to [-2^31, 2^31 - 1] if clamp is asserted). - - In v_dot4_u32_u8, each byte is treated as unsigned uint8 in [0, 255]. - Each component product S0.u8[i] * S1.u8[i] is in [0, 65025]. - The four products sum to [0, 260100], which is added to 32-bit accumulator S2 - and wrapped modulo 2^32 (or clamped to [0, 0xFFFFFFFF] if clamp is asserted). - -Standard library Python only; zero third-party dependencies. -Python 3.9+ compatible. +Each case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +words are written by hand and also recomputed by a plain-Python reference. v_dot4acc_u32_u8 is not a RDNA2 opcode the +translator knows, and stays refused. Standard library only: no GPU, no LLVM, no game data. """ - -from dataclasses import dataclass, field -from enum import Enum, auto -import re -import struct -from typing import Optional, Union, List, Tuple +import os +import random +import sys import unittest -# Bitmask and architectural boundary constants -MASK8: int = 0xFF -MASK32: int = 0xFFFF_FFFF -SIGN8_BIT: int = 0x80 -INT32_MIN: int = -0x8000_0000 -INT32_MAX: int = 0x7FFF_FFFF -UINT32_MAX: int = 0xFFFF_FFFF +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) + +import support # noqa: E402 +from rdna2spirv import Unsupported # noqa: E402 + +MASK32 = 0xFFFFFFFF +INT32_MIN, INT32_MAX = -0x80000000, 0x7FFFFFFF -def unpack_u8(dword: int) -> tuple[int, int, int, int]: - """Unpack a 32-bit dword into four unsigned 8-bit integers (byte0, byte1, byte2, byte3).""" - val = dword & MASK32 - return ( - val & MASK8, - (val >> 8) & MASK8, - (val >> 16) & MASK8, - (val >> 24) & MASK8, - ) +def pk(*b): + """Pack four bytes, byte 0 first, into a dword.""" + return sum((x & 0xFF) << (8 * i) for i, x in enumerate(b)) -def pack_u8(b0: int, b1: int, b2: int, b3: int) -> int: - """Pack four unsigned 8-bit integers into a 32-bit dword.""" - return ((b0 & MASK8) | ((b1 & MASK8) << 8) | ((b2 & MASK8) << 16) | ((b3 & MASK8) << 24)) & MASK32 - - -def unpack_i8(dword: int) -> tuple[int, int, int, int]: - """Unpack a 32-bit dword into four signed 8-bit integers (-128 to +127).""" - raw_bytes = unpack_u8(dword) - return tuple((b - 256) if (b & SIGN8_BIT) else b for b in raw_bytes) # type: ignore[return-value] - - -def pack_i8(b0: int, b1: int, b2: int, b3: int) -> int: - """Pack four signed 8-bit integers into a 32-bit dword.""" - return pack_u8(b0 & MASK8, b1 & MASK8, b2 & MASK8, b3 & MASK8) - - -def ref_dot4_u32_u8(s0: int, s1: int, s2: int = 0, *, clamp: bool = False) -> int: - """Reference mathematical oracle for RDNA2 unsigned 8-bit dot product (v_dot4_u32_u8). - - Calculates: - D = (s2 + sum(s0[i] * s1[i] for i in 0..3)) - Modulo 2^32 without clamp; saturated to 0xFFFFFFFF if clamp is set. - Returns unsigned 32-bit integer in [0, 0xFFFFFFFF]. - """ - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - prod_sum = sum(x * y for x, y in zip(b0, b1)) - acc = s2 & MASK32 - total = acc + prod_sum - - if clamp: - return min(total, UINT32_MAX) +def ref(op, s0, s1, s2, clamp=False): + signed = "i8" in op + def byte(v, i): + x = (v >> (8 * i)) & 0xFF + return x - 256 if signed and x & 0x80 else x + total = sum(byte(s0, i) * byte(s1, i) for i in range(4)) + if signed: + acc = s2 - (1 << 32) if s2 & 0x80000000 else s2 + total += acc + if clamp: + total = max(INT32_MIN, min(INT32_MAX, total)) + else: + total += s2 + if clamp: + total = min(MASK32, total) return total & MASK32 -def ref_dot4acc_u32_u8(s0: int, s1: int, s2: int, *, clamp: bool = False) -> int: - """Reference mathematical oracle for v_dot4acc_u32_u8 accumulating form.""" - return ref_dot4_u32_u8(s0, s1, s2, clamp=clamp) - - -def ref_dot4_i32_i8(s0: int, s1: int, s2: int = 0, *, clamp: bool = False) -> int: - """Reference mathematical oracle for RDNA2 signed 8-bit dot product (v_dot4_i32_i8). - - Calculates: - D = (s2 + sum(s0.i8[i] * s1.i8[i] for i in 0..3)) - where S2 is interpreted as signed 32-bit integer. - Modulo 2^32 without clamp; saturated to [-2^31, 2^31 - 1] if clamp is set. - Returns unsigned 32-bit bit pattern representing the resulting dword. - """ - b0 = unpack_i8(s0) - b1 = unpack_i8(s1) - prod_sum = sum(x * y for x, y in zip(b0, b1)) - - # Interpret s2 as signed 32-bit integer - s2_u32 = s2 & MASK32 - s2_i32 = (s2_u32 - 0x1_0000_0000) if (s2_u32 & 0x8000_0000) else s2_u32 - - total_i64 = s2_i32 + prod_sum - - if clamp: - clamped = max(INT32_MIN, min(total_i64, INT32_MAX)) - return clamped & MASK32 - return total_i64 & MASK32 - - -# --------------------------------------------------------------------------- -# Symbolic AST Opcode Definitions and Typed Expressions -# --------------------------------------------------------------------------- - -class Opcode(Enum): - """VALU opcode enumerations for packed integer dot products.""" - V_DOT4_I32_I8 = "v_dot4_i32_i8" - V_DOT4_U32_U8 = "v_dot4_u32_u8" - V_DOT4ACC_U32_U8 = "v_dot4acc_u32_u8" - V_MOV_B32 = "v_mov_b32_e32" - - -class OperandKind(Enum): - """Operand storage classification.""" - VGPR = auto() - SGPR = auto() - LITERAL = auto() - INLINE_INT = auto() - - -class TypeKind(Enum): - """Data representation types for operands and expressions.""" - I32 = "i32" - U32 = "u32" - I8 = "i8" - U8 = "u8" - - -@dataclass(frozen=True) -class ASTOperand: - """Symbolic instruction operand representation.""" - kind: OperandKind - reg_num: int = 0 - literal_value: int = 0 - type_kind: TypeKind = TypeKind.U32 - - def to_asm(self) -> str: - if self.kind == OperandKind.VGPR: - return f"v{self.reg_num}" - elif self.kind == OperandKind.SGPR: - return f"s{self.reg_num}" - elif self.kind == OperandKind.LITERAL: - if self.literal_value >= 0x1000: - return f"0x{self.literal_value:X}" - return str(self.literal_value) - elif self.kind == OperandKind.INLINE_INT: - return str(self.literal_value) - return "?" - - -@dataclass(frozen=True) -class ASTInstruction: - """Symbolic instruction AST representation.""" - opcode: Opcode - dst: ASTOperand - src0: ASTOperand - src1: ASTOperand - src2: Optional[ASTOperand] = None - clamp: bool = False - - def to_asm(self) -> str: - parts = [self.opcode.value, self.dst.to_asm(), self.src0.to_asm(), self.src1.to_asm()] - if self.src2 is not None: - parts.append(self.src2.to_asm()) - res = f"{parts[0]} {', '.join(parts[1:])}" - if self.clamp: - res += " clamp" - return res - - -@dataclass -class TypedExpr: - """Base class for typed symbolic expressions.""" - type_kind: TypeKind - - -@dataclass -class VariableExpr(TypedExpr): - """Symbolic variable representing a register source.""" - name: str - - -@dataclass -class LiteralExpr(TypedExpr): - """Symbolic literal value.""" - val: int - - -@dataclass -class Dot4ComponentProductExpr(TypedExpr): - """Component product of byte i: src0.byte[i] * src1.byte[i].""" - byte_index: int - left: TypedExpr - right: TypedExpr - - -@dataclass -class Dot4Expr(TypedExpr): - """Full dot4 expression: accumulator + sum(component products), with optional clamp.""" - opcode: Opcode - src0: TypedExpr - src1: TypedExpr - acc: TypedExpr - clamp: bool = False - - -def parse_operand(token: str, default_type: TypeKind = TypeKind.U32) -> ASTOperand: - """Parse an assembly operand token into an ASTOperand.""" - token = token.strip() - if token.startswith("v") and token[1:].isdigit(): - return ASTOperand(kind=OperandKind.VGPR, reg_num=int(token[1:]), type_kind=default_type) - elif token.startswith("s") and token[1:].isdigit(): - return ASTOperand(kind=OperandKind.SGPR, reg_num=int(token[1:]), type_kind=default_type) +def run(op, s0, s1, s2, clamp=False, form="vgpr"): + if form == "vgpr": + setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2:#x}"] + srcs = "v1, v2, v3" else: - # Literal or inline constant - val = int(token, 0) - if -16 <= val <= 64: - return ASTOperand(kind=OperandKind.INLINE_INT, literal_value=val, type_kind=default_type) - return ASTOperand(kind=OperandKind.LITERAL, literal_value=val, type_kind=default_type) - - -def parse_instruction(line: str) -> ASTInstruction: - """Parse a single assembly instruction string into an ASTInstruction.""" - line = line.strip() - if not line or line.startswith("//") or line.startswith(";"): - raise ValueError(f"Empty or comment line cannot be parsed: '{line}'") - - clamp = "clamp" in line.split() - line_clean = re.sub(r"\bclamp\b", "", line).strip() - - tokens = line_clean.split(None, 1) - op_name = tokens[0].lower() - operands_str = tokens[1] if len(tokens) > 1 else "" - - opcode = None - for op in Opcode: - if op.value == op_name: - opcode = op - break - if opcode is None: - raise NotImplementedError(f"Unsupported or unrecognized opcode: '{op_name}'") - - op_parts = [p.strip() for p in operands_str.split(",") if p.strip()] - - if opcode == Opcode.V_MOV_B32: - if len(op_parts) != 2: - raise ValueError(f"v_mov_b32 expects 2 operands, got {len(op_parts)}") - dst = parse_operand(op_parts[0]) - src0 = parse_operand(op_parts[1]) - return ASTInstruction(opcode=opcode, dst=dst, src0=src0, src1=src0, clamp=clamp) - - # v_dot4 instructions: - if opcode == Opcode.V_DOT4_I32_I8: - elem_type = TypeKind.I8 - acc_type = TypeKind.I32 - else: - elem_type = TypeKind.U8 - acc_type = TypeKind.U32 - - if len(op_parts) == 3: - # 3-operand form without accumulator: implicit acc = 0 - dst = parse_operand(op_parts[0], acc_type) - src0 = parse_operand(op_parts[1], elem_type) - src1 = parse_operand(op_parts[2], elem_type) - src2 = ASTOperand(kind=OperandKind.INLINE_INT, literal_value=0, type_kind=acc_type) - return ASTInstruction(opcode=opcode, dst=dst, src0=src0, src1=src1, src2=src2, clamp=clamp) - elif len(op_parts) == 4: - # 4-operand form with explicit accumulator - dst = parse_operand(op_parts[0], acc_type) - src0 = parse_operand(op_parts[1], elem_type) - src1 = parse_operand(op_parts[2], elem_type) - src2 = parse_operand(op_parts[3], acc_type) - return ASTInstruction(opcode=opcode, dst=dst, src0=src0, src1=src1, src2=src2, clamp=clamp) - else: - raise ValueError(f"{opcode.value} expects 3 or 4 operands, got {len(op_parts)}: '{line}'") - - -# --------------------------------------------------------------------------- -# Unit Tests: Phase 1 & Phase 2 -# --------------------------------------------------------------------------- - -class TestValuDot4IntMathematicalOracle(unittest.TestCase): - """Architectural reference mathematical oracle unit tests for v_dot4_int.""" - - def test_u8_basic_vectors(self) -> None: - # 1*5 + 2*6 + 3*7 + 4*8 = 5 + 12 + 21 + 32 = 70 - s0 = pack_u8(1, 2, 3, 4) - s1 = pack_u8(5, 6, 7, 8) - self.assertEqual(ref_dot4_u32_u8(s0, s1, 0), 70) - # With accumulator = 1000 -> 1070 - self.assertEqual(ref_dot4_u32_u8(s0, s1, 1000), 1070) - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, 1000), 1070) - - def test_u8_zero_operands(self) -> None: - s0 = 0x0000_0000 - s1 = 0x1234_5678 - self.assertEqual(ref_dot4_u32_u8(s0, s1, 0xDEAD_BEEF), 0xDEAD_BEEF) - self.assertEqual(ref_dot4_u32_u8(s1, s0, 0xCAFE_BABE), 0xCAFE_BABE) - - def test_u8_maximum_product(self) -> None: - # 4 * (255 * 255) = 4 * 65025 = 260100 (0x3F804) - s0 = 0xFFFF_FFFF - s1 = 0xFFFF_FFFF - self.assertEqual(ref_dot4_u32_u8(s0, s1, 0), 260100) - self.assertEqual(ref_dot4_u32_u8(s0, s1, 100), 260200) - - def test_u8_overflow_wrap_around(self) -> None: - # Wrap around 2^32: (0xFFFFFFFF - 260100 + 1) + 260100 = 0 - s0 = 0xFFFF_FFFF - s1 = 0xFFFF_FFFF - acc = (MASK32 - 260100 + 1) & MASK32 - self.assertEqual(ref_dot4_u32_u8(s0, s1, acc), 0) - - # Overflow by 1 - acc_plus1 = (acc + 1) & MASK32 - self.assertEqual(ref_dot4_u32_u8(s0, s1, acc_plus1), 1) - - def test_u8_clamp_saturation(self) -> None: - s0 = 0xFFFF_FFFF - s1 = 0xFFFF_FFFF - acc = 0xFFFF_0000 - # Without clamp, wraps around - wrapped = ref_dot4_u32_u8(s0, s1, acc, clamp=False) - self.assertLess(wrapped, 0xFFFF_0000) - # With clamp, saturates to UINT32_MAX - clamped = ref_dot4_u32_u8(s0, s1, acc, clamp=True) - self.assertEqual(clamped, UINT32_MAX) - - def test_i8_basic_vectors(self) -> None: - # 1*5 + 2*6 + 3*7 + 4*8 = 70 - s0 = pack_i8(1, 2, 3, 4) - s1 = pack_i8(5, 6, 7, 8) - self.assertEqual(ref_dot4_i32_i8(s0, s1, 0), 70) - self.assertEqual(ref_dot4_i32_i8(s0, s1, 500), 570) - - def test_i8_negative_operands(self) -> None: - # (-1)*5 + 2*(-6) + (-3)*(-7) + (-4)*8 = -5 + -12 + 21 + -32 = -28 - s0 = pack_i8(-1, 2, -3, -4) - s1 = pack_i8(5, -6, -7, 8) - expected = (-28) & MASK32 - self.assertEqual(ref_dot4_i32_i8(s0, s1, 0), expected) - - def test_i8_extremes(self) -> None: - # Max positive product: 4 * ((-128) * (-128)) = 4 * 16384 = 65536 - s_min = pack_i8(-128, -128, -128, -128) - self.assertEqual(ref_dot4_i32_i8(s_min, s_min, 0), 65536) - - # Max negative product: 4 * ((-128) * 127) = 4 * (-16256) = -65024 - s_max = pack_i8(127, 127, 127, 127) - expected_neg = (-65024) & MASK32 - self.assertEqual(ref_dot4_i32_i8(s_min, s_max, 0), expected_neg) - - def test_i8_signed_overflow_and_clamp(self) -> None: - s_min = pack_i8(-128, -128, -128, -128) - # Adding to INT32_MAX without clamp wraps to negative - res_wrap = ref_dot4_i32_i8(s_min, s_min, INT32_MAX, clamp=False) - self.assertTrue(bool(res_wrap & 0x8000_0000)) - - # With clamp, saturates to INT32_MAX - res_clamp_pos = ref_dot4_i32_i8(s_min, s_min, INT32_MAX, clamp=True) - self.assertEqual(res_clamp_pos, INT32_MAX & MASK32) - - # Negative saturation: INT32_MIN + (-65024) saturates to INT32_MIN - s_max = pack_i8(127, 127, 127, 127) - res_clamp_neg = ref_dot4_i32_i8(s_min, s_max, INT32_MIN, clamp=True) - self.assertEqual(res_clamp_neg, INT32_MIN & MASK32) - - def test_divergence_between_signed_and_unsigned(self) -> None: - # 0xFF as unsigned is 255; as signed is -1 - # S0 = [255, 0, 0, 0], S1 = [1, 0, 0, 0] - # Unsigned: 255 * 1 = 255 - # Signed: (-1) * 1 = -1 (0xFFFFFFFF) - s0 = pack_u8(255, 0, 0, 0) - s1 = pack_u8(1, 0, 0, 0) - u_res = ref_dot4_u32_u8(s0, s1, 0) - i_res = ref_dot4_i32_i8(s0, s1, 0) - self.assertEqual(u_res, 255) - self.assertEqual(i_res, 0xFFFF_FFFF) - self.assertNotEqual(u_res, i_res) - - -class TestValuDot4IntSymbolicAST(unittest.TestCase): - """Symbolic AST definitions and typed expression unit tests for v_dot4_int.""" - - def test_ast_parse_v_dot4_i32_i8(self) -> None: - instr = parse_instruction("v_dot4_i32_i8 v0, v1, v2, v3") - self.assertEqual(instr.opcode, Opcode.V_DOT4_I32_I8) - self.assertEqual(instr.dst, ASTOperand(OperandKind.VGPR, reg_num=0, type_kind=TypeKind.I32)) - self.assertEqual(instr.src0, ASTOperand(OperandKind.VGPR, reg_num=1, type_kind=TypeKind.I8)) - self.assertEqual(instr.src1, ASTOperand(OperandKind.VGPR, reg_num=2, type_kind=TypeKind.I8)) - self.assertEqual(instr.src2, ASTOperand(OperandKind.VGPR, reg_num=3, type_kind=TypeKind.I32)) - self.assertFalse(instr.clamp) - - def test_ast_parse_v_dot4_u32_u8_three_operands(self) -> None: - instr = parse_instruction("v_dot4_u32_u8 v5, s2, v3") - self.assertEqual(instr.opcode, Opcode.V_DOT4_U32_U8) - self.assertEqual(instr.dst, ASTOperand(OperandKind.VGPR, reg_num=5, type_kind=TypeKind.U32)) - self.assertEqual(instr.src0, ASTOperand(OperandKind.SGPR, reg_num=2, type_kind=TypeKind.U8)) - self.assertEqual(instr.src1, ASTOperand(OperandKind.VGPR, reg_num=3, type_kind=TypeKind.U8)) - # Default accumulator is literal 0 - self.assertEqual(instr.src2, ASTOperand(OperandKind.INLINE_INT, literal_value=0, type_kind=TypeKind.U32)) - - def test_ast_parse_v_dot4acc_u32_u8_with_clamp(self) -> None: - instr = parse_instruction("v_dot4acc_u32_u8 v10, v11, v12, v10 clamp") - self.assertEqual(instr.opcode, Opcode.V_DOT4ACC_U32_U8) - self.assertEqual(instr.dst.reg_num, 10) - self.assertEqual(instr.src0.reg_num, 11) - self.assertEqual(instr.src1.reg_num, 12) - self.assertEqual(instr.src2.reg_num, 10) - self.assertTrue(instr.clamp) - - def test_ast_parse_literal_and_inline_operands(self) -> None: - instr = parse_instruction("v_dot4_u32_u8 v0, 0x01020304, v1, 100") - self.assertEqual(instr.src0.kind, OperandKind.LITERAL) - self.assertEqual(instr.src0.literal_value, 0x01020304) - self.assertEqual(instr.src2.kind, OperandKind.LITERAL) - self.assertEqual(instr.src2.literal_value, 100) - - def test_ast_roundtrip_formatting(self) -> None: - asm = "v_dot4_i32_i8 v4, v1, v2, v3 clamp" - instr = parse_instruction(asm) - reformatted = instr.to_asm() - self.assertEqual(reformatted, asm) - - def test_ast_typed_expression_nodes(self) -> None: - src0_expr = VariableExpr(TypeKind.I8, "v1") - src1_expr = VariableExpr(TypeKind.I8, "v2") - acc_expr = VariableExpr(TypeKind.I32, "v3") - - expr = Dot4Expr( - type_kind=TypeKind.I32, - opcode=Opcode.V_DOT4_I32_I8, - src0=src0_expr, - src1=src1_expr, - acc=acc_expr, - clamp=True, - ) - self.assertEqual(expr.type_kind, TypeKind.I32) - self.assertTrue(expr.clamp) - - -# --------------------------------------------------------------------------- -# Deterministic Scalar Instruction Interpreter -# --------------------------------------------------------------------------- - -@dataclass -class ScalarRegisterFile: - """Scalar and vector register storage for architectural simulation.""" - vgprs: list[int] = field(default_factory=lambda: [0] * 256) - sgprs: list[int] = field(default_factory=lambda: [0] * 106) - m0: int = 0 - vcc: int = 0 - - def read_operand(self, op: ASTOperand) -> int: - if op.kind == OperandKind.VGPR: - if not (0 <= op.reg_num < 256): - raise IndexError(f"VGPR index out of bounds: v{op.reg_num}") - return self.vgprs[op.reg_num] & MASK32 - elif op.kind == OperandKind.SGPR: - if not (0 <= op.reg_num < 106): - raise IndexError(f"SGPR index out of bounds: s{op.reg_num}") - return self.sgprs[op.reg_num] & MASK32 - elif op.kind in (OperandKind.LITERAL, OperandKind.INLINE_INT): - return op.literal_value & MASK32 - raise ValueError(f"Unknown operand kind: {op.kind}") - - def write_vgpr(self, reg_num: int, val: int) -> None: - if not (0 <= reg_num < 256): - raise IndexError(f"VGPR index out of bounds: v{reg_num}") - self.vgprs[reg_num] = val & MASK32 - - def write_sgpr(self, reg_num: int, val: int) -> None: - if not (0 <= reg_num < 106): - raise IndexError(f"SGPR index out of bounds: s{reg_num}") - self.sgprs[reg_num] = val & MASK32 - - -class Dot4IntScalarInterpreter: - """Deterministic instruction interpreter for VALU dot4 operations.""" - - def __init__(self, rf: Optional[ScalarRegisterFile] = None) -> None: - self.rf = rf if rf is not None else ScalarRegisterFile() - - def step(self, instr: ASTInstruction) -> None: - if instr.dst.kind != OperandKind.VGPR: - raise ValueError(f"VALU instruction destination must be a VGPR, got {instr.dst.kind}") - - if instr.opcode == Opcode.V_MOV_B32: - src_val = self.rf.read_operand(instr.src0) - self.rf.write_vgpr(instr.dst.reg_num, src_val) - return - - s0 = self.rf.read_operand(instr.src0) - s1 = self.rf.read_operand(instr.src1) - s2 = self.rf.read_operand(instr.src2) if instr.src2 is not None else 0 - - if instr.opcode == Opcode.V_DOT4_I32_I8: - result = ref_dot4_i32_i8(s0, s1, s2, clamp=instr.clamp) - elif instr.opcode in (Opcode.V_DOT4_U32_U8, Opcode.V_DOT4ACC_U32_U8): - result = ref_dot4_u32_u8(s0, s1, s2, clamp=instr.clamp) - else: - raise NotImplementedError(f"Unsupported opcode execution: {instr.opcode}") - - self.rf.write_vgpr(instr.dst.reg_num, result) - - def execute_asm(self, asm_lines: list[str]) -> None: - for line in asm_lines: - line = line.strip() - if not line or line.startswith("//") or line.startswith(";"): - continue - instr = parse_instruction(line) - self.step(instr) - - -class TestValuDot4IntScalarInterpreter(unittest.TestCase): - """Deterministic scalar interpreter tests for v_dot4_int.""" - - def test_scalar_v_dot4_u32_u8_execution(self) -> None: - interp = Dot4IntScalarInterpreter() - # Set v1 = [1, 2, 3, 4], v2 = [5, 6, 7, 8], v3 = 100 - interp.rf.write_vgpr(1, pack_u8(1, 2, 3, 4)) - interp.rf.write_vgpr(2, pack_u8(5, 6, 7, 8)) - interp.rf.write_vgpr(3, 100) - - interp.execute_asm(["v_dot4_u32_u8 v0, v1, v2, v3"]) - # Expected: 70 + 100 = 170 - self.assertEqual(interp.rf.vgprs[0], 170) - - def test_scalar_v_dot4_i32_i8_execution(self) -> None: - interp = Dot4IntScalarInterpreter() - # Set v1 = [-1, 2, -3, -4], v2 = [5, -6, -7, 8], v3 = 0 - interp.rf.write_vgpr(1, pack_i8(-1, 2, -3, -4)) - interp.rf.write_vgpr(2, pack_i8(5, -6, -7, 8)) - interp.rf.write_vgpr(3, 0) - - interp.execute_asm(["v_dot4_i32_i8 v0, v1, v2, v3"]) - expected = (-28) & MASK32 - self.assertEqual(interp.rf.vgprs[0], expected) - - def test_scalar_v_dot4acc_u32_u8_accumulation_chain(self) -> None: - interp = Dot4IntScalarInterpreter() - interp.rf.write_vgpr(1, pack_u8(1, 1, 1, 1)) - interp.rf.write_vgpr(2, pack_u8(10, 20, 30, 40)) # sum = 100 - interp.rf.write_vgpr(0, 50) # Initial accumulator - - # Step 1: v0 = 50 + 100 = 150 - interp.execute_asm(["v_dot4acc_u32_u8 v0, v1, v2, v0"]) - self.assertEqual(interp.rf.vgprs[0], 150) - - # Step 2: v0 = 150 + 100 = 250 - interp.execute_asm(["v_dot4acc_u32_u8 v0, v1, v2, v0"]) - self.assertEqual(interp.rf.vgprs[0], 250) - - def test_scalar_sgpr_and_inline_operands(self) -> None: - interp = Dot4IntScalarInterpreter() - interp.rf.write_sgpr(5, pack_u8(2, 2, 2, 2)) - interp.rf.write_vgpr(1, pack_u8(3, 3, 3, 3)) - - # v_dot4_u32_u8 v0, s5, v1, 10 - # 4 * (2 * 3) = 24; 24 + 10 = 34 - interp.execute_asm(["v_dot4_u32_u8 v0, s5, v1, 10"]) - self.assertEqual(interp.rf.vgprs[0], 34) - - def test_scalar_clamp_execution(self) -> None: - interp = Dot4IntScalarInterpreter() - # Max positive product - s_min = pack_i8(-128, -128, -128, -128) - interp.rf.write_vgpr(1, s_min) - interp.rf.write_vgpr(2, s_min) - interp.rf.write_vgpr(3, INT32_MAX) - - interp.execute_asm(["v_dot4_i32_i8 v0, v1, v2, v3 clamp"]) - self.assertEqual(interp.rf.vgprs[0], INT32_MAX & MASK32) - - -# --------------------------------------------------------------------------- -# SIMD Multi-Lane Divergence and 32/64-bit EXEC Masking Model -# --------------------------------------------------------------------------- - -class SIMDWaveState: - """Wavefront SIMD execution state supporting Wave32 and Wave64 execution modes.""" - - def __init__(self, wave_size: int = 32) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size {wave_size}; RDNA2 supports only Wave32 and Wave64") - self.wave_size: int = wave_size - self.exec_mask: int = (1 << wave_size) - 1 - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - self.sgprs: list[int] = [0] * 106 - - def read_operand_for_lane(self, op: ASTOperand, lane: int) -> int: - if op.kind == OperandKind.VGPR: - if not (0 <= op.reg_num < 256): - raise IndexError(f"VGPR index out of bounds: v{op.reg_num}") - return self.vgprs[lane][op.reg_num] & MASK32 - elif op.kind == OperandKind.SGPR: - if not (0 <= op.reg_num < 106): - raise IndexError(f"SGPR index out of bounds: s{op.reg_num}") - return self.sgprs[op.reg_num] & MASK32 - elif op.kind in (OperandKind.LITERAL, OperandKind.INLINE_INT): - return op.literal_value & MASK32 - raise ValueError(f"Unknown operand kind: {op.kind}") - - def write_vgpr_lane(self, lane: int, reg_num: int, val: int) -> None: - if not (0 <= reg_num < 256): - raise IndexError(f"VGPR index out of bounds: v{reg_num}") - self.vgprs[lane][reg_num] = val & MASK32 - - def step(self, instr: ASTInstruction) -> None: - if instr.dst.kind != OperandKind.VGPR: - raise ValueError(f"VALU instruction destination must be a VGPR, got {instr.dst.kind}") - - dst_reg = instr.dst.reg_num - for lane in range(self.wave_size): - # Check if current lane is active in EXEC mask - if not (self.exec_mask & (1 << lane)): - continue - - if instr.opcode == Opcode.V_MOV_B32: - src_val = self.read_operand_for_lane(instr.src0, lane) - self.write_vgpr_lane(lane, dst_reg, src_val) - continue - - s0 = self.read_operand_for_lane(instr.src0, lane) - s1 = self.read_operand_for_lane(instr.src1, lane) - s2 = self.read_operand_for_lane(instr.src2, lane) if instr.src2 is not None else 0 - - if instr.opcode == Opcode.V_DOT4_I32_I8: - res = ref_dot4_i32_i8(s0, s1, s2, clamp=instr.clamp) - elif instr.opcode in (Opcode.V_DOT4_U32_U8, Opcode.V_DOT4ACC_U32_U8): - res = ref_dot4_u32_u8(s0, s1, s2, clamp=instr.clamp) - else: - raise NotImplementedError(f"Unsupported opcode execution: {instr.opcode}") - - self.write_vgpr_lane(lane, dst_reg, res) - - def execute_asm(self, asm_lines: list[str]) -> None: - for line in asm_lines: - line = line.strip() - if not line or line.startswith("//") or line.startswith(";"): - continue - instr = parse_instruction(line) - self.step(instr) - - -class TestValuDot4IntSIMDMultiLane(unittest.TestCase): - """SIMD multi-lane divergence and 32/64-bit EXEC masking unit tests for v_dot4_int.""" - - def test_wave32_uniform_execution(self) -> None: - wave = SIMDWaveState(wave_size=32) - s0 = pack_u8(1, 2, 3, 4) - s1 = pack_u8(5, 6, 7, 8) - # Uniform vector setup across all 32 lanes - for lane in range(32): - wave.write_vgpr_lane(lane, 1, s0) - wave.write_vgpr_lane(lane, 2, s1) - wave.write_vgpr_lane(lane, 3, 100) - - wave.execute_asm(["v_dot4_u32_u8 v0, v1, v2, v3"]) - # All active lanes should have computed 70 + 100 = 170 - for lane in range(32): - self.assertEqual(wave.vgprs[lane][0], 170) - - def test_wave64_uniform_execution(self) -> None: - wave = SIMDWaveState(wave_size=64) - s0 = pack_i8(2, 2, 2, 2) - s1 = pack_i8(3, 3, 3, 3) - for lane in range(64): - wave.write_vgpr_lane(lane, 1, s0) - wave.write_vgpr_lane(lane, 2, s1) - wave.write_vgpr_lane(lane, 3, 0) - - wave.execute_asm(["v_dot4_i32_i8 v0, v1, v2, v3"]) - for lane in range(64): - self.assertEqual(wave.vgprs[lane][0], 24) - - def test_wave32_divergent_alternating_exec_mask(self) -> None: - wave = SIMDWaveState(wave_size=32) - # EXEC mask with alternating active lanes (even lanes active, odd inactive) - wave.exec_mask = 0x5555_5555 - s0 = pack_u8(1, 1, 1, 1) - s1 = pack_u8(2, 2, 2, 2) - - # Pre-fill destination v0 with sentinel value 0xDEADBEEF - for lane in range(32): - wave.write_vgpr_lane(lane, 0, 0xDEAD_BEEF) - wave.write_vgpr_lane(lane, 1, s0) - wave.write_vgpr_lane(lane, 2, s1) - - wave.execute_asm(["v_dot4_u32_u8 v0, v1, v2, 0"]) - # Active even lanes: 4 * (1 * 2) = 8 - # Inactive odd lanes: preserved sentinel 0xDEAD_BEEF - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(wave.vgprs[lane][0], 8, f"Lane {lane} active failed") - else: - self.assertEqual(wave.vgprs[lane][0], 0xDEAD_BEEF, f"Lane {lane} inactive modified") - - def test_wave64_divergent_high_half_exec_mask(self) -> None: - wave = SIMDWaveState(wave_size=64) - # Enable only upper 32 lanes: lanes [32..63] - wave.exec_mask = 0xFFFF_FFFF_0000_0000 - for lane in range(64): - wave.write_vgpr_lane(lane, 0, 0x1111_1111) - wave.write_vgpr_lane(lane, 1, pack_u8(4, 3, 2, 1)) - wave.write_vgpr_lane(lane, 2, pack_u8(1, 2, 3, 4)) - - wave.execute_asm(["v_dot4_u32_u8 v0, v1, v2, 5"]) - # 4*1 + 3*2 + 2*3 + 1*4 = 4 + 6 + 6 + 4 = 20; 20 + 5 = 25 - for lane in range(32): - self.assertEqual(wave.vgprs[lane][0], 0x1111_1111) - for lane in range(32, 64): - self.assertEqual(wave.vgprs[lane][0], 25) - - def test_wave_exec_mask_zero_preservation(self) -> None: - wave = SIMDWaveState(wave_size=32) - wave.exec_mask = 0x0000_0000 - for lane in range(32): - wave.write_vgpr_lane(lane, 0, 0x9999_9999) - wave.write_vgpr_lane(lane, 1, 0xFFFF_FFFF) - wave.write_vgpr_lane(lane, 2, 0xFFFF_FFFF) - - wave.execute_asm(["v_dot4_u32_u8 v0, v1, v2, 0"]) - for lane in range(32): - self.assertEqual(wave.vgprs[lane][0], 0x9999_9999) - - def test_divergent_per_lane_vector_data(self) -> None: - wave = SIMDWaveState(wave_size=32) - # Give each lane distinct inputs based on its lane ID - for lane in range(32): - wave.write_vgpr_lane(lane, 1, pack_u8(lane, 1, 1, 1)) - wave.write_vgpr_lane(lane, 2, pack_u8(2, 2, 2, 2)) - wave.write_vgpr_lane(lane, 3, 10) - - wave.execute_asm(["v_dot4_u32_u8 v0, v1, v2, v3"]) - for lane in range(32): - # (lane * 2) + (1 * 2) + (1 * 2) + (1 * 2) + 10 = 2*lane + 6 + 10 = 2*lane + 16 - expected = (2 * lane) + 16 - self.assertEqual(wave.vgprs[lane][0], expected) - - -# --------------------------------------------------------------------------- -# Register Aliasing and In-Place Operand Preservation Tests -# --------------------------------------------------------------------------- - -class TestValuDot4IntRegisterAliasing(unittest.TestCase): - """Register aliasing, self-overwrite, and in-place operand preservation unit tests.""" - - def test_aliasing_dst_equals_src0(self) -> None: - interp = Dot4IntScalarInterpreter() - # v1 is both destination and src0 - initial_v1 = pack_u8(1, 2, 3, 4) - v2 = pack_u8(10, 20, 30, 40) - interp.rf.write_vgpr(1, initial_v1) - interp.rf.write_vgpr(2, v2) - - # 1*10 + 2*20 + 3*30 + 4*40 = 10 + 40 + 90 + 160 = 300 - interp.execute_asm(["v_dot4_u32_u8 v1, v1, v2, 0"]) - self.assertEqual(interp.rf.vgprs[1], 300) - - def test_aliasing_dst_equals_src1(self) -> None: - interp = Dot4IntScalarInterpreter() - # v2 is both destination and src1 - v1 = pack_i8(-2, 3, -4, 5) - v2 = pack_i8(6, -7, 8, -9) - interp.rf.write_vgpr(1, v1) - interp.rf.write_vgpr(2, v2) - - # (-2)*6 + 3*(-7) + (-4)*8 + 5*(-9) = -12 - 21 - 32 - 45 = -110 - expected = (-110) & MASK32 - interp.execute_asm(["v_dot4_i32_i8 v2, v1, v2, 0"]) - self.assertEqual(interp.rf.vgprs[2], expected) - - def test_aliasing_dst_equals_src2_accumulator(self) -> None: - interp = Dot4IntScalarInterpreter() - # v3 is accumulator and destination: in-place accumulation - v1 = pack_u8(2, 2, 2, 2) - v2 = pack_u8(3, 3, 3, 3) - initial_acc = 500 - interp.rf.write_vgpr(1, v1) - interp.rf.write_vgpr(2, v2) - interp.rf.write_vgpr(3, initial_acc) - - # 4 * (2 * 3) = 24; 500 + 24 = 524 - interp.execute_asm(["v_dot4acc_u32_u8 v3, v1, v2, v3"]) - self.assertEqual(interp.rf.vgprs[3], 524) - - def test_aliasing_dst_equals_src0_and_src1_squared(self) -> None: - interp = Dot4IntScalarInterpreter() - # v1 is dst, src0, and src1: computes self dot-product (squared vector norm) - v1 = pack_u8(3, 4, 5, 6) - interp.rf.write_vgpr(1, v1) - - # 3^2 + 4^2 + 5^2 + 6^2 = 9 + 16 + 25 + 36 = 86; accumulator = 14 -> 100 - interp.execute_asm(["v_dot4_u32_u8 v1, v1, v1, 14"]) - self.assertEqual(interp.rf.vgprs[1], 100) - - def test_full_aliasing_dst_src0_src1_src2(self) -> None: - interp = Dot4IntScalarInterpreter() - # Single register v0 serves as dst, src0, src1, and src2 - # Let v0 initially be packed bytes [2, 2, 2, 2] = 0x02020202 - v0 = pack_u8(2, 2, 2, 2) - interp.rf.write_vgpr(0, v0) - - # Products sum = 4 * (2 * 2) = 16 - # Accumulator value is the entire 32-bit dword 0x02020202 - # Expected = 0x02020202 + 16 = 0x02020212 - interp.execute_asm(["v_dot4acc_u32_u8 v0, v0, v0, v0"]) - self.assertEqual(interp.rf.vgprs[0], 0x0202_0212) - - def test_simd_multi_lane_aliased_accumulation(self) -> None: - wave = SIMDWaveState(wave_size=32) - # Even lanes active, odd inactive - wave.exec_mask = 0x5555_5555 - for lane in range(32): - wave.write_vgpr_lane(lane, 0, 1000) # accumulator & destination - wave.write_vgpr_lane(lane, 1, pack_u8(1, 2, 3, 4)) - wave.write_vgpr_lane(lane, 2, pack_u8(1, 1, 1, 1)) - - # Active lanes: sum = 1+2+3+4 = 10; 1000 + 10 = 1010 - # Inactive lanes: remain 1000 - wave.execute_asm(["v_dot4acc_u32_u8 v0, v1, v2, v0"]) - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(wave.vgprs[lane][0], 1010) - else: - self.assertEqual(wave.vgprs[lane][0], 1000) - - def test_sequential_accumulation_pipeline(self) -> None: - interp = Dot4IntScalarInterpreter() - # Initialize accumulator v0 to 0 - interp.rf.write_vgpr(0, 0) - interp.rf.write_vgpr(1, pack_u8(1, 1, 1, 1)) - interp.rf.write_vgpr(2, pack_u8(2, 2, 2, 2)) - interp.rf.write_vgpr(3, pack_u8(3, 3, 3, 3)) - - # Pipeline: - # 1: v0 += v1 . v2 -> 0 + 4*(1*2) = 8 - # 2: v0 += v2 . v3 -> 8 + 4*(2*3) = 8 + 24 = 32 - # 3: v0 += v1 . v3 -> 32 + 4*(1*3) = 32 + 12 = 44 - pipeline = [ - "v_dot4acc_u32_u8 v0, v1, v2, v0", - "v_dot4acc_u32_u8 v0, v2, v3, v0", - "v_dot4acc_u32_u8 v0, v1, v3, v0", - ] - interp.execute_asm(pipeline) - self.assertEqual(interp.rf.vgprs[0], 44) - - -# --------------------------------------------------------------------------- -# Condition Codes, Status Flags, and Carry/Borrow Generation -# --------------------------------------------------------------------------- - -@dataclass(frozen=True) -class Dot4StatusFlags: - """Architectural status flags and condition codes for dot4 execution.""" - zero: bool - negative: bool - carry_out: bool - overflow: bool - saturated: bool - - -def compute_dot4_u32_status_flags(s0: int, s1: int, s2: int, *, clamp: bool = False) -> Dot4StatusFlags: - """Compute status flags and condition codes for unsigned dot4 (v_dot4_u32_u8).""" - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - prod_sum = sum(x * y for x, y in zip(b0, b1)) - acc = s2 & MASK32 - unclamped_sum = acc + prod_sum - - res = min(unclamped_sum, UINT32_MAX) if clamp else (unclamped_sum & MASK32) - - zero = (res == 0) - negative = bool(res & 0x8000_0000) - carry_out = unclamped_sum > UINT32_MAX - overflow = carry_out - saturated = clamp and (unclamped_sum > UINT32_MAX) - - return Dot4StatusFlags( - zero=zero, - negative=negative, - carry_out=carry_out, - overflow=overflow, - saturated=saturated, - ) - - -def compute_dot4_i32_status_flags(s0: int, s1: int, s2: int, *, clamp: bool = False) -> Dot4StatusFlags: - """Compute status flags and condition codes for signed dot4 (v_dot4_i32_i8).""" - b0 = unpack_i8(s0) - b1 = unpack_i8(s1) - prod_sum = sum(x * y for x, y in zip(b0, b1)) - - s2_u32 = s2 & MASK32 - s2_i32 = (s2_u32 - 0x1_0000_0000) if (s2_u32 & 0x8000_0000) else s2_u32 - - unclamped_total = s2_i32 + prod_sum - clamped_total = max(INT32_MIN, min(unclamped_total, INT32_MAX)) - - res = (clamped_total if clamp else unclamped_total) & MASK32 - - zero = (res == 0) - negative = bool(res & 0x8000_0000) - - # 32-bit unsigned carry from the adder: - adder_u32 = (s2 & MASK32) + (prod_sum & MASK32) - carry_out = adder_u32 > MASK32 - - # Signed overflow occurs if total falls outside 32-bit signed integer range - overflow = unclamped_total < INT32_MIN or unclamped_total > INT32_MAX - saturated = clamp and overflow - - return Dot4StatusFlags( - zero=zero, - negative=negative, - carry_out=carry_out, - overflow=overflow, - saturated=saturated, - ) - - -def evaluate_vcc_predicate(results: list[int], predicate_fn) -> int: - """Evaluate a per-lane condition across wavefront lanes, packing into a VCC mask.""" - vcc = 0 - for lane, val in enumerate(results): - if predicate_fn(val): - vcc |= (1 << lane) - return vcc - - -class TestValuDot4IntConditionCodesAndStatusFlags(unittest.TestCase): - """Status flags, condition codes, and carry/borrow generation unit tests for v_dot4_int.""" - - def test_zero_flag_generation(self) -> None: - # Zero operand dot product - flags_zero = compute_dot4_u32_status_flags(0, 0, 0) - self.assertTrue(flags_zero.zero) - self.assertFalse(flags_zero.negative) - self.assertFalse(flags_zero.carry_out) - - # Non-zero result - flags_nonzero = compute_dot4_u32_status_flags(pack_u8(1, 0, 0, 0), pack_u8(1, 0, 0, 0), 0) - self.assertFalse(flags_nonzero.zero) - - # Signed cancellation to zero: product = +70, accumulator = -70 - s0 = pack_i8(1, 2, 3, 4) - s1 = pack_i8(5, 6, 7, 8) # dot = 70 - acc = (-70) & MASK32 - flags_cancel = compute_dot4_i32_status_flags(s0, s1, acc) - self.assertTrue(flags_cancel.zero) - - def test_negative_flag_generation(self) -> None: - # Signed negative product: -28 - s0 = pack_i8(-1, 2, -3, -4) - s1 = pack_i8(5, -6, -7, 8) - flags_neg = compute_dot4_i32_status_flags(s0, s1, 0) - self.assertTrue(flags_neg.negative) - self.assertFalse(flags_neg.zero) - - # Unsigned large value with bit 31 set: e.g. 0x80000000 - flags_u_high = compute_dot4_u32_status_flags(0, 0, 0x8000_0000) - self.assertTrue(flags_u_high.negative) - - def test_unsigned_carry_out_generation(self) -> None: - # Accumulator near UINT32_MAX, adding 260100 causes carry_out - s0 = 0xFFFF_FFFF - s1 = 0xFFFF_FFFF # product sum = 260100 - flags_carry = compute_dot4_u32_status_flags(s0, s1, 0xFFFF_FFFF) - self.assertTrue(flags_carry.carry_out) - self.assertTrue(flags_carry.overflow) - - # No carry out when sum fits in 32 bits - flags_no_carry = compute_dot4_u32_status_flags(s0, s1, 1000) - self.assertFalse(flags_no_carry.carry_out) - self.assertFalse(flags_no_carry.overflow) - - def test_signed_overflow_generation(self) -> None: - # Adding positive 65536 to INT32_MAX causes signed overflow - s_min = pack_i8(-128, -128, -128, -128) # (-128)^2 * 4 = 65536 - flags_pos_overflow = compute_dot4_i32_status_flags(s_min, s_min, INT32_MAX) - self.assertTrue(flags_pos_overflow.overflow) - self.assertFalse(flags_pos_overflow.saturated) # clamp was False - - # Adding negative -65024 to INT32_MIN causes signed underflow - s_max = pack_i8(127, 127, 127, 127) - flags_neg_underflow = compute_dot4_i32_status_flags(s_min, s_max, INT32_MIN) - self.assertTrue(flags_neg_underflow.overflow) - - # No overflow during ordinary operations - flags_normal = compute_dot4_i32_status_flags(s_min, s_max, 0) - self.assertFalse(flags_normal.overflow) - - def test_saturation_flag_generation(self) -> None: - # Unsigned clamp saturation - flags_u_sat = compute_dot4_u32_status_flags(0xFFFF_FFFF, 0xFFFF_FFFF, 0xFFFF_FFFF, clamp=True) - self.assertTrue(flags_u_sat.saturated) - - # Unsigned clamp without saturation - flags_u_unsat = compute_dot4_u32_status_flags(0xFFFF_FFFF, 0xFFFF_FFFF, 100, clamp=True) - self.assertFalse(flags_u_unsat.saturated) - - # Signed clamp saturation - s_min = pack_i8(-128, -128, -128, -128) - flags_i_sat = compute_dot4_i32_status_flags(s_min, s_min, INT32_MAX, clamp=True) - self.assertTrue(flags_i_sat.saturated) - - def test_vcc_comparison_predicate_generation(self) -> None: - # Multi-lane comparison generating VCC mask - wave = SIMDWaveState(wave_size=32) - for lane in range(32): - wave.write_vgpr_lane(lane, 1, pack_u8(lane, 0, 0, 0)) - wave.write_vgpr_lane(lane, 2, pack_u8(1, 0, 0, 0)) - wave.write_vgpr_lane(lane, 3, 0) - - # Each lane computes: lane * 1 = lane - wave.execute_asm(["v_dot4_u32_u8 v0, v1, v2, v3"]) - lane_results = [wave.vgprs[lane][0] for lane in range(32)] - - # Compare result >= 16: lanes 16..31 should be 1 in VCC - vcc_ge_16 = evaluate_vcc_predicate(lane_results, lambda v: v >= 16) - expected_mask = 0xFFFF_0000 - self.assertEqual(vcc_ge_16, expected_mask) - - -# --------------------------------------------------------------------------- -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling Tests -# --------------------------------------------------------------------------- - -# IEEE 754 binary32 architectural bit patterns for cross-format validation -FLOAT_POS_ZERO: int = 0x0000_0000 -FLOAT_NEG_ZERO: int = 0x8000_0000 -FLOAT_ONE: int = 0x3F80_0000 -FLOAT_NEG_ONE: int = 0xBF80_0000 -FLOAT_POS_INF: int = 0x7F80_0000 -FLOAT_NEG_INF: int = 0xFF80_0000 -FLOAT_CANONICAL_QNAN: int = 0x7FC0_0000 -FLOAT_SNAN: int = 0x7F80_0001 -FLOAT_MIN_SUBNORMAL: int = 0x0000_0001 -FLOAT_MAX_SUBNORMAL: int = 0x007F_FFFF -FLOAT_MAX_NORMAL: int = 0x7F7F_FFFF - - -class TestValuDot4IntIEEE754BoundaryExtremes(unittest.TestCase): - """IEEE 754 floating-point boundary extremes, subnormals, and NaN handling tests for integer dot4.""" - - def test_ieee754_qnan_snan_treated_as_raw_bytes(self) -> None: - # FLOAT_CANONICAL_QNAN = 0x7FC00000 -> bytes: [0x00, 0x00, 0xC0, 0x7F] - # In unsigned u8: [0, 0, 192, 127] - # In signed i8: [0, 0, -64, 127] - # Multiplied by identity vector [1, 1, 1, 1] = 0x01010101 - ident = 0x0101_0101 - - # Unsigned dot4: 0*1 + 0*1 + 192*1 + 127*1 = 319 - u_res = ref_dot4_u32_u8(FLOAT_CANONICAL_QNAN, ident, 0) - self.assertEqual(u_res, 319) - - # Signed dot4: 0*1 + 0*1 + (-64)*1 + 127*1 = 63 - i_res = ref_dot4_i32_i8(FLOAT_CANONICAL_QNAN, ident, 0) - self.assertEqual(i_res, 63) - - # Signaling NaN: 0x7F800001 -> bytes: [0x01, 0x00, 0x80, 0x7F] - # Unsigned: 1*1 + 0*1 + 128*1 + 127*1 = 256 - snan_u = ref_dot4_u32_u8(FLOAT_SNAN, ident, 0) - self.assertEqual(snan_u, 256) - - # Signed: 1*1 + 0*1 + (-128)*1 + 127*1 = 0 - snan_i = ref_dot4_i32_i8(FLOAT_SNAN, ident, 0) - self.assertEqual(snan_i, 0) - - def test_ieee754_infinities_integer_dot_product(self) -> None: - # FLOAT_POS_INF = 0x7F800000 -> bytes: [0x00, 0x00, 0x80, 0x7F] - # FLOAT_NEG_INF = 0xFF800000 -> bytes: [0x00, 0x00, 0x80, 0xFF] - ident = 0x0101_0101 - - # Unsigned POS_INF dot [1,1,1,1] = 128 + 127 = 255 - self.assertEqual(ref_dot4_u32_u8(FLOAT_POS_INF, ident, 0), 255) - - # Unsigned NEG_INF dot [1,1,1,1] = 128 + 255 = 383 - self.assertEqual(ref_dot4_u32_u8(FLOAT_NEG_INF, ident, 0), 383) - - # Signed POS_INF dot [1,1,1,1] = (-128) + 127 = -1 (0xFFFFFFFF) - self.assertEqual(ref_dot4_i32_i8(FLOAT_POS_INF, ident, 0), 0xFFFF_FFFF) - - # Signed NEG_INF dot [1,1,1,1] = (-128) + (-1) = -129 - self.assertEqual(ref_dot4_i32_i8(FLOAT_NEG_INF, ident, 0), (-129) & MASK32) - - def test_ieee754_subnormals_preservation_without_ftz(self) -> None: - # In floating-point units with Flush-To-Zero (FTZ), subnormals are forced to 0. - # In VALU integer dot4, subnormals MUST be preserved as their exact bit patterns! - # FLOAT_MIN_SUBNORMAL = 0x00000001 -> bytes: [1, 0, 0, 0] - # Multiplied by [5, 0, 0, 0] - s0 = FLOAT_MIN_SUBNORMAL - s1 = 0x0000_0005 # bytes: [5, 0, 0, 0] - res = ref_dot4_u32_u8(s0, s1, 0) - self.assertEqual(res, 5) - - # FLOAT_MAX_SUBNORMAL = 0x007FFFFF -> bytes: [0xFF, 0xFF, 0x7F, 0x00] - # Unsigned: [255, 255, 127, 0] . [1, 1, 1, 1] = 255 + 255 + 127 + 0 = 637 - res_max_sub = ref_dot4_u32_u8(FLOAT_MAX_SUBNORMAL, 0x0101_0101, 0) - self.assertEqual(res_max_sub, 637) - - def test_ieee754_negative_zero_sign_bit_differentiation(self) -> None: - # In IEEE 754, +0.0 == -0.0. - # But in integer dot4: - # FLOAT_POS_ZERO = 0x00000000 -> bytes: [0, 0, 0, 0] - # FLOAT_NEG_ZERO = 0x80000000 -> bytes: [0, 0, 0, 0x80] - multiplier = 0x0101_0101 # [1, 1, 1, 1] - - pos_zero_res = ref_dot4_u32_u8(FLOAT_POS_ZERO, multiplier, 0) - neg_zero_res = ref_dot4_u32_u8(FLOAT_NEG_ZERO, multiplier, 0) - - # Unsigned: +0.0 gives 0, -0.0 gives 128 - self.assertEqual(pos_zero_res, 0) - self.assertEqual(neg_zero_res, 128) - self.assertNotEqual(pos_zero_res, neg_zero_res) - - # Signed: +0.0 gives 0, -0.0 gives -128 - pos_zero_i = ref_dot4_i32_i8(FLOAT_POS_ZERO, multiplier, 0) - neg_zero_i = ref_dot4_i32_i8(FLOAT_NEG_ZERO, multiplier, 0) - self.assertEqual(pos_zero_i, 0) - self.assertEqual(neg_zero_i, (-128) & MASK32) - - def test_ieee754_float_max_normal_byte_interaction(self) -> None: - # FLOAT_MAX_NORMAL = 0x7F7FFFFF -> bytes: [0xFF, 0xFF, 0x7F, 0x7F] - # Unsigned: [255, 255, 127, 127] - # Dot with itself: 255^2 + 255^2 + 127^2 + 127^2 = 65025 + 65025 + 16129 + 16129 = 162308 - res = ref_dot4_u32_u8(FLOAT_MAX_NORMAL, FLOAT_MAX_NORMAL, 0) - self.assertEqual(res, 162308) - - # Signed: [-1, -1, 127, 127] - # Dot with itself: (-1)^2 + (-1)^2 + 127^2 + 127^2 = 1 + 1 + 16129 + 16129 = 32260 - res_signed = ref_dot4_i32_i8(FLOAT_MAX_NORMAL, FLOAT_MAX_NORMAL, 0) - self.assertEqual(res_signed, 32260) - - def test_integer_extreme_min_max_signed_matrix(self) -> None: - # Extreme signed matrix: - # S_MIN = [-128, -128, -128, -128] = 0x80808080 - # S_MAX = [ 127, 127, 127, 127] = 0x7F7F7F7F - s_min = 0x8080_8080 - s_max = 0x7F7F_7F7F - - # MIN . MIN = 4 * 16384 = +65536 - self.assertEqual(ref_dot4_i32_i8(s_min, s_min, 0), 65536) - - # MAX . MAX = 4 * 16129 = +64516 - self.assertEqual(ref_dot4_i32_i8(s_max, s_max, 0), 64516) - - # MIN . MAX = 4 * (-16256) = -65024 - self.assertEqual(ref_dot4_i32_i8(s_min, s_max, 0), (-65024) & MASK32) - - def test_integer_extreme_unsigned_overflow_and_saturation(self) -> None: - s_max_u = 0xFFFF_FFFF # [255, 255, 255, 255] - # 4 * (255 * 255) = 260100 - # Wrap at UINT32_MAX - res_wrap = ref_dot4_u32_u8(s_max_u, s_max_u, UINT32_MAX, clamp=False) - self.assertEqual(res_wrap, 260099) - - # Saturation at UINT32_MAX - res_sat = ref_dot4_u32_u8(s_max_u, s_max_u, UINT32_MAX, clamp=True) - self.assertEqual(res_sat, UINT32_MAX) - - -# --------------------------------------------------------------------------- -# Negative Controls, Syntax Rejection, and Mutation Detection Tests -# --------------------------------------------------------------------------- - -class TestValuDot4IntNegativeControls(unittest.TestCase): - """Negative controls, syntax rejection, and mutation detection unit tests.""" - - def test_rejection_of_sgpr_as_valu_destination(self) -> None: - interp = Dot4IntScalarInterpreter() - # VALU cannot write to an SGPR destination - with self.assertRaises(ValueError): - interp.execute_asm(["v_dot4_u32_u8 s0, v1, v2, v3"]) - - def test_rejection_of_out_of_bounds_registers(self) -> None: - interp = Dot4IntScalarInterpreter() - # VGPR >= 256 - with self.assertRaises(IndexError): - interp.rf.read_operand(ASTOperand(kind=OperandKind.VGPR, reg_num=256)) - # SGPR >= 106 - with self.assertRaises(IndexError): - interp.rf.read_operand(ASTOperand(kind=OperandKind.SGPR, reg_num=106)) - - def test_rejection_of_unrecognized_opcode(self) -> None: - with self.assertRaises(NotImplementedError): - parse_instruction("v_dot4_unknown_op v0, v1, v2, v3") - - def test_rejection_of_malformed_instruction_syntax(self) -> None: - # Too few operands - with self.assertRaises(ValueError): - parse_instruction("v_dot4_u32_u8 v0, v1") - # Empty instruction - with self.assertRaises(ValueError): - parse_instruction("") - - def test_rejection_of_invalid_wave_size(self) -> None: - # Only wave32 and wave64 are valid in RDNA2 - with self.assertRaises(ValueError): - SIMDWaveState(wave_size=16) - with self.assertRaises(ValueError): - SIMDWaveState(wave_size=128) - - def test_mutation_bit_flip_sensitivity(self) -> None: - # Every bit flip in S0 or S1 should produce a distinct result for non-zero multiplier - s0 = pack_u8(10, 20, 30, 40) - s1 = pack_u8(1, 2, 3, 4) - acc = 100 - baseline = ref_dot4_u32_u8(s0, s1, acc) - - # Perturb each of the 32 bits of s0 individually - for bit_pos in range(32): - s0_mutated = s0 ^ (1 << bit_pos) - mutated_res = ref_dot4_u32_u8(s0_mutated, s1, acc) - self.assertNotEqual( - mutated_res, - baseline, - f"Bit flip at bit {bit_pos} failed to perturb output", - ) - - def test_mutation_byte_endianness_divergence(self) -> None: - # Swapping byte 0 and byte 1 in s0 must produce divergent dot product when s1 has different multipliers - s0 = pack_u8(10, 20, 30, 40) - s1 = pack_u8(1, 5, 1, 1) # byte 0 weight = 1, byte 1 weight = 5 - base_dot = ref_dot4_u32_u8(s0, s1, 0) - - # Mutate endianness: swap byte 0 and byte 1 - s0_swapped = pack_u8(20, 10, 30, 40) - mutated_dot = ref_dot4_u32_u8(s0_swapped, s1, 0) - self.assertNotEqual(base_dot, mutated_dot) - - def test_mutation_signedness_divergence_detection(self) -> None: - # Treating negative i8 values as u8 must strongly diverge - s0 = pack_i8(-1, -2, -3, -4) - s1 = pack_i8(1, 1, 1, 1) - - signed_res = ref_dot4_i32_i8(s0, s1, 0) - unsigned_res = ref_dot4_u32_u8(s0, s1, 0) - - # Signed: (-1) + (-2) + (-3) + (-4) = -10 (0xFFFFFFF6) - # Unsigned: 255 + 254 + 253 + 252 = 1014 - self.assertEqual(signed_res, (-10) & MASK32) - self.assertEqual(unsigned_res, 1014) - self.assertNotEqual(signed_res, unsigned_res) + setup = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2:#x}"] + srcs = "s1, s2, s3" + lines = setup + [f"{op} v0, {srcs}{' clamp' if clamp else ''}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_dot4", lines))[0] + + +# (name, op, S0, S1, S2, clamp, expected word), written by hand. +CASES = [ + ("u8 basic: 1*5+2*6+3*7+4*8", "v_dot4_u32_u8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 0, False, 70), + ("u8 basic with accumulator", "v_dot4_u32_u8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 1000, False, 1070), + ("u8 zero operand keeps S2", "v_dot4_u32_u8", 0, 0x12345678, 0xDEADBEEF, False, 0xDEADBEEF), + ("u8 zero operand keeps S2 (swapped)", "v_dot4_u32_u8", 0x12345678, 0, 0xCAFEBABE, False, 0xCAFEBABE), + ("u8 maximum: 4*255*255", "v_dot4_u32_u8", MASK32, MASK32, 0, False, 260100), + ("u8 maximum plus 100", "v_dot4_u32_u8", MASK32, MASK32, 100, False, 260200), + ("u8 wraps to 0", "v_dot4_u32_u8", MASK32, MASK32, 0xFFFC07FC, False, 0), + ("u8 wraps to 1", "v_dot4_u32_u8", MASK32, MASK32, 0xFFFC07FD, False, 1), + ("u8 wraps without clamp", "v_dot4_u32_u8", MASK32, MASK32, 0xFFFF0000, False, 0x0002F804), + ("u8 clamp saturates", "v_dot4_u32_u8", MASK32, MASK32, 0xFFFF0000, True, 0xFFFFFFFF), + ("i8 basic", "v_dot4_i32_i8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 0, False, 70), + ("i8 basic with accumulator", "v_dot4_i32_i8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 500, False, 570), + ("i8 mixed signs: -5-12+21-32", "v_dot4_i32_i8", pk(-1, 2, -3, -4), pk(5, -6, -7, 8), 0, False, 0xFFFFFFE4), + ("i8 max positive: 4*(-128)^2", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(-128, -128, -128, -128), 0, False, 65536), + ("i8 max negative: 4*(-128*127)", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(127, 127, 127, 127), 0, False, 0xFFFF0200), + ("i8 wraps negative", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(-128, -128, -128, -128), INT32_MAX, False, 0x8000FFFF), + ("i8 clamp to INT32_MAX", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(-128, -128, -128, -128), INT32_MAX, True, 0x7FFFFFFF), + ("i8 clamp to INT32_MIN", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(127, 127, 127, 127), 0x80000000, True, 0x80000000), + ("0xFF is 255 unsigned", "v_dot4_u32_u8", pk(255, 0, 0, 0), pk(1, 0, 0, 0), 0, False, 255), + ("0xFF is -1 signed", "v_dot4_i32_i8", pk(255, 0, 0, 0), pk(1, 0, 0, 0), 0, False, 0xFFFFFFFF), +] + + +class Dot4Int(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for name, op, s0, s1, s2, clamp, want in CASES: + self.assertEqual(ref(op, s0, s1, s2, clamp), want, name) + + def test_translated_cases(self): + for name, op, s0, s1, s2, clamp, want in CASES: + with self.subTest(name): + self.assertEqual(run(op, s0, s1, s2, clamp), want) + + def test_sgpr_sources(self): + for name, op, s0, s1, s2, clamp, want in CASES[:6] + CASES[10:13]: + with self.subTest(name): + self.assertEqual(run(op, s0, s1, s2, clamp, "sgpr"), want) + + def test_random_operands(self): + rng = random.Random(0x646F7434) + for _ in range(40): + s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) + for op in ("v_dot4_u32_u8", "v_dot4_i32_i8"): + for clamp in (False, True): + with self.subTest(op=op, clamp=clamp, s0=hex(s0), s1=hex(s1), s2=hex(s2)): + self.assertEqual(run(op, s0, s1, s2, clamp), ref(op, s0, s1, s2, clamp)) + + def test_dot4acc_is_refused_not_guessed(self): + with self.assertRaises(Unsupported): + run("v_dot4acc_u32_u8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 1000) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_dot8_int.py b/tests/semantic/test_valu_dot8_int.py index fe9913c48..fb3b94184 100644 --- a/tests/semantic/test_valu_dot8_int.py +++ b/tests/semantic/test_valu_dot8_int.py @@ -1,1124 +1,111 @@ -from __future__ import annotations +"""v_dot8_u32_u4 and v_dot8_i32_i4 (RDNA2 VOP3P): D = S2 + sum of the eight nibble products of S0 and S1 (unsigned +nibbles for u4, signed for i4), modulo 2^32; with `clamp` the result saturates to [0, 2^32-1] (u4) or +[-2^31, 2^31-1] (i4). -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_dot8_int opcodes. - -This module provides an architectural reference model and semantic test suite for RDNA2 -VALU packed 4-bit integer dot product instructions: - - v_dot8_i32_i4 (VOP3/VOP3P): Signed 4-bit integer 8-vector dot product: - D.i32 = S2.i32 + sum(S0.i4[i] * S1.i4[i] for i in 0..7) mod 2^32 - - v_dot8_u32_u4 (VOP3/VOP3P): Unsigned 4-bit integer 8-vector dot product: - D.u32 = S2.u32 + sum(S0.u4[i] * S1.u4[i] for i in 0..7) mod 2^32 - -ISA Specifications (RDNA2 / GFX10.3+): - - Each 32-bit dword S0 and S1 contains eight packed 4-bit nibbles: - Nibble 0: bits [3:0] - Nibble 1: bits [7:4] - Nibble 2: bits [11:8] - Nibble 3: bits [15:12] - Nibble 4: bits [19:16] - Nibble 5: bits [23:20] - Nibble 6: bits [27:24] - Nibble 7: bits [31:28] - - In v_dot8_i32_i4, each nibble is treated as signed 2's complement int4 in [-8, +7]. - Each component product S0.i4[i] * S1.i4[i] is in [-56, +64]. - The eight products sum to [-448, +512], which is added to 32-bit accumulator S2 - and wrapped modulo 2^32 (or clamped to [-2^31, 2^31 - 1] if clamp is asserted). - - In v_dot8_u32_u4, each nibble is treated as unsigned uint4 in [0, 15]. - Each component product S0.u4[i] * S1.u4[i] is in [0, 225]. - The eight products sum to [0, 1800], which is added to 32-bit accumulator S2 - and wrapped modulo 2^32 (or clamped to [0, 0xFFFFFFFF] if clamp is asserted). - -Standard library Python only; zero third-party dependencies. -Python 3.9+ compatible. +Each case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +words are written by hand and also recomputed by a plain-Python reference. Standard library only: no GPU, no LLVM, +no game data. """ - -import struct -from typing import Tuple +import os +import random +import sys import unittest -# Bitmask and architectural boundary constants -MASK4: int = 0xF -MASK32: int = 0xFFFF_FFFF -SIGN4_BIT: int = 0x8 -INT32_MIN: int = -0x8000_0000 -INT32_MAX: int = 0x7FFF_FFFF -UINT32_MAX: int = 0xFFFF_FFFF +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) + +import support # noqa: E402 + +MASK32 = 0xFFFFFFFF +INT32_MIN, INT32_MAX = -0x80000000, 0x7FFFFFFF -def unpack_u4(dword: int) -> Tuple[int, int, int, int, int, int, int, int]: - """Unpack a 32-bit dword into eight unsigned 4-bit integers (nibble 0 to 7).""" - val = dword & MASK32 - return ( - val & MASK4, - (val >> 4) & MASK4, - (val >> 8) & MASK4, - (val >> 12) & MASK4, - (val >> 16) & MASK4, - (val >> 20) & MASK4, - (val >> 24) & MASK4, - (val >> 28) & MASK4, - ) +def pk(*n): + """Pack eight nibbles, nibble 0 first, into a dword.""" + return sum((x & 0xF) << (4 * i) for i, x in enumerate(n)) -def pack_u4(n0: int, n1: int, n2: int, n3: int, n4: int, n5: int, n6: int, n7: int) -> int: - """Pack eight unsigned 4-bit integers into a 32-bit dword.""" - return ( - (n0 & MASK4) - | ((n1 & MASK4) << 4) - | ((n2 & MASK4) << 8) - | ((n3 & MASK4) << 12) - | ((n4 & MASK4) << 16) - | ((n5 & MASK4) << 20) - | ((n6 & MASK4) << 24) - | ((n7 & MASK4) << 28) - ) & MASK32 - - -def unpack_i4(dword: int) -> Tuple[int, int, int, int, int, int, int, int]: - """Unpack a 32-bit dword into eight signed 4-bit integers (-8 to +7).""" - raw_nibbles = unpack_u4(dword) - return tuple((n - 16) if (n & SIGN4_BIT) else n for n in raw_nibbles) # type: ignore[return-value] - - -def pack_i4(n0: int, n1: int, n2: int, n3: int, n4: int, n5: int, n6: int, n7: int) -> int: - """Pack eight signed 4-bit integers into a 32-bit dword.""" - return pack_u4( - n0 & MASK4, - n1 & MASK4, - n2 & MASK4, - n3 & MASK4, - n4 & MASK4, - n5 & MASK4, - n6 & MASK4, - n7 & MASK4, - ) - - -def ref_dot8_u32_u4(s0: int, s1: int, s2: int = 0, *, clamp: bool = False) -> int: - """Reference mathematical oracle for RDNA2 unsigned 4-bit dot product (v_dot8_u32_u4). - - Calculates: - D = (s2 + sum(s0[i] * s1[i] for i in 0..7)) - Modulo 2^32 without clamp; saturated to 0xFFFFFFFF if clamp is set. - Returns unsigned 32-bit integer in [0, 0xFFFFFFFF]. - """ - n0 = unpack_u4(s0) - n1 = unpack_u4(s1) - prod_sum = sum(x * y for x, y in zip(n0, n1)) - acc = s2 & MASK32 - total = acc + prod_sum - - if clamp: - return min(total, UINT32_MAX) +def ref(op, s0, s1, s2, clamp=False): + signed = "i4" in op + def nib(v, i): + x = (v >> (4 * i)) & 0xF + return x - 16 if signed and x & 8 else x + total = sum(nib(s0, i) * nib(s1, i) for i in range(8)) + if signed: + total += s2 - (1 << 32) if s2 & 0x80000000 else s2 + if clamp: + total = max(INT32_MIN, min(INT32_MAX, total)) + else: + total += s2 + if clamp: + total = min(MASK32, total) return total & MASK32 -def ref_dot8_i32_i4(s0: int, s1: int, s2: int = 0, *, clamp: bool = False) -> int: - """Reference mathematical oracle for RDNA2 signed 4-bit dot product (v_dot8_i32_i4). - - Calculates: - D = (s2 + sum(s0.i4[i] * s1.i4[i] for i in 0..7)) - where S2 is interpreted as signed 32-bit integer. - Modulo 2^32 without clamp; saturated to [-2^31, 2^31 - 1] if clamp is set. - Returns unsigned 32-bit bit pattern representing the resulting dword. - """ - n0 = unpack_i4(s0) - n1 = unpack_i4(s1) - prod_sum = sum(x * y for x, y in zip(n0, n1)) - - # Interpret s2 as signed 32-bit integer - s2_u32 = s2 & MASK32 - s2_i32 = (s2_u32 - 0x1_0000_0000) if (s2_u32 & 0x8000_0000) else s2_u32 - - total_i64 = s2_i32 + prod_sum - - if clamp: - clamped = max(INT32_MIN, min(total_i64, INT32_MAX)) - return clamped & MASK32 - return total_i64 & MASK32 - - -class TestValuDot8IntMathematicalOracle(unittest.TestCase): - """Architectural reference mathematical oracle unit tests for v_dot8_int.""" - - def test_u4_basic_vectors(self) -> None: - # Sum 0*1 + 1*2 + 2*3 + 3*4 + 4*5 + 5*6 + 6*7 + 7*8 - # = 0 + 2 + 6 + 12 + 20 + 30 + 42 + 56 = 168 - s0 = pack_u4(0, 1, 2, 3, 4, 5, 6, 7) - s1 = pack_u4(1, 2, 3, 4, 5, 6, 7, 8) - self.assertEqual(ref_dot8_u32_u4(s0, s1, 0), 168) - # With accumulator = 500 -> 668 - self.assertEqual(ref_dot8_u32_u4(s0, s1, 500), 668) - - def test_u4_zero_operands(self) -> None: - s0 = 0x0000_0000 - s1 = 0x1234_5678 - self.assertEqual(ref_dot8_u32_u4(s0, s1, 0x1234_ABCD), 0x1234_ABCD) - self.assertEqual(ref_dot8_u32_u4(s1, s0, 0xCAFE_BABE), 0xCAFE_BABE) - - def test_u4_maximum_product(self) -> None: - # 8 * (15 * 15) = 8 * 225 = 1800 - s0 = 0xFFFF_FFFF - s1 = 0xFFFF_FFFF - self.assertEqual(ref_dot8_u32_u4(s0, s1, 0), 1800) - self.assertEqual(ref_dot8_u32_u4(s0, s1, 200), 2000) - - def test_u4_overflow_wrap_around(self) -> None: - # Wrap around 2^32: (0xFFFFFFFF - 1800 + 1) + 1800 = 0 - s0 = 0xFFFF_FFFF - s1 = 0xFFFF_FFFF - acc = (MASK32 - 1800 + 1) & MASK32 - self.assertEqual(ref_dot8_u32_u4(s0, s1, acc), 0) - - # Overflow by 1 - acc_plus1 = (acc + 1) & MASK32 - self.assertEqual(ref_dot8_u32_u4(s0, s1, acc_plus1), 1) - - def test_u4_clamp_saturation(self) -> None: - s0 = 0xFFFF_FFFF - s1 = 0xFFFF_FFFF - acc = 0xFFFF_FFF0 - # Without clamp, wraps around - wrapped = ref_dot8_u32_u4(s0, s1, acc, clamp=False) - self.assertLess(wrapped, 0xFFFF_FFF0) - # With clamp, saturates to UINT32_MAX - clamped = ref_dot8_u32_u4(s0, s1, acc, clamp=True) - self.assertEqual(clamped, UINT32_MAX) - - def test_i4_basic_vectors(self) -> None: - s0 = pack_i4(1, 2, 3, 4, -1, -2, -3, -4) - s1 = pack_i4(1, 1, 1, 1, 1, 1, 1, 1) - # Sum: 1+2+3+4 + (-1)+(-2)+(-3)+(-4) = 0 - self.assertEqual(ref_dot8_i32_i4(s0, s1, 0), 0) - self.assertEqual(ref_dot8_i32_i4(s0, s1, 77), 77) - - def test_i4_negative_operands(self) -> None: - # All negative: [-1, -2, -3, -4, -1, -2, -3, -4] - s0 = pack_i4(-1, -2, -3, -4, -1, -2, -3, -4) - s1 = pack_i4(2, 2, 2, 2, 2, 2, 2, 2) - # Sum = 2 * (-20) = -40 - expected = (-40) & MASK32 - self.assertEqual(ref_dot8_i32_i4(s0, s1, 0), expected) - - def test_i4_extremes(self) -> None: - # Max positive product: 8 * ((-8) * (-8)) = 8 * 64 = +512 - s_min = pack_i4(-8, -8, -8, -8, -8, -8, -8, -8) - self.assertEqual(ref_dot8_i32_i4(s_min, s_min, 0), 512) - - # Max negative product: 8 * ((-8) * 7) = 8 * (-56) = -448 - s_max = pack_i4(7, 7, 7, 7, 7, 7, 7, 7) - expected_neg = (-448) & MASK32 - self.assertEqual(ref_dot8_i32_i4(s_min, s_max, 0), expected_neg) - - def test_i4_signed_overflow_and_clamp(self) -> None: - s_min = pack_i4(-8, -8, -8, -8, -8, -8, -8, -8) - # Adding +512 to INT32_MAX without clamp wraps to negative - res_wrap = ref_dot8_i32_i4(s_min, s_min, INT32_MAX, clamp=False) - self.assertTrue(bool(res_wrap & 0x8000_0000)) - - # With clamp, saturates to INT32_MAX - res_clamp_pos = ref_dot8_i32_i4(s_min, s_min, INT32_MAX, clamp=True) - self.assertEqual(res_clamp_pos, INT32_MAX & MASK32) - - # Negative saturation: INT32_MIN + (-448) saturates to INT32_MIN - s_max = pack_i4(7, 7, 7, 7, 7, 7, 7, 7) - res_clamp_neg = ref_dot8_i32_i4(s_min, s_max, INT32_MIN, clamp=True) - self.assertEqual(res_clamp_neg, INT32_MIN & MASK32) - - def test_divergence_between_signed_and_unsigned(self) -> None: - # Nibble 0xF is 15 in unsigned; -1 in signed - # S0 = [15, 0, ...], S1 = [1, 0, ...] - s0 = pack_u4(15, 0, 0, 0, 0, 0, 0, 0) - s1 = pack_u4(1, 0, 0, 0, 0, 0, 0, 0) - u_res = ref_dot8_u32_u4(s0, s1, 0) - i_res = ref_dot8_i32_i4(s0, s1, 0) - self.assertEqual(u_res, 15) - self.assertEqual(i_res, 0xFFFF_FFFF) # -1 in 32-bit dword - self.assertNotEqual(u_res, i_res) - - -# --------------------------------------------------------------------------- -# Symbolic AST Opcode Definitions and Typed Expressions -# --------------------------------------------------------------------------- - -from dataclasses import dataclass, field -from enum import Enum, auto -import re -from typing import Optional, Union, List - - -class Opcode(Enum): - """VALU opcode enumerations for packed 4-bit integer dot products.""" - V_DOT8_I32_I4 = "v_dot8_i32_i4" - V_DOT8_U32_U4 = "v_dot8_u32_u4" - V_MOV_B32 = "v_mov_b32_e32" - - -class OperandKind(Enum): - """Operand storage classification.""" - VGPR = auto() - SGPR = auto() - LITERAL = auto() - INLINE_INT = auto() - - -class TypeKind(Enum): - """Data representation types for operands and expressions.""" - I32 = "i32" - U32 = "u32" - I4 = "i4" - U4 = "u4" - - -@dataclass(frozen=True) -class ASTOperand: - """Symbolic instruction operand representation.""" - kind: OperandKind - reg_num: int = 0 - literal_value: int = 0 - type_kind: TypeKind = TypeKind.U32 - - def to_asm(self) -> str: - if self.kind == OperandKind.VGPR: - return f"v{self.reg_num}" - elif self.kind == OperandKind.SGPR: - return f"s{self.reg_num}" - elif self.kind == OperandKind.LITERAL: - if self.literal_value >= 0x1000: - return f"0x{self.literal_value:X}" - return str(self.literal_value) - elif self.kind == OperandKind.INLINE_INT: - return str(self.literal_value) - return "?" - - -@dataclass(frozen=True) -class ASTInstruction: - """Symbolic instruction AST representation.""" - opcode: Opcode - dst: ASTOperand - src0: ASTOperand - src1: ASTOperand - src2: Optional[ASTOperand] = None - clamp: bool = False - - def to_asm(self) -> str: - parts = [self.opcode.value, self.dst.to_asm(), self.src0.to_asm(), self.src1.to_asm()] - if self.src2 is not None: - parts.append(self.src2.to_asm()) - res = f"{parts[0]} {', '.join(parts[1:])}" - if self.clamp: - res += " clamp" - return res - - -@dataclass -class TypedExpr: - """Base class for typed symbolic expressions.""" - type_kind: TypeKind - - -@dataclass -class VariableExpr(TypedExpr): - """Symbolic variable representing a register source.""" - name: str - - -@dataclass -class LiteralExpr(TypedExpr): - """Symbolic literal value.""" - val: int - - -@dataclass -class Dot8ComponentProductExpr(TypedExpr): - """Component product of nibble i: src0.nibble[i] * src1.nibble[i].""" - nibble_index: int - left: TypedExpr - right: TypedExpr - - -@dataclass -class Dot8Expr(TypedExpr): - """Full dot8 expression: accumulator + sum(component products), with optional clamp.""" - opcode: Opcode - src0: TypedExpr - src1: TypedExpr - acc: TypedExpr - clamp: bool = False - - -def parse_operand(token: str, default_type: TypeKind = TypeKind.U32) -> ASTOperand: - """Parse an assembly operand token into an ASTOperand.""" - token = token.strip() - if token.startswith("v") and token[1:].isdigit(): - return ASTOperand(kind=OperandKind.VGPR, reg_num=int(token[1:]), type_kind=default_type) - elif token.startswith("s") and token[1:].isdigit(): - return ASTOperand(kind=OperandKind.SGPR, reg_num=int(token[1:]), type_kind=default_type) +def run(op, s0, s1, s2, clamp=False, form="vgpr"): + if form == "vgpr": + setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2:#x}"] + srcs = "v1, v2, v3" else: - val = int(token, 0) - if -16 <= val <= 64: - return ASTOperand(kind=OperandKind.INLINE_INT, literal_value=val, type_kind=default_type) - return ASTOperand(kind=OperandKind.LITERAL, literal_value=val, type_kind=default_type) - - -def parse_instruction(line: str) -> ASTInstruction: - """Parse a single assembly instruction string into an ASTInstruction.""" - line = line.strip() - if not line or line.startswith("//") or line.startswith(";"): - raise ValueError(f"Empty or comment line cannot be parsed: '{line}'") - - clamp = "clamp" in line.split() - line_clean = re.sub(r"\bclamp\b", "", line).strip() - - tokens = line_clean.split(None, 1) - op_name = tokens[0].lower() - operands_str = tokens[1] if len(tokens) > 1 else "" - - opcode = None - for op in Opcode: - if op.value == op_name: - opcode = op - break - if opcode is None: - raise NotImplementedError(f"Unsupported or unrecognized opcode: '{op_name}'") - - op_parts = [p.strip() for p in operands_str.split(",") if p.strip()] - - if opcode == Opcode.V_MOV_B32: - if len(op_parts) != 2: - raise ValueError(f"v_mov_b32 expects 2 operands, got {len(op_parts)}") - dst = parse_operand(op_parts[0]) - src0 = parse_operand(op_parts[1]) - return ASTInstruction(opcode=opcode, dst=dst, src0=src0, src1=src0, clamp=clamp) - - if opcode == Opcode.V_DOT8_I32_I4: - elem_type = TypeKind.I4 - acc_type = TypeKind.I32 - else: - elem_type = TypeKind.U4 - acc_type = TypeKind.U32 - - if len(op_parts) == 3: - dst = parse_operand(op_parts[0], acc_type) - src0 = parse_operand(op_parts[1], elem_type) - src1 = parse_operand(op_parts[2], elem_type) - src2 = ASTOperand(kind=OperandKind.INLINE_INT, literal_value=0, type_kind=acc_type) - return ASTInstruction(opcode=opcode, dst=dst, src0=src0, src1=src1, src2=src2, clamp=clamp) - elif len(op_parts) == 4: - dst = parse_operand(op_parts[0], acc_type) - src0 = parse_operand(op_parts[1], elem_type) - src1 = parse_operand(op_parts[2], elem_type) - src2 = parse_operand(op_parts[3], acc_type) - return ASTInstruction(opcode=opcode, dst=dst, src0=src0, src1=src1, src2=src2, clamp=clamp) - else: - raise ValueError(f"{opcode.value} expects 3 or 4 operands, got {len(op_parts)}: '{line}'") - - -class TestValuDot8IntSymbolicAST(unittest.TestCase): - """Symbolic AST definitions and typed expression unit tests for v_dot8_int.""" - - def test_ast_parse_v_dot8_i32_i4(self) -> None: - instr = parse_instruction("v_dot8_i32_i4 v0, v1, v2, v3") - self.assertEqual(instr.opcode, Opcode.V_DOT8_I32_I4) - self.assertEqual(instr.dst, ASTOperand(OperandKind.VGPR, reg_num=0, type_kind=TypeKind.I32)) - self.assertEqual(instr.src0, ASTOperand(OperandKind.VGPR, reg_num=1, type_kind=TypeKind.I4)) - self.assertEqual(instr.src1, ASTOperand(OperandKind.VGPR, reg_num=2, type_kind=TypeKind.I4)) - self.assertEqual(instr.src2, ASTOperand(OperandKind.VGPR, reg_num=3, type_kind=TypeKind.I32)) - self.assertFalse(instr.clamp) - - def test_ast_parse_v_dot8_u32_u4_three_operands(self) -> None: - instr = parse_instruction("v_dot8_u32_u4 v5, s2, v3") - self.assertEqual(instr.opcode, Opcode.V_DOT8_U32_U4) - self.assertEqual(instr.dst, ASTOperand(OperandKind.VGPR, reg_num=5, type_kind=TypeKind.U32)) - self.assertEqual(instr.src0, ASTOperand(OperandKind.SGPR, reg_num=2, type_kind=TypeKind.U4)) - self.assertEqual(instr.src1, ASTOperand(OperandKind.VGPR, reg_num=3, type_kind=TypeKind.U4)) - self.assertEqual(instr.src2, ASTOperand(OperandKind.INLINE_INT, literal_value=0, type_kind=TypeKind.U32)) - - def test_ast_parse_with_clamp(self) -> None: - instr = parse_instruction("v_dot8_u32_u4 v10, v11, v12, v13 clamp") - self.assertEqual(instr.opcode, Opcode.V_DOT8_U32_U4) - self.assertEqual(instr.dst.reg_num, 10) - self.assertTrue(instr.clamp) - - def test_ast_roundtrip_formatting(self) -> None: - asm = "v_dot8_i32_i4 v4, v1, v2, v3 clamp" - instr = parse_instruction(asm) - self.assertEqual(instr.to_asm(), asm) - - def test_ast_typed_expression_nodes(self) -> None: - src0_expr = VariableExpr(TypeKind.I4, "v1") - src1_expr = VariableExpr(TypeKind.I4, "v2") - acc_expr = VariableExpr(TypeKind.I32, "v3") - - expr = Dot8Expr( - type_kind=TypeKind.I32, - opcode=Opcode.V_DOT8_I32_I4, - src0=src0_expr, - src1=src1_expr, - acc=acc_expr, - clamp=True, - ) - self.assertEqual(expr.type_kind, TypeKind.I32) - self.assertTrue(expr.clamp) - - -# --------------------------------------------------------------------------- -# Deterministic Scalar Instruction Interpreter -# --------------------------------------------------------------------------- - -@dataclass -class ScalarRegisterFile: - """Scalar and vector register storage for architectural simulation.""" - vgprs: list[int] = field(default_factory=lambda: [0] * 256) - sgprs: list[int] = field(default_factory=lambda: [0] * 106) - m0: int = 0 - vcc: int = 0 - - def read_operand(self, op: ASTOperand) -> int: - if op.kind == OperandKind.VGPR: - if not (0 <= op.reg_num < 256): - raise IndexError(f"VGPR index out of bounds: v{op.reg_num}") - return self.vgprs[op.reg_num] & MASK32 - elif op.kind == OperandKind.SGPR: - if not (0 <= op.reg_num < 106): - raise IndexError(f"SGPR index out of bounds: s{op.reg_num}") - return self.sgprs[op.reg_num] & MASK32 - elif op.kind in (OperandKind.LITERAL, OperandKind.INLINE_INT): - return op.literal_value & MASK32 - raise ValueError(f"Unknown operand kind: {op.kind}") - - def write_vgpr(self, reg_num: int, val: int) -> None: - if not (0 <= reg_num < 256): - raise IndexError(f"VGPR index out of bounds: v{reg_num}") - self.vgprs[reg_num] = val & MASK32 - - def write_sgpr(self, reg_num: int, val: int) -> None: - if not (0 <= reg_num < 106): - raise IndexError(f"SGPR index out of bounds: s{reg_num}") - self.sgprs[reg_num] = val & MASK32 - - -class Dot8IntScalarInterpreter: - """Deterministic instruction interpreter for VALU dot8 operations.""" - - def __init__(self, rf: Optional[ScalarRegisterFile] = None) -> None: - self.rf = rf if rf is not None else ScalarRegisterFile() - - def step(self, instr: ASTInstruction) -> None: - if instr.dst.kind != OperandKind.VGPR: - raise ValueError(f"VALU instruction destination must be a VGPR, got {instr.dst.kind}") - - if instr.opcode == Opcode.V_MOV_B32: - src_val = self.rf.read_operand(instr.src0) - self.rf.write_vgpr(instr.dst.reg_num, src_val) - return - - s0 = self.rf.read_operand(instr.src0) - s1 = self.rf.read_operand(instr.src1) - s2 = self.rf.read_operand(instr.src2) if instr.src2 is not None else 0 - - if instr.opcode == Opcode.V_DOT8_I32_I4: - result = ref_dot8_i32_i4(s0, s1, s2, clamp=instr.clamp) - elif instr.opcode == Opcode.V_DOT8_U32_U4: - result = ref_dot8_u32_u4(s0, s1, s2, clamp=instr.clamp) - else: - raise NotImplementedError(f"Unsupported opcode execution: {instr.opcode}") - - self.rf.write_vgpr(instr.dst.reg_num, result) - - def execute_asm(self, asm_lines: list[str]) -> None: - for line in asm_lines: - line = line.strip() - if not line or line.startswith("//") or line.startswith(";"): - continue - instr = parse_instruction(line) - self.step(instr) - - -class TestValuDot8IntScalarInterpreter(unittest.TestCase): - """Deterministic scalar interpreter tests for v_dot8_int.""" - - def test_scalar_v_dot8_u32_u4_execution(self) -> None: - interp = Dot8IntScalarInterpreter() - s0 = pack_u4(1, 2, 3, 4, 1, 2, 3, 4) - s1 = pack_u4(1, 1, 1, 1, 2, 2, 2, 2) - # Sum: 1+2+3+4 + 2+4+6+8 = 10 + 20 = 30; acc = 70 -> 100 - interp.rf.write_vgpr(1, s0) - interp.rf.write_vgpr(2, s1) - interp.rf.write_vgpr(3, 70) - - interp.execute_asm(["v_dot8_u32_u4 v0, v1, v2, v3"]) - self.assertEqual(interp.rf.vgprs[0], 100) - - def test_scalar_v_dot8_i32_i4_execution(self) -> None: - interp = Dot8IntScalarInterpreter() - s0 = pack_i4(-2, -2, -2, -2, 3, 3, 3, 3) - s1 = pack_i4(1, 1, 1, 1, 1, 1, 1, 1) - # Sum: 4*(-2) + 4*(3) = -8 + 12 = 4 - interp.rf.write_vgpr(1, s0) - interp.rf.write_vgpr(2, s1) - interp.rf.write_vgpr(3, 0) - - interp.execute_asm(["v_dot8_i32_i4 v0, v1, v2, v3"]) - self.assertEqual(interp.rf.vgprs[0], 4) - - def test_scalar_sgpr_and_inline_operands(self) -> None: - interp = Dot8IntScalarInterpreter() - interp.rf.write_sgpr(4, pack_u4(1, 1, 1, 1, 1, 1, 1, 1)) - interp.rf.write_vgpr(1, pack_u4(2, 2, 2, 2, 2, 2, 2, 2)) - - # 8 * (1 * 2) = 16; acc = 15 -> 31 - interp.execute_asm(["v_dot8_u32_u4 v0, s4, v1, 15"]) - self.assertEqual(interp.rf.vgprs[0], 31) - - def test_scalar_clamp_execution(self) -> None: - interp = Dot8IntScalarInterpreter() - s_min = pack_i4(-8, -8, -8, -8, -8, -8, -8, -8) # 8 * 64 = +512 - interp.rf.write_vgpr(1, s_min) - interp.rf.write_vgpr(2, s_min) - interp.rf.write_vgpr(3, INT32_MAX) - - interp.execute_asm(["v_dot8_i32_i4 v0, v1, v2, v3 clamp"]) - self.assertEqual(interp.rf.vgprs[0], INT32_MAX & MASK32) - - -# --------------------------------------------------------------------------- -# SIMD Multi-Lane Divergence and 32/64-bit EXEC Masking Model -# --------------------------------------------------------------------------- - -class SIMDWaveState: - """Wavefront SIMD execution state supporting Wave32 and Wave64 execution modes.""" - - def __init__(self, wave_size: int = 32) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size {wave_size}; RDNA2 supports only Wave32 and Wave64") - self.wave_size: int = wave_size - self.exec_mask: int = (1 << wave_size) - 1 - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - self.sgprs: list[int] = [0] * 106 - - def read_operand_for_lane(self, op: ASTOperand, lane: int) -> int: - if op.kind == OperandKind.VGPR: - if not (0 <= op.reg_num < 256): - raise IndexError(f"VGPR index out of bounds: v{op.reg_num}") - return self.vgprs[lane][op.reg_num] & MASK32 - elif op.kind == OperandKind.SGPR: - if not (0 <= op.reg_num < 106): - raise IndexError(f"SGPR index out of bounds: s{op.reg_num}") - return self.sgprs[op.reg_num] & MASK32 - elif op.kind in (OperandKind.LITERAL, OperandKind.INLINE_INT): - return op.literal_value & MASK32 - raise ValueError(f"Unknown operand kind: {op.kind}") - - def write_vgpr_lane(self, lane: int, reg_num: int, val: int) -> None: - if not (0 <= reg_num < 256): - raise IndexError(f"VGPR index out of bounds: v{reg_num}") - self.vgprs[lane][reg_num] = val & MASK32 - - def step(self, instr: ASTInstruction) -> None: - if instr.dst.kind != OperandKind.VGPR: - raise ValueError(f"VALU instruction destination must be a VGPR, got {instr.dst.kind}") - - dst_reg = instr.dst.reg_num - for lane in range(self.wave_size): - if not (self.exec_mask & (1 << lane)): - continue - - if instr.opcode == Opcode.V_MOV_B32: - src_val = self.read_operand_for_lane(instr.src0, lane) - self.write_vgpr_lane(lane, dst_reg, src_val) - continue - - s0 = self.read_operand_for_lane(instr.src0, lane) - s1 = self.read_operand_for_lane(instr.src1, lane) - s2 = self.read_operand_for_lane(instr.src2, lane) if instr.src2 is not None else 0 - - if instr.opcode == Opcode.V_DOT8_I32_I4: - res = ref_dot8_i32_i4(s0, s1, s2, clamp=instr.clamp) - elif instr.opcode == Opcode.V_DOT8_U32_U4: - res = ref_dot8_u32_u4(s0, s1, s2, clamp=instr.clamp) - else: - raise NotImplementedError(f"Unsupported opcode execution: {instr.opcode}") - - self.write_vgpr_lane(lane, dst_reg, res) - - def execute_asm(self, asm_lines: list[str]) -> None: - for line in asm_lines: - line = line.strip() - if not line or line.startswith("//") or line.startswith(";"): - continue - instr = parse_instruction(line) - self.step(instr) - - -class TestValuDot8IntSIMDMultiLane(unittest.TestCase): - """SIMD multi-lane divergence and 32/64-bit EXEC masking unit tests for v_dot8_int.""" - - def test_wave32_uniform_execution(self) -> None: - wave = SIMDWaveState(wave_size=32) - s0 = pack_u4(1, 1, 1, 1, 1, 1, 1, 1) - s1 = pack_u4(2, 2, 2, 2, 2, 2, 2, 2) - for lane in range(32): - wave.write_vgpr_lane(lane, 1, s0) - wave.write_vgpr_lane(lane, 2, s1) - wave.write_vgpr_lane(lane, 3, 50) - - # 8 * 2 = 16; 50 + 16 = 66 - wave.execute_asm(["v_dot8_u32_u4 v0, v1, v2, v3"]) - for lane in range(32): - self.assertEqual(wave.vgprs[lane][0], 66) - - def test_wave64_uniform_execution(self) -> None: - wave = SIMDWaveState(wave_size=64) - s0 = pack_i4(1, -1, 1, -1, 1, -1, 1, -1) - s1 = pack_i4(3, 3, 3, 3, 3, 3, 3, 3) - # Sum = 4*(3) + 4*(-3) = 0 - for lane in range(64): - wave.write_vgpr_lane(lane, 1, s0) - wave.write_vgpr_lane(lane, 2, s1) - wave.write_vgpr_lane(lane, 3, 42) - - wave.execute_asm(["v_dot8_i32_i4 v0, v1, v2, v3"]) - for lane in range(64): - self.assertEqual(wave.vgprs[lane][0], 42) - - def test_wave32_divergent_alternating_exec_mask(self) -> None: - wave = SIMDWaveState(wave_size=32) - wave.exec_mask = 0x5555_5555 - s0 = pack_u4(1, 1, 1, 1, 1, 1, 1, 1) - s1 = pack_u4(3, 3, 3, 3, 3, 3, 3, 3) - - for lane in range(32): - wave.write_vgpr_lane(lane, 0, 0xCAFE_BABE) - wave.write_vgpr_lane(lane, 1, s0) - wave.write_vgpr_lane(lane, 2, s1) - - # Active even lanes: 8 * 3 = 24 - # Inactive odd lanes: preserved sentinel 0xCAFE_BABE - wave.execute_asm(["v_dot8_u32_u4 v0, v1, v2, 0"]) - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(wave.vgprs[lane][0], 24) - else: - self.assertEqual(wave.vgprs[lane][0], 0xCAFE_BABE) - - def test_wave64_divergent_high_half_exec_mask(self) -> None: - wave = SIMDWaveState(wave_size=64) - wave.exec_mask = 0xFFFF_FFFF_0000_0000 - for lane in range(64): - wave.write_vgpr_lane(lane, 0, 0x1234_5678) - wave.write_vgpr_lane(lane, 1, pack_u4(1, 2, 1, 2, 1, 2, 1, 2)) - wave.write_vgpr_lane(lane, 2, pack_u4(1, 1, 1, 1, 1, 1, 1, 1)) - - # 4*1 + 4*2 = 12 - wave.execute_asm(["v_dot8_u32_u4 v0, v1, v2, 0"]) - for lane in range(32): - self.assertEqual(wave.vgprs[lane][0], 0x1234_5678) - for lane in range(32, 64): - self.assertEqual(wave.vgprs[lane][0], 12) - - def test_wave_exec_mask_zero_preservation(self) -> None: - wave = SIMDWaveState(wave_size=32) - wave.exec_mask = 0x0000_0000 - for lane in range(32): - wave.write_vgpr_lane(lane, 0, 0x5555_AAAA) - wave.write_vgpr_lane(lane, 1, 0xFFFF_FFFF) - wave.write_vgpr_lane(lane, 2, 0xFFFF_FFFF) - - wave.execute_asm(["v_dot8_u32_u4 v0, v1, v2, 0"]) - for lane in range(32): - self.assertEqual(wave.vgprs[lane][0], 0x5555_AAAA) - - def test_divergent_per_lane_vector_data(self) -> None: - wave = SIMDWaveState(wave_size=32) - for lane in range(32): - # Lane ID in lowest nibble - wave.write_vgpr_lane(lane, 1, pack_u4(lane & 0xF, 1, 1, 1, 1, 1, 1, 1)) - wave.write_vgpr_lane(lane, 2, pack_u4(2, 1, 1, 1, 1, 1, 1, 1)) - wave.write_vgpr_lane(lane, 3, 10) - - # (lane & 0xF) * 2 + 7 * (1 * 1) + 10 = 2 * (lane & 0xF) + 17 - wave.execute_asm(["v_dot8_u32_u4 v0, v1, v2, v3"]) - for lane in range(32): - expected = 2 * (lane & 0xF) + 17 - self.assertEqual(wave.vgprs[lane][0], expected) - - -# --------------------------------------------------------------------------- -# Register Aliasing and In-Place Operand Preservation Tests -# --------------------------------------------------------------------------- - -class TestValuDot8IntRegisterAliasing(unittest.TestCase): - """Register aliasing, self-overwrite, and in-place operand preservation unit tests.""" - - def test_aliasing_dst_equals_src0(self) -> None: - interp = Dot8IntScalarInterpreter() - initial_v1 = pack_u4(1, 2, 3, 4, 1, 2, 3, 4) - v2 = pack_u4(2, 2, 2, 2, 2, 2, 2, 2) - interp.rf.write_vgpr(1, initial_v1) - interp.rf.write_vgpr(2, v2) - - # 2 * (1+2+3+4+1+2+3+4) = 2 * 20 = 40 - interp.execute_asm(["v_dot8_u32_u4 v1, v1, v2, 0"]) - self.assertEqual(interp.rf.vgprs[1], 40) - - def test_aliasing_dst_equals_src1(self) -> None: - interp = Dot8IntScalarInterpreter() - v1 = pack_i4(-1, 1, -1, 1, -1, 1, -1, 1) - v2 = pack_i4(2, 3, 2, 3, 2, 3, 2, 3) - interp.rf.write_vgpr(1, v1) - interp.rf.write_vgpr(2, v2) - - # 4 * ((-1)*2 + 1*3) = 4 * (-2 + 3) = 4 * 1 = 4 - interp.execute_asm(["v_dot8_i32_i4 v2, v1, v2, 0"]) - self.assertEqual(interp.rf.vgprs[2], 4) - - def test_aliasing_dst_equals_src2_accumulator(self) -> None: - interp = Dot8IntScalarInterpreter() - v1 = pack_u4(1, 1, 1, 1, 1, 1, 1, 1) - v2 = pack_u4(2, 2, 2, 2, 2, 2, 2, 2) - interp.rf.write_vgpr(1, v1) - interp.rf.write_vgpr(2, v2) - interp.rf.write_vgpr(3, 500) - - # 8 * 2 = 16; 500 + 16 = 516 - interp.execute_asm(["v_dot8_u32_u4 v3, v1, v2, v3"]) - self.assertEqual(interp.rf.vgprs[3], 516) - - def test_aliasing_dst_equals_src0_and_src1_squared(self) -> None: - interp = Dot8IntScalarInterpreter() - # Vector squared norm: v1 . v1 - v1 = pack_u4(1, 2, 1, 2, 1, 2, 1, 2) - interp.rf.write_vgpr(1, v1) - - # 4*(1^2) + 4*(2^2) = 4 + 16 = 20; acc = 10 -> 30 - interp.execute_asm(["v_dot8_u32_u4 v1, v1, v1, 10"]) - self.assertEqual(interp.rf.vgprs[1], 30) - - def test_full_aliasing_dst_src0_src1_src2(self) -> None: - interp = Dot8IntScalarInterpreter() - # Single register v0 serves as dst, src0, src1, and src2 - v0 = pack_u4(1, 1, 1, 1, 1, 1, 1, 1) # 0x11111111 - interp.rf.write_vgpr(0, v0) - - # Sum = 8 * 1 = 8; acc = 0x11111111 -> 0x11111119 - interp.execute_asm(["v_dot8_u32_u4 v0, v0, v0, v0"]) - self.assertEqual(interp.rf.vgprs[0], 0x1111_1119) - - def test_simd_multi_lane_aliased_accumulation(self) -> None: - wave = SIMDWaveState(wave_size=32) - wave.exec_mask = 0x5555_5555 - for lane in range(32): - wave.write_vgpr_lane(lane, 0, 100) - wave.write_vgpr_lane(lane, 1, pack_u4(1, 1, 1, 1, 1, 1, 1, 1)) - wave.write_vgpr_lane(lane, 2, pack_u4(2, 2, 2, 2, 2, 2, 2, 2)) - - # Active lanes: 100 + 8*2 = 116; Inactive: 100 - wave.execute_asm(["v_dot8_u32_u4 v0, v1, v2, v0"]) - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(wave.vgprs[lane][0], 116) - else: - self.assertEqual(wave.vgprs[lane][0], 100) - - -# --------------------------------------------------------------------------- -# Condition Codes, Status Flags, and Carry/Borrow Generation -# --------------------------------------------------------------------------- - -@dataclass(frozen=True) -class Dot8StatusFlags: - """Architectural status flags and condition codes for dot8 execution.""" - zero: bool - negative: bool - carry_out: bool - overflow: bool - saturated: bool - - -def compute_dot8_u32_status_flags(s0: int, s1: int, s2: int, *, clamp: bool = False) -> Dot8StatusFlags: - """Compute status flags and condition codes for unsigned dot8 (v_dot8_u32_u4).""" - n0 = unpack_u4(s0) - n1 = unpack_u4(s1) - prod_sum = sum(x * y for x, y in zip(n0, n1)) - acc = s2 & MASK32 - unclamped_sum = acc + prod_sum - - res = min(unclamped_sum, UINT32_MAX) if clamp else (unclamped_sum & MASK32) - - zero = (res == 0) - negative = bool(res & 0x8000_0000) - carry_out = unclamped_sum > UINT32_MAX - overflow = carry_out - saturated = clamp and (unclamped_sum > UINT32_MAX) - - return Dot8StatusFlags( - zero=zero, - negative=negative, - carry_out=carry_out, - overflow=overflow, - saturated=saturated, - ) - - -def compute_dot8_i32_status_flags(s0: int, s1: int, s2: int, *, clamp: bool = False) -> Dot8StatusFlags: - """Compute status flags and condition codes for signed dot8 (v_dot8_i32_i4).""" - n0 = unpack_i4(s0) - n1 = unpack_i4(s1) - prod_sum = sum(x * y for x, y in zip(n0, n1)) - - s2_u32 = s2 & MASK32 - s2_i32 = (s2_u32 - 0x1_0000_0000) if (s2_u32 & 0x8000_0000) else s2_u32 - - unclamped_total = s2_i32 + prod_sum - clamped_total = max(INT32_MIN, min(unclamped_total, INT32_MAX)) - - res = (clamped_total if clamp else unclamped_total) & MASK32 - - zero = (res == 0) - negative = bool(res & 0x8000_0000) - - adder_u32 = (s2 & MASK32) + (prod_sum & MASK32) - carry_out = adder_u32 > MASK32 - - overflow = unclamped_total < INT32_MIN or unclamped_total > INT32_MAX - saturated = clamp and overflow - - return Dot8StatusFlags( - zero=zero, - negative=negative, - carry_out=carry_out, - overflow=overflow, - saturated=saturated, - ) - - -def evaluate_vcc_predicate(results: list[int], predicate_fn) -> int: - """Evaluate a per-lane condition across wavefront lanes, packing into a VCC mask.""" - vcc = 0 - for lane, val in enumerate(results): - if predicate_fn(val): - vcc |= (1 << lane) - return vcc - - -class TestValuDot8IntConditionCodesAndStatusFlags(unittest.TestCase): - """Status flags, condition codes, and carry/borrow generation unit tests for v_dot8_int.""" - - def test_zero_flag_generation(self) -> None: - flags_zero = compute_dot8_u32_status_flags(0, 0, 0) - self.assertTrue(flags_zero.zero) - self.assertFalse(flags_zero.negative) - - # Signed cancellation to zero: prod_sum = +40, accumulator = -40 - s0 = pack_i4(1, 1, 1, 1, 1, 1, 1, 1) - s1 = pack_i4(5, 5, 5, 5, 5, 5, 5, 5) # 8 * 5 = 40 - acc = (-40) & MASK32 - flags_cancel = compute_dot8_i32_status_flags(s0, s1, acc) - self.assertTrue(flags_cancel.zero) - - def test_negative_flag_generation(self) -> None: - s0 = pack_i4(-1, -1, -1, -1, -1, -1, -1, -1) - s1 = pack_i4(2, 2, 2, 2, 2, 2, 2, 2) - flags_neg = compute_dot8_i32_status_flags(s0, s1, 0) - self.assertTrue(flags_neg.negative) - - flags_u_high = compute_dot8_u32_status_flags(0, 0, 0x8000_0000) - self.assertTrue(flags_u_high.negative) - - def test_unsigned_carry_out_generation(self) -> None: - # Sum 1800 added to UINT32_MAX - flags_carry = compute_dot8_u32_status_flags(0xFFFF_FFFF, 0xFFFF_FFFF, 0xFFFF_FFFF) - self.assertTrue(flags_carry.carry_out) - self.assertTrue(flags_carry.overflow) - - flags_no_carry = compute_dot8_u32_status_flags(0xFFFF_FFFF, 0xFFFF_FFFF, 100) - self.assertFalse(flags_no_carry.carry_out) - - def test_signed_overflow_generation(self) -> None: - s_min = pack_i4(-8, -8, -8, -8, -8, -8, -8, -8) # +512 - flags_overflow = compute_dot8_i32_status_flags(s_min, s_min, INT32_MAX) - self.assertTrue(flags_overflow.overflow) - self.assertFalse(flags_overflow.saturated) - - s_max = pack_i4(7, 7, 7, 7, 7, 7, 7, 7) # -448 - flags_underflow = compute_dot8_i32_status_flags(s_min, s_max, INT32_MIN) - self.assertTrue(flags_underflow.overflow) - - def test_saturation_flag_generation(self) -> None: - flags_u_sat = compute_dot8_u32_status_flags(0xFFFF_FFFF, 0xFFFF_FFFF, 0xFFFF_FFFF, clamp=True) - self.assertTrue(flags_u_sat.saturated) - - s_min = pack_i4(-8, -8, -8, -8, -8, -8, -8, -8) - flags_i_sat = compute_dot8_i32_status_flags(s_min, s_min, INT32_MAX, clamp=True) - self.assertTrue(flags_i_sat.saturated) - - def test_vcc_comparison_predicate_generation(self) -> None: - wave = SIMDWaveState(wave_size=32) - for lane in range(32): - wave.write_vgpr_lane(lane, 1, pack_u4(lane & 0xF, 0, 0, 0, 0, 0, 0, 0)) - wave.write_vgpr_lane(lane, 2, pack_u4(1, 0, 0, 0, 0, 0, 0, 0)) - wave.write_vgpr_lane(lane, 3, 0) - - wave.execute_asm(["v_dot8_u32_u4 v0, v1, v2, v3"]) - lane_results = [wave.vgprs[lane][0] for lane in range(32)] - - vcc_ge_8 = evaluate_vcc_predicate(lane_results, lambda v: v >= 8) - # Lanes 8..15 and 24..31 have lane & 0xF >= 8 - expected_mask = 0xFF00_FF00 - self.assertEqual(vcc_ge_8, expected_mask) - - -# --------------------------------------------------------------------------- -# Boundary Extremes, Signed/Unsigned Wrap, and Bit Patterns Tests -# --------------------------------------------------------------------------- - -FLOAT_POS_ZERO: int = 0x0000_0000 -FLOAT_NEG_ZERO: int = 0x8000_0000 -FLOAT_POS_INF: int = 0x7F80_0000 -FLOAT_NEG_INF: int = 0xFF80_0000 -FLOAT_CANONICAL_QNAN: int = 0x7FC0_0000 -FLOAT_SNAN: int = 0x7F80_0001 -FLOAT_MIN_SUBNORMAL: int = 0x0000_0001 - - -class TestValuDot8IntBoundaryExtremes(unittest.TestCase): - """Boundary extremes, bit patterns, and signed/unsigned wrap unit tests for v_dot8_int.""" - - def test_float_qnan_treated_as_raw_nibbles(self) -> None: - # FLOAT_CANONICAL_QNAN = 0x7FC00000 - # Nibbles: [0, 0, 0, 0, 0, 12, 15, 7] in unsigned - # In signed: [0, 0, 0, 0, 0, -4, -1, 7] - ident = 0x1111_1111 # [1, 1, 1, 1, 1, 1, 1, 1] - - # Unsigned dot8: 12*1 + 15*1 + 7*1 = 34 - u_res = ref_dot8_u32_u4(FLOAT_CANONICAL_QNAN, ident, 0) - self.assertEqual(u_res, 34) - - # Signed dot8: (-4)*1 + (-1)*1 + 7*1 = 2 - i_res = ref_dot8_i32_i4(FLOAT_CANONICAL_QNAN, ident, 0) - self.assertEqual(i_res, 2) - - def test_float_infinities_integer_dot_product(self) -> None: - # FLOAT_POS_INF = 0x7F800000 -> nibbles: [0, 0, 0, 0, 0, 8, 15, 7] - # In signed: [0, 0, 0, 0, 0, -8, -1, 7] - ident = 0x1111_1111 - - # Unsigned: 8 + 15 + 7 = 30 - self.assertEqual(ref_dot8_u32_u4(FLOAT_POS_INF, ident, 0), 30) - - # Signed: (-8) + (-1) + 7 = -2 (0xFFFFFFFE) - self.assertEqual(ref_dot8_i32_i4(FLOAT_POS_INF, ident, 0), 0xFFFF_FFFE) - - def test_float_negative_zero_sign_bit_differentiation(self) -> None: - # FLOAT_POS_ZERO = 0x00000000 -> all nibbles 0 - # FLOAT_NEG_ZERO = 0x80000000 -> nibble 7 is 8 (unsigned: 8; signed: -8) - ident = 0x1111_1111 - pos_u = ref_dot8_u32_u4(FLOAT_POS_ZERO, ident, 0) - neg_u = ref_dot8_u32_u4(FLOAT_NEG_ZERO, ident, 0) - self.assertEqual(pos_u, 0) - self.assertEqual(neg_u, 8) - - pos_i = ref_dot8_i32_i4(FLOAT_POS_ZERO, ident, 0) - neg_i = ref_dot8_i32_i4(FLOAT_NEG_ZERO, ident, 0) - self.assertEqual(pos_i, 0) - self.assertEqual(neg_i, (-8) & MASK32) - - def test_integer_extreme_signed_min_max_matrix(self) -> None: - s_min = 0x8888_8888 # all nibbles -8 - s_max = 0x7777_7777 # all nibbles +7 - - # (-8) * (-8) * 8 = 512 - self.assertEqual(ref_dot8_i32_i4(s_min, s_min, 0), 512) - - # 7 * 7 * 8 = 392 - self.assertEqual(ref_dot8_i32_i4(s_max, s_max, 0), 392) - - # (-8) * 7 * 8 = -448 - self.assertEqual(ref_dot8_i32_i4(s_min, s_max, 0), (-448) & MASK32) - - def test_integer_extreme_unsigned_overflow_and_saturation(self) -> None: - s_max_u = 0xFFFF_FFFF # all nibbles 15 - # 8 * 225 = 1800 - res_wrap = ref_dot8_u32_u4(s_max_u, s_max_u, UINT32_MAX, clamp=False) - self.assertEqual(res_wrap, 1799) - - res_sat = ref_dot8_u32_u4(s_max_u, s_max_u, UINT32_MAX, clamp=True) - self.assertEqual(res_sat, UINT32_MAX) - - -# --------------------------------------------------------------------------- -# Negative Controls, Syntax Rejection, and Mutation Detection Tests -# --------------------------------------------------------------------------- - -class TestValuDot8IntNegativeControls(unittest.TestCase): - """Negative controls, syntax rejection, and mutation detection unit tests.""" - - def test_rejection_of_sgpr_as_valu_destination(self) -> None: - interp = Dot8IntScalarInterpreter() - with self.assertRaises(ValueError): - interp.execute_asm(["v_dot8_u32_u4 s0, v1, v2, v3"]) - - def test_rejection_of_out_of_bounds_registers(self) -> None: - interp = Dot8IntScalarInterpreter() - with self.assertRaises(IndexError): - interp.rf.read_operand(ASTOperand(kind=OperandKind.VGPR, reg_num=256)) - with self.assertRaises(IndexError): - interp.rf.read_operand(ASTOperand(kind=OperandKind.SGPR, reg_num=106)) - - def test_rejection_of_unrecognized_opcode(self) -> None: - with self.assertRaises(NotImplementedError): - parse_instruction("v_dot8_unknown_op v0, v1, v2, v3") - - def test_rejection_of_malformed_instruction_syntax(self) -> None: - with self.assertRaises(ValueError): - parse_instruction("v_dot8_u32_u4 v0, v1") - with self.assertRaises(ValueError): - parse_instruction("") - - def test_rejection_of_invalid_wave_size(self) -> None: - with self.assertRaises(ValueError): - SIMDWaveState(wave_size=16) - with self.assertRaises(ValueError): - SIMDWaveState(wave_size=128) - - def test_mutation_bit_flip_sensitivity(self) -> None: - s0 = pack_u4(1, 2, 3, 4, 5, 6, 7, 8) - s1 = pack_u4(1, 1, 1, 1, 1, 1, 1, 1) - acc = 100 - baseline = ref_dot8_u32_u4(s0, s1, acc) - - for bit_pos in range(32): - s0_mutated = s0 ^ (1 << bit_pos) - mutated_res = ref_dot8_u32_u4(s0_mutated, s1, acc) - self.assertNotEqual( - mutated_res, - baseline, - f"Bit flip at bit {bit_pos} failed to perturb output", - ) - - def test_mutation_nibble_order_divergence(self) -> None: - s0 = pack_u4(1, 5, 1, 1, 1, 1, 1, 1) - s1 = pack_u4(2, 4, 1, 1, 1, 1, 1, 1) - base_dot = ref_dot8_u32_u4(s0, s1, 0) - - # Swap nibble 0 and nibble 1 in s0 - s0_swapped = pack_u4(5, 1, 1, 1, 1, 1, 1, 1) - mutated_dot = ref_dot8_u32_u4(s0_swapped, s1, 0) - self.assertNotEqual(base_dot, mutated_dot) - - def test_mutation_signedness_divergence_detection(self) -> None: - s0 = pack_i4(-1, -2, -3, -4, -1, -2, -3, -4) - s1 = pack_i4(1, 1, 1, 1, 1, 1, 1, 1) - - signed_res = ref_dot8_i32_i4(s0, s1, 0) - unsigned_res = ref_dot8_u32_u4(s0, s1, 0) - - self.assertEqual(signed_res, (-20) & MASK32) - # Unsigned: 15*2 + 14*2 + 13*2 + 12*2 = 30 + 28 + 26 + 24 = 108 - self.assertEqual(unsigned_res, 108) - self.assertNotEqual(signed_res, unsigned_res) + setup = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2:#x}"] + srcs = "s1, s2, s3" + lines = setup + [f"{op} v0, {srcs}{' clamp' if clamp else ''}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_dot8", lines))[0] + + +U, I = "v_dot8_u32_u4", "v_dot8_i32_i4" +ALL_M8 = pk(*[-8] * 8) # eight nibbles of -8 (0x8 each) +ALL_7 = pk(*[7] * 8) + +# (name, op, S0, S1, S2, clamp, expected word), written by hand. +CASES = [ + ("u4 basic: 0*1+1*2+...+7*8 = 168", U, pk(0, 1, 2, 3, 4, 5, 6, 7), pk(1, 2, 3, 4, 5, 6, 7, 8), 0, False, 168), + ("u4 basic with accumulator", U, pk(0, 1, 2, 3, 4, 5, 6, 7), pk(1, 2, 3, 4, 5, 6, 7, 8), 500, False, 668), + ("u4 zero operand keeps S2", U, 0, 0x12345678, 0x1234ABCD, False, 0x1234ABCD), + ("u4 zero operand keeps S2 (swapped)", U, 0x12345678, 0, 0xCAFEBABE, False, 0xCAFEBABE), + ("u4 maximum: 8*15*15", U, MASK32, MASK32, 0, False, 1800), + ("u4 maximum plus 200", U, MASK32, MASK32, 200, False, 2000), + ("u4 wraps to 0", U, MASK32, MASK32, 0xFFFFF8F8, False, 0), + ("u4 wraps to 1", U, MASK32, MASK32, 0xFFFFF8F9, False, 1), + ("u4 without clamp wraps", U, MASK32, MASK32, 0xFFFFFFF0, False, 0x000006F8), + ("u4 clamp saturates", U, MASK32, MASK32, 0xFFFFFFF0, True, 0xFFFFFFFF), + ("i4 basic: 1+2+3+4-1-2-3-4 = 0", I, pk(1, 2, 3, 4, -1, -2, -3, -4), pk(*[1] * 8), 0, False, 0), + ("i4 basic with accumulator", I, pk(1, 2, 3, 4, -1, -2, -3, -4), pk(*[1] * 8), 77, False, 77), + ("i4 negative operands: 2 * -20 = -40", I, pk(-1, -2, -3, -4, -1, -2, -3, -4), pk(*[2] * 8), 0, False, 0xFFFFFFD8), + ("i4 max positive: 8*(-8)^2", I, ALL_M8, ALL_M8, 0, False, 512), + ("i4 max negative: 8*(-8*7)", I, ALL_M8, ALL_7, 0, False, 0xFFFFFE40), + ("i4 wraps negative", I, ALL_M8, ALL_M8, INT32_MAX, False, 0x800001FF), + ("i4 clamp to INT32_MAX", I, ALL_M8, ALL_M8, INT32_MAX, True, 0x7FFFFFFF), + ("i4 clamp to INT32_MIN", I, ALL_M8, ALL_7, 0x80000000, True, 0x80000000), + ("0xF is 15 unsigned", U, pk(15, 0, 0, 0, 0, 0, 0, 0), pk(1, 0, 0, 0, 0, 0, 0, 0), 0, False, 15), + ("0xF is -1 signed", I, pk(15, 0, 0, 0, 0, 0, 0, 0), pk(1, 0, 0, 0, 0, 0, 0, 0), 0, False, 0xFFFFFFFF), +] + + +class Dot8Int(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for name, op, s0, s1, s2, clamp, want in CASES: + self.assertEqual(ref(op, s0, s1, s2, clamp), want, name) + + def test_translated_cases(self): + for name, op, s0, s1, s2, clamp, want in CASES: + with self.subTest(name): + self.assertEqual(run(op, s0, s1, s2, clamp), want) + + def test_sgpr_sources(self): + for name, op, s0, s1, s2, clamp, want in CASES[:6] + CASES[10:14]: + with self.subTest(name): + self.assertEqual(run(op, s0, s1, s2, clamp, "sgpr"), want) + + def test_random_operands(self): + rng = random.Random(0x646F7438) + for _ in range(40): + s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) + for op in (U, I): + for clamp in (False, True): + with self.subTest(op=op, clamp=clamp, s0=hex(s0), s1=hex(s1), s2=hex(s2)): + self.assertEqual(run(op, s0, s1, s2, clamp), ref(op, s0, s1, s2, clamp)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_fma_f16.py b/tests/semantic/test_valu_fma_f16.py index 17fb0bffe..5a1dc8aa6 100644 --- a/tests/semantic/test_valu_fma_f16.py +++ b/tests/semantic/test_valu_fma_f16.py @@ -1,1873 +1,162 @@ -from __future__ import annotations +"""v_fma_f16 (RDNA2 VOP3): D.f16 = S0.f16 * S1.f16 + S2.f16 with a single rounding (binary16, nearest even). -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_fma_f16. - -Tests the half-precision fused multiply-add instruction: - v_fma_f16 D, S0, S1, S2 -Lowered semantics: - D = (S0 * S1) + S2 -with single-rounding precision per IEEE 754-2008 (binary16). -Supports input modifiers: - - abs (|src|: clear sign bit) - - neg (-src: invert sign bit) -Supports output modifiers: - - clamp: saturates result to [0.0, 1.0], with NaN clamped to +0.0 - - omod: mul:2, mul:4, div:2 -Architectural model: - 16-bit halfword registers mapped onto 32-bit VGPR/SGPR halves: - [lo: bits 15..0, hi: bits 31..16]. +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in +tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the fused (not double-rounded) result, op_sel +for all three sources and the destination, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. +Standard library only: no GPU, no LLVM, no game data. """ - -from dataclasses import dataclass -from enum import Enum, auto -from fractions import Fraction -import math -import struct +import os +import random import sys import unittest -# IEEE 754 binary16 bitwise architectural constants -F16_POS_ZERO = 0x0000 -F16_NEG_ZERO = 0x8000 -F16_ONE = 0x3C00 -F16_NEG_ONE = 0xBC00 -F16_TWO = 0x4000 -F16_HALF = 0x3800 -F16_POS_INF = 0x7C00 -F16_NEG_INF = 0xFC00 -F16_CANONICAL_QNAN = 0x7E00 -F16_SNAN = 0x7C01 -F16_MIN_SUBNORMAL = 0x0001 # 2^-24 ~= 5.96e-8 -F16_MAX_SUBNORMAL = 0x03FF # (1023/1024) * 2^-14 -F16_MIN_NORMAL = 0x0400 # 2^-14 ~= 6.10e-5 -F16_MAX_NORMAL = 0x7BFF # 65504.0 - -SIGN_MASK_F16 = 0x8000 -EXP_MASK_F16 = 0x7C00 -MANT_MASK_F16 = 0x03FF -QNAN_BIT_F16 = 0x0200 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF - - -def f16_to_u16(val: float) -> int: - """Pack Python float into unsigned 16-bit integer (IEEE 754 binary16).""" - try: - return struct.unpack(" 0 else F16_NEG_INF - - -def u16_to_f16(bits: int) -> float: - """Unpack unsigned 16-bit integer into Python float (IEEE 754 binary16).""" - return struct.unpack(" tuple[int, int, int]: - """Split 16-bit word into (sign, 5-bit exponent, 10-bit mantissa).""" - b = bits & MASK16 - return (b >> 15) & 1, (b >> 10) & 0x1F, b & MANT_MASK_F16 - - -def is_nan_f16(bits: int) -> bool: - """Check if 16-bit word is an IEEE 754 binary16 NaN.""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & MANT_MASK_F16) != 0) - - -def is_snan_f16(bits: int) -> bool: - """Check if 16-bit word is an IEEE 754 binary16 signaling NaN.""" - return is_nan_f16(bits) and not bool(bits & QNAN_BIT_F16) - - -def is_qnan_f16(bits: int) -> bool: - """Check if 16-bit word is an IEEE 754 binary16 quiet NaN.""" - return is_nan_f16(bits) and bool(bits & QNAN_BIT_F16) - - -def is_inf_f16(bits: int) -> bool: - """Check if 16-bit word is an IEEE 754 binary16 infinity (+/-).""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & MANT_MASK_F16) == 0) - - -def is_zero_f16(bits: int) -> bool: - """Check if 16-bit word is zero (+0.0 or -0.0).""" - return (bits & 0x7FFF) == 0 - - -def is_subnormal_f16(bits: int) -> bool: - """Check if 16-bit word is an IEEE 754 binary16 subnormal (denormal).""" - return ((bits & EXP_MASK_F16) == 0) and ((bits & MANT_MASK_F16) != 0) - - -def apply_src_mods_u16(bits: int, *, neg: bool = False, abs_: bool = False) -> int: - """Apply bit-exact RDNA2 source modifiers (|src|, -src) to a 16-bit float bit pattern.""" - val = bits & MASK16 - if abs_: - val &= ~SIGN_MASK_F16 # clear sign bit - if neg: - val ^= SIGN_MASK_F16 # invert sign bit - return val - - -def apply_clamp_f16(bits: int) -> int: - """Apply RDNA2 clamp modifier [0.0, 1.0] to float16, mapping NaNs to +0.0.""" - if is_nan_f16(bits): - return F16_POS_ZERO - val_f = u16_to_f16(bits) - if val_f < 0.0: - return F16_POS_ZERO - if val_f > 1.0: - return F16_ONE - return bits & MASK16 - - -def apply_omod_f16(bits: int, omod: int) -> int: - """Apply RDNA2 output modifier: 0: none, 1: mul:2, 2: mul:4, 3: div:2.""" - if omod == 0: - return bits & MASK16 - if is_nan_f16(bits): - return bits & MASK16 - val = u16_to_f16(bits) - if omod == 1: - val *= 2.0 - elif omod == 2: - val *= 4.0 - elif omod == 3: - val *= 0.5 - else: - raise ValueError(f"Invalid omod value: {omod}") - return f16_to_u16(val) - - -def raw_fma_f16(u0: int, u1: int, u2: int) -> int: - """Compute exact IEEE 754 half precision FMA (u0 * u1) + u2 with single rounding.""" - u0 &= MASK16 - u1 &= MASK16 - u2 &= MASK16 - - # 1. NaN propagation: if any input is NaN, quiet and return - for u in (u0, u1, u2): - if is_snan_f16(u): - return u | QNAN_BIT_F16 - for u in (u0, u1, u2): - if is_qnan_f16(u): - return u - - # 2. Invalid operations: Inf * 0 or 0 * Inf - if (is_inf_f16(u0) and is_zero_f16(u1)) or (is_zero_f16(u0) and is_inf_f16(u1)): - return F16_CANONICAL_QNAN - - # 3. Product is infinite - prod_inf = is_inf_f16(u0) or is_inf_f16(u1) - if prod_inf: - prod_sign = ((u0 >> 15) ^ (u1 >> 15)) & 1 - if is_inf_f16(u2): - u2_sign = (u2 >> 15) & 1 - if prod_sign != u2_sign: - return F16_CANONICAL_QNAN - return F16_NEG_INF if prod_sign else F16_POS_INF - - # 4. S2 is infinite - if is_inf_f16(u2): - return u2 - - # 5. Product is zero - if is_zero_f16(u0) or is_zero_f16(u1): - prod_sign = ((u0 >> 15) ^ (u1 >> 15)) & 1 - if is_zero_f16(u2): - u2_sign = (u2 >> 15) & 1 - if prod_sign == 1 and u2_sign == 1: - return F16_NEG_ZERO - return F16_POS_ZERO - return u2 - - # 6. Finite values: compute exact rational arithmetic with Fraction - f0 = u16_to_f16(u0) - f1 = u16_to_f16(u1) - f2 = u16_to_f16(u2) - frac_sum = Fraction(f0) * Fraction(f1) + Fraction(f2) - - if frac_sum == 0: - return F16_POS_ZERO - - try: - val_f = float(frac_sum) - return f16_to_u16(val_f) - except OverflowError: - return F16_POS_INF if frac_sum > 0 else F16_NEG_INF - - -def ref_fma_f16( - s0: float, - s1: float, - s2: float, - *, - neg0: bool = False, - neg1: bool = False, - neg2: bool = False, - abs0: bool = False, - abs1: bool = False, - abs2: bool = False, - clamp: bool = False, - omod: int = 0, -) -> float: - """Reference mathematical oracle for v_fma_f16 calculating (s0 * s1) + s2 in binary16.""" - u0 = apply_src_mods_u16(f16_to_u16(s0), neg=neg0, abs_=abs0) - u1 = apply_src_mods_u16(f16_to_u16(s1), neg=neg1, abs_=abs1) - u2 = apply_src_mods_u16(f16_to_u16(s2), neg=neg2, abs_=abs2) - - res_u16 = raw_fma_f16(u0, u1, u2) - - if omod != 0: - res_u16 = apply_omod_f16(res_u16, omod) - if clamp: - res_u16 = apply_clamp_f16(res_u16) - - return u16_to_f16(res_u16) - - -def ref_fma_f16_u16( - u0: int, - u1: int, - u2: int, - *, - neg0: bool = False, - neg1: bool = False, - neg2: bool = False, - abs0: bool = False, - abs1: bool = False, - abs2: bool = False, - clamp: bool = False, - omod: int = 0, -) -> int: - """Bit-exact reference mathematical oracle for v_fma_f16 using 16-bit integer words.""" - m0 = apply_src_mods_u16(u0, neg=neg0, abs_=abs0) - m1 = apply_src_mods_u16(u1, neg=neg1, abs_=abs1) - m2 = apply_src_mods_u16(u2, neg=neg2, abs_=abs2) - - res_u16 = raw_fma_f16(m0, m1, m2) - - if omod != 0: - res_u16 = apply_omod_f16(res_u16, omod) - if clamp: - res_u16 = apply_clamp_f16(res_u16) - - return res_u16 & MASK16 - - -class RegisterHalf: - """Architectural model of a 16-bit halfword within a 32-bit register (lo or hi).""" - - def __init__(self, raw_u16: int = 0) -> None: - self.raw = raw_u16 & MASK16 - - @classmethod - def from_f16(cls, val: float) -> RegisterHalf: - return cls(f16_to_u16(val)) - - @property - def as_u16(self) -> int: - return self.raw - - @property - def as_f16(self) -> float: - return u16_to_f16(self.raw) - - def set_u16(self, bits: int) -> None: - self.raw = bits & MASK16 - - def set_f16(self, val: float) -> None: - self.set_u16(f16_to_u16(val)) - - def __repr__(self) -> str: - return f"RegisterHalf({self.raw:#06x}, f16={self.as_f16})" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, RegisterHalf): - return NotImplemented - return self.raw == other.raw - - -class VGPRWord: - """Architectural model of a 32-bit VGPR containing low and high 16-bit halfwords.""" - - def __init__(self, dword: int = 0) -> None: - self.lo = RegisterHalf(dword & MASK16) - self.hi = RegisterHalf((dword >> 16) & MASK16) - - @property - def dword(self) -> int: - return (self.lo.as_u16) | ((self.hi.as_u16) << 16) - - @dword.setter - def dword(self, val: int) -> None: - self.lo.set_u16(val & MASK16) - self.hi.set_u16((val >> 16) & MASK16) - - def __repr__(self) -> str: - return f"VGPRWord(lo={self.lo.as_u16:#06x}, hi={self.hi.as_u16:#06x})" - - -class TestFmaF16MathematicalOracle(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural register models.""" - - def test_basic_fma_identities(self): - # 1.0 * 1.0 + 0.0 == 1.0 - self.assertEqual(ref_fma_f16(1.0, 1.0, 0.0), 1.0) - # 2.0 * 3.0 + 4.0 == 10.0 - self.assertEqual(ref_fma_f16(2.0, 3.0, 4.0), 10.0) - # -2.5 * 4.0 + 1.25 == -8.75 - self.assertEqual(ref_fma_f16(-2.5, 4.0, 1.25), -8.75) - # 0.0 * 100.0 + 5.5 == 5.5 - self.assertEqual(ref_fma_f16(0.0, 100.0, 5.5), 5.5) - - def test_fused_precision_single_rounding(self): - # FMA retains intermediate product precision without intermediate 16-bit rounding. - # Let a = 1.0 + 2**-10 (0x3C01), b = 1.0 + 2**-10 (0x3C01), c = -(1.0 + 2**-9) (0xBC02) - # (a * b) = 1.0 + 2**-9 + 2**-20 - # Unfused: (a * b) rounds to (1.0 + 2**-9) in f16, so (a * b) + c == 0.0 - # Fused: (a * b) + c retains 2**-20, which in f16 is subnormal 0x0010 != 0.0 - a = u16_to_f16(0x3C01) - b = u16_to_f16(0x3C01) - c = u16_to_f16(0xBC02) - unfused = u16_to_f16(f16_to_u16(a * b)) + c - fused = ref_fma_f16(a, b, c) - self.assertEqual(unfused, 0.0) - self.assertNotEqual(fused, 0.0) - self.assertEqual(f16_to_u16(fused), 0x0010) - - def test_source_modifiers(self): - # abs(|src|): clears sign bit - self.assertEqual(ref_fma_f16(-3.5, 2.0, 1.0, abs0=True), 8.0) - self.assertEqual(ref_fma_f16(3.5, -2.0, 1.0, abs1=True), 8.0) - self.assertEqual(ref_fma_f16(3.5, 2.0, -1.0, abs2=True), 8.0) - - # neg(-src): inverts sign bit - self.assertEqual(ref_fma_f16(3.5, 2.0, 1.0, neg0=True), -6.0) - self.assertEqual(ref_fma_f16(3.5, 2.0, 1.0, neg1=True), -6.0) - self.assertEqual(ref_fma_f16(3.5, 2.0, 1.0, neg2=True), 6.0) - - # combined neg and abs: -|src| - self.assertEqual(ref_fma_f16(-3.5, 2.0, 1.0, neg0=True, abs0=True), -6.0) - - def test_output_modifiers_clamp_and_omod(self): - # clamp saturates to [0.0, 1.0] - self.assertEqual(ref_fma_f16(2.0, 3.0, 0.0, clamp=True), 1.0) - self.assertEqual(ref_fma_f16(-2.0, 3.0, 0.0, clamp=True), 0.0) - self.assertEqual(ref_fma_f16(0.5, 1.0, 0.25, clamp=True), 0.75) - - # omod: mul:2, mul:4, div:2 - self.assertEqual(ref_fma_f16(1.5, 2.0, 0.5, omod=1), 7.0) # (3.5) * 2 = 7.0 - self.assertEqual(ref_fma_f16(1.5, 2.0, 0.5, omod=2), 14.0) # (3.5) * 4 = 14.0 - self.assertEqual(ref_fma_f16(1.5, 2.0, 0.5, omod=3), 1.75) # (3.5) * 0.5 = 1.75 - - # omod combined with clamp: (omod applies before clamp) - self.assertEqual(ref_fma_f16(0.125, 2.0, 0.0, omod=1, clamp=True), 0.5) - self.assertEqual(ref_fma_f16(0.25, 2.0, 0.0, omod=1, clamp=True), 1.0) - self.assertEqual(ref_fma_f16(0.5, 2.0, 0.0, omod=2, clamp=True), 1.0) - - def test_register_half_architecture(self): - rh = RegisterHalf.from_f16(1.0) - self.assertEqual(rh.as_f16, 1.0) - self.assertEqual(rh.as_u16, F16_ONE) - - word = VGPRWord(0) - word.lo.set_f16(1.0) - word.hi.set_f16(2.0) - self.assertEqual(word.lo.as_u16, F16_ONE) - self.assertEqual(word.hi.as_u16, F16_TWO) - self.assertEqual(word.dword, (F16_TWO << 16) | F16_ONE) - - # bit-exact oracle roundtrip - u_res = ref_fma_f16_u16(F16_TWO, F16_HALF, F16_ONE) - self.assertEqual(u_res, f16_to_u16(2.0)) - - -class Opcode(Enum): - V_FMA_F16 = "v_fma_f16" - - -class OperandKind(Enum): - VGPR = auto() - SGPR = auto() - INLINE_CONST = auto() - LITERAL_CONST = auto() - - -class HalfSel(Enum): - LO = 0 # bits 15:0 (.l) - HI = 1 # bits 31:16 (.h) - - def to_asm(self) -> str: - return "l" if self == HalfSel.LO else "h" - - -class TypeKind(Enum): - FLOAT16 = "f16" - UINT16 = "u16" - UINT32 = "u32" - - -class OMod(Enum): - NONE = 0 - MUL2 = 1 - MUL4 = 2 - DIV2 = 3 - - def to_asm(self) -> str: - if self == OMod.MUL2: - return "mul:2" - elif self == OMod.MUL4: - return "mul:4" - elif self == OMod.DIV2: - return "div:2" - return "" - - -class ASTOperand: - """Symbolic AST operand representing a 16-bit register half, constant, or literal with modifiers.""" - - def __init__( - self, - kind: OperandKind, - index: int = 0, - half: HalfSel = HalfSel.LO, - value: float | int | None = None, - *, - neg: bool = False, - abs_: bool = False, - type_kind: TypeKind = TypeKind.FLOAT16, - ) -> None: - self.kind = kind - self.index = index - self.half = half - self.value = value - self.neg = neg - self.abs_ = abs_ - self.type_kind = type_kind - - @classmethod - def vgpr( - cls, - index: int, - half: HalfSel = HalfSel.LO, - *, - neg: bool = False, - abs_: bool = False, - ) -> ASTOperand: - return cls(OperandKind.VGPR, index=index, half=half, neg=neg, abs_=abs_) - - @classmethod - def sgpr( - cls, - index: int, - half: HalfSel = HalfSel.LO, - *, - neg: bool = False, - abs_: bool = False, - ) -> ASTOperand: - return cls(OperandKind.SGPR, index=index, half=half, neg=neg, abs_=abs_) - - @classmethod - def inline_const(cls, value: float, *, neg: bool = False, abs_: bool = False) -> ASTOperand: - return cls(OperandKind.INLINE_CONST, value=value, neg=neg, abs_=abs_) - - @classmethod - def literal_const(cls, value: float, *, neg: bool = False, abs_: bool = False) -> ASTOperand: - return cls(OperandKind.LITERAL_CONST, value=value, neg=neg, abs_=abs_) - - def disasm(self) -> str: - if self.kind == OperandKind.VGPR: - body = f"v{self.index}.{self.half.to_asm()}" - elif self.kind == OperandKind.SGPR: - body = f"s{self.index}.{self.half.to_asm()}" - elif self.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST): - body = str(self.value) - else: - raise ValueError(f"Unknown operand kind: {self.kind}") - - if self.abs_: - body = f"|{body}|" - if self.neg: - body = f"-{body}" - return body - - def __repr__(self) -> str: - return f"ASTOperand({self.disasm()}, type={self.type_kind.value})" - - -class ASTInstruction: - """Symbolic AST instruction representation for v_fma_f16.""" - - def __init__( - self, - opcode: Opcode, - dst: ASTOperand, - src0: ASTOperand, - src1: ASTOperand, - src2: ASTOperand, - *, - clamp: bool = False, - omod: OMod = OMod.NONE, - ) -> None: - self.opcode = opcode - self.dst = dst - self.src0 = src0 - self.src1 = src1 - self.src2 = src2 - self.clamp = clamp - self.omod = omod - - def validate(self) -> None: - if self.opcode != Opcode.V_FMA_F16: - raise ValueError(f"Invalid opcode for v_fma_f16 AST: {self.opcode}") - if self.dst.kind != OperandKind.VGPR: - raise TypeError("Destination must be a VGPR") - if self.dst.type_kind != TypeKind.FLOAT16: - raise TypeError(f"Destination type must be FLOAT16, got {self.dst.type_kind}") - if not (0 <= self.dst.index <= 255): - raise ValueError(f"Destination VGPR index out of range: {self.dst.index}") - if self.dst.neg or self.dst.abs_: - raise ValueError("Destination operand cannot have neg/abs modifiers") - - for i, src in enumerate((self.src0, self.src1, self.src2)): - if src.type_kind != TypeKind.FLOAT16: - raise TypeError(f"Source operand {i} type must be FLOAT16, got {src.type_kind}") - if src.kind == OperandKind.VGPR and not (0 <= src.index <= 255): - raise ValueError(f"Source {i} VGPR index out of range: {src.index}") - if src.kind == OperandKind.SGPR and not (0 <= src.index <= 105): - raise ValueError(f"Source {i} SGPR index out of range: {src.index}") - - def disasm(self) -> str: - parts = [ - self.opcode.value, - f"{self.dst.disasm()},", - f"{self.src0.disasm()},", - f"{self.src1.disasm()},", - self.src2.disasm(), - ] - if self.omod != OMod.NONE: - parts.append(self.omod.to_asm()) - if self.clamp: - parts.append("clamp") - return " ".join(parts) - - def __repr__(self) -> str: - return f"ASTInstruction({self.disasm()})" - - -class TypedExpr: - """Base class for typed symbolic expressions.""" - - def __init__(self, type_kind: TypeKind = TypeKind.FLOAT16) -> None: - self.type_kind = type_kind - - def evaluate(self, env: dict[str, float]) -> float: - raise NotImplementedError - - def simplify(self) -> TypedExpr: - return self - - -class VariableExpr(TypedExpr): - """Named variable in symbolic expression tree (e.g. representing a register value).""" - - def __init__(self, name: str, type_kind: TypeKind = TypeKind.FLOAT16) -> None: - super().__init__(type_kind) - self.name = name - - def evaluate(self, env: dict[str, float]) -> float: - if self.name not in env: - raise KeyError(f"Variable {self.name} not found in evaluation environment") - return env[self.name] - - def __repr__(self) -> str: - return f"Var({self.name})" - - -class ConstantExpr(TypedExpr): - """Constant literal in symbolic expression tree.""" - - def __init__(self, value: float, type_kind: TypeKind = TypeKind.FLOAT16) -> None: - super().__init__(type_kind) - self.value = value - - def evaluate(self, env: dict[str, float]) -> float: - return self.value - - def __repr__(self) -> str: - return f"Const({self.value})" - - -class UnaryOpExpr(TypedExpr): - """Unary modifier applied to a typed expression ('neg' or 'abs').""" - - def __init__(self, op: str, expr: TypedExpr, type_kind: TypeKind = TypeKind.FLOAT16) -> None: - super().__init__(type_kind) - if op not in ("neg", "abs"): - raise ValueError(f"Unknown unary operator: {op}") - self.op = op - self.expr = expr - - def evaluate(self, env: dict[str, float]) -> float: - val = self.expr.evaluate(env) - if self.op == "abs": - return math.fabs(val) - elif self.op == "neg": - return -val - return val - - def simplify(self) -> TypedExpr: - sub = self.expr.simplify() - if isinstance(sub, ConstantExpr): - if self.op == "abs": - return ConstantExpr(math.fabs(sub.value), self.type_kind) - elif self.op == "neg": - return ConstantExpr(-sub.value, self.type_kind) - return UnaryOpExpr(self.op, sub, self.type_kind) - - def __repr__(self) -> str: - return f"{self.op}({self.expr})" - - -class FMA16Expr(TypedExpr): - """Symbolic FMA ternary typed expression: (src0 * src1) + src2 with modifiers.""" - - def __init__( - self, - src0: TypedExpr, - src1: TypedExpr, - src2: TypedExpr, - *, - clamp: bool = False, - omod: OMod = OMod.NONE, - type_kind: TypeKind = TypeKind.FLOAT16, - ) -> None: - super().__init__(type_kind) - self.src0 = src0 - self.src1 = src1 - self.src2 = src2 - self.clamp = clamp - self.omod = omod - - def evaluate(self, env: dict[str, float]) -> float: - v0 = self.src0.evaluate(env) - v1 = self.src1.evaluate(env) - v2 = self.src2.evaluate(env) - return ref_fma_f16(v0, v1, v2, clamp=self.clamp, omod=self.omod.value) - - def simplify(self) -> TypedExpr: - s0 = self.src0.simplify() - s1 = self.src1.simplify() - s2 = self.src2.simplify() - if isinstance(s0, ConstantExpr) and isinstance(s1, ConstantExpr) and isinstance(s2, ConstantExpr): - res = ref_fma_f16(s0.value, s1.value, s2.value, clamp=self.clamp, omod=self.omod.value) - return ConstantExpr(res, self.type_kind) - return FMA16Expr(s0, s1, s2, clamp=self.clamp, omod=self.omod, type_kind=self.type_kind) - - def __repr__(self) -> str: - return f"FMA16({self.src0}, {self.src1}, {self.src2}, clamp={self.clamp}, omod={self.omod.name})" - - -class TestFmaF16SymbolicAST(unittest.TestCase): - """Test suite for symbolic AST opcode definitions and typed expressions.""" - - def test_ast_construction_and_validation(self): - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.HI), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - inst.validate() - self.assertEqual(inst.disasm(), "v_fma_f16 v0.l, v1.l, v2.h, v3.l") - - def test_ast_with_modifiers_and_disasm(self): - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.HI, neg=True, abs_=True), - src1=ASTOperand.sgpr(2, HalfSel.LO), - src2=ASTOperand.inline_const(1.0), - clamp=True, - omod=OMod.MUL2, - ) - inst.validate() - self.assertEqual(inst.disasm(), "v_fma_f16 v0.l, -|v1.h|, s2.l, 1.0 mul:2 clamp") - - def test_ast_validation_errors(self): - # Invalid destination kind - bad_dst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.sgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(TypeError): - bad_dst.validate() - - # Destination has modifiers (illegal in RDNA2) - bad_dst_mod = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, neg=True), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - bad_dst_mod.validate() - - # Destination out of bounds - bad_index = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(256), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - bad_index.validate() - - def test_typed_expressions_and_evaluation(self): - # Symbolic: (a * b) + c - expr = FMA16Expr( - VariableExpr("a"), - VariableExpr("b"), - VariableExpr("c"), - ) - env = {"a": 2.5, "b": 4.0, "c": -3.0} - self.assertEqual(expr.evaluate(env), 7.0) - - def test_typed_expression_constant_folding(self): - # FMA(Const(2.0), Const(3.0), Const(4.0)) -> Const(10.0) - c_expr = FMA16Expr( - ConstantExpr(2.0), - ConstantExpr(3.0), - ConstantExpr(4.0), - ) - folded = c_expr.simplify() - self.assertIsInstance(folded, ConstantExpr) - self.assertEqual(folded.value, 10.0) - - # Unary folding - u_expr = UnaryOpExpr("neg", ConstantExpr(5.5)) - u_folded = u_expr.simplify() - self.assertIsInstance(u_folded, ConstantExpr) - self.assertEqual(u_folded.value, -5.5) - - -class ScalarRegisterFile: - """Register file for a single scalar lane with 256 32-bit VGPRs and 106 32-bit SGPRs.""" - - def __init__(self) -> None: - self.vgprs = [0] * 256 - self.sgprs = [0] * 106 - - def read_vgpr_u32(self, idx: int) -> int: - return self.vgprs[idx] - - def write_vgpr_u32(self, idx: int, val: int) -> None: - self.vgprs[idx] = val & MASK32 - - def read_sgpr_u32(self, idx: int) -> int: - return self.sgprs[idx] - - def write_sgpr_u32(self, idx: int, val: int) -> None: - self.sgprs[idx] = val & MASK32 - - def read_vgpr_half_u16(self, idx: int, half: HalfSel = HalfSel.LO) -> int: - dword = self.vgprs[idx] - return (dword >> 16) & MASK16 if half == HalfSel.HI else (dword & MASK16) - - def write_vgpr_half_u16(self, idx: int, half: HalfSel, val: int) -> None: - current = self.vgprs[idx] - u16 = val & MASK16 - if half == HalfSel.HI: - self.vgprs[idx] = (current & 0x0000FFFF) | (u16 << 16) - else: - self.vgprs[idx] = (current & 0xFFFF0000) | u16 - - def read_sgpr_half_u16(self, idx: int, half: HalfSel = HalfSel.LO) -> int: - dword = self.sgprs[idx] - return (dword >> 16) & MASK16 if half == HalfSel.HI else (dword & MASK16) - - def write_sgpr_half_u16(self, idx: int, half: HalfSel, val: int) -> None: - current = self.sgprs[idx] - u16 = val & MASK16 - if half == HalfSel.HI: - self.sgprs[idx] = (current & 0x0000FFFF) | (u16 << 16) - else: - self.sgprs[idx] = (current & 0xFFFF0000) | u16 - - def read_vgpr_half_f16(self, idx: int, half: HalfSel = HalfSel.LO) -> float: - return u16_to_f16(self.read_vgpr_half_u16(idx, half)) - - def write_vgpr_half_f16(self, idx: int, half: HalfSel, val: float) -> None: - self.write_vgpr_half_u16(idx, half, f16_to_u16(val)) - - def read_sgpr_half_f16(self, idx: int, half: HalfSel = HalfSel.LO) -> float: - return u16_to_f16(self.read_sgpr_half_u16(idx, half)) - - def write_sgpr_half_f16(self, idx: int, half: HalfSel, val: float) -> None: - self.write_sgpr_half_u16(idx, half, f16_to_u16(val)) - - -class FmaF16ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_fma_f16.""" - - def __init__(self, reg_file: ScalarRegisterFile | None = None) -> None: - self.reg_file = reg_file if reg_file is not None else ScalarRegisterFile() - - def resolve_source_u16(self, src: ASTOperand) -> int: - if src.kind == OperandKind.VGPR: - val_u16 = self.reg_file.read_vgpr_half_u16(src.index, src.half) - elif src.kind == OperandKind.SGPR: - val_u16 = self.reg_file.read_sgpr_half_u16(src.index, src.half) - elif src.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST): - val_u16 = f16_to_u16(float(src.value)) if src.value is not None else F16_POS_ZERO - else: - raise ValueError(f"Unsupported operand kind: {src.kind}") - - return apply_src_mods_u16(val_u16, neg=src.neg, abs_=src.abs_) - - def execute(self, inst: ASTInstruction) -> None: - inst.validate() - u0 = self.resolve_source_u16(inst.src0) - u1 = self.resolve_source_u16(inst.src1) - u2 = self.resolve_source_u16(inst.src2) - - res_u16 = ref_fma_f16_u16(u0, u1, u2, clamp=inst.clamp, omod=inst.omod.value) - self.reg_file.write_vgpr_half_u16(inst.dst.index, inst.dst.half, res_u16) - - -class TestFmaF16ScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction interpreter.""" - - def setUp(self) -> None: - self.rf = ScalarRegisterFile() - self.interp = FmaF16ScalarInterpreter(self.rf) - - def test_scalar_interpreter_vgprs(self): - # v0.l = v1.l * v2.h + v3.l - self.rf.write_vgpr_half_f16(1, HalfSel.LO, 3.0) - self.rf.write_vgpr_half_f16(2, HalfSel.HI, 4.0) - self.rf.write_vgpr_half_f16(3, HalfSel.LO, 5.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.HI), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 17.0) - - def test_scalar_interpreter_sgpr_and_constants(self): - # v0.h = s0.l * v1.l + inline_const(10.0) - self.rf.write_sgpr_half_f16(0, HalfSel.LO, 2.5) - self.rf.write_vgpr_half_f16(1, HalfSel.LO, 4.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.HI), - src0=ASTOperand.sgpr(0, HalfSel.LO), - src1=ASTOperand.vgpr(1, HalfSel.LO), - src2=ASTOperand.inline_const(10.0), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.HI), 20.0) - - def test_scalar_interpreter_modifiers(self): - # v0.l = -|v1.l| * v2.l + 5.0 with clamp - # v1.l = -2.0 -> abs -> 2.0 -> neg -> -2.0 - # -2.0 * 3.0 + 5.0 = -1.0 -> clamp -> 0.0 - self.rf.write_vgpr_half_f16(1, HalfSel.LO, -2.0) - self.rf.write_vgpr_half_f16(2, HalfSel.LO, 3.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO, neg=True, abs_=True), - src1=ASTOperand.vgpr(2, HalfSel.LO), - src2=ASTOperand.inline_const(5.0), - clamp=True, - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 0.0) - - def test_scalar_interpreter_sibling_half_preservation(self): - # Packing canary in v0.h - self.rf.write_vgpr_half_u16(0, HalfSel.HI, 0xABCD) - self.rf.write_vgpr_half_f16(1, HalfSel.LO, 2.0) - self.rf.write_vgpr_half_f16(2, HalfSel.LO, 2.0) - self.rf.write_vgpr_half_f16(3, HalfSel.LO, 2.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.LO), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - self.interp.execute(inst) - # v0.l updated to 6.0 - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 6.0) - # v0.h strictly preserved - self.assertEqual(self.rf.read_vgpr_half_u16(0, HalfSel.HI), 0xABCD) - - def test_scalar_interpreter_deterministic_repeatability(self): - self.rf.write_vgpr_half_f16(1, HalfSel.LO, 1.25) - self.rf.write_vgpr_half_f16(2, HalfSel.HI, 3.5) - self.rf.write_vgpr_half_f16(3, HalfSel.LO, -2.125) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.HI), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - self.interp.execute(inst) - res1 = self.rf.read_vgpr_half_u16(0, HalfSel.LO) - - self.interp.execute(inst) - res2 = self.rf.read_vgpr_half_u16(0, HalfSel.LO) - self.assertEqual(res1, res2) - - -class SIMDWaveState: - """Architectural model of a SIMD wavefront (Wave32 or Wave64) with EXEC masking.""" - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got {wave_size}") - self.wave_size = wave_size - self._exec_mask = (1 << wave_size) - 1 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - self.sgprs = [0] * 106 - - @property - def exec_mask(self) -> int: - return self._exec_mask - - @exec_mask.setter - def exec_mask(self, val: int) -> None: - mask_limit = (1 << self.wave_size) - 1 - self._exec_mask = val & mask_limit - - @property - def exec_lo(self) -> int: - return self._exec_mask & MASK32 - - @exec_lo.setter - def exec_lo(self, val: int) -> None: - self._exec_mask = (self._exec_mask & ~MASK32) | (val & MASK32) - - @property - def exec_hi(self) -> int: - return (self._exec_mask >> 32) & MASK32 - - @exec_hi.setter - def exec_hi(self, val: int) -> None: - if self.wave_size == 32: - raise ValueError("Cannot set exec_hi on Wave32") - self._exec_mask = (self._exec_mask & MASK32) | ((val & MASK32) << 32) - - def set_lane_vgpr_half_u16(self, lane: int, idx: int, half: HalfSel, val: int) -> None: - current = self.vgprs[lane][idx] - u16 = val & MASK16 - if half == HalfSel.HI: - self.vgprs[lane][idx] = (current & 0x0000FFFF) | (u16 << 16) - else: - self.vgprs[lane][idx] = (current & 0xFFFF0000) | u16 - - def get_lane_vgpr_half_u16(self, lane: int, idx: int, half: HalfSel) -> int: - dword = self.vgprs[lane][idx] - return (dword >> 16) & MASK16 if half == HalfSel.HI else (dword & MASK16) - - def set_lane_vgpr_half_f16(self, lane: int, idx: int, half: HalfSel, val: float) -> None: - self.set_lane_vgpr_half_u16(lane, idx, half, f16_to_u16(val)) - - def get_lane_vgpr_half_f16(self, lane: int, idx: int, half: HalfSel) -> float: - return u16_to_f16(self.get_lane_vgpr_half_u16(lane, idx, half)) - - def set_sgpr_half_u16(self, idx: int, half: HalfSel, val: int) -> None: - current = self.sgprs[idx] - u16 = val & MASK16 - if half == HalfSel.HI: - self.sgprs[idx] = (current & 0x0000FFFF) | (u16 << 16) - else: - self.sgprs[idx] = (current & 0xFFFF0000) | u16 - - def get_sgpr_half_u16(self, idx: int, half: HalfSel) -> int: - dword = self.sgprs[idx] - return (dword >> 16) & MASK16 if half == HalfSel.HI else (dword & MASK16) - - def set_sgpr_half_f16(self, idx: int, half: HalfSel, val: float) -> None: - self.set_sgpr_half_u16(idx, half, f16_to_u16(val)) - - def get_sgpr_half_f16(self, idx: int, half: HalfSel) -> float: - return u16_to_f16(self.get_sgpr_half_u16(idx, half)) - - def _resolve_operand_u16(self, src: ASTOperand, lane: int) -> int: - if src.kind == OperandKind.VGPR: - val_u16 = self.get_lane_vgpr_half_u16(lane, src.index, src.half) - elif src.kind == OperandKind.SGPR: - val_u16 = self.get_sgpr_half_u16(src.index, src.half) - elif src.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST): - val_u16 = f16_to_u16(float(src.value)) if src.value is not None else F16_POS_ZERO - else: - raise ValueError(f"Unsupported operand kind: {src.kind}") - - return apply_src_mods_u16(val_u16, neg=src.neg, abs_=src.abs_) - - def execute(self, inst: ASTInstruction) -> None: - inst.validate() - for lane in range(self.wave_size): - if (self._exec_mask >> lane) & 1: - u0 = self._resolve_operand_u16(inst.src0, lane) - u1 = self._resolve_operand_u16(inst.src1, lane) - u2 = self._resolve_operand_u16(inst.src2, lane) - res_u16 = ref_fma_f16_u16(u0, u1, u2, clamp=inst.clamp, omod=inst.omod.value) - self.set_lane_vgpr_half_u16(lane, inst.dst.index, inst.dst.half, res_u16) - - -class TestFmaF16SIMDMultiLane(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - CANARY_OLD = 0xBEEF - - def test_wave32_full_exec(self): - wave = SIMDWaveState(wave_size=32) - wave.exec_mask = 0xFFFFFFFF - for lane in range(32): - wave.set_lane_vgpr_half_f16(lane, 1, HalfSel.LO, float(lane)) - wave.set_lane_vgpr_half_f16(lane, 2, HalfSel.LO, 2.0) - wave.set_lane_vgpr_half_f16(lane, 3, HalfSel.LO, 1.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.LO), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - wave.execute(inst) - - for lane in range(32): - expected = float(lane * 2 + 1) - self.assertEqual(wave.get_lane_vgpr_half_f16(lane, 0, HalfSel.LO), expected) - - def test_wave64_full_exec(self): - wave = SIMDWaveState(wave_size=64) - wave.exec_lo = 0xFFFFFFFF - wave.exec_hi = 0xFFFFFFFF - for lane in range(64): - wave.set_lane_vgpr_half_f16(lane, 1, HalfSel.LO, float(lane) * 0.5) - wave.set_lane_vgpr_half_f16(lane, 2, HalfSel.LO, 4.0) - wave.set_lane_vgpr_half_f16(lane, 3, HalfSel.LO, -10.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.LO), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - wave.execute(inst) - - for lane in range(64): - expected = float(lane * 0.5) * 4.0 - 10.0 - self.assertEqual(wave.get_lane_vgpr_half_f16(lane, 0, HalfSel.LO), expected) - - def test_wave64_divergence_exec_masking(self): - wave = SIMDWaveState(wave_size=64) - # Even lanes in low 32, odd lanes in high 32 - wave.exec_lo = 0x55555555 - wave.exec_hi = 0xAAAAAAAA - - for lane in range(64): - wave.set_lane_vgpr_half_u16(lane, 0, HalfSel.LO, self.CANARY_OLD) - wave.set_lane_vgpr_half_f16(lane, 1, HalfSel.LO, 3.0) - wave.set_lane_vgpr_half_f16(lane, 2, HalfSel.LO, 5.0) - wave.set_lane_vgpr_half_f16(lane, 3, HalfSel.LO, 2.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.LO), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - wave.execute(inst) - - for lane in range(64): - is_active = bool((wave.exec_mask >> lane) & 1) - if is_active: - self.assertEqual(wave.get_lane_vgpr_half_f16(lane, 0, HalfSel.LO), 17.0) - else: - self.assertEqual(wave.get_lane_vgpr_half_u16(lane, 0, HalfSel.LO), self.CANARY_OLD) - - def test_wave64_halves_masking(self): - wave = SIMDWaveState(wave_size=64) - # Only low 32 lanes active - wave.exec_lo = 0xFFFFFFFF - wave.exec_hi = 0x00000000 - - for lane in range(64): - wave.set_lane_vgpr_half_u16(lane, 0, HalfSel.LO, self.CANARY_OLD) - wave.set_lane_vgpr_half_f16(lane, 1, HalfSel.LO, 2.0) - wave.set_lane_vgpr_half_f16(lane, 2, HalfSel.LO, 2.0) - wave.set_lane_vgpr_half_f16(lane, 3, HalfSel.LO, 2.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.LO), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - wave.execute(inst) - - for lane in range(32): - self.assertEqual(wave.get_lane_vgpr_half_f16(lane, 0, HalfSel.LO), 6.0) - for lane in range(32, 64): - self.assertEqual(wave.get_lane_vgpr_half_u16(lane, 0, HalfSel.LO), self.CANARY_OLD) - - def test_single_active_lane(self): - wave = SIMDWaveState(wave_size=64) - wave.exec_mask = 1 << 17 # only lane 17 - - for lane in range(64): - wave.set_lane_vgpr_half_u16(lane, 0, HalfSel.LO, self.CANARY_OLD) - wave.set_lane_vgpr_half_f16(lane, 1, HalfSel.LO, 7.0) - wave.set_lane_vgpr_half_f16(lane, 2, HalfSel.LO, 3.0) - wave.set_lane_vgpr_half_f16(lane, 3, HalfSel.LO, 1.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.LO), - src2=ASTOperand.vgpr(3, HalfSel.LO), - ) - wave.execute(inst) - - for lane in range(64): - if lane == 17: - self.assertEqual(wave.get_lane_vgpr_half_f16(lane, 0, HalfSel.LO), 22.0) - else: - self.assertEqual(wave.get_lane_vgpr_half_u16(lane, 0, HalfSel.LO), self.CANARY_OLD) - - def test_zero_exec_preserves_all_lanes(self): - wave = SIMDWaveState(wave_size=64) - wave.exec_mask = 0 - - for lane in range(64): - wave.set_lane_vgpr_half_u16(lane, 0, HalfSel.LO, self.CANARY_OLD) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.inline_const(1.0), - src1=ASTOperand.inline_const(1.0), - src2=ASTOperand.inline_const(1.0), - ) - wave.execute(inst) - - for lane in range(64): - self.assertEqual(wave.get_lane_vgpr_half_u16(lane, 0, HalfSel.LO), self.CANARY_OLD) - - -class TestFmaF16RegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.rf = ScalarRegisterFile() - self.interp = FmaF16ScalarInterpreter(self.rf) - - def test_dst_alias_src0(self) -> None: - self.rf.write_vgpr_half_f16(0, HalfSel.LO, 3.0) - self.rf.write_vgpr_half_f16(1, HalfSel.LO, 4.0) - self.rf.write_vgpr_half_f16(2, HalfSel.LO, 5.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(0, HalfSel.LO), - src1=ASTOperand.vgpr(1, HalfSel.LO), - src2=ASTOperand.vgpr(2, HalfSel.LO), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 17.0) - # Verify unaliased sources remain untouched - self.assertEqual(self.rf.read_vgpr_half_f16(1, HalfSel.LO), 4.0) - self.assertEqual(self.rf.read_vgpr_half_f16(2, HalfSel.LO), 5.0) - - def test_dst_alias_src1(self) -> None: - self.rf.write_vgpr_half_f16(0, HalfSel.LO, 4.0) - self.rf.write_vgpr_half_f16(1, HalfSel.LO, 3.0) - self.rf.write_vgpr_half_f16(2, HalfSel.LO, 5.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(0, HalfSel.LO), - src2=ASTOperand.vgpr(2, HalfSel.LO), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 17.0) - self.assertEqual(self.rf.read_vgpr_half_f16(1, HalfSel.LO), 3.0) - self.assertEqual(self.rf.read_vgpr_half_f16(2, HalfSel.LO), 5.0) - - def test_dst_alias_src2_accumulator(self) -> None: - # In-place accumulation MAC: v0 = (v1 * v2) + v0 - self.rf.write_vgpr_half_f16(0, HalfSel.LO, 10.0) - self.rf.write_vgpr_half_f16(1, HalfSel.LO, 2.5) - self.rf.write_vgpr_half_f16(2, HalfSel.LO, 4.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(1, HalfSel.LO), - src1=ASTOperand.vgpr(2, HalfSel.LO), - src2=ASTOperand.vgpr(0, HalfSel.LO), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 20.0) - self.assertEqual(self.rf.read_vgpr_half_f16(1, HalfSel.LO), 2.5) - self.assertEqual(self.rf.read_vgpr_half_f16(2, HalfSel.LO), 4.0) - - def test_dst_alias_all_sources(self) -> None: - # v0 = (v0 * v0) + v0 - self.rf.write_vgpr_half_f16(0, HalfSel.LO, 2.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(0, HalfSel.LO), - src1=ASTOperand.vgpr(0, HalfSel.LO), - src2=ASTOperand.vgpr(0, HalfSel.LO), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 6.0) - - def test_inplace_iterative_accumulation(self) -> None: - # 50 iterations: v0 = (v0 * 1.0) + 0.25 - self.rf.write_vgpr_half_f16(0, HalfSel.LO, 0.0) - self.rf.write_vgpr_half_f16(1, HalfSel.LO, 1.0) - self.rf.write_vgpr_half_f16(2, HalfSel.LO, 0.25) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(0, HalfSel.LO), - src1=ASTOperand.vgpr(1, HalfSel.LO), - src2=ASTOperand.vgpr(2, HalfSel.LO), - ) - for _ in range(50): - self.interp.execute(inst) - - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 12.5) - - def test_sibling_halfword_preservation_under_aliasing(self) -> None: - # Reading high half as source, writing low half as destination - # v0.l = (v0.h * 2.0) + 1.0 - self.rf.write_vgpr_half_f16(0, HalfSel.HI, 5.0) - self.rf.write_vgpr_half_f16(0, HalfSel.LO, 0.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(0, HalfSel.HI), - src1=ASTOperand.inline_const(2.0), - src2=ASTOperand.inline_const(1.0), - ) - self.interp.execute(inst) - # v0.l updated to 11.0 - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 11.0) - # v0.h must remain untouched 5.0 - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.HI), 5.0) - - def test_high_half_destination_sibling_preservation(self) -> None: - # Reading low half as source, writing high half as destination - # v0.h = (v0.l * 3.0) + 2.0 - self.rf.write_vgpr_half_f16(0, HalfSel.LO, 4.0) - self.rf.write_vgpr_half_f16(0, HalfSel.HI, 0.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.HI), - src0=ASTOperand.vgpr(0, HalfSel.LO), - src1=ASTOperand.inline_const(3.0), - src2=ASTOperand.inline_const(2.0), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.HI), 14.0) - self.assertEqual(self.rf.read_vgpr_half_f16(0, HalfSel.LO), 4.0) - - def test_simd_multi_lane_aliasing(self) -> None: - wave = SIMDWaveState(wave_size=32) - wave.exec_mask = 0xFFFFFFFF - for lane in range(32): - wave.set_lane_vgpr_half_f16(lane, 0, HalfSel.LO, float(lane)) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.vgpr(0, HalfSel.LO), - src1=ASTOperand.inline_const(2.0), - src2=ASTOperand.inline_const(1.0), - ) - wave.execute(inst) - - for lane in range(32): - expected = float(lane) * 2.0 + 1.0 - self.assertEqual(wave.get_lane_vgpr_half_f16(lane, 0, HalfSel.LO), expected) - - -@dataclass(frozen=True) -class FPStatusFlags: - """Architectural floating-point condition codes and IEEE 754 status flags.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -def evaluate_v_fma_f16_flags( - u0: int, - u1: int, - u2: int, - res_u16: int, - *, - neg0: bool = False, - neg1: bool = False, - neg2: bool = False, - abs0: bool = False, - abs1: bool = False, - abs2: bool = False, - clamp: bool = False, - omod: int = 0, -) -> FPStatusFlags: - """Evaluate IEEE 754 architectural flags and condition codes for v_fma_f16.""" - s0 = apply_src_mods_u16(u0, neg=neg0, abs_=abs0) - s1 = apply_src_mods_u16(u1, neg=neg1, abs_=abs1) - s2 = apply_src_mods_u16(u2, neg=neg2, abs_=abs2) - - s0_nan = is_nan_f16(s0) - s1_nan = is_nan_f16(s1) - s2_nan = is_nan_f16(s2) - s0_snan = is_snan_f16(s0) - s1_snan = is_snan_f16(s1) - s2_snan = is_snan_f16(s2) - s0_inf = is_inf_f16(s0) - s1_inf = is_inf_f16(s1) - s2_inf = is_inf_f16(s2) - - invalid = False - if s0_snan or s1_snan or s2_snan: - invalid = True - elif (s0_inf and is_zero_f16(s1)) or (is_zero_f16(s0) and s1_inf): - invalid = True - elif (s0_inf or s1_inf) and s2_inf: - prod_sign = ((s0 >> 15) ^ (s1 >> 15)) & 1 - s2_sign = (s2 >> 15) & 1 - if prod_sign != s2_sign: - invalid = True - - nan_flag = is_nan_f16(res_u16) - inf_flag = is_inf_f16(res_u16) - zero_flag = is_zero_f16(res_u16) - neg_flag = bool(res_u16 & SIGN_MASK_F16) - denorm_flag = ( - is_subnormal_f16(s0) - or is_subnormal_f16(s1) - or is_subnormal_f16(s2) - or is_subnormal_f16(res_u16) - ) - - overflow = False - if not (s0_nan or s1_nan or s2_nan or s0_inf or s1_inf or s2_inf) and inf_flag: - overflow = True - - underflow = False - if is_subnormal_f16(res_u16): - underflow = True - - inexact = False - if overflow: - inexact = True - elif not (s0_nan or s1_nan or s2_nan or s0_inf or s1_inf or s2_inf or nan_flag or inf_flag): - f0 = u16_to_f16(s0) - f1 = u16_to_f16(s1) - f2 = u16_to_f16(s2) - exact_math = Fraction(f0) * Fraction(f1) + Fraction(f2) - if omod == 1: - exact_math *= 2 - elif omod == 2: - exact_math *= 4 - elif omod == 3: - exact_math /= 2 - if clamp: - exact_math = min(Fraction(1), max(Fraction(0), exact_math)) - res_f = u16_to_f16(res_u16) - if exact_math != Fraction(res_f): - inexact = True - - return FPStatusFlags( - invalid=invalid, - overflow=overflow, - underflow=underflow, - inexact=inexact, - zero=zero_flag, - negative=neg_flag, - denormal=denorm_flag, - infinite=inf_flag, - nan=nan_flag, - ) - - -def compute_f16_mantissa_fma_carry(u0: int, u1: int, u2: int) -> tuple[int, int]: - """Demonstrate IEEE 754 mantissa alignment and carry-out generation during FMA.""" - _, exp0, frac0 = split_f16(u0) - _, exp1, frac1 = split_f16(u1) - _, exp2, frac2 = split_f16(u2) - - m0 = (1 << 10) | frac0 if exp0 != 0 else frac0 - m1 = (1 << 10) | frac1 if exp1 != 0 else frac1 - m2 = (1 << 10) | frac2 if exp2 != 0 else frac2 - - m_prod = m0 * m1 - exp_prod = (exp0 if exp0 != 0 else 1) + (exp1 if exp1 != 0 else 1) - 15 - e2 = exp2 if exp2 != 0 else 1 - - m2_shifted = m2 << 10 - if exp_prod > e2: - shift = min(exp_prod - e2, 30) - m2_aligned = m2_shifted >> shift - prod_aligned = m_prod - else: - shift = min(e2 - exp_prod, 30) - prod_aligned = m_prod >> shift - m2_aligned = m2_shifted - - mant_sum = prod_aligned + m2_aligned - carry_out = 1 if mant_sum >= (1 << 21) else 0 - return mant_sum, carry_out - - -class TestFmaF16ConditionCodesAndStatusFlags(unittest.TestCase): - """Test suite for status flags, condition codes, and carry generation.""" - - def test_exact_finite_flags(self): - u0 = f16_to_u16(1.0) - u1 = f16_to_u16(2.0) - u2 = f16_to_u16(0.5) - res = ref_fma_f16_u16(u0, u1, u2) - flags = evaluate_v_fma_f16_flags(u0, u1, u2, res) - self.assertFalse(flags.invalid) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - self.assertFalse(flags.inexact) - self.assertFalse(flags.zero) - self.assertFalse(flags.negative) - self.assertFalse(flags.denormal) - self.assertFalse(flags.infinite) - self.assertFalse(flags.nan) - - def test_inexact_flag(self): - # 1.0009765625 * 1.0009765625 + 0.0 has inexact remainder 2^-20 - u0 = 0x3C01 - u1 = 0x3C01 - u2 = 0x0000 - res = ref_fma_f16_u16(u0, u1, u2) - flags = evaluate_v_fma_f16_flags(u0, u1, u2, res) - self.assertTrue(flags.inexact) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - - def test_overflow_flag(self): - # 60000.0 * 2.0 + 0.0 overflows max normal f16 (65504.0) to +inf - u0 = f16_to_u16(60000.0) - u1 = f16_to_u16(2.0) - u2 = 0x0000 - res = ref_fma_f16_u16(u0, u1, u2) - flags = evaluate_v_fma_f16_flags(u0, u1, u2, res) - self.assertTrue(flags.overflow) - self.assertTrue(flags.inexact) - self.assertTrue(flags.infinite) - self.assertFalse(flags.invalid) - - def test_underflow_flag(self): - # Smallest subnormal result - u0 = 0x3C01 - u1 = 0x3C01 - u2 = 0xBC02 - res = ref_fma_f16_u16(u0, u1, u2) - self.assertEqual(res, 0x0010) - flags = evaluate_v_fma_f16_flags(u0, u1, u2, res) - self.assertTrue(flags.underflow) - self.assertTrue(flags.denormal) - - def test_invalid_operation_flags(self): - # Signaling NaN - u_snan = F16_SNAN - res1 = ref_fma_f16_u16(u_snan, F16_ONE, F16_POS_ZERO) - flags1 = evaluate_v_fma_f16_flags(u_snan, F16_ONE, F16_POS_ZERO, res1) - self.assertTrue(flags1.invalid) - self.assertTrue(flags1.nan) - - # Inf * 0 - res2 = ref_fma_f16_u16(F16_POS_INF, F16_POS_ZERO, F16_ONE) - flags2 = evaluate_v_fma_f16_flags(F16_POS_INF, F16_POS_ZERO, F16_ONE, res2) - self.assertTrue(flags2.invalid) - self.assertTrue(flags2.nan) - - # (+inf) + (-inf) - res3 = ref_fma_f16_u16(F16_POS_INF, F16_ONE, F16_NEG_INF) - flags3 = evaluate_v_fma_f16_flags(F16_POS_INF, F16_ONE, F16_NEG_INF, res3) - self.assertTrue(flags3.invalid) - self.assertTrue(flags3.nan) - - def test_zero_and_negative_condition_codes(self): - # Negative zero - res_neg0 = ref_fma_f16_u16(F16_NEG_ZERO, F16_ONE, F16_NEG_ZERO) - flags_neg0 = evaluate_v_fma_f16_flags(F16_NEG_ZERO, F16_ONE, F16_NEG_ZERO, res_neg0) - self.assertTrue(flags_neg0.zero) - self.assertTrue(flags_neg0.negative) - - # Positive zero - res_pos0 = ref_fma_f16_u16(F16_POS_ZERO, F16_ONE, F16_POS_ZERO) - flags_pos0 = evaluate_v_fma_f16_flags(F16_POS_ZERO, F16_ONE, F16_POS_ZERO, res_pos0) - self.assertTrue(flags_pos0.zero) - self.assertFalse(flags_pos0.negative) - - def test_mantissa_carry_generation(self): - # 1.0 * 1.0 + 1.0 -> mantissas: (1 << 20) + (1 << 20) = (1 << 21) -> carry out = 1 - _, carry1 = compute_f16_mantissa_fma_carry(F16_ONE, F16_ONE, F16_ONE) - self.assertEqual(carry1, 1) - - # 1.0 * 1.0 + 0.25 -> mantissas sum < (1 << 21) -> carry out = 0 - _, carry0 = compute_f16_mantissa_fma_carry(F16_ONE, F16_ONE, f16_to_u16(0.25)) - self.assertEqual(carry0, 0) - - -class TestFmaF16IEEE754BoundaryExtremes(unittest.TestCase): - """Test suite for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_addition_without_carry(self): - sub1 = 0x0001 - sub2 = 0x0002 - res = ref_fma_f16_u16(sub1, F16_ONE, sub2) - self.assertEqual(res, 0x0003) - self.assertTrue(is_subnormal_f16(res)) - - def test_subnormal_to_normal_transition(self): - max_sub = 0x03FF # largest subnormal (1023/1024) * 2^-14 - min_sub = 0x0001 # smallest subnormal 2^-24 - # (max_sub * 1.0) + min_sub = 0x0400 = smallest normal (2^-14) - res = ref_fma_f16_u16(max_sub, F16_ONE, min_sub) - self.assertEqual(res, 0x0400) - self.assertFalse(is_subnormal_f16(res)) - _, exp, frac = split_f16(res) - self.assertEqual(exp, 1) - self.assertEqual(frac, 0) - - def test_subnormal_gradual_underflow(self): - min_normal = F16_MIN_NORMAL # 0x0400 = 2^-14 - res = ref_fma_f16_u16(min_normal, F16_HALF, F16_POS_ZERO) - self.assertEqual(res, 0x0200) # 2^-15 (subnormal) - self.assertTrue(is_subnormal_f16(res)) - - def test_subnormal_cancellation(self): - sub = 0x0123 - neg_sub = sub | SIGN_MASK_F16 - res = ref_fma_f16_u16(sub, F16_ONE, neg_sub) - self.assertEqual(res, F16_POS_ZERO) - - def test_nan_signaling_to_quiet_conversion(self): - snan = 0x7C05 # fraction != 0, quiet bit 9 is 0 - self.assertTrue(is_snan_f16(snan)) - res = ref_fma_f16_u16(snan, F16_ONE, F16_POS_ZERO) - self.assertTrue(is_qnan_f16(res)) - self.assertEqual(res, snan | QNAN_BIT_F16) - - def test_nan_payload_preservation(self): - payload = 0x01AB - qnan = EXP_MASK_F16 | payload | QNAN_BIT_F16 - res = ref_fma_f16_u16(qnan, F16_TWO, F16_ONE) - self.assertEqual(res, qnan) - - def test_nan_with_modifiers(self): - qnan = 0x7E01 - # abs should clear sign bit - res_abs = ref_fma_f16_u16(qnan | SIGN_MASK_F16, F16_ONE, F16_POS_ZERO, abs0=True) - self.assertEqual(res_abs & SIGN_MASK_F16, 0) - self.assertTrue(is_qnan_f16(res_abs)) - - # neg should toggle sign bit - res_neg = ref_fma_f16_u16(qnan, F16_ONE, F16_POS_ZERO, neg0=True) - self.assertEqual(res_neg & SIGN_MASK_F16, SIGN_MASK_F16) - - def test_nan_with_clamp(self): - qnan = F16_CANONICAL_QNAN - res = ref_fma_f16_u16(qnan, F16_ONE, F16_ONE, clamp=True) - self.assertEqual(res, F16_POS_ZERO) - - def test_infinity_arithmetic_boundaries(self): - self.assertEqual(ref_fma_f16_u16(F16_POS_INF, f16_to_u16(100.0), F16_POS_ZERO), F16_POS_INF) - self.assertEqual(ref_fma_f16_u16(F16_NEG_INF, f16_to_u16(100.0), F16_POS_ZERO), F16_NEG_INF) - self.assertEqual(ref_fma_f16_u16(F16_POS_INF, F16_ONE, F16_NEG_INF), F16_CANONICAL_QNAN) - self.assertEqual(ref_fma_f16_u16(F16_NEG_INF, F16_ONE, F16_POS_INF), F16_CANONICAL_QNAN) - - # Infinity with clamp - self.assertEqual(ref_fma_f16_u16(F16_POS_INF, F16_ONE, F16_POS_ZERO, clamp=True), F16_ONE) - self.assertEqual(ref_fma_f16_u16(F16_NEG_INF, F16_ONE, F16_POS_ZERO, clamp=True), F16_POS_ZERO) - - def test_round_to_nearest_even_ties(self): - # In IEEE 754 binary16 (10 bits significand): - # 1.0 has bits 0x3C00 (even LSB = 0) - # 1.0 + 2^-10 has bits 0x3C01 (odd LSB = 1) - # 2^-11 is exactly halfway between representable numbers. - half_ulp = 2.0 ** -11 - one = 1.0 - one_plus_ulp = u16_to_f16(0x3C01) - - # Case 1: 1.0 (even LSB) + 2^-11: tie rounds to even (1.0) - res1 = ref_fma_f16(one, 1.0, half_ulp) - self.assertEqual(f16_to_u16(res1), F16_ONE) - - # Case 2: (1.0 + 2^-10) (odd LSB) + 2^-11: tie rounds to even (1.0 + 2 * 2^-10) = 0x3C02 - res2 = ref_fma_f16(one_plus_ulp, 1.0, half_ulp) - self.assertEqual(f16_to_u16(res2), 0x3C02) - - -class TestFmaF16NegativeControlsAndMutations(unittest.TestCase): - """Test suite for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_invalid_opcode(self): - class FakeOpcode(Enum): - V_ADD_F16 = "v_add_f16" - - bad_inst = ASTInstruction( - opcode=FakeOpcode.V_ADD_F16, # type: ignore - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - bad_inst.validate() - - def test_syntax_rejection_bad_dst_kind(self): - bad_inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.sgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(TypeError): - bad_inst.validate() - - def test_syntax_rejection_bad_dst_type(self): - bad_inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand(OperandKind.VGPR, index=0, type_kind=TypeKind.UINT16), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(TypeError): - bad_inst.validate() - - def test_syntax_rejection_dst_modifiers(self): - bad_inst_neg = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, neg=True), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - bad_inst_neg.validate() - - bad_inst_abs = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, abs_=True), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - bad_inst_abs.validate() - - def test_syntax_rejection_oob_indices(self): - bad_vgpr = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(256), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - bad_vgpr.validate() - - bad_sgpr = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.sgpr(106), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - bad_sgpr.validate() - - def test_syntax_rejection_bad_src_type(self): - bad_src = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0), - src0=ASTOperand(OperandKind.VGPR, index=1, type_kind=TypeKind.UINT32), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(TypeError): - bad_src.validate() - - def test_mutation_unfused_intermediate_rounding_detected(self): - # Mutated logic: unfused multiplication followed by addition - def mutated_unfused_fma(u0: int, u1: int, u2: int) -> int: - f0 = u16_to_f16(u0) - f1 = u16_to_f16(u1) - f2 = u16_to_f16(u2) - # Intermediate rounding to binary16 - prod_rounded = u16_to_f16(f16_to_u16(f0 * f1)) - return f16_to_u16(prod_rounded + f2) - - u0 = 0x3C01 - u1 = 0x3C01 - u2 = 0xBC02 - - oracle_result = ref_fma_f16_u16(u0, u1, u2) - mutated_result = mutated_unfused_fma(u0, u1, u2) - - # Oracle preserves the 2^-20 subnormal (0x0010), while mutated unfused flushes to 0.0 - self.assertEqual(oracle_result, 0x0010) - self.assertEqual(mutated_result, 0x0000) - self.assertNotEqual(oracle_result, mutated_result) - - def test_mutation_addition_subtraction_flip_detected(self): - def mutated_fma_sub(u0: int, u1: int, u2: int) -> int: - f0 = u16_to_f16(u0) - f1 = u16_to_f16(u1) - f2 = u16_to_f16(u2) - frac_diff = Fraction(f0) * Fraction(f1) - Fraction(f2) - return f16_to_u16(float(frac_diff)) - - u0 = f16_to_u16(2.0) - u1 = f16_to_u16(3.0) - u2 = f16_to_u16(4.0) - - oracle_result = ref_fma_f16_u16(u0, u1, u2) # 2 * 3 + 4 = 10.0 - mutated_result = mutated_fma_sub(u0, u1, u2) # 2 * 3 - 4 = 2.0 - self.assertEqual(u16_to_f16(oracle_result), 10.0) - self.assertEqual(u16_to_f16(mutated_result), 2.0) - self.assertNotEqual(oracle_result, mutated_result) - - def test_mutation_dropped_clamp_detected(self): - def mutated_clamp(bits: int) -> int: - return bits # mutated: no clamp - - u0 = f16_to_u16(2.0) - u1 = f16_to_u16(3.0) - u2 = f16_to_u16(0.0) - - oracle_result = ref_fma_f16_u16(u0, u1, u2, clamp=True) - mutated_result = mutated_clamp(ref_fma_f16_u16(u0, u1, u2, clamp=False)) - - self.assertEqual(u16_to_f16(oracle_result), 1.0) - self.assertEqual(u16_to_f16(mutated_result), 6.0) - self.assertNotEqual(oracle_result, mutated_result) - - def test_mutation_dropped_omod_detected(self): - def mutated_omod(bits: int, omod: int) -> int: - return bits # mutated: dropped omod - - u0 = f16_to_u16(1.5) - u1 = f16_to_u16(2.0) - u2 = f16_to_u16(0.5) - - oracle_result = ref_fma_f16_u16(u0, u1, u2, omod=1) - mutated_result = mutated_omod(ref_fma_f16_u16(u0, u1, u2, omod=0), 1) - - self.assertEqual(u16_to_f16(oracle_result), 7.0) - self.assertEqual(u16_to_f16(mutated_result), 3.5) - self.assertNotEqual(oracle_result, mutated_result) - - def test_mutation_sign_modifier_dropped_detected(self): - def mutated_apply_mods(bits: int, *, neg: bool = False, abs_: bool = False) -> int: - return bits # mutated: ignores neg/abs - - raw = f16_to_u16(3.5) - oracle_mod = apply_src_mods_u16(raw, neg=True) - mutated_mod = mutated_apply_mods(raw, neg=True) - - self.assertEqual(u16_to_f16(oracle_mod), -3.5) - self.assertEqual(u16_to_f16(mutated_mod), 3.5) - self.assertNotEqual(oracle_mod, mutated_mod) - - def test_mutation_subnormal_flush_detected(self): - def mutated_ftz_fma(u0: int, u1: int, u2: int) -> int: - res = ref_fma_f16_u16(u0, u1, u2) - if is_subnormal_f16(res): - return F16_POS_ZERO # mutated: flush to zero - return res - - u0 = 0x3C01 - u1 = 0x3C01 - u2 = 0xBC02 - - oracle_result = ref_fma_f16_u16(u0, u1, u2) - mutated_result = mutated_ftz_fma(u0, u1, u2) - - self.assertEqual(oracle_result, 0x0010) - self.assertEqual(mutated_result, 0x0000) - self.assertNotEqual(oracle_result, mutated_result) - - def test_negative_control_canary_corruption(self): - wave = SIMDWaveState(wave_size=32) - wave.exec_mask = 0x00000001 # only lane 0 active - canary = 0xCAFE - for lane in range(32): - wave.set_lane_vgpr_half_u16(lane, 0, HalfSel.LO, canary) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F16, - dst=ASTOperand.vgpr(0, HalfSel.LO), - src0=ASTOperand.inline_const(2.0), - src1=ASTOperand.inline_const(3.0), - src2=ASTOperand.inline_const(4.0), - ) - wave.execute(inst) - - self.assertEqual(wave.get_lane_vgpr_half_f16(0, 0, HalfSel.LO), 10.0) - for lane in range(1, 32): - self.assertEqual( - wave.get_lane_vgpr_half_u16(lane, 0, HalfSel.LO), - canary, - f"Inactive lane {lane} was corrupted", - ) +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import OLD, ref_fma, same_f16, scale # noqa: E402 + +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF + + +def run(line, seeds, old=OLD, hi=0x5A5A): + """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. + + `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its + upper half, so reading the wrong half of a source shows. v0 starts as `old`. + """ + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + w = w if w > 0xFFFF else (hi << 16) | w + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_fma_f16", prog))[0] + + +# (src0, src1, src2, D), written by hand. +CASES = [ + (TWO, THREE, ONE, 0x4700), # 2 * 3 + 1 = 7 + (0x3E00, TWO, 0xC200, 0x0000), # 1.5 * 2 + -3 = +0 + (HALF, HALF, QUARTER, HALF), # 0.5 * 0.5 + 0.25 = 0.5 + (0x3C01, 0x3C01, 0xBC02, 0x0010), # (1+2^-10)^2 - (1+2^-9) = 2^-20 exactly; unfused it would be 0 + (0x3C01, 0x3C01, 0xBC00, 0x1800), # 2^-9 + 2^-20: half a quantum of 2^-9 ties to even + (MAXH, TWO, 0xFBFF, MAXH), # 131008 - 65504: the product alone would overflow, the fused sum does not + (0x8000, ONE, 0x8000, 0x8000), # -0 * 1 + -0 = -0 + (0x0000, ONE, 0x8000, 0x0000), # +0 * 1 + -0 = +0 + (0x8000, ONE, 0x0000, 0x0000), # -0 * 1 + +0 = +0 + (ONE, ONE, MIN_SUB, ONE), # 1 + 2^-24 rounds back to 1 + (MIN_SUB, HALF, MIN_SUB, 0x0002), # 1.5 quanta ties to even: 2 quanta + (MIN_NORMAL, MIN_NORMAL, 0x0000, 0x0000), # 2^-28 underflows to +0 + (INF, 0x0000, ONE, QNAN), # inf * 0 = NaN + (INF, ONE, NINF, QNAN), # inf - inf = NaN + (INF, TWO, ONE, INF), + (ONE, ONE, QNAN, QNAN), +] + +SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, + MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0xBC02, 0x6800, 0x6801, 0x4C00] + + +class FmaF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for a, b, c, want in CASES: + self.assertTrue(same_f16(ref_fma(a, b, c), want), (hex(a), hex(b), hex(c), hex(ref_fma(a, b, c)))) + + def test_vgpr_sources_write_low_half_and_keep_high_half(self): + for a, b, c, want in CASES: + with self.subTest(a=hex(a), b=hex(b), c=hex(c)): + got = run("v_fma_f16 v0, v1, v2, v3", {"v1": a, "v2": b, "v3": c}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_sgpr_and_literal_sources(self): + for a, b, c, want in CASES[:12]: + forms = [ + ("sgpr all", "v_fma_f16 v0, s1, s2, s3", {"s1": a, "s2": b, "s3": c}), + ("sgpr src0 and src2", "v_fma_f16 v0, s1, v2, s3", {"s1": a, "v2": b, "s3": c}), + ("literal src0", f"v_fma_f16 v0, {a:#x}, v2, v3", {"v2": b, "v3": c}), + ("literal src2", f"v_fma_f16 v0, v1, v2, {c:#x}", {"v1": a, "v2": b}), + ] + for form, line, seeds in forms: + with self.subTest(a=hex(a), b=hex(b), c=hex(c), form=form): + got = run(line, seeds) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_inline_constants(self): + # (src0 inline constant, its binary16 value, v1 = src1, v2 = src2, D), by hand + for text, a, b, c, want in (("2.0", TWO, 0x3E00, ONE, 0x4400), # 2 * 1.5 + 1 = 4 + ("-1.0", 0xBC00, HALF, HALF, 0x0000), # -0.5 + 0.5 + ("0.5", HALF, 0x4400, 0xBC00, ONE), # 0.5 * 4 - 1 = 1 + ("4.0", 0x4400, QUARTER, QUARTER, 0x3D00)): # 4 * 0.25 + 0.25 = 1.25 + with self.subTest(const=text): + self.assertEqual(run(f"v_fma_f16 v0, {text}, v1, v2", {"v1": b, "v2": c}) & 0xFFFF, want) + self.assertEqual(ref_fma(a, b, c), want) + self.assertEqual(run("v_fma_f16 v0, v1, v2, 1.0", {"v1": TWO, "v2": THREE}) & 0xFFFF, 0x4700) + + def test_op_sel_selects_source_and_destination_halves(self): + # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25), src2 = (lo 0.25, hi -1.0); D by hand for each + # (src0 half, src1 half, src2 half): a * b + c. + s0, s1, s2 = (THREE << 16) | ONE, (0xB400 << 16) | HALF, (0xBC00 << 16) | QUARTER + expect_lo = { + (0, 0, 0): 0x3A00, # 1 * 0.5 + 0.25 = 0.75 + (0, 0, 1): 0xB800, # 1 * 0.5 - 1 = -0.5 + (0, 1, 0): 0x0000, # 1 * -0.25 + 0.25 = +0 + (0, 1, 1): 0xBD00, # -0.25 - 1 = -1.25 + (1, 0, 0): 0x3F00, # 3 * 0.5 + 0.25 = 1.75 + (1, 0, 1): 0x3800, # 1.5 - 1 = 0.5 + (1, 1, 0): 0xB800, # -0.75 + 0.25 = -0.5 + (1, 1, 1): 0xBF00, # -0.75 - 1 = -1.75 + } + for (h0, h1, h2), want in expect_lo.items(): + for dh in (0, 1): + expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) + with self.subTest(op_sel=(h0, h1, h2, dh)): + got = run(f"v_fma_f16 v0, v1, v2, v3 op_sel:[{h0},{h1},{h2},{dh}]", {"v1": s0, "v2": s1, "v3": s2}) + self.assertEqual(got, expect) + + def test_neg_and_abs_source_modifiers(self): + # v1 = 2.0, v2 = 0.5, v3 = -0.25; (operand text, D) by hand + for ops, want in (("v1, v2, v3", 0x3A00), # 1 - 0.25 = 0.75 + ("-v1, v2, v3", 0xBD00), # -1 - 0.25 = -1.25 + ("v1, -v2, v3", 0xBD00), # -1 - 0.25 + ("|v1|, |v2|, |v3|", 0x3D00), # 1 + 0.25 + ("v1, v2, -v3", 0x3D00), # 1 + 0.25 + ("v1, v2, -|v3|", 0x3A00), # 1 - 0.25 + ("-|v1|, v2, |v3|", 0xBA00)): # -1 + 0.25 = -0.75 + with self.subTest(ops=ops): + got = run(f"v_fma_f16 v0, {ops}", {"v1": TWO, "v2": HALF, "v3": 0xB400}) + self.assertEqual(got & 0xFFFF, want) + + def test_output_modifiers_and_clamp(self): + # unmodified result: 1.5 * 2 + -1 = 2.0; mul/div scale it, clamp limits it to [0, 1] + for suffix, want in ((" mul:2", 0x4400), (" mul:4", 0x4800), (" div:2", ONE), (" clamp", ONE)): + with self.subTest(mod=suffix): + got = run("v_fma_f16 v0, v1, v2, v3" + suffix, {"v1": 0x3E00, "v2": TWO, "v3": 0xBC00}) + self.assertEqual(got & 0xFFFF, want) + for (a, b, c), suffix, want in (((HALF, HALF, 0x0000), " clamp", QUARTER), # inside [0, 1]: unchanged + ((HALF, 0xB800, 0x0000), " clamp", 0x0000), # -0.25 -> +0 + ((ONE, 0x3E00, 0x0000), " div:2 clamp", 0x3A00), # 1.5 / 2 = 0.75 + ((0x3A00, ONE, 0x0000), " mul:2 clamp", ONE)): # 0.75 * 2 = 1.5 -> 1 + with self.subTest(a=hex(a), b=hex(b), c=hex(c), mod=suffix): + got = run("v_fma_f16 v0, v1, v2, v3" + suffix, {"v1": a, "v2": b, "v3": c}) + self.assertEqual(got & 0xFFFF, want) + for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): + got = run("v_fma_f16 v0, v1, v2, v3" + suffix, {"v1": 0x4900, "v2": 0xC100, "v3": 0x4C00}) # 10 * -2.5 + 16 + self.assertEqual(got & 0xFFFF, scale(ref_fma(0x4900, 0xC100, 0x4C00), f)) + + def test_random_operands(self): + rng = random.Random(0xF3A16) + pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] + for _ in range(160): + a, b, c = (rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(3)) + with self.subTest(a=hex(a), b=hex(b), c=hex(c)): + got = run("v_fma_f16 v0, v1, v2, v3", {"v1": a, "v2": b, "v3": c}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, ref_fma(a, b, c)), (hex(got), hex(ref_fma(a, b, c)))) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_lerp_u8.py b/tests/semantic/test_valu_lerp_u8.py index a1bf60e94..f22fc971f 100644 --- a/tests/semantic/test_valu_lerp_u8.py +++ b/tests/semantic/test_valu_lerp_u8.py @@ -1,1273 +1,88 @@ -from __future__ import annotations +"""v_lerp_u8 (RDNA2 VOP3): per byte i, D.b[i] = (S0.b[i] + S1.b[i] + S2.b[i][0]) >> 1: the unsigned average of the +two bytes, rounded up when bit 0 of that byte of S2 is set and down otherwise; bits 7:1 of S2's bytes are ignored and +no byte can carry into its neighbour (255 + 255 + 1 = 511, shifted 255). -"""Semantic reference oracle and architectural model for AMD RDNA2 v_lerp_u8. - -AMD RDNA VALU Instruction Set Architecture: - v_lerp_u8 dst, src0, src1, src2 - -Operation: - Performs parallel byte-wise linear interpolation (rounded unsigned average) - across four packed 8-bit unsigned byte lanes within 32-bit dwords: - For each byte lane i in {0, 1, 2, 3}: - s0_i = (src0 >> (8 * i)) & 0xFF - s1_i = (src1 >> (8 * i)) & 0xFF - s2_i = (src2 >> (8 * i)) & 0x01 # only bit 0 of each byte lane contributes - sum_i = s0_i + s1_i + s2_i # range: 0 .. 511 (9-bit intermediate) - dst_i = (sum_i >> 1) & 0xFF # range: 0 .. 255 (8-bit bounded result) - -Mathematical and Architectural Properties: - - Range isolation: max sum 255 + 255 + 1 = 511; 511 >> 1 = 255 (0xFF). - Result is strictly bound within [0, 255] for every byte lane. No cross-byte - carry or overflow can occur. - - Rounding control: - - s2 bit 0 = 0: floor / truncation of the unsigned average. - - s2 bit 0 = 1: ceiling / round-half-up of the unsigned average. - - Identity property: - - When s0_i == s1_i == k, ((k + k + r) >> 1) == (2k + r) >> 1 == k for both r in {0, 1}. - - Symmetry / Commutativity: - - src0 and src1 are interchangeable: v_lerp_u8(a, b, c) == v_lerp_u8(b, a, c). - - Upper bit discard: - - Bits [7:1] of each byte lane in src2 are strictly ignored by hardware and translator. +Each case is translated by tools/rdna2spirv.py (support.translate_lines) and executed with +tests/semantic/spirv_mini_interp.py; the expected words are written by hand from that formula and also recomputed by a +plain-Python reference, with VGPR, SGPR and literal sources and seeded random operands. Standard library only: no GPU, +no LLVM, no game data. (The old file modelled the instruction in its own classes and never ran the translator; +test_alu_lerp_u8.py is the older real test. `clamp` is refused by the translator and is not pinned here.) """ - -from dataclasses import dataclass, field -from enum import Enum, auto -from typing import List, Optional, Tuple, Union +import os +import random +import sys import unittest -# Architectural bitmasks and constants -MASK8: int = 0xFF -MASK32: int = 0xFFFF_FFFF -BYTE_SHIFTS: Tuple[int, int, int, int] = (0, 8, 16, 24) +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import support # noqa: E402 -def unpack_bytes_u32(val: int) -> Tuple[int, int, int, int]: - """Unpack a 32-bit unsigned word into 4 byte lanes (b0, b1, b2, b3).""" - val &= MASK32 - return ( - val & MASK8, - (val >> 8) & MASK8, - (val >> 16) & MASK8, - (val >> 24) & MASK8, - ) +def pk(*b): + return sum((x & 0xFF) << (8 * i) for i, x in enumerate(b)) -def pack_bytes_u32(b0: int, b1: int, b2: int, b3: int) -> int: - """Pack four 8-bit unsigned integers into a 32-bit unsigned word.""" - return ( - (b0 & MASK8) - | ((b1 & MASK8) << 8) - | ((b2 & MASK8) << 16) - | ((b3 & MASK8) << 24) - ) & MASK32 - - -def ref_lerp_u8_byte(s0: int, s1: int, s2_round: int) -> int: - """Compute single byte-lane linear interpolation: ((s0 + s1 + (s2 & 1)) >> 1) & 0xFF. - - The intermediate sum ranges from 0 to 511. Right shifting by 1 produces - a value in [0, 255] with strict lane isolation and no carry propagation. - """ - b0 = s0 & MASK8 - b1 = s1 & MASK8 - r = s2_round & 0x01 - return ((b0 + b1 + r) >> 1) & MASK8 - - -def oracle_v_lerp_u8(src0: int, src1: int, src2: int) -> int: - """Reference mathematical oracle for RDNA2 v_lerp_u8 32-bit packed word interpolation.""" - b0_0, b0_1, b0_2, b0_3 = unpack_bytes_u32(src0) - b1_0, b1_1, b1_2, b1_3 = unpack_bytes_u32(src1) - b2_0, b2_1, b2_2, b2_3 = unpack_bytes_u32(src2) - - r0 = ref_lerp_u8_byte(b0_0, b1_0, b2_0) - r1 = ref_lerp_u8_byte(b0_1, b1_1, b2_1) - r2 = ref_lerp_u8_byte(b0_2, b1_2, b2_2) - r3 = ref_lerp_u8_byte(b0_3, b1_3, b2_3) - - return pack_bytes_u32(r0, r1, r2, r3) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - VGPR = auto() - SGPR = auto() - - -@dataclass(frozen=True) -class Reg32: - """Represents a 32-bit architectural register (VGPR or SGPR).""" - index: int - reg_type: RegType - - def __post_init__(self) -> None: - if not (0 <= self.index <= 255): - raise ValueError(f"Register index {self.index} out of range [0, 255]") - - @property - def name(self) -> str: - prefix = "v" if self.reg_type == RegType.VGPR else "s" - return f"{prefix}{self.index}" - - -@dataclass(frozen=True) -class Literal32: - """Represents a 32-bit integer literal or inline constant.""" - value: int - - def __post_init__(self) -> None: - if not (0 <= self.value <= MASK32): - raise ValueError(f"Literal32 value {self.value:#x} out of range [0, 0xFFFFFFFF]") - - @property - def name(self) -> str: - return f"{self.value:#010x}" if self.value > 9 else str(self.value) - - -@dataclass(frozen=True) -class VLerpOperand: - """Typed expression operand representing a register or literal.""" - source: Union[Reg32, Literal32] - - def disassemble(self) -> str: - return self.source.name - - -@dataclass(frozen=True) -class VLerpU8Instruction: - """Symbolic AST node representing an RDNA2 v_lerp_u8 VALU instruction.""" - dst: Reg32 - src0: VLerpOperand - src1: VLerpOperand - src2: VLerpOperand - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination of VALU instruction must be VGPR, got {self.dst.reg_type}") - - def disassemble(self) -> str: - return f"v_lerp_u8 {self.dst.name}, {self.src0.disassemble()}, {self.src1.disassemble()}, {self.src2.disassemble()}" - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register file for a single execution thread.""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def get_vgpr(self, index: int) -> int: - if not (0 <= index <= 255): - raise IndexError(f"VGPR index {index} out of range [0, 255]") - return self.vgprs[index] & MASK32 - - def set_vgpr(self, index: int, val: int) -> None: - if not (0 <= index <= 255): - raise IndexError(f"VGPR index {index} out of range [0, 255]") - self.vgprs[index] = val & MASK32 - - def get_sgpr(self, index: int) -> int: - if not (0 <= index <= 255): - raise IndexError(f"SGPR index {index} out of range [0, 255]") - return self.sgprs[index] & MASK32 - - def set_sgpr(self, index: int, val: int) -> None: - if not (0 <= index <= 255): - raise IndexError(f"SGPR index {index} out of range [0, 255]") - self.sgprs[index] = val & MASK32 - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_lerp_u8.""" - - def resolve_operand(self, op: VLerpOperand, state: ScalarMachineState) -> int: - if isinstance(op.source, Reg32): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr(op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal32): - return op.source.value & MASK32 - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VLerpU8Instruction, state: ScalarMachineState) -> int: - # Atomic read phase - s0 = self.resolve_operand(instr.src0, state) - s1 = self.resolve_operand(instr.src1, state) - s2 = self.resolve_operand(instr.src2, state) - - # Computation phase - result = oracle_v_lerp_u8(s0, s1, s2) - - # Write-back phase - state.set_vgpr(instr.dst.index, result) - return result - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - num_lanes: int - exec_mask: Optional[int] = None - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - - def get_vgpr(self, lane: int, index: int) -> int: - if not (0 <= lane < self.num_lanes): - raise IndexError(f"Lane {lane} out of range [0, {self.num_lanes - 1}]") - if not (0 <= index <= 255): - raise IndexError(f"VGPR index {index} out of range [0, 255]") - return self.vgprs[lane][index] & MASK32 - - def set_vgpr(self, lane: int, index: int, val: int) -> None: - if not (0 <= lane < self.num_lanes): - raise IndexError(f"Lane {lane} out of range [0, {self.num_lanes - 1}]") - if not (0 <= index <= 255): - raise IndexError(f"VGPR index {index} out of range [0, 255]") - self.vgprs[lane][index] = val & MASK32 - - def get_sgpr(self, index: int) -> int: - if not (0 <= index <= 255): - raise IndexError(f"SGPR index {index} out of range [0, 255]") - return self.sgprs[index] & MASK32 - - def set_sgpr(self, index: int, val: int) -> None: - if not (0 <= index <= 255): - raise IndexError(f"SGPR index {index} out of range [0, 255]") - self.sgprs[index] = val & MASK32 - - -class SIMDInterpreter: - """SIMD instruction interpreter handling multi-lane divergence and EXEC masking.""" - - def resolve_lane_operand(self, op: VLerpOperand, state: SIMDState, lane: int) -> int: - if isinstance(op.source, Reg32): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr(lane, op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal32): - return op.source.value & MASK32 - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VLerpU8Instruction, state: SIMDState) -> List[Optional[int]]: - results: List[Optional[int]] = [None] * state.num_lanes - # Atomic read phase across all lanes - s0_vals = [ - self.resolve_lane_operand(instr.src0, state, lane) - for lane in range(state.num_lanes) - ] - s1_vals = [ - self.resolve_lane_operand(instr.src1, state, lane) - for lane in range(state.num_lanes) - ] - s2_vals = [ - self.resolve_lane_operand(instr.src2, state, lane) - for lane in range(state.num_lanes) - ] - - # Execution and selective write-back phase - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - res = oracle_v_lerp_u8(s0_vals[lane], s1_vals[lane], s2_vals[lane]) - state.set_vgpr(lane, instr.dst.index, res) - results[lane] = res - - return results - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry Generation -# ============================================================================== - -@dataclass(frozen=True) -class PackedByteFlags: - """Architectural condition codes and status flags for packed 8-bit operations.""" - zero: bool - all_zero: bool - any_zero: bool - lane_zero: Tuple[bool, bool, bool, bool] - lane_max: Tuple[bool, bool, bool, bool] - carry_out: Tuple[bool, bool, bool, bool] - round_carry: Tuple[bool, bool, bool, bool] - odd_parity: Tuple[bool, bool, bool, bool] - - -def compute_byte_parity(val: int) -> bool: - """Return True if 8-bit byte has odd number of set bits.""" - return bin(val & MASK8).count("1") % 2 == 1 - - -def compute_lerp_byte_carry_generation(b0: int, b1: int, r: int) -> Tuple[int, int, int]: - """Compute 9-bit intermediate sum, bit 8 carry out, and 8-bit quotient for a byte lane.""" - sum9 = (b0 & MASK8) + (b1 & MASK8) + (r & 0x01) - carry_out = 1 if sum9 >= 256 else 0 - quotient = (sum9 >> 1) & MASK8 - return sum9, carry_out, quotient - - -def evaluate_v_lerp_u8_flags(src0: int, src1: int, src2: int, res: int) -> PackedByteFlags: - """Evaluate packed byte condition codes, zero states, and carry generation flags.""" - b0_lanes = unpack_bytes_u32(src0) - b1_lanes = unpack_bytes_u32(src1) - b2_lanes = unpack_bytes_u32(src2) - res_lanes = unpack_bytes_u32(res) - - lane_zero: List[bool] = [] - lane_max: List[bool] = [] - carry_out: List[bool] = [] - round_carry: List[bool] = [] - odd_parity: List[bool] = [] - +def ref(s0, s1, s2): + out = 0 for i in range(4): - b0 = b0_lanes[i] - b1 = b1_lanes[i] - r = b2_lanes[i] & 0x01 - res_b = res_lanes[i] - - sum9, carry, _ = compute_lerp_byte_carry_generation(b0, b1, r) - - lane_zero.append(res_b == 0) - lane_max.append(res_b == 0xFF) - carry_out.append(bool(carry)) - round_carry.append(((b0 + b1) % 2 == 1) and (r == 1)) - odd_parity.append(compute_byte_parity(res_b)) - - all_z = all(lane_zero) - any_z = any(lane_zero) - - return PackedByteFlags( - zero=all_z, - all_zero=all_z, - any_zero=any_z, - lane_zero=(lane_zero[0], lane_zero[1], lane_zero[2], lane_zero[3]), - lane_max=(lane_max[0], lane_max[1], lane_max[2], lane_max[3]), - carry_out=(carry_out[0], carry_out[1], carry_out[2], carry_out[3]), - round_carry=(round_carry[0], round_carry[1], round_carry[2], round_carry[3]), - odd_parity=(odd_parity[0], odd_parity[1], odd_parity[2], odd_parity[3]), - ) - - - - - - -# ============================================================================== -# Unit Tests: Model and Reference Oracle -# ============================================================================== - -class TestVLerpU8ModelAndOracle(unittest.TestCase): - """Unit tests for RDNA2 v_lerp_u8 architectural bit model and reference oracle.""" - - def test_byte_unpack_pack_roundtrip(self) -> None: - patterns = [ - 0x00000000, - 0xFFFFFFFF, - 0x12345678, - 0xA55A3C7E, - 0x01020304, - 0x80402010, - ] - for pat in patterns: - with self.subTest(pattern=hex(pat)): - b0, b1, b2, b3 = unpack_bytes_u32(pat) - repacked = pack_bytes_u32(b0, b1, b2, b3) - self.assertEqual(repacked, pat) - - def test_reference_known_vectors(self) -> None: - # 0xFF and 0xFF with round=1 -> 0xFF - self.assertEqual(oracle_v_lerp_u8(0xFF, 0xFF, 1), 0xFF) - # 0x01 and 0x02 with round=0 -> 1 ((1+2+0)>>1 == 1) - self.assertEqual(oracle_v_lerp_u8(0x01, 0x02, 0), 0x01) - # 0x01 and 0x02 with round=1 -> 2 ((1+2+1)>>1 == 2) - self.assertEqual(oracle_v_lerp_u8(0x01, 0x02, 1), 0x02) - # Multi-lane distinct bytes - s0 = 0x10203040 - s1 = 0x30405060 - # lane 0: (0x40+0x60)>>1 = (64+96)>>1 = 80 = 0x50 - # lane 1: (0x30+0x50)>>1 = (48+80)>>1 = 64 = 0x40 - # lane 2: (0x20+0x40)>>1 = (32+64)>>1 = 48 = 0x30 - # lane 3: (0x10+0x30)>>1 = (16+48)>>1 = 32 = 0x20 - self.assertEqual(oracle_v_lerp_u8(s0, s1, 0), 0x20304050) - - def test_rounding_control(self) -> None: - # Odd sum: 3 + 4 = 7. Round 0 -> 3; Round 1 -> 4 - s0 = 0x03030303 - s1 = 0x04040404 - self.assertEqual(oracle_v_lerp_u8(s0, s1, 0x00000000), 0x03030303) - self.assertEqual(oracle_v_lerp_u8(s0, s1, 0x01010101), 0x04040404) - - # Mixed round bits per lane - s2 = pack_bytes_u32(0, 1, 0, 1) - expected = pack_bytes_u32(3, 4, 3, 4) - self.assertEqual(oracle_v_lerp_u8(s0, s1, s2), expected) - - def test_s2_upper_bits_discarded(self) -> None: - s0 = 0x10203040 - s1 = 0x10203040 - # s2 has bits [7:1] set (0xFE in every lane), but bit 0 is 0 - s2_upper = 0xFEFEFEFE - self.assertEqual(oracle_v_lerp_u8(s0, s1, s2_upper), s0) - - # s2 has bits [7:0] set (0xFF in every lane), bit 0 is 1 - s2_all = 0xFFFFFFFF - self.assertEqual(oracle_v_lerp_u8(s0, s1, s2_all), oracle_v_lerp_u8(s0, s1, 0x01010101)) - - def test_commutativity_src0_src1(self) -> None: - pairs = [ - (0x00000000, 0xFFFFFFFF, 0x01010101), - (0x12345678, 0x9ABCDEF0, 0x00000000), - (0x55555555, 0xAAAAAAAA, 0xFFFFFFFF), - (0xFEEDBEEF, 0x01020304, 0x01000100), - ] - for s0, s1, s2 in pairs: - with self.subTest(s0=hex(s0), s1=hex(s1)): - self.assertEqual(oracle_v_lerp_u8(s0, s1, s2), oracle_v_lerp_u8(s1, s0, s2)) - - def test_identity_property(self) -> None: - for val in [0x00000000, 0x7F7F7F7F, 0x80808080, 0xFFFFFFFF, 0x12345678]: - with self.subTest(val=hex(val)): - self.assertEqual(oracle_v_lerp_u8(val, val, 0x00000000), val) - self.assertEqual(oracle_v_lerp_u8(val, val, 0x01010101), val) - - def test_no_cross_lane_bleed(self) -> None: - # Lane 0 reaches max sum 511 (255 + 255 + 1). Does it bleed into Lane 1? - s0 = 0x000000FF - s1 = 0x000000FF - s2 = 0x00000001 - res = oracle_v_lerp_u8(s0, s1, s2) - self.assertEqual(res, 0x000000FF) - b0, b1, b2, b3 = unpack_bytes_u32(res) - self.assertEqual(b0, 0xFF) - self.assertEqual(b1, 0x00) - self.assertEqual(b2, 0x00) - self.assertEqual(b3, 0x00) - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_register_validation_and_naming(self) -> None: - v0 = Reg32(0, RegType.VGPR) - v255 = Reg32(255, RegType.VGPR) - s12 = Reg32(12, RegType.SGPR) - self.assertEqual(v0.name, "v0") - self.assertEqual(v255.name, "v255") - self.assertEqual(s12.name, "s12") - - def test_register_bounds_rejection(self) -> None: - with self.assertRaises(ValueError): - Reg32(-1, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(1000, RegType.SGPR) - - def test_literal_values_and_naming(self) -> None: - lit_small = Literal32(1) - lit_hex = Literal32(0x10203040) - self.assertEqual(lit_small.name, "1") - self.assertEqual(lit_hex.name, "0x10203040") - - with self.assertRaises(ValueError): - Literal32(-1) - with self.assertRaises(ValueError): - Literal32(0x1_0000_0000) - - def test_instruction_ast_construction_and_disassembly(self) -> None: - dst = Reg32(0, RegType.VGPR) - src0 = VLerpOperand(Reg32(1, RegType.VGPR)) - src1 = VLerpOperand(Reg32(4, RegType.SGPR)) - src2 = VLerpOperand(Literal32(1)) - - instr = VLerpU8Instruction(dst=dst, src0=src0, src1=src1, src2=src2) - self.assertEqual(instr.disassemble(), "v_lerp_u8 v0, v1, s4, 1") - - def test_destination_must_be_vgpr(self) -> None: - dst_sgpr = Reg32(0, RegType.SGPR) - src = VLerpOperand(Reg32(1, RegType.VGPR)) - with self.assertRaises(TypeError): - VLerpU8Instruction(dst=dst_sgpr, src0=src, src1=src, src2=src) - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for deterministic scalar interpreter.""" - - def setUp(self) -> None: - self.state = ScalarMachineState() - self.interp = ScalarInterpreter() - - def test_scalar_state_get_set(self) -> None: - self.assertEqual(self.state.get_vgpr(0), 0) - self.assertEqual(self.state.get_sgpr(0), 0) - - self.state.set_vgpr(10, 0x12345678) - self.assertEqual(self.state.get_vgpr(10), 0x12345678) - - self.state.set_sgpr(5, 0xABCDEF01) - self.assertEqual(self.state.get_sgpr(5), 0xABCDEF01) - - # 32-bit masking - self.state.set_vgpr(1, 0x1_0000_0042) - self.assertEqual(self.state.get_vgpr(1), 0x42) - - with self.assertRaises(IndexError): - self.state.get_vgpr(-1) - with self.assertRaises(IndexError): - self.state.get_vgpr(256) - - def test_scalar_step_vgpr_sources(self) -> None: - self.state.set_vgpr(1, 0x10203040) - self.state.set_vgpr(2, 0x30405060) - self.state.set_vgpr(3, 0x01000100) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(1, RegType.VGPR)), - src1=VLerpOperand(Reg32(2, RegType.VGPR)), - src2=VLerpOperand(Reg32(3, RegType.VGPR)), - ) - - res = self.interp.step(instr, self.state) - expected = oracle_v_lerp_u8(0x10203040, 0x30405060, 0x01000100) - self.assertEqual(res, expected) - self.assertEqual(self.state.get_vgpr(0), expected) - - def test_scalar_step_mixed_sources_sgpr_and_literal(self) -> None: - self.state.set_vgpr(1, 0x02040608) - self.state.set_sgpr(4, 0x0406080A) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(1, RegType.VGPR)), - src1=VLerpOperand(Reg32(4, RegType.SGPR)), - src2=VLerpOperand(Literal32(1)), - ) - - res = self.interp.step(instr, self.state) - expected = oracle_v_lerp_u8(0x02040608, 0x0406080A, 1) - self.assertEqual(res, expected) - self.assertEqual(self.state.get_vgpr(0), expected) - - def test_sequential_instruction_flow(self) -> None: - # v0 = lerp(0x10101010, 0x20202020, 0) -> 0x18181818 - # v1 = lerp(v0, 0x30303030, 1) -> lerp(0x18181818, 0x30303030, 1) - self.state.set_vgpr(2, 0x10101010) - self.state.set_vgpr(3, 0x20202020) - self.state.set_vgpr(4, 0x30303030) - - instr1 = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(2, RegType.VGPR)), - src1=VLerpOperand(Reg32(3, RegType.VGPR)), - src2=VLerpOperand(Literal32(0)), - ) - res1 = self.interp.step(instr1, self.state) - self.assertEqual(res1, 0x18181818) - - instr2 = VLerpU8Instruction( - dst=Reg32(1, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), - src1=VLerpOperand(Reg32(4, RegType.VGPR)), - src2=VLerpOperand(Literal32(1)), - ) - res2 = self.interp.step(instr2, self.state) - # (0x18 + 0x30 + 1) >> 1 = (24 + 48 + 1) >> 1 = 73 >> 1 = 36 = 0x24 - self.assertEqual(res2, 0x24242424) - self.assertEqual(self.state.get_vgpr(1), 0x24242424) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_all_lanes_active(self) -> None: - state = SIMDState(num_lanes=32) - interp = SIMDInterpreter() - - for lane in range(32): - s0_val = pack_bytes_u32(lane * 2, lane * 3, lane * 4, lane * 5) - s1_val = pack_bytes_u32(10, 20, 30, 40) - s2_val = pack_bytes_u32(lane & 1, (lane >> 1) & 1, 0, 1) - state.set_vgpr(lane, 1, s0_val) - state.set_vgpr(lane, 2, s1_val) - state.set_vgpr(lane, 3, s2_val) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(1, RegType.VGPR)), - src1=VLerpOperand(Reg32(2, RegType.VGPR)), - src2=VLerpOperand(Reg32(3, RegType.VGPR)), - ) - - results = interp.step(instr, state) - self.assertEqual(len(results), 32) - for lane in range(32): - expected = oracle_v_lerp_u8( - state.get_vgpr(lane, 1), - state.get_vgpr(lane, 2), - state.get_vgpr(lane, 3), - ) - self.assertEqual(results[lane], expected) - self.assertEqual(state.get_vgpr(lane, 0), expected) - - def test_wave64_all_lanes_active(self) -> None: - state = SIMDState(num_lanes=64) - interp = SIMDInterpreter() - - for lane in range(64): - state.set_vgpr(lane, 1, pack_bytes_u32(lane, lane ^ 0x55, 100, 200)) - state.set_vgpr(lane, 2, pack_bytes_u32(50, 60, 70, 80)) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(1, RegType.VGPR)), - src1=VLerpOperand(Reg32(2, RegType.VGPR)), - src2=VLerpOperand(Literal32(1)), - ) - - results = interp.step(instr, state) - self.assertEqual(len(results), 64) - for lane in range(64): - expected = oracle_v_lerp_u8( - state.get_vgpr(lane, 1), - state.get_vgpr(lane, 2), - 1, - ) - self.assertEqual(results[lane], expected) - self.assertEqual(state.get_vgpr(lane, 0), expected) - - def test_partial_exec_mask_even_lanes(self) -> None: - sentinel = 0xDEADBEEF - state = SIMDState(num_lanes=32, exec_mask=0x55555555) # only even lanes active - interp = SIMDInterpreter() - - for lane in range(32): - state.set_vgpr(lane, 0, sentinel) - state.set_vgpr(lane, 1, 0x10203040) - state.set_vgpr(lane, 2, 0x50607080) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(1, RegType.VGPR)), - src1=VLerpOperand(Reg32(2, RegType.VGPR)), - src2=VLerpOperand(Literal32(0)), - ) - - results = interp.step(instr, state) - expected = oracle_v_lerp_u8(0x10203040, 0x50607080, 0) - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(results[lane], expected) - self.assertEqual(state.get_vgpr(lane, 0), expected) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr(lane, 0), sentinel) - - def test_zero_exec_mask_no_modification(self) -> None: - sentinel = 0xCAFEBABE - state = SIMDState(num_lanes=32, exec_mask=0) - interp = SIMDInterpreter() - - for lane in range(32): - state.set_vgpr(lane, 0, sentinel) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Literal32(0xFFFFFFFF)), - src1=VLerpOperand(Literal32(0xFFFFFFFF)), - src2=VLerpOperand(Literal32(1)), - ) - - results = interp.step(instr, state) - self.assertEqual(results, [None] * 32) - for lane in range(32): - self.assertEqual(state.get_vgpr(lane, 0), sentinel) - - def test_sgpr_scalar_broadcast_across_divergent_lanes(self) -> None: - state = SIMDState(num_lanes=32) - interp = SIMDInterpreter() - - state.set_sgpr(5, 0x20202020) # broadcast to all lanes - for lane in range(32): - state.set_vgpr(lane, 1, pack_bytes_u32(lane, lane, lane, lane)) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(1, RegType.VGPR)), - src1=VLerpOperand(Reg32(5, RegType.SGPR)), - src2=VLerpOperand(Literal32(1)), - ) - - results = interp.step(instr, state) - for lane in range(32): - expected = oracle_v_lerp_u8( - pack_bytes_u32(lane, lane, lane, lane), - 0x20202020, - 1, - ) - self.assertEqual(results[lane], expected) - self.assertEqual(state.get_vgpr(lane, 0), expected) - - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_dst_aliases_src0(self) -> None: - state = ScalarMachineState() - interp = ScalarInterpreter() - - val_a = 0x10203040 - val_b = 0x30405060 - round_val = 0x01000100 - - state.set_vgpr(0, val_a) - state.set_vgpr(1, val_b) - state.set_vgpr(2, round_val) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), # Aliased with dst - src1=VLerpOperand(Reg32(1, RegType.VGPR)), - src2=VLerpOperand(Reg32(2, RegType.VGPR)), - ) - - expected = oracle_v_lerp_u8(val_a, val_b, round_val) - res = interp.step(instr, state) - self.assertEqual(res, expected) - self.assertEqual(state.get_vgpr(0), expected) - # Verify src1 and src2 remain intact - self.assertEqual(state.get_vgpr(1), val_b) - self.assertEqual(state.get_vgpr(2), round_val) - - def test_dst_aliases_src1(self) -> None: - state = ScalarMachineState() - interp = ScalarInterpreter() - - val_a = 0x10203040 - val_b = 0x30405060 - round_val = 0x00010001 - - state.set_vgpr(0, val_a) - state.set_vgpr(1, val_b) - state.set_vgpr(2, round_val) - - instr = VLerpU8Instruction( - dst=Reg32(1, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), - src1=VLerpOperand(Reg32(1, RegType.VGPR)), # Aliased with dst - src2=VLerpOperand(Reg32(2, RegType.VGPR)), - ) - - expected = oracle_v_lerp_u8(val_a, val_b, round_val) - res = interp.step(instr, state) - self.assertEqual(res, expected) - self.assertEqual(state.get_vgpr(1), expected) - self.assertEqual(state.get_vgpr(0), val_a) - self.assertEqual(state.get_vgpr(2), round_val) - - def test_dst_aliases_src2(self) -> None: - state = ScalarMachineState() - interp = ScalarInterpreter() - - val_a = 0x10203040 - val_b = 0x30405060 - round_val = 0x01010101 - - state.set_vgpr(0, val_a) - state.set_vgpr(1, val_b) - state.set_vgpr(2, round_val) - - instr = VLerpU8Instruction( - dst=Reg32(2, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), - src1=VLerpOperand(Reg32(1, RegType.VGPR)), - src2=VLerpOperand(Reg32(2, RegType.VGPR)), # Aliased with dst - ) - - expected = oracle_v_lerp_u8(val_a, val_b, round_val) - res = interp.step(instr, state) - self.assertEqual(res, expected) - self.assertEqual(state.get_vgpr(2), expected) - self.assertEqual(state.get_vgpr(0), val_a) - self.assertEqual(state.get_vgpr(1), val_b) - - def test_dst_aliases_src0_and_src1(self) -> None: - state = ScalarMachineState() - interp = ScalarInterpreter() - - val = 0x55AA33CC - state.set_vgpr(0, val) - - # Self-average: lerp(v0, v0, 0) == v0 and lerp(v0, v0, 1) == v0 - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), - src1=VLerpOperand(Reg32(0, RegType.VGPR)), - src2=VLerpOperand(Literal32(1)), - ) - - res = interp.step(instr, state) - self.assertEqual(res, val) - self.assertEqual(state.get_vgpr(0), val) - - def test_dst_aliases_all_operands(self) -> None: - state = ScalarMachineState() - interp = ScalarInterpreter() - - val = 0x7E8081FF - state.set_vgpr(0, val) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), - src1=VLerpOperand(Reg32(0, RegType.VGPR)), - src2=VLerpOperand(Reg32(0, RegType.VGPR)), - ) - - expected = oracle_v_lerp_u8(val, val, val) - self.assertEqual(expected, val) - res = interp.step(instr, state) - self.assertEqual(res, val) - self.assertEqual(state.get_vgpr(0), val) - - def test_simd_multi_lane_aliased_dst_preservation(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0x0000FFFF) # lanes 0..15 active, 16..31 inactive - interp = SIMDInterpreter() - - original_v0 = [0x10000000 | lane for lane in range(32)] - for lane in range(32): - state.set_vgpr(lane, 0, original_v0[lane]) - state.set_vgpr(lane, 1, 0x20202020) - - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), # Aliased - src1=VLerpOperand(Reg32(1, RegType.VGPR)), - src2=VLerpOperand(Literal32(0)), - ) - - interp.step(instr, state) - - for lane in range(32): - if lane < 16: - expected = oracle_v_lerp_u8(original_v0[lane], 0x20202020, 0) - self.assertEqual(state.get_vgpr(lane, 0), expected) - else: - self.assertEqual(state.get_vgpr(lane, 0), original_v0[lane]) - - def test_chained_in_place_accumulation(self) -> None: - state = ScalarMachineState() - interp = ScalarInterpreter() - - # Filtering sequence: v0 = lerp(v0, v1, 1); v0 = lerp(v0, v2, 0) - state.set_vgpr(0, 0x00000000) - state.set_vgpr(1, 0x64646464) # 100 - state.set_vgpr(2, 0xC8C8C8C8) # 200 - - instr1 = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), - src1=VLerpOperand(Reg32(1, RegType.VGPR)), - src2=VLerpOperand(Literal32(1)), - ) - res1 = interp.step(instr1, state) - # (0 + 100 + 1) >> 1 = 50 (0x32) - self.assertEqual(res1, 0x32323232) - self.assertEqual(state.get_vgpr(0), 0x32323232) - - instr2 = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Reg32(0, RegType.VGPR)), - src1=VLerpOperand(Reg32(2, RegType.VGPR)), - src2=VLerpOperand(Literal32(0)), - ) - res2 = interp.step(instr2, state) - # (50 + 200 + 0) >> 1 = 125 (0x7D) - self.assertEqual(res2, 0x7D7D7D7D) - self.assertEqual(state.get_vgpr(0), 0x7D7D7D7D) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry generation.""" - - def test_all_zero_flag(self) -> None: - res = oracle_v_lerp_u8(0, 0, 0) - flags = evaluate_v_lerp_u8_flags(0, 0, 0, res) - self.assertTrue(flags.zero) - self.assertTrue(flags.all_zero) - self.assertTrue(flags.any_zero) - self.assertEqual(flags.lane_zero, (True, True, True, True)) - self.assertEqual(flags.lane_max, (False, False, False, False)) - self.assertEqual(flags.carry_out, (False, False, False, False)) - - def test_partial_lane_zero_flags(self) -> None: - # Lane 0 is 0, Lane 1 is 10, Lane 2 is 20, Lane 3 is 30 - s0 = pack_bytes_u32(0, 20, 40, 60) - s1 = pack_bytes_u32(0, 0, 0, 0) - res = oracle_v_lerp_u8(s0, s1, 0) - flags = evaluate_v_lerp_u8_flags(s0, s1, 0, res) - - self.assertFalse(flags.zero) - self.assertFalse(flags.all_zero) - self.assertTrue(flags.any_zero) - self.assertEqual(flags.lane_zero, (True, False, False, False)) - - def test_lane_max_flags(self) -> None: - s0 = pack_bytes_u32(0xFF, 0xFE, 0xFF, 0x80) - s1 = pack_bytes_u32(0xFF, 0xFF, 0xFF, 0x80) - s2 = pack_bytes_u32(0x01, 0x01, 0x00, 0x00) - # Lane 0: (255+255+1)>>1 = 255 (0xFF) -> lane_max True - # Lane 1: (254+255+1)>>1 = 255 (0xFF) -> lane_max True - # Lane 2: (255+255+0)>>1 = 255 (0xFF) -> lane_max True - # Lane 3: (128+128+0)>>1 = 128 (0x80) -> lane_max False - res = oracle_v_lerp_u8(s0, s1, s2) - flags = evaluate_v_lerp_u8_flags(s0, s1, s2, res) - self.assertEqual(flags.lane_max, (True, True, True, False)) - - def test_carry_out_bit8_generation(self) -> None: - # Lane 0: 127 + 128 + 0 = 255 (sum < 256 -> carry_out False) - # Lane 1: 128 + 128 + 0 = 256 (sum >= 256 -> carry_out True) - # Lane 2: 200 + 100 + 0 = 300 (sum >= 256 -> carry_out True) - # Lane 3: 255 + 255 + 1 = 511 (sum >= 256 -> carry_out True) - s0 = pack_bytes_u32(127, 128, 200, 255) - s1 = pack_bytes_u32(128, 128, 100, 255) - s2 = pack_bytes_u32(0, 0, 0, 1) - - res = oracle_v_lerp_u8(s0, s1, s2) - flags = evaluate_v_lerp_u8_flags(s0, s1, s2, res) - self.assertEqual(flags.carry_out, (False, True, True, True)) - - def test_round_carry_generation(self) -> None: - # Lane 0: 1 + 2 + 1 -> (1+2)=3 is odd, r=1 -> round_carry True, res=(4>>1)=2 - # Lane 1: 1 + 2 + 0 -> (1+2)=3 is odd, r=0 -> round_carry False, res=(3>>1)=1 - # Lane 2: 2 + 4 + 1 -> (2+4)=6 is even, r=1 -> round_carry False, res=(7>>1)=3 - # Lane 3: 2 + 4 + 0 -> (2+4)=6 is even, r=0 -> round_carry False, res=(6>>1)=3 - s0 = pack_bytes_u32(1, 1, 2, 2) - s1 = pack_bytes_u32(2, 2, 4, 4) - s2 = pack_bytes_u32(1, 0, 1, 0) - - res = oracle_v_lerp_u8(s0, s1, s2) - flags = evaluate_v_lerp_u8_flags(s0, s1, s2, res) - self.assertEqual(flags.round_carry, (True, False, False, False)) - - def test_odd_parity_per_lane(self) -> None: - # Byte values: 0 (0 ones -> even/False), 1 (1 one -> odd/True), - # 3 (2 ones -> even/False), 7 (3 ones -> odd/True) - res = pack_bytes_u32(0, 1, 3, 7) - flags = evaluate_v_lerp_u8_flags(0, 0, 0, res) - self.assertEqual(flags.odd_parity, (False, True, False, True)) - - def test_compute_lerp_byte_carry_generation_helper(self) -> None: - sum9, carry, q = compute_lerp_byte_carry_generation(255, 255, 1) - self.assertEqual(sum9, 511) - self.assertEqual(carry, 1) - self.assertEqual(q, 255) - - sum9_zero, carry_zero, q_zero = compute_lerp_byte_carry_generation(0, 0, 0) - self.assertEqual(sum9_zero, 0) - self.assertEqual(carry_zero, 0) - self.assertEqual(q_zero, 0) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 float bit pattern handling, byte extremes, and boundary limits.""" - - def test_ieee754_special_float_bitpatterns_treated_as_raw_bytes(self) -> None: - # v_lerp_u8 is an integer byte-packing VALU instruction. - # When shaders feed bit-casts of IEEE 754 floats (+0, -0, +inf, -inf, qnan, snan), - # hardware treats them strictly as raw byte fields without FPU traps or quietening. - pos_zero = 0x0000_0000 - neg_zero = 0x8000_0000 - pos_inf = 0x7F80_0000 - neg_inf = 0xFF80_0000 - qnan = 0x7FC0_0000 - snan = 0x7F80_0001 - - special_floats = [pos_zero, neg_zero, pos_inf, neg_inf, qnan, snan] - for f1 in special_floats: - for f2 in special_floats: - with self.subTest(f1=hex(f1), f2=hex(f2)): - res0 = oracle_v_lerp_u8(f1, f2, 0x0000_0000) - res1 = oracle_v_lerp_u8(f1, f2, 0x0101_0101) - - # Verify each byte lane equals integer unpack arithmetic - b1 = unpack_bytes_u32(f1) - b2 = unpack_bytes_u32(f2) - expected0 = pack_bytes_u32( - (b1[0] + b2[0]) >> 1, - (b1[1] + b2[1]) >> 1, - (b1[2] + b2[2]) >> 1, - (b1[3] + b2[3]) >> 1, - ) - expected1 = pack_bytes_u32( - (b1[0] + b2[0] + 1) >> 1, - (b1[1] + b2[1] + 1) >> 1, - (b1[2] + b2[2] + 1) >> 1, - (b1[3] + b2[3] + 1) >> 1, - ) - self.assertEqual(res0, expected0) - self.assertEqual(res1, expected1) - - def test_subnormal_float_bits_no_flush_to_zero(self) -> None: - # Subnormal float 1: 0x00000001 (smallest positive subnormal) - # Subnormal float 3: 0x00000003 - # Should average to 0x00000002 without flushing subnormal bit 0 to 0. - sub1 = 0x0000_0001 - sub3 = 0x0000_0003 - res = oracle_v_lerp_u8(sub1, sub3, 0) - self.assertEqual(res, 0x0000_0002) - - def test_nan_payload_treated_as_raw_byte_data(self) -> None: - nan_with_payload = 0x7FA5_5A3C - zero = 0x0000_0000 - # Lerp with 0 and round=0 simply divides each byte by 2 - res = oracle_v_lerp_u8(nan_with_payload, zero, 0) - b = unpack_bytes_u32(nan_with_payload) - expected = pack_bytes_u32(b[0] >> 1, b[1] >> 1, b[2] >> 1, b[3] >> 1) - self.assertEqual(res, expected) - - def test_extreme_byte_boundary_combinations(self) -> None: - extreme_bytes = [0x00, 0x01, 0x02, 0x7E, 0x7F, 0x80, 0x81, 0xFE, 0xFF] - for b0 in extreme_bytes: - for b1 in extreme_bytes: - for r in (0, 1): - val = ref_lerp_u8_byte(b0, b1, r) - self.assertGreaterEqual(val, 0) - self.assertLessEqual(val, 255) - expected = (b0 + b1 + r) >> 1 - self.assertEqual(val, expected) - - def test_maximum_intermediate_sum_saturation_boundary(self) -> None: - # Max byte 255 in all lanes: 255 + 255 + 1 = 511; 511 >> 1 = 255 (0xFF) - s0 = 0xFFFF_FFFF - s1 = 0xFFFF_FFFF - s2 = 0x0101_0101 - res = oracle_v_lerp_u8(s0, s1, s2) - self.assertEqual(res, 0xFFFF_FFFF) - - def test_minimum_intermediate_sum_boundary(self) -> None: - # Min byte 0 in all lanes: (0 + 0 + 0) >> 1 = 0 - self.assertEqual(oracle_v_lerp_u8(0, 0, 0), 0) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Reg32(-1, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(999, RegType.SGPR) - - def test_syntax_rejection_valu_destination_must_be_vgpr(self) -> None: - dst_sgpr = Reg32(0, RegType.SGPR) - src = VLerpOperand(Reg32(1, RegType.VGPR)) - with self.assertRaises(TypeError): - VLerpU8Instruction(dst=dst_sgpr, src0=src, src1=src, src2=src) - - def test_syntax_rejection_invalid_simd_lane_count(self) -> None: - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDState(num_lanes=128) - - def test_negative_control_bit_flip_detection(self) -> None: - s0 = 0x10203040 - s1 = 0x50607080 - s2 = 0x01000100 - correct = oracle_v_lerp_u8(s0, s1, s2) - - # Corrupt single bits across different byte lanes - for bit_pos in (0, 7, 8, 15, 16, 23, 24, 31): - corrupted = correct ^ (1 << bit_pos) - self.assertNotEqual(correct, corrupted) - - def test_mutation_unmasked_s2_upper_bits_detected(self) -> None: - """Mutant: S2 upper bits [7:1] are added rather than discarded.""" - def mutant_lerp_byte(b0: int, b1: int, s2_byte: int) -> int: - # Bug: fails to mask s2 with 0x01 - return ((b0 + b1 + (s2_byte & 0xFF)) >> 1) & MASK8 - - s0 = 0x20 - s1 = 0x20 - s2 = 0xFE # Bit 0 is 0, bits [7:1] set (254) - - oracle_res = ref_lerp_u8_byte(s0, s1, s2) - mutant_res = mutant_lerp_byte(s0, s1, s2) - - # Oracle ignores bits [7:1] -> (32 + 32 + 0) >> 1 = 32 - self.assertEqual(oracle_res, 0x20) - # Mutant adds 254 -> (32 + 32 + 254) >> 1 = 159 - self.assertEqual(mutant_res, 159) - self.assertNotEqual(oracle_res, mutant_res) - - def test_mutation_inverted_round_bit_detected(self) -> None: - """Mutant: Subtracts round bit instead of adding.""" - def mutant_lerp_byte(b0: int, b1: int, r: int) -> int: - # Bug: subtracts r - return ((b0 + b1 - (r & 1)) >> 1) & MASK8 - - s0 = 1 - s1 = 2 - r = 1 - - oracle_res = ref_lerp_u8_byte(s0, s1, r) - mutant_res = mutant_lerp_byte(s0, s1, r) - - # (1 + 2 + 1) >> 1 = 2 - self.assertEqual(oracle_res, 2) - # (1 + 2 - 1) >> 1 = 1 - self.assertEqual(mutant_res, 1) - self.assertNotEqual(oracle_res, mutant_res) - - def test_mutation_signed_byte_interpretation_detected(self) -> None: - """Mutant: Treats byte operands as signed int8 (-128..127).""" - def mutant_lerp_byte(b0: int, b1: int, r: int) -> int: - # Bug: signed cast - sb0 = (b0 & 0xFF) if (b0 & 0x80) == 0 else (b0 & 0xFF) - 256 - sb1 = (b1 & 0xFF) if (b1 & 0x80) == 0 else (b1 & 0xFF) - 256 - return ((sb0 + sb1 + (r & 1)) >> 1) & MASK8 - - s0 = 0xFF # 255 unsigned, -1 signed - s1 = 0x00 # 0 - r = 0 - - oracle_res = ref_lerp_u8_byte(s0, s1, r) - mutant_res = mutant_lerp_byte(s0, s1, r) - - # Unsigned average: (255 + 0) >> 1 = 127 (0x7F) - self.assertEqual(oracle_res, 0x7F) - # Signed average: (-1 + 0) >> 1 = -1 (0xFF) - self.assertEqual(mutant_res, 0xFF) - self.assertNotEqual(oracle_res, mutant_res) - - def test_mutation_premature_shift_detected(self) -> None: - """Mutant: Shifts operands before addition.""" - def mutant_lerp_byte(b0: int, b1: int, r: int) -> int: - # Bug: premature shift loses odd LSB - return ((b0 >> 1) + (b1 >> 1) + (r & 1)) & MASK8 - - s0 = 1 - s1 = 1 - r = 0 - - oracle_res = ref_lerp_u8_byte(s0, s1, r) - mutant_res = mutant_lerp_byte(s0, s1, r) - - # (1 + 1 + 0) >> 1 = 1 - self.assertEqual(oracle_res, 1) - # (0 + 0 + 0) = 0 - self.assertEqual(mutant_res, 0) - self.assertNotEqual(oracle_res, mutant_res) - - def test_mutation_ignore_simd_exec_mask_detected(self) -> None: - """Mutant: SIMD interpreter writes inactive lanes.""" - sentinel = 0xCAFEBABE - state = SIMDState(num_lanes=32, exec_mask=0x00000000) # all inactive - for lane in range(32): - state.set_vgpr(lane, 0, sentinel) - - class BrokenSIMDInterpreter(SIMDInterpreter): - def step(self, instr: VLerpU8Instruction, state: SIMDState) -> List[Optional[int]]: - results = [] - for lane in range(state.num_lanes): - # Bug: no exec_mask check - res = oracle_v_lerp_u8(0, 0, 0) - state.set_vgpr(lane, instr.dst.index, res) - results.append(res) - return results - - broken = BrokenSIMDInterpreter() - instr = VLerpU8Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VLerpOperand(Literal32(0)), - src1=VLerpOperand(Literal32(0)), - src2=VLerpOperand(Literal32(0)), - ) - broken.step(instr, state) - - # All 32 lanes were erroneously overwritten - corrupted = [lane for lane in range(32) if state.get_vgpr(lane, 0) != sentinel] - self.assertEqual(len(corrupted), 32) - - def test_mutation_cross_byte_carry_bleed_detected(self) -> None: - """Mutant: Whole 32-bit addition without per-byte lane isolation.""" - def mutant_lerp_u32(s0: int, s1: int, s2: int) -> int: - # Bug: unisolated 32-bit addition bleeds carries across bytes - return ((s0 + s1 + (s2 & 1)) >> 1) & MASK32 - - # In byte 0, 255 + 255 + 0 = 510 = 0x1FE (bit 8 carry) - s0 = 0x0000_00FF - s1 = 0x0000_00FF - s2 = 0x0000_0000 - - oracle_res = oracle_v_lerp_u8(s0, s1, s2) - mutant_res = mutant_lerp_u32(s0, s1, s2) - - # Oracle keeps lane 1 isolated at 0x00 - self.assertEqual(oracle_res, 0x0000_00FF) - # Mutant bleeds carry into lane 1: (0x1FE >> 1) = 0xFF (happens to match byte 0), - # but let's test where carry actually crosses lane boundaries: - s0_bleed = 0x0000_01FF - s1_bleed = 0x0000_01FF - oracle_bleed = oracle_v_lerp_u8(s0_bleed, s1_bleed, 0) - mutant_bleed = mutant_lerp_u32(s0_bleed, s1_bleed, 0) - # Oracle: byte 0 = (255+255)>>1 = 255 (0xFF); byte 1 = (1+1)>>1 = 1 (0x01) -> 0x000001FF - self.assertEqual(oracle_bleed, 0x0000_01FF) - # Mutant: (0x1FF + 0x1FF) >> 1 = 0x3FE >> 1 = 0x1FF - # Now test with odd byte 0 that spills bit 0 into next bit - s0_spill = 0x0000_0080 - s1_spill = 0x0000_0080 - # Let's test non-isolated shift where bit 8 of lane 0 shifts into bit 7 of lane 0 - s0_cross = 0x0000_0200 - s1_cross = 0x0000_0200 - self.assertEqual(oracle_v_lerp_u8(s0_cross, s1_cross, 0), 0x0000_0200) - - def test_mutation_bit1_instead_of_bit0_round_detected(self) -> None: - """Mutant: S2 round bit reads bit 1 instead of bit 0.""" - def mutant_lerp_byte(b0: int, b1: int, s2_byte: int) -> int: - # Bug: samples bit 1 - return ((b0 + b1 + ((s2_byte >> 1) & 1)) >> 1) & MASK8 - - # s2 has bit 0 set, bit 1 clear - s2_bit0 = 0x01 - s0 = 1 - s1 = 2 - - oracle_res = ref_lerp_u8_byte(s0, s1, s2_bit0) - mutant_res = mutant_lerp_byte(s0, s1, s2_bit0) - - # Oracle: (1 + 2 + 1) >> 1 = 2 - self.assertEqual(oracle_res, 2) - # Mutant: (1 + 2 + 0) >> 1 = 1 - self.assertEqual(mutant_res, 1) - self.assertNotEqual(oracle_res, mutant_res) + b0, b1, r = (s0 >> 8 * i) & 0xFF, (s1 >> 8 * i) & 0xFF, (s2 >> 8 * i) & 1 + out |= ((b0 + b1 + r) >> 1) << 8 * i + return out + + +def run(s0, s1, s2, form="vgpr"): + if form == "vgpr": + lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2:#x}", "v_lerp_u8 v0, v1, v2, v3"] + elif form == "sgpr": + lines = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2:#x}", "v_lerp_u8 v0, s1, s2, s3"] + elif form == "literal": + lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v3, {s2:#x}", f"v_lerp_u8 v0, v1, {s1:#x}, v3"] + else: + raise ValueError(form) + lines += ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_lerp_u8", lines))[0] + + +# (S0, S1, S2, expected word), written by hand, byte 0 first in pk(). +CASES = [ + (pk(0, 0, 0, 0), pk(0, 0, 0, 0), 0, 0), + (pk(10, 20, 30, 40), pk(20, 40, 60, 80), 0, pk(15, 30, 45, 60)), # exact averages + (pk(1, 2, 3, 4), pk(2, 3, 4, 5), 0, pk(1, 2, 3, 4)), # .5 rounds down with bit 0 clear + (pk(1, 2, 3, 4), pk(2, 3, 4, 5), 0x01010101, pk(2, 3, 4, 5)), # and up with it set + (pk(1, 2, 3, 4), pk(2, 3, 4, 5), pk(1, 0, 1, 0), pk(2, 2, 4, 4)), # per byte rounding + (pk(1, 2, 3, 4), pk(2, 3, 4, 5), 0xFEFEFEFE, pk(1, 2, 3, 4)), # bits 7:1 of S2 ignored + (pk(255, 255, 255, 255), pk(255, 255, 255, 255), 0x01010101, 0xFFFFFFFF), # 511 >> 1, no carry out of a byte + (pk(255, 0, 255, 0), pk(255, 0, 0, 255), 0x01010101, pk(255, 0, 128, 128)), + (pk(0, 0, 0, 0), pk(1, 1, 1, 1), 0x01010101, pk(1, 1, 1, 1)), + (pk(0x80, 0x7F, 0x81, 0xFE), pk(0x80, 0x80, 0x7F, 0xFF), 0, pk(0x80, 0x7F, 0x80, 0xFE)), +] + + +class LerpU8(unittest.TestCase): + def test_hand_table_matches_reference(self): + for s0, s1, s2, want in CASES: + self.assertEqual(ref(s0, s1, s2), want, (hex(s0), hex(s1), hex(s2))) + + def test_translated_forms(self): + for form in ("vgpr", "sgpr", "literal"): + for s0, s1, s2, want in CASES: + with self.subTest(form=form, s0=hex(s0), s1=hex(s1), s2=hex(s2)): + self.assertEqual(run(s0, s1, s2, form), want) + + def test_symmetric_and_identity(self): + rng = random.Random(0x1E8) + for _ in range(20): + a, b, c = (rng.getrandbits(32) for _ in range(3)) + self.assertEqual(run(a, b, c), run(b, a, c)) + self.assertEqual(run(a, a, c), a) + + def test_random_operands(self): + rng = random.Random(0x1E8B) + for _ in range(60): + s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) + for form in ("vgpr", "sgpr", "literal"): + with self.subTest(form=form, s0=hex(s0), s1=hex(s1), s2=hex(s2)): + self.assertEqual(run(s0, s1, s2, form), ref(s0, s1, s2)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_mul_f16.py b/tests/semantic/test_valu_mul_f16.py index 05eefd6f9..db65eefe0 100644 --- a/tests/semantic/test_valu_mul_f16.py +++ b/tests/semantic/test_valu_mul_f16.py @@ -1,1200 +1,145 @@ -"""Semantic reference tests and mathematical oracle for AMD RDNA2 v_mul_f16. +"""v_mul_f16 (RDNA2 VOP2 / VOP3): D.f16 = S0.f16 * S1.f16, binary16 with round to nearest even. -RDNA2 Vector Arithmetic Logic Unit (VALU) Architecture: - In AMD RDNA2 (GFX10/GFX1030) ISA, vector registers (VGPRs) are 32 bits wide. - Operations on 16-bit half-precision floating-point quantities (binary16, IEEE 754) - operate on 16-bit packed or scalar sub-words: - - VOP2: v_mul_f16 v[d], src0, v[s1] - - VOP3: v_mul_f16 v[d], src0, src1 [clamp] [omod] [op_sel] - - IEEE 754-2008 binary16 encoding: - - 1 sign bit (bit 15) - - 5 exponent bits with bias 15 (bits 14:10) - - 10 mantissa / fraction bits (bits 9:0) - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in +tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the _e32 form (the high half of the +destination is kept), the _e64 form with op_sel, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. +Standard library only: no GPU, no LLVM, no game data. """ -from __future__ import annotations - -from dataclasses import dataclass -import enum -import math -import re -import struct +import os +import random +import sys import unittest -from fractions import Fraction -from typing import List, Optional, Tuple -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import OLD, ref_mul, same_f16, scale # noqa: E402 -# IEEE 754 binary16 bit constants -SIGN_MASK_F16 = 0x8000 -EXP_MASK_F16 = 0x7C00 -MANT_MASK_F16 = 0x03FF -QNAN_BIT_F16 = 0x0200 -CANONICAL_QNAN_F16 = 0x7E00 -SNAN_F16 = 0x7D00 - -POS_ZERO_F16 = 0x0000 -NEG_ZERO_F16 = 0x8000 -POS_INF_F16 = 0x7C00 -NEG_INF_F16 = 0xFC00 - -POS_ONE_F16 = 0x3C00 # 1.0 -NEG_ONE_F16 = 0xBC00 # -1.0 -POS_TWO_F16 = 0x4000 # 2.0 -NEG_TWO_F16 = 0xC000 # -2.0 -POS_HALF_F16 = 0x3800 # 0.5 -NEG_HALF_F16 = 0xB800 # -0.5 - -MAX_FINITE_F16 = 0x7BFF # 65504.0 -MIN_NORMAL_F16 = 0x0400 # 2^-14 (~6.1035e-5) -MAX_SUBNORMAL_F16 = 0x03FF # ~6.0975e-5 -MIN_SUBNORMAL_F16 = 0x0001 # 2^-24 (~5.9605e-8) - -DEFAULT_VGPR_SENTINEL = 0xA55A5AA5 +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF -def u16(val: int) -> int: - """Normalize integer to unsigned 16-bit range [0, 65535].""" - return val & MASK16 +def run(line, seeds, old=OLD, hi=0x5A5A): + """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def f16_to_bits(val: float) -> int: - """Pack a Python float into an IEEE 754 half-precision 16-bit unsigned integer.""" - if math.isnan(val): - return CANONICAL_QNAN_F16 - try: - return struct.unpack(" float: - """Unpack an unsigned 16-bit integer into a Python float via IEEE 754 half-precision.""" - return struct.unpack(" Tuple[int, int, int]: - """Split 16-bit float into (sign, exponent, mantissa).""" - b = bits & MASK16 - sign = (b >> 15) & 1 - exp = (b >> 10) & 0x1F - mant = b & 0x03FF - return sign, exp, mant - - -def is_nan_f16(bits: int) -> bool: - """Return True if 16-bit pattern represents an IEEE 754 NaN.""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & MANT_MASK_F16) != 0) - - -def is_snan_f16(bits: int) -> bool: - """Return True if 16-bit pattern represents a signaling NaN.""" - return is_nan_f16(bits) and ((bits & QNAN_BIT_F16) == 0) - - -def is_qnan_f16(bits: int) -> bool: - """Return True if 16-bit pattern represents a quiet NaN.""" - return is_nan_f16(bits) and ((bits & QNAN_BIT_F16) != 0) - - -def is_inf_f16(bits: int) -> bool: - """Return True if 16-bit pattern represents +inf or -inf.""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & MANT_MASK_F16) == 0) - - -def is_zero_f16(bits: int) -> bool: - """Return True if 16-bit pattern represents +0.0 or -0.0.""" - return (bits & ~SIGN_MASK_F16) == 0 - - -def is_subnormal_f16(bits: int) -> bool: - """Return True if 16-bit pattern represents a subnormal (denormal) float.""" - return ((bits & EXP_MASK_F16) == 0) and ((bits & MANT_MASK_F16) != 0) - - -def is_normal_f16(bits: int) -> bool: - """Return True if 16-bit pattern represents a normalized finite float.""" - exp = (bits >> 10) & 0x1F - return 1 <= exp <= 30 - - -def apply_f16_modifiers(bits: int, *, abs_mod: bool = False, neg_mod: bool = False) -> int: - """Apply VOP3 input modifiers: abs clears sign bit; neg toggles sign bit.""" - res = bits & MASK16 - if abs_mod: - res &= ~SIGN_MASK_F16 - if neg_mod: - res ^= SIGN_MASK_F16 - return res - - -def ref_mul_f16( - s0_bits: int, - s1_bits: int, - *, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, - omod: str = "none", -) -> int: - """Reference mathematical oracle for AMD RDNA2 v_mul_f16 half-precision multiplication. - - Computes: D = s0 * s1 conforming to IEEE 754-2008 binary16, applying - input modifiers, output clamp, and omod multipliers. + `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its + upper half, so reading the wrong half of a source shows. v0 starts as `old`. """ - s0 = apply_f16_modifiers(s0_bits, abs_mod=abs0, neg_mod=neg0) - s1 = apply_f16_modifiers(s1_bits, abs_mod=abs1, neg_mod=neg1) - - # 1. NaN propagation: if any operand is NaN, produce quieted NaN - if is_nan_f16(s0) or is_nan_f16(s1): - if clamp: - # RDNA2 architecture rule: Clamping NaN produces +0.0 - return POS_ZERO_F16 - nan_bits = s0 if is_nan_f16(s0) else s1 - return (nan_bits | QNAN_BIT_F16) & MASK16 - - sign = ((s0 >> 15) ^ (s1 >> 15)) & 1 - - # 2. Multiplication of 0 by Infinity is Invalid Operation -> Canonical QNaN - if (is_zero_f16(s0) and is_inf_f16(s1)) or (is_inf_f16(s0) and is_zero_f16(s1)): - if clamp: - return POS_ZERO_F16 - return CANONICAL_QNAN_F16 - - # 3. Infinity * Finite -> Infinity - if is_inf_f16(s0) or is_inf_f16(s1): - res = (sign << 15) | POS_INF_F16 - if clamp: - # Clamping [0.0, 1.0]: -inf -> 0.0, +inf -> 1.0 - return POS_ZERO_F16 if sign else POS_ONE_F16 - return res - - # 4. Zero * Finite -> Zero - if is_zero_f16(s0) or is_zero_f16(s1): - res = (sign << 15) | POS_ZERO_F16 - if clamp: - # -0.0 clamped to [0.0, 1.0] produces +0.0 - return POS_ZERO_F16 - return res - - # 5. Finite non-zero arithmetic via IEEE 754 half precision - val0 = bits_to_f16(s0) - val1 = bits_to_f16(s1) - prod = val0 * val1 - - # Apply omod multiplier - if omod == "mul:2": - prod *= 2.0 - elif omod == "mul:4": - prod *= 4.0 - elif omod == "div:2": - prod *= 0.5 - - # Apply clamp to [0.0, 1.0] - if clamp: - if math.isnan(prod) or prod < 0.0: - return POS_ZERO_F16 - if prod > 1.0: - return POS_ONE_F16 - - return f16_to_bits(prod) - - -def ref_mul_f16_rational(s0_bits: int, s1_bits: int) -> int: - """Exact rational multiplication cross-check for finite binary16 operands.""" - s0 = s0_bits & MASK16 - s1 = s1_bits & MASK16 - if is_nan_f16(s0) or is_nan_f16(s1): - return CANONICAL_QNAN_F16 - if (is_zero_f16(s0) and is_inf_f16(s1)) or (is_inf_f16(s0) and is_zero_f16(s1)): - return CANONICAL_QNAN_F16 - sign = ((s0 >> 15) ^ (s1 >> 15)) & 1 - if is_inf_f16(s0) or is_inf_f16(s1): - return (sign << 15) | POS_INF_F16 - if is_zero_f16(s0) or is_zero_f16(s1): - return (sign << 15) | POS_ZERO_F16 - - def decode_fraction(b: int) -> Fraction: - exp = (b >> 10) & 0x1F - mant = b & 0x03FF - if exp == 0: - # Subnormal: (-1)^sign * 2^-14 * (mant / 1024) - return Fraction(mant, 1024 * (1 << 14)) - # Normal: (-1)^sign * 2^(exp - 15) * (1 + mant / 1024) - sig = Fraction(1024 + mant, 1024) - p = exp - 15 - if p >= 0: - return sig * (1 << p) - return sig / (1 << (-p)) - - frac_prod = decode_fraction(s0) * decode_fraction(s1) - val = float(frac_prod) - if sign: - val = -val - return f16_to_bits(val) - - -def ref_simd_mul_f16( - s0_wave: List[int], - s1_wave: List[int], - *, - wave_size: int = 32, - exec_mask: int = 0xFFFFFFFF, - prev_dst: Optional[List[int]] = None, - clamp: bool = False, - omod: str = "none", -) -> List[int]: - """Reference multi-lane SIMD vector multiplication under EXEC mask.""" - result: List[int] = [] - for lane in range(wave_size): - mask_bit = (exec_mask >> lane) & 1 - if mask_bit: - s0 = s0_wave[lane] - s1 = s1_wave[lane] - val = ref_mul_f16(s0, s1, clamp=clamp, omod=omod) - result.append(val) - else: - old_val = prev_dst[lane] if prev_dst is not None else 0 - result.append(old_val & MASK16) - return result - - -@dataclass -class StatusFlags: - """Architectural floating-point status flags and condition codes.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -def compute_f16_mantissa_product_carry(s0_bits: int, s1_bits: int) -> Tuple[int, int]: - """Compute product of normalized significands and carry-out bit. - - In IEEE 754 binary16, normal numbers have an implicit leading 1: - significand = 1024 + mantissa (in range [1024, 2047]). - Significand product is in range [1024^2, 2047^2] = [2^20, ~4 * 2^20). - Carry out is 1 if product >= 2^21, which requires right-shift normalization. - """ - _, exp0, mant0 = split_f16(s0_bits) - _, exp1, mant1 = split_f16(s1_bits) - - sig0 = (1024 | mant0) if exp0 > 0 else mant0 - sig1 = (1024 | mant1) if exp1 > 0 else mant1 - - raw_prod = sig0 * sig1 - carry = 1 if raw_prod >= (1 << 21) else 0 - return raw_prod, carry - - -def evaluate_v_mul_f16_flags(s0_bits: int, s1_bits: int, res_bits: int) -> StatusFlags: - """Evaluate condition codes and IEEE 754 exception flags for v_mul_f16.""" - flags = StatusFlags() - - s0 = s0_bits & MASK16 - s1 = s1_bits & MASK16 - res = res_bits & MASK16 - - # Signaling NaN or Invalid Operation (0 * inf) - if is_snan_f16(s0) or is_snan_f16(s1): - flags.invalid = True - elif (is_zero_f16(s0) and is_inf_f16(s1)) or (is_inf_f16(s0) and is_zero_f16(s1)): - flags.invalid = True - - # NaN result - if is_nan_f16(res): - flags.nan = True - return flags - - # Infinite result - if is_inf_f16(res): - flags.infinite = True - if not (is_inf_f16(s0) or is_inf_f16(s1)): - flags.overflow = True - flags.inexact = True - - # Zero result - if is_zero_f16(res): - flags.zero = True - if not (is_zero_f16(s0) or is_zero_f16(s1)): - flags.underflow = True - flags.inexact = True - - # Sign flag - if (res >> 15) & 1: - flags.negative = True - - # Denormal operand or result - if is_subnormal_f16(s0) or is_subnormal_f16(s1) or is_subnormal_f16(res): - flags.denormal = True - if is_subnormal_f16(res) and not (is_subnormal_f16(s0) or is_subnormal_f16(s1)): - flags.underflow = True - flags.inexact = True - - # Check for inexact rounding on finite numbers - if not (flags.invalid or flags.overflow or is_zero_f16(res) or is_inf_f16(res)): - exact_bits = ref_mul_f16_rational(s0, s1) - if exact_bits != res: - flags.inexact = True - - return flags - - -class RegisterFile: - """Architectural register model supporting 32-bit VGPR/SGPR storage and 16-bit halfword access.""" - - def __init__(self, num_vgprs: int = 64, num_sgprs: int = 32): - self.vgprs = [DEFAULT_VGPR_SENTINEL] * num_vgprs - self.sgprs = [0] * num_sgprs - - def get_vgpr(self, idx: int) -> int: - return self.vgprs[idx] & MASK32 - - def set_vgpr(self, idx: int, val: int) -> None: - self.vgprs[idx] = val & MASK32 - - def get_vgpr_half(self, idx: int, hi: bool) -> int: - dword = self.vgprs[idx] - return ((dword >> 16) if hi else dword) & MASK16 - - def set_vgpr_half(self, idx: int, hi: bool, val: int) -> None: - val16 = val & MASK16 - old = self.vgprs[idx] - if hi: - self.vgprs[idx] = (old & 0x0000FFFF) | (val16 << 16) - else: - self.vgprs[idx] = (old & 0xFFFF0000) | val16 - - def get_sgpr(self, idx: int) -> int: - return self.sgprs[idx] & MASK32 - - def set_sgpr(self, idx: int, val: int) -> None: - self.sgprs[idx] = val & MASK32 - - def get_sgpr_half(self, idx: int, hi: bool) -> int: - dword = self.sgprs[idx] - return ((dword >> 16) if hi else dword) & MASK16 - - def set_sgpr_half(self, idx: int, hi: bool, val: int) -> None: - val16 = val & MASK16 - old = self.sgprs[idx] - if hi: - self.sgprs[idx] = (old & 0x0000FFFF) | (val16 << 16) - else: - self.sgprs[idx] = (old & 0xFFFF0000) | val16 - - -class DataType(enum.Enum): - """Data types supported by the symbolic VALU AST.""" - F16 = "f16" - F32 = "f32" - I32 = "i32" - U32 = "u32" - - -class OperandKind(enum.Enum): - """Operand categories for RDNA2 VALU instructions.""" - VGPR = "vgpr" - SGPR = "sgpr" - LITERAL = "literal" - INLINE_FLOAT = "inline_float" - - -@dataclass -class ASTOperand: - """Symbolic typed operand with modifier attributes.""" - kind: OperandKind - reg_index: int = 0 - hi: bool = False - abs_mod: bool = False - neg_mod: bool = False - literal_val: int = 0 - data_type: DataType = DataType.F16 - - def to_asm(self) -> str: - if self.kind == OperandKind.VGPR: - base = f"v{self.reg_index}" + (".h" if self.hi else ".l") - elif self.kind == OperandKind.SGPR: - base = f"s{self.reg_index}" + (".h" if self.hi else ".l") - elif self.kind == OperandKind.INLINE_FLOAT: - base = f"{bits_to_f16(self.literal_val)}" - elif self.kind == OperandKind.LITERAL: - base = f"0x{self.literal_val:04X}" - else: - base = "?" - - if self.abs_mod: - base = f"|{base}|" - if self.neg_mod: - base = f"-{base}" - return base - - -@dataclass -class ASTInstruction: - """Symbolic AST node for v_mul_f16 instruction with typed validation.""" - opcode: str - dst: ASTOperand - src0: ASTOperand - src1: ASTOperand - clamp: bool = False - omod: str = "none" - - def validate(self) -> None: - if self.opcode != "v_mul_f16": - raise ValueError(f"Unsupported opcode: {self.opcode}") - if self.dst.kind != OperandKind.VGPR: - raise TypeError("Destination must be a VGPR") - if self.dst.abs_mod or self.dst.neg_mod: - raise ValueError("Destination cannot have input modifiers (abs/neg)") - if self.omod not in ("none", "mul:2", "mul:4", "div:2"): - raise ValueError(f"Invalid omod specifier: {self.omod}") - - def to_asm(self) -> str: - parts = [f"{self.opcode} {self.dst.to_asm()}, {self.src0.to_asm()}, {self.src1.to_asm()}"] - if self.clamp: - parts.append("clamp") - if self.omod != "none": - parts.append(self.omod) - return " ".join(parts) - - -def parse_v_mul_f16_asm(asm_line: str) -> ASTInstruction: - """Parse a single assembly instruction line into an ASTInstruction node.""" - line = asm_line.strip() - match = re.match(r"^v_mul_f16\s+([^,]+),\s*([^,]+),\s*(\S+)(.*)$", line) - if not match: - raise ValueError(f"Cannot parse v_mul_f16 assembly: {asm_line}") - - dst_str, src0_str, src1_str, trailing = match.groups() - clamp = False - omod = "none" - trailing_tokens = trailing.strip().split() - for tok in trailing_tokens: - if tok == "clamp": - clamp = True - elif tok in ("mul:2", "mul:4", "div:2"): - omod = tok - else: - raise ValueError(f"Invalid instruction modifier or token: {tok}") - - def parse_operand(op_str: str) -> ASTOperand: - s = op_str.strip() - neg_mod = False - abs_mod = False - - if s.startswith("-"): - neg_mod = True - s = s[1:].strip() - - if s.startswith("|") and s.endswith("|"): - abs_mod = True - s = s[1:-1].strip() - - # Check VGPR or SGPR - vgpr_match = re.match(r"^v(\d+)(\.([lh]))?$", s) - if vgpr_match: - idx = int(vgpr_match.group(1)) - hi = vgpr_match.group(3) == "h" - return ASTOperand(kind=OperandKind.VGPR, reg_index=idx, hi=hi, abs_mod=abs_mod, neg_mod=neg_mod) - - sgpr_match = re.match(r"^s(\d+)(\.([lh]))?$", s) - if sgpr_match: - idx = int(sgpr_match.group(1)) - hi = sgpr_match.group(3) == "h" - return ASTOperand(kind=OperandKind.SGPR, reg_index=idx, hi=hi, abs_mod=abs_mod, neg_mod=neg_mod) - - # Hex literal - if s.startswith("0x") or s.startswith("0X"): - val = int(s, 16) - return ASTOperand(kind=OperandKind.LITERAL, literal_val=val, abs_mod=abs_mod, neg_mod=neg_mod) - - # Float constant - try: - val_f = float(s) - val_bits = f16_to_bits(val_f) - return ASTOperand(kind=OperandKind.INLINE_FLOAT, literal_val=val_bits, abs_mod=abs_mod, neg_mod=neg_mod) - except ValueError: - pass - - raise ValueError(f"Unrecognized operand format: {op_str}") - - dst_op = parse_operand(dst_str) - src0_op = parse_operand(src0_str) - src1_op = parse_operand(src1_str) - - ast = ASTInstruction(opcode="v_mul_f16", dst=dst_op, src0=src0_op, src1=src1_op, clamp=clamp, omod=omod) - ast.validate() - return ast - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 v_mul_f16.""" - - def __init__(self, num_vgprs: int = 64, num_sgprs: int = 32): - self.reg_file = RegisterFile(num_vgprs=num_vgprs, num_sgprs=num_sgprs) - - def resolve_operand(self, op: ASTOperand) -> int: - """Resolve an AST operand to its raw 16-bit binary representation.""" - if op.kind == OperandKind.VGPR: - return self.reg_file.get_vgpr_half(op.reg_index, hi=op.hi) - elif op.kind == OperandKind.SGPR: - return self.reg_file.get_sgpr_half(op.reg_index, hi=op.hi) - elif op.kind in (OperandKind.LITERAL, OperandKind.INLINE_FLOAT): - return op.literal_val & MASK16 - raise ValueError(f"Cannot resolve operand: {op}") - - def execute_ast(self, inst: ASTInstruction) -> int: - """Execute a validated AST instruction and commit result to destination VGPR.""" - inst.validate() - raw_s0 = self.resolve_operand(inst.src0) - raw_s1 = self.resolve_operand(inst.src1) - - res = ref_mul_f16( - raw_s0, - raw_s1, - abs0=inst.src0.abs_mod, - neg0=inst.src0.neg_mod, - abs1=inst.src1.abs_mod, - neg1=inst.src1.neg_mod, - clamp=inst.clamp, - omod=inst.omod, - ) - - self.reg_file.set_vgpr_half(inst.dst.reg_index, hi=inst.dst.hi, val=res) - return res - - def execute_asm(self, asm_line: str) -> int: - """Parse assembly string and execute on the scalar interpreter.""" - inst = parse_v_mul_f16_asm(asm_line) - return self.execute_ast(inst) - - -class SIMDWavefront: - """Vectorized SIMD wavefront model supporting Wave32/Wave64 divergence and EXEC masking.""" - - def __init__(self, wave_size: int = 32): - if wave_size not in (32, 64): - raise ValueError("Wave size must be 32 or 64") - self.wave_size = wave_size - self.exec_mask = MASK32 if wave_size == 32 else MASK64 - self.lanes = [RegisterFile() for _ in range(wave_size)] - - def is_lane_active(self, lane: int) -> bool: - """Return True if the specified lane index is active under the current EXEC mask.""" - return bool((self.exec_mask >> lane) & 1) - - def load_vgpr_half_wave(self, reg_idx: int, hi: bool) -> List[int]: - """Read 16-bit values from all lanes in the wavefront for the specified VGPR halfword.""" - return [self.lanes[i].get_vgpr_half(reg_idx, hi=hi) for i in range(self.wave_size)] - - def store_vgpr_half_wave(self, reg_idx: int, hi: bool, values: List[int]) -> None: - """Store 16-bit values to all lanes in the wavefront for the specified VGPR halfword.""" - for i in range(min(len(values), self.wave_size)): - self.lanes[i].set_vgpr_half(reg_idx, hi=hi, val=values[i]) - - def step_v_mul_f16( - self, - dst_reg: int, - dst_hi: bool, - src0_reg: int, - src0_hi: bool, - src1_reg: int, - src1_hi: bool, - clamp: bool = False, - omod: str = "none", - ) -> List[int]: - """Execute a SIMD v_mul_f16 step across all lanes adhering to EXEC masking.""" - results: List[int] = [] - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.lanes[lane].get_vgpr_half(src0_reg, hi=src0_hi) - s1 = self.lanes[lane].get_vgpr_half(src1_reg, hi=src1_hi) - res = ref_mul_f16(s0, s1, clamp=clamp, omod=omod) - self.lanes[lane].set_vgpr_half(dst_reg, hi=dst_hi, val=res) - results.append(res) - else: - old_val = self.lanes[lane].get_vgpr_half(dst_reg, hi=dst_hi) - results.append(old_val) - return results - - -class TestValuMulF16Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_oracle_normal_multiplication(self) -> None: - # 2.0 * 3.0 = 6.0 - f_2 = f16_to_bits(2.0) - f_3 = f16_to_bits(3.0) - res = ref_mul_f16(f_2, f_3) - self.assertEqual(bits_to_f16(res), 6.0) - - # -1.5 * 4.0 = -6.0 - f_neg1p5 = f16_to_bits(-1.5) - f_4 = f16_to_bits(4.0) - res_neg = ref_mul_f16(f_neg1p5, f_4) - self.assertEqual(bits_to_f16(res_neg), -6.0) - - def test_oracle_cross_check_rational(self) -> None: - test_pairs = [ - (f16_to_bits(1.5), f16_to_bits(2.5)), - (f16_to_bits(-0.75), f16_to_bits(8.0)), - (f16_to_bits(0.0625), f16_to_bits(16.0)), - (f16_to_bits(3.0), f16_to_bits(0.333251953125)), - ] - for s0, s1 in test_pairs: - self.assertEqual(ref_mul_f16(s0, s1), ref_mul_f16_rational(s0, s1)) - - def test_oracle_zero_and_infinity_invariants(self) -> None: - # 0.0 * inf = NaN - self.assertEqual(ref_mul_f16(POS_ZERO_F16, POS_INF_F16), CANONICAL_QNAN_F16) - self.assertEqual(ref_mul_f16(NEG_ZERO_F16, POS_INF_F16), CANONICAL_QNAN_F16) - self.assertEqual(ref_mul_f16(POS_ZERO_F16, NEG_INF_F16), CANONICAL_QNAN_F16) - - # 0.0 * 5.0 = 0.0 (sign rules) - f_5 = f16_to_bits(5.0) - self.assertEqual(ref_mul_f16(POS_ZERO_F16, f_5), POS_ZERO_F16) - self.assertEqual(ref_mul_f16(NEG_ZERO_F16, f_5), NEG_ZERO_F16) - - # inf * -2.0 = -inf - self.assertEqual(ref_mul_f16(POS_INF_F16, NEG_TWO_F16), NEG_INF_F16) - self.assertEqual(ref_mul_f16(NEG_INF_F16, NEG_TWO_F16), POS_INF_F16) - - def test_oracle_nan_propagation(self) -> None: - # QNaN propagation - qnan = CANONICAL_QNAN_F16 - res = ref_mul_f16(qnan, POS_TWO_F16) - self.assertTrue(is_qnan_f16(res)) - - # SNaN quietened - res_snan = ref_mul_f16(SNAN_F16, POS_ONE_F16) - self.assertTrue(is_qnan_f16(res_snan)) - - def test_oracle_subnormal_gradual_underflow(self) -> None: - # Subnormal * 2.0 - sub = MIN_SUBNORMAL_F16 - res = ref_mul_f16(sub, POS_TWO_F16) - self.assertEqual(res, 0x0002) - - def test_oracle_modifiers(self) -> None: - # abs and neg modifiers - f_neg2 = f16_to_bits(-2.0) - f_3 = f16_to_bits(3.0) - # abs(s0) * s1 -> 2.0 * 3.0 = 6.0 - self.assertEqual(bits_to_f16(ref_mul_f16(f_neg2, f_3, abs0=True)), 6.0) - # neg(s0) * s1 -> -(-2.0) * 3.0 = 6.0 - self.assertEqual(bits_to_f16(ref_mul_f16(f_neg2, f_3, neg0=True)), 6.0) - - # clamp modifier - self.assertEqual(bits_to_f16(ref_mul_f16(f_neg2, f_3, clamp=True)), 0.0) - self.assertEqual(bits_to_f16(ref_mul_f16(POS_TWO_F16, POS_TWO_F16, clamp=True)), 1.0) - self.assertEqual(ref_mul_f16(CANONICAL_QNAN_F16, POS_TWO_F16, clamp=True), POS_ZERO_F16) - - # omod modifiers - self.assertEqual(bits_to_f16(ref_mul_f16(POS_ONE_F16, POS_ONE_F16, omod="mul:2")), 2.0) - self.assertEqual(bits_to_f16(ref_mul_f16(POS_ONE_F16, POS_ONE_F16, omod="mul:4")), 4.0) - self.assertEqual(bits_to_f16(ref_mul_f16(POS_ONE_F16, POS_ONE_F16, omod="div:2")), 0.5) - - def test_register_file_halfword_isolation(self) -> None: - rf = RegisterFile(num_vgprs=4) - rf.set_vgpr(0, 0x12345678) - self.assertEqual(rf.get_vgpr_half(0, hi=False), 0x5678) - self.assertEqual(rf.get_vgpr_half(0, hi=True), 0x1234) - - rf.set_vgpr_half(0, hi=False, val=0xBEEF) - self.assertEqual(rf.get_vgpr(0), 0x1234BEEF) - - rf.set_vgpr_half(0, hi=True, val=0xCAFE) - self.assertEqual(rf.get_vgpr(0), 0xCAFEBEEF) - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for AST opcode definitions, type checking, and expression serialization.""" - - def test_ast_to_asm_roundtrip(self) -> None: - inst = ASTInstruction( - opcode="v_mul_f16", - dst=ASTOperand(OperandKind.VGPR, reg_index=0, hi=False), - src0=ASTOperand(OperandKind.VGPR, reg_index=1, hi=True, neg_mod=True), - src1=ASTOperand(OperandKind.SGPR, reg_index=2, hi=False, abs_mod=True), - clamp=True, - omod="mul:2", - ) - asm_str = inst.to_asm() - self.assertEqual(asm_str, "v_mul_f16 v0.l, -v1.h, |s2.l| clamp mul:2") - - parsed = parse_v_mul_f16_asm(asm_str) - self.assertEqual(parsed.dst.reg_index, 0) - self.assertFalse(parsed.dst.hi) - self.assertEqual(parsed.src0.reg_index, 1) - self.assertTrue(parsed.src0.hi) - self.assertTrue(parsed.src0.neg_mod) - self.assertEqual(parsed.src1.reg_index, 2) - self.assertFalse(parsed.src1.hi) - self.assertTrue(parsed.src1.abs_mod) - self.assertTrue(parsed.clamp) - self.assertEqual(parsed.omod, "mul:2") - - def test_parser_modifiers_and_literals(self) -> None: - inst = parse_v_mul_f16_asm("v_mul_f16 v2.h, 0x3C00, 2.0 div:2") - self.assertEqual(inst.dst.reg_index, 2) - self.assertTrue(inst.dst.hi) - self.assertEqual(inst.src0.literal_val, 0x3C00) - self.assertEqual(inst.src1.literal_val, POS_TWO_F16) - self.assertEqual(inst.omod, "div:2") - - def test_ast_validation_errors(self) -> None: - # Invalid opcode - with self.assertRaises(ValueError): - bad = ASTInstruction( - opcode="v_add_f16", - dst=ASTOperand(OperandKind.VGPR, 0), - src0=ASTOperand(OperandKind.VGPR, 1), - src1=ASTOperand(OperandKind.VGPR, 2), - ) - bad.validate() - - # Non-VGPR destination - with self.assertRaises(TypeError): - bad_dst = ASTInstruction( - opcode="v_mul_f16", - dst=ASTOperand(OperandKind.SGPR, 0), - src0=ASTOperand(OperandKind.VGPR, 1), - src1=ASTOperand(OperandKind.VGPR, 2), - ) - bad_dst.validate() - - # Destination with input modifiers - with self.assertRaises(ValueError): - bad_mod = ASTInstruction( - opcode="v_mul_f16", - dst=ASTOperand(OperandKind.VGPR, 0, neg_mod=True), - src0=ASTOperand(OperandKind.VGPR, 1), - src1=ASTOperand(OperandKind.VGPR, 2), - ) - bad_mod.validate() - - # Invalid omod - with self.assertRaises(ValueError): - bad_omod = ASTInstruction( - opcode="v_mul_f16", - dst=ASTOperand(OperandKind.VGPR, 0), - src0=ASTOperand(OperandKind.VGPR, 1), - src1=ASTOperand(OperandKind.VGPR, 2), - omod="bad_omod", - ) - bad_omod.validate() - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar instruction interpreter.""" - - def test_scalar_vgpr_execution(self) -> None: - interp = ScalarInterpreter() - interp.reg_file.set_vgpr_half(1, hi=False, val=f16_to_bits(2.5)) - interp.reg_file.set_vgpr_half(2, hi=False, val=f16_to_bits(4.0)) - - res = interp.execute_asm("v_mul_f16 v0.l, v1.l, v2.l") - self.assertEqual(bits_to_f16(res), 10.0) - self.assertEqual(interp.reg_file.get_vgpr_half(0, hi=False), f16_to_bits(10.0)) - - def test_scalar_sgpr_and_inline_execution(self) -> None: - interp = ScalarInterpreter() - interp.reg_file.set_sgpr_half(3, hi=True, val=f16_to_bits(-3.0)) - - res = interp.execute_asm("v_mul_f16 v4.h, s3.h, 2.0") - self.assertEqual(bits_to_f16(res), -6.0) - self.assertEqual(interp.reg_file.get_vgpr_half(4, hi=True), f16_to_bits(-6.0)) - - def test_scalar_destination_halfword_preservation(self) -> None: - interp = ScalarInterpreter() - interp.reg_file.set_vgpr(5, 0xAAAA5555) - interp.reg_file.set_vgpr_half(1, hi=False, val=POS_ONE_F16) - interp.reg_file.set_vgpr_half(2, hi=False, val=POS_TWO_F16) - - # Write to v5.l, v5.h must remain 0xAAAA - interp.execute_asm("v_mul_f16 v5.l, v1.l, v2.l") - self.assertEqual(interp.reg_file.get_vgpr_half(5, hi=True), 0xAAAA) - self.assertEqual(interp.reg_file.get_vgpr_half(5, hi=False), POS_TWO_F16) - - # Write to v5.h, v5.l must remain POS_TWO_F16 - interp.execute_asm("v_mul_f16 v5.h, v1.l, 2.0") - self.assertEqual(interp.reg_file.get_vgpr_half(5, hi=False), POS_TWO_F16) - self.assertEqual(interp.reg_file.get_vgpr_half(5, hi=True), POS_TWO_F16) - - -class TestSIMDExecution(unittest.TestCase): - """Unit tests for SIMD wavefront multi-lane execution, divergence, and EXEC masking.""" - - def test_wave32_uniform_execution(self) -> None: - sim = SIMDWavefront(wave_size=32) - s0_vals = [f16_to_bits(2.0)] * 32 - s1_vals = [f16_to_bits(float(i)) for i in range(32)] - sim.store_vgpr_half_wave(1, hi=False, values=s0_vals) - sim.store_vgpr_half_wave(2, hi=False, values=s1_vals) - - results = sim.step_v_mul_f16(dst_reg=0, dst_hi=False, src0_reg=1, src0_hi=False, src1_reg=2, src1_hi=False) - for i in range(32): - self.assertEqual(bits_to_f16(results[i]), 2.0 * float(i)) - self.assertEqual(bits_to_f16(sim.lanes[i].get_vgpr_half(0, hi=False)), 2.0 * float(i)) - - def test_wave32_divergence_mask(self) -> None: - sim = SIMDWavefront(wave_size=32) - prev_dst = [0x5555] * 32 - sim.store_vgpr_half_wave(0, hi=False, values=prev_dst) - - s0_vals = [f16_to_bits(3.0)] * 32 - s1_vals = [f16_to_bits(2.0)] * 32 - sim.store_vgpr_half_wave(1, hi=False, values=s0_vals) - sim.store_vgpr_half_wave(2, hi=False, values=s1_vals) - - # Mask: alternating lanes active (0xAAAAAAAA) - sim.exec_mask = 0xAAAAAAAA - results = sim.step_v_mul_f16(dst_reg=0, dst_hi=False, src0_reg=1, src0_hi=False, src1_reg=2, src1_hi=False) - - for i in range(32): - if i % 2 == 1: - # Active lane - self.assertEqual(bits_to_f16(results[i]), 6.0) - self.assertEqual(bits_to_f16(sim.lanes[i].get_vgpr_half(0, hi=False)), 6.0) - else: - # Inactive lane: original value preserved - self.assertEqual(results[i], 0x5555) - self.assertEqual(sim.lanes[i].get_vgpr_half(0, hi=False), 0x5555) - - def test_wave64_divergence_and_oracle_cross_check(self) -> None: - sim = SIMDWavefront(wave_size=64) - exec_mask = 0x00000000FFFFFFFF # Lower 32 lanes active, upper 32 inactive - sim.exec_mask = exec_mask - - prev_dst = [u16(0x9000 + i) for i in range(64)] - sim.store_vgpr_half_wave(0, hi=True, values=prev_dst) - - s0_vals = [f16_to_bits(float(i + 1)) for i in range(64)] - s1_vals = [f16_to_bits(0.5) for _ in range(64)] - sim.store_vgpr_half_wave(3, hi=False, values=s0_vals) - sim.store_vgpr_half_wave(4, hi=True, values=s1_vals) - - expected = ref_simd_mul_f16( - s0_vals, s1_vals, wave_size=64, exec_mask=exec_mask, prev_dst=prev_dst - ) - - results = sim.step_v_mul_f16(dst_reg=0, dst_hi=True, src0_reg=3, src0_hi=False, src1_reg=4, src1_hi=True) - self.assertEqual(results, expected) - - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_inplace_dst_equals_src0(self) -> None: - interp = ScalarInterpreter() - interp.reg_file.set_vgpr_half(0, hi=False, val=f16_to_bits(3.0)) - interp.reg_file.set_vgpr_half(1, hi=False, val=f16_to_bits(5.0)) - - # v0.l = v0.l * v1.l -> 15.0 - res = interp.execute_asm("v_mul_f16 v0.l, v0.l, v1.l") - self.assertEqual(bits_to_f16(res), 15.0) - self.assertEqual(bits_to_f16(interp.reg_file.get_vgpr_half(0, hi=False)), 15.0) - # src1 v1.l must remain intact - self.assertEqual(bits_to_f16(interp.reg_file.get_vgpr_half(1, hi=False)), 5.0) - - def test_inplace_dst_equals_src1(self) -> None: - interp = ScalarInterpreter() - interp.reg_file.set_vgpr_half(0, hi=False, val=f16_to_bits(7.0)) - interp.reg_file.set_vgpr_half(1, hi=False, val=f16_to_bits(2.0)) - - # v1.l = v0.l * v1.l -> 14.0 - res = interp.execute_asm("v_mul_f16 v1.l, v0.l, v1.l") - self.assertEqual(bits_to_f16(res), 14.0) - self.assertEqual(bits_to_f16(interp.reg_file.get_vgpr_half(1, hi=False)), 14.0) - # src0 v0.l must remain intact - self.assertEqual(bits_to_f16(interp.reg_file.get_vgpr_half(0, hi=False)), 7.0) - - def test_inplace_self_squaring(self) -> None: - interp = ScalarInterpreter() - interp.reg_file.set_vgpr_half(2, hi=False, val=f16_to_bits(-4.0)) - - # v2.l = v2.l * v2.l -> 16.0 - res = interp.execute_asm("v_mul_f16 v2.l, v2.l, v2.l") - self.assertEqual(bits_to_f16(res), 16.0) - self.assertEqual(bits_to_f16(interp.reg_file.get_vgpr_half(2, hi=False)), 16.0) - - def test_subword_intra_register_crossover(self) -> None: - interp = ScalarInterpreter() - # Setup v3: low = 2.0, high = 3.0 - interp.reg_file.set_vgpr_half(3, hi=False, val=f16_to_bits(2.0)) - interp.reg_file.set_vgpr_half(3, hi=True, val=f16_to_bits(3.0)) - - # High = Low * High -> 2.0 * 3.0 = 6.0 into v3.h - res = interp.execute_asm("v_mul_f16 v3.h, v3.l, v3.h") - self.assertEqual(bits_to_f16(res), 6.0) - self.assertEqual(bits_to_f16(interp.reg_file.get_vgpr_half(3, hi=True)), 6.0) - # v3.l must remain exactly 2.0 - self.assertEqual(bits_to_f16(interp.reg_file.get_vgpr_half(3, hi=False)), 2.0) - - def test_successive_inplace_doubling_chain(self) -> None: - interp = ScalarInterpreter() - interp.reg_file.set_vgpr_half(0, hi=False, val=f16_to_bits(1.0)) - - # Doubling 5 times: 1.0 -> 2.0 -> 4.0 -> 8.0 -> 16.0 -> 32.0 - for _ in range(5): - interp.execute_asm("v_mul_f16 v0.l, v0.l, 2.0") - - self.assertEqual(bits_to_f16(interp.reg_file.get_vgpr_half(0, hi=False)), 32.0) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for condition codes, IEEE 754 status flags, and mantissa product carry.""" - - def test_exact_finite_flags(self) -> None: - s0 = f16_to_bits(2.0) - s1 = f16_to_bits(3.0) - res = ref_mul_f16(s0, s1) - flags = evaluate_v_mul_f16_flags(s0, s1, res) - self.assertFalse(flags.invalid) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - self.assertFalse(flags.inexact) - self.assertFalse(flags.zero) - self.assertFalse(flags.negative) - self.assertFalse(flags.denormal) - self.assertFalse(flags.infinite) - self.assertFalse(flags.nan) - - def test_overflow_and_infinite_flags(self) -> None: - s0 = MAX_FINITE_F16 - s1 = POS_TWO_F16 - res = ref_mul_f16(s0, s1) - self.assertEqual(res, POS_INF_F16) - flags = evaluate_v_mul_f16_flags(s0, s1, res) - self.assertTrue(flags.overflow) - self.assertTrue(flags.infinite) - self.assertTrue(flags.inexact) - self.assertFalse(flags.invalid) - - def test_underflow_and_denormal_flags(self) -> None: - # Smallest normal * 0.5 -> subnormal - s0 = MIN_NORMAL_F16 - s1 = POS_HALF_F16 - res = ref_mul_f16(s0, s1) - self.assertTrue(is_subnormal_f16(res)) - flags = evaluate_v_mul_f16_flags(s0, s1, res) - self.assertTrue(flags.denormal) - self.assertTrue(flags.underflow) - self.assertFalse(flags.overflow) - - def test_invalid_operation_flags(self) -> None: - # 0 * inf is invalid operation - res = ref_mul_f16(POS_ZERO_F16, POS_INF_F16) - flags = evaluate_v_mul_f16_flags(POS_ZERO_F16, POS_INF_F16, res) - self.assertTrue(flags.invalid) - self.assertTrue(flags.nan) - - # Signaling NaN triggers invalid operation flag - res_snan = ref_mul_f16(SNAN_F16, POS_TWO_F16) - flags_snan = evaluate_v_mul_f16_flags(SNAN_F16, POS_TWO_F16, res_snan) - self.assertTrue(flags_snan.invalid) - self.assertTrue(flags_snan.nan) - - def test_zero_and_negative_flags(self) -> None: - # +0.0 * +2.0 = +0.0 - res_pz = ref_mul_f16(POS_ZERO_F16, POS_TWO_F16) - flags_pz = evaluate_v_mul_f16_flags(POS_ZERO_F16, POS_TWO_F16, res_pz) - self.assertTrue(flags_pz.zero) - self.assertFalse(flags_pz.negative) - - # -0.0 * +2.0 = -0.0 - res_nz = ref_mul_f16(NEG_ZERO_F16, POS_TWO_F16) - flags_nz = evaluate_v_mul_f16_flags(NEG_ZERO_F16, POS_TWO_F16, res_nz) - self.assertTrue(flags_nz.zero) - self.assertTrue(flags_nz.negative) - - # -3.0 * +2.0 = -6.0 - s0 = f16_to_bits(-3.0) - s1 = f16_to_bits(2.0) - res_neg = ref_mul_f16(s0, s1) - flags_neg = evaluate_v_mul_f16_flags(s0, s1, res_neg) - self.assertFalse(flags_neg.zero) - self.assertTrue(flags_neg.negative) - - def test_mantissa_product_carry(self) -> None: - # 1.0 * 1.0: mantissas are 1024 * 1024 = 2^20 -> carry = 0 - _, carry0 = compute_f16_mantissa_product_carry(POS_ONE_F16, POS_ONE_F16) - self.assertEqual(carry0, 0) - - # 1.5 * 1.5: significands are 1536 * 1536 = 2359296 >= 2^21 (2097152) -> carry = 1 - f_1p5 = f16_to_bits(1.5) - _, carry1 = compute_f16_mantissa_product_carry(f_1p5, f_1p5) - self.assertEqual(carry1, 1) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 edge cases, subnormals, signed zero, and NaN behavior.""" - - def test_subnormal_multiplication_gradual_underflow(self) -> None: - # Smallest subnormal * 2.0 = 2 * 2^-24 - res = ref_mul_f16(MIN_SUBNORMAL_F16, POS_TWO_F16) - self.assertEqual(res, 0x0002) - - # Max subnormal (1023 * 2^-24) * 0.5 = 511.5 * 2^-24 -> rounds to nearest even (512, 0x0200) - res_half = ref_mul_f16(MAX_SUBNORMAL_F16, POS_HALF_F16) - self.assertEqual(res_half, 0x0200) - - # Complete underflow to zero - res_zero = ref_mul_f16(MIN_SUBNORMAL_F16, MIN_SUBNORMAL_F16) - self.assertEqual(res_zero, POS_ZERO_F16) - - def test_max_finite_overflow_boundaries(self) -> None: - # Max finite * 1.0 == max finite - self.assertEqual(ref_mul_f16(MAX_FINITE_F16, POS_ONE_F16), MAX_FINITE_F16) - # Max finite * -1.0 == -max finite - self.assertEqual(ref_mul_f16(MAX_FINITE_F16, NEG_ONE_F16), MAX_FINITE_F16 | SIGN_MASK_F16) - - # Max finite * 2.0 overflows to +inf - self.assertEqual(ref_mul_f16(MAX_FINITE_F16, POS_TWO_F16), POS_INF_F16) - # -Max finite * 2.0 overflows to -inf - self.assertEqual(ref_mul_f16(MAX_FINITE_F16 | SIGN_MASK_F16, POS_TWO_F16), NEG_INF_F16) - - def test_signed_zero_combinations(self) -> None: - # +0 * +0 = +0 - self.assertEqual(ref_mul_f16(POS_ZERO_F16, POS_ZERO_F16), POS_ZERO_F16) - # +0 * -0 = -0 - self.assertEqual(ref_mul_f16(POS_ZERO_F16, NEG_ZERO_F16), NEG_ZERO_F16) - # -0 * -0 = +0 - self.assertEqual(ref_mul_f16(NEG_ZERO_F16, NEG_ZERO_F16), POS_ZERO_F16) - # -0 * 5.0 = -0 - self.assertEqual(ref_mul_f16(NEG_ZERO_F16, f16_to_bits(5.0)), NEG_ZERO_F16) - # -0 * -5.0 = +0 - self.assertEqual(ref_mul_f16(NEG_ZERO_F16, f16_to_bits(-5.0)), POS_ZERO_F16) - - def test_infinity_arithmetic(self) -> None: - # +inf * +inf = +inf - self.assertEqual(ref_mul_f16(POS_INF_F16, POS_INF_F16), POS_INF_F16) - # +inf * -inf = -inf - self.assertEqual(ref_mul_f16(POS_INF_F16, NEG_INF_F16), NEG_INF_F16) - # -inf * -inf = +inf - self.assertEqual(ref_mul_f16(NEG_INF_F16, NEG_INF_F16), POS_INF_F16) - - # inf * -0.5 = -inf - self.assertEqual(ref_mul_f16(POS_INF_F16, NEG_HALF_F16), NEG_INF_F16) - - def test_nan_quietening_and_clamp_rule(self) -> None: - # SNaN quietening: bit 9 (0x0200) becomes 1 - snan = 0x7D55 - res = ref_mul_f16(snan, POS_ONE_F16) - self.assertTrue(is_qnan_f16(res)) - self.assertEqual(res, snan | QNAN_BIT_F16) - - # NaN with clamp modifier produces +0.0 under RDNA2 rules - qnan = CANONICAL_QNAN_F16 - self.assertEqual(ref_mul_f16(qnan, POS_ONE_F16, clamp=True), POS_ZERO_F16) - self.assertEqual(ref_mul_f16(snan, POS_TWO_F16, clamp=True), POS_ZERO_F16) - - -class TestNegativeControlsAndMutationDetection(unittest.TestCase): - """Negative controls, syntax rejection, and mutation detection test cases.""" - - def test_syntax_rejection_invalid_opcodes(self) -> None: - # Rejection of invalid opcode - with self.assertRaises(ValueError): - parse_v_mul_f16_asm("v_add_f16 v0.l, v1.l, v2.l") - with self.assertRaises(ValueError): - parse_v_mul_f16_asm("v_mul_f32 v0, v1, v2") - - def test_syntax_rejection_malformed_registers(self) -> None: - # Invalid halfword specifier (.x instead of .l or .h) - with self.assertRaises(ValueError): - parse_v_mul_f16_asm("v_mul_f16 v0.x, v1.l, v2.l") - # Invalid register name - with self.assertRaises(ValueError): - parse_v_mul_f16_asm("v_mul_f16 reg0, v1.l, v2.l") - - def test_syntax_rejection_invalid_destination(self) -> None: - # Destination with input modifier (abs/neg) - with self.assertRaises(ValueError): - parse_v_mul_f16_asm("v_mul_f16 -v0.l, v1.l, v2.l") - with self.assertRaises(ValueError): - parse_v_mul_f16_asm("v_mul_f16 |v0.l|, v1.l, v2.l") - # Non-VGPR destination - with self.assertRaises(TypeError): - parse_v_mul_f16_asm("v_mul_f16 s0.l, v1.l, v2.l") - - def test_syntax_rejection_invalid_omod(self) -> None: - # Unsupported omod - with self.assertRaises(ValueError): - parse_v_mul_f16_asm("v_mul_f16 v0.l, v1.l, v2.l mul:8") - - def test_mutation_sabotage_arithmetic_operator(self) -> None: - # Sabotage: replace multiplication by addition - s0 = f16_to_bits(3.0) - s1 = f16_to_bits(2.0) - expected_mul = ref_mul_f16(s0, s1) # 6.0 - mutated_add = f16_to_bits(bits_to_f16(s0) + bits_to_f16(s1)) # 5.0 - self.assertNotEqual(expected_mul, mutated_add) - - def test_mutation_sabotage_sign_logic(self) -> None: - # Sabotage: replace XOR sign rule with AND - s0 = f16_to_bits(-2.0) - s1 = f16_to_bits(3.0) - expected = ref_mul_f16(s0, s1) # -6.0 - sign0 = (s0 >> 15) & 1 - sign1 = (s1 >> 15) & 1 - mutated_sign = sign0 & sign1 # 1 & 0 = 0 -> +6.0 - mutated_bits = (s0 & ~SIGN_MASK_F16) | (mutated_sign << 15) - self.assertNotEqual(expected, mutated_bits) - - def test_mutation_sabotage_clamp_bypass(self) -> None: - # Sabotage: clamp omitted on negative result - s0 = f16_to_bits(-4.0) - s1 = f16_to_bits(2.0) - expected_clamped = ref_mul_f16(s0, s1, clamp=True) - mutated_unclamped = ref_mul_f16(s0, s1, clamp=False) - self.assertEqual(expected_clamped, POS_ZERO_F16) - self.assertEqual(mutated_unclamped, f16_to_bits(-8.0)) - self.assertNotEqual(expected_clamped, mutated_unclamped) - - def test_mutation_sabotage_nan_clamp_suppression(self) -> None: - # Sabotage: clamp fails to force NaN to +0.0 - qnan = CANONICAL_QNAN_F16 - expected = ref_mul_f16(qnan, POS_TWO_F16, clamp=True) - self.assertEqual(expected, POS_ZERO_F16) - mutated_nan_leak = qnan - self.assertNotEqual(expected, mutated_nan_leak) - - def test_mutation_sabotage_exec_mask_leak(self) -> None: - # Sabotage: inactive SIMD lane is incorrectly overwritten - sim = SIMDWavefront(wave_size=32) - sim.exec_mask = 0x00000001 # only lane 0 active - sim.store_vgpr_half_wave(0, hi=False, values=[0xDEAD] * 32) - sim.store_vgpr_half_wave(1, hi=False, values=[POS_TWO_F16] * 32) - sim.store_vgpr_half_wave(2, hi=False, values=[POS_TWO_F16] * 32) - - results = sim.step_v_mul_f16(0, False, 1, False, 2, False) - # Lane 0 active -> 4.0 - self.assertEqual(bits_to_f16(results[0]), 4.0) - # Lane 1 inactive -> must remain 0xDEAD - self.assertEqual(results[1], 0xDEAD) + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + w = w if w > 0xFFFF else (hi << 16) | w + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_mul_f16", prog))[0] + + +# (src0, src1, D), written by hand. +CASES = [ + (0x3E00, TWO, THREE), # 1.5 * 2 = 3 + (HALF, HALF, QUARTER), # 0.5 * 0.5 + (0xBC00, TWO, 0xC000), # -1 * 2 = -2 + (0x0000, 0xBC00, 0x8000), # +0 * -1 = -0 + (0x8000, 0xBC00, 0x0000), # -0 * -1 = +0 + (INF, 0x0000, QNAN), # inf * 0 = NaN + (INF, 0xC000, NINF), # inf * -2 = -inf + (MAXH, TWO, INF), # 131008 overflows + (MAXH, HALF, 0x77FF), # 32752, exact + (MIN_NORMAL, HALF, 0x0200), # 2^-15 is subnormal: 512 quanta of 2^-24 + (MIN_SUB, HALF, 0x0000), # half a quantum: tie to even is 0 + (MIN_SUB, 0x3A00, MIN_SUB), # 0.75 of a quantum rounds up to 1 + (0x3C01, 0x3C01, 0x3C02), # 1 + 2^-9 + 2^-20 rounds to 1 + 2^-9 + (0x5640, 0x5640, 0x70E2), # 100 * 100 = 10000 + (0x4900, 0xC100, 0xCE40), # 10 * -2.5 = -25 + (QNAN, ONE, QNAN), +] + +SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, + MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0x1000, 0x6800, 0x6801, 0x4C00] + + +class MulF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for a, b, want in CASES: + self.assertTrue(same_f16(ref_mul(a, b), want), (hex(a), hex(b), hex(ref_mul(a, b)))) + + def test_e32_writes_low_half_and_keeps_high_half(self): + for a, b, want in CASES: + with self.subTest(a=hex(a), b=hex(b)): + got = run("v_mul_f16 v0, v1, v2", {"v1": a, "v2": b}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_vop3_sgpr_and_literal_sources(self): + for a, b, want in CASES[:14]: + forms = [ + ("e64 vgpr", "v_mul_f16_e64 v0, v1, v2", {"v1": a, "v2": b}), + ("e64 sgpr", "v_mul_f16_e64 v0, s1, s2", {"s1": a, "s2": b}), + ("e32 sgpr src0", "v_mul_f16 v0, s1, v2", {"s1": a, "v2": b}), + ("e32 literal src0", f"v_mul_f16 v0, {a:#x}, v2", {"v2": b}), + ("e64 literal src1", f"v_mul_f16_e64 v0, v1, {b:#x}", {"v1": a}), + ] + for form, line, seeds in forms: + with self.subTest(a=hex(a), b=hex(b), form=form): + got = run(line, seeds) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_inline_constants(self): + # (inline constant as src0, its binary16 value, v1 low half, D), by hand + for text, c, b, want in (("2.0", TWO, 0x3E00, THREE), ("-1.0", 0xBC00, HALF, 0xB800), ("0.5", HALF, 0x4400, TWO), + ("4.0", 0x4400, 0xB800, 0xC000), ("1.0", ONE, 0x3A00, 0x3A00)): + with self.subTest(const=text): + self.assertEqual(run(f"v_mul_f16 v0, {text}, v1", {"v1": b}) & 0xFFFF, want) + self.assertEqual(ref_mul(c, b), want) + + def test_op_sel_selects_source_and_destination_halves(self): + # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25); D by hand for each (src0 half, src1 half). + s0, s1 = (THREE << 16) | ONE, (0xB400 << 16) | HALF + expect_lo = {(0, 0): 0x3800, (1, 0): 0x3E00, (0, 1): 0xB400, (1, 1): 0xBA00} # 0.5, 1.5, -0.25, -0.75 + for h0 in (0, 1): + for h1 in (0, 1): + for dh in (0, 1): + want = expect_lo[(h0, h1)] + expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) + with self.subTest(op_sel=(h0, h1, dh)): + got = run(f"v_mul_f16_e64 v0, v1, v2 op_sel:[{h0},{h1},{dh}]", {"v1": s0, "v2": s1}) + self.assertEqual(got, expect) + + def test_neg_and_abs_source_modifiers(self): + # v1 = 1.5, v2 = -2.0; (operand text, D) by hand + for ops, want in (("v1, v2", 0xC200), ("-v1, v2", 0x4200), ("v1, -v2", 0x4200), ("|v1|, |v2|", 0x4200), + ("-|v1|, v2", 0x4200), ("v1, -|v2|", 0xC200), ("|v1|, v2", 0xC200), ("v1, |v2|", 0x4200)): + with self.subTest(ops=ops): + got = run(f"v_mul_f16_e64 v0, {ops}", {"v1": 0x3E00, "v2": 0xC000}) + self.assertEqual(got & 0xFFFF, want) + + def test_output_modifiers_and_clamp(self): + # unmodified result: 1.5 * 2 = 3.0; mul/div scale it, clamp limits it to [0, 1] (negatives and NaN become +0) + for suffix, want in ((" mul:2", 0x4600), (" mul:4", 0x4A00), (" div:2", 0x3E00), (" clamp", ONE)): + with self.subTest(mod=suffix): + got = run("v_mul_f16_e64 v0, v1, v2" + suffix, {"v1": 0x3E00, "v2": TWO}) + self.assertEqual(got & 0xFFFF, want) + for (a, b), suffix, want in (((HALF, HALF), " clamp", QUARTER), ((0xB800, HALF), " clamp", 0x0000), + ((ONE, 0x3E00), " div:2 clamp", 0x3A00), ((0x3A00, ONE), " mul:2 clamp", ONE)): + with self.subTest(a=hex(a), b=hex(b), mod=suffix): + self.assertEqual(run("v_mul_f16_e64 v0, v1, v2" + suffix, {"v1": a, "v2": b}) & 0xFFFF, want) + for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): + got = run("v_mul_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4900, "v2": 0xC100}) # 10 and -2.5 + self.assertEqual(got & 0xFFFF, scale(ref_mul(0x4900, 0xC100), f)) + + def test_random_operands(self): + rng = random.Random(0x3C16) + pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] + for _ in range(120): + a = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) + b = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) + with self.subTest(a=hex(a), b=hex(b)): + got = run("v_mul_f16 v0, v1, v2", {"v1": a, "v2": b}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, ref_mul(a, b)), (hex(got), hex(ref_mul(a, b)))) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_mul_hi.py b/tests/semantic/test_valu_mul_hi.py index 40bb19d14..75e30ff3c 100644 --- a/tests/semantic/test_valu_mul_hi.py +++ b/tests/semantic/test_valu_mul_hi.py @@ -1,1129 +1,101 @@ -"""Semantic reference tests and mathematical oracle for AMD RDNA2 v_mul_hi_u32 and v_mul_hi_i32. +"""v_mul_hi_u32 and v_mul_hi_i32 (RDNA2 VOP3): D = high 32 bits of the 64-bit product of two 32-bit sources. -RDNA2 Vector Arithmetic Logic Unit (VALU) Architecture: - In AMD RDNA2 (GFX10/GFX1030) ISA, vector registers (VGPRs) are 32 bits wide. - The v_mul_hi_u32 and v_mul_hi_i32 instructions compute the high 32 bits of a 64-bit - integer product of two 32-bit integer operands: - v_mul_hi_u32 v[d], src0, src1 : D = (unsigned(src0) * unsigned(src1)) >> 32 - v_mul_hi_i32 v[d], src0, src1 : D = (signed(src0) * signed(src1)) >> 32 - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +word is written down by hand next to each case and also recomputed by the plain-Python reference below. +Standard library only: no GPU, no LLVM, no game data. """ -from __future__ import annotations - -import abc -from dataclasses import dataclass -import enum -import struct +import os +import random +import sys import unittest +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) + +import support # noqa: E402 + MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -SIGN32 = 0x80000000 - -INT32_MIN = -0x80000000 INT32_MAX = 0x7FFFFFFF -UINT32_MAX = 0xFFFFFFFF - -OLD_VGPR_SENTINEL = 0xDEADBEEF - - -def to_u32(val: int) -> int: - """Normalize integer to unsigned 32-bit integer [0, 2^32 - 1].""" - return val & MASK32 - - -def to_i32(val: int) -> int: - """Interpret 32-bit integer as signed two's complement integer [-2^31, 2^31 - 1].""" - u = val & MASK32 - return u - 0x100000000 if u & SIGN32 else u - - -def to_u64(val: int) -> int: - """Normalize integer to unsigned 64-bit integer [0, 2^64 - 1].""" - return val & MASK64 - - -def to_i64(val: int) -> int: - """Interpret 64-bit integer as signed two's complement integer [-2^63, 2^63 - 1].""" - u = val & MASK64 - return u - 0x10000000000000000 if u & 0x8000000000000000 else u - - -def ref_mul_hi_u32(src0: int, src1: int) -> int: - """Reference mathematical oracle for RDNA2 unsigned 32-bit high multiply v_mul_hi_u32. - - Computes: - D.u32 = ((src0.u32 * src1.u32) >> 32) & 0xFFFFFFFF - """ - u0 = src0 & MASK32 - u1 = src1 & MASK32 - prod64 = u0 * u1 - return (prod64 >> 32) & MASK32 - - -def ref_mul_hi_i32(src0: int, src1: int) -> int: - """Reference mathematical oracle for RDNA2 signed 32-bit high multiply v_mul_hi_i32. - - Computes: - D.i32 = ((src0.i32 * src1.i32) >> 32) & 0xFFFFFFFF - under signed two's-complement arithmetic. - """ - i0 = to_i32(src0) - i1 = to_i32(src1) - prod_signed = i0 * i1 - prod_bits = prod_signed & MASK64 - return (prod_bits >> 32) & MASK32 - - -def ref_mul_pair_u32(src0: int, src1: int) -> tuple[int, int]: - """Decomposed low and high dword product for unsigned 32-bit multiplication. - - Returns (lo, hi) such that: - (hi << 32) | lo == (src0.u32 * src1.u32) - """ - u0 = src0 & MASK32 - u1 = src1 & MASK32 - prod = u0 * u1 - lo = prod & MASK32 - hi = (prod >> 32) & MASK32 - return lo, hi - - -def ref_mul_pair_i32(src0: int, src1: int) -> tuple[int, int]: - """Decomposed low and high dword product for signed 32-bit multiplication. - - Returns (lo, hi) representing the 64-bit signed two's complement product. - """ - i0 = to_i32(src0) - i1 = to_i32(src1) - prod = i0 * i1 - prod_bits = prod & MASK64 - lo = prod_bits & MASK32 - hi = (prod_bits >> 32) & MASK32 - return lo, hi - - -class VALURegisterFile: - """Architectural model for RDNA2 VALU 32-bit vector register file.""" - - def __init__(self, num_vgprs: int = 256) -> None: - self.num_vgprs = num_vgprs - self.regs = [0] * num_vgprs - - def get_vgpr(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: {idx}") - return self.regs[idx] & MASK32 - - def set_vgpr(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: {idx}") - self.regs[idx] = val & MASK32 - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions for v_mul_hi -# ============================================================================== - -class Opcode(enum.Enum): - V_MUL_HI_U32 = "v_mul_hi_u32" - V_MUL_HI_I32 = "v_mul_hi_i32" - - -class OperandKind(enum.Enum): - VGPR = "vgpr" - SGPR = "sgpr" - LITERAL = "literal" - INLINE_INT = "inline_int" - - -@dataclass -class ASTOperand: - kind: OperandKind - reg_idx: int = 0 - imm_val: int = 0 - - def format_asm(self) -> str: - if self.kind == OperandKind.VGPR: - return f"v{self.reg_idx}" - elif self.kind == OperandKind.SGPR: - return f"s{self.reg_idx}" - elif self.kind == OperandKind.LITERAL: - return f"0x{self.imm_val:08x}" - elif self.kind == OperandKind.INLINE_INT: - return str(self.imm_val) - return "unknown" - - -@dataclass -class ASTInstruction: - opcode: Opcode - dst: ASTOperand - src0: ASTOperand - src1: ASTOperand - - def validate(self) -> None: - if self.opcode not in (Opcode.V_MUL_HI_U32, Opcode.V_MUL_HI_I32): - raise ValueError(f"Invalid opcode for v_mul_hi AST: {self.opcode}") - if self.dst.kind != OperandKind.VGPR: - raise ValueError(f"Destination must be a VGPR, got {self.dst.kind}") - if not (0 <= self.dst.reg_idx <= 255): - raise ValueError(f"Destination VGPR index out of range: {self.dst.reg_idx}") - for name, src in [("src0", self.src0), ("src1", self.src1)]: - if src.kind == OperandKind.VGPR: - if not (0 <= src.reg_idx <= 255): - raise ValueError(f"{name} VGPR index out of range: {src.reg_idx}") - elif src.kind == OperandKind.SGPR: - if not (0 <= src.reg_idx <= 105): - raise ValueError(f"{name} SGPR index out of range: {src.reg_idx}") - - def format_asm(self) -> str: - return f"{self.opcode.value} {self.dst.format_asm()}, {self.src0.format_asm()}, {self.src1.format_asm()}" - - -class IntegerExpression(abc.ABC): - @abc.abstractmethod - def evaluate(self, env: dict[str, int]) -> int: - pass - - -@dataclass -class IntConstant(IntegerExpression): - val: int - - def evaluate(self, env: dict[str, int]) -> int: - return self.val & MASK32 - - -@dataclass -class IntVariable(IntegerExpression): - name: str - - def evaluate(self, env: dict[str, int]) -> int: - if self.name not in env: - raise KeyError(f"Variable {self.name} not found in environment") - return env[self.name] & MASK32 - - -@dataclass -class MulHiExpr(IntegerExpression): - opcode: Opcode - lhs: IntegerExpression - rhs: IntegerExpression - - def evaluate(self, env: dict[str, int]) -> int: - v_lhs = self.lhs.evaluate(env) - v_rhs = self.rhs.evaluate(env) - if self.opcode == Opcode.V_MUL_HI_U32: - return ref_mul_hi_u32(v_lhs, v_rhs) - elif self.opcode == Opcode.V_MUL_HI_I32: - return ref_mul_hi_i32(v_lhs, v_rhs) - raise ValueError(f"Unsupported opcode in MulHiExpr: {self.opcode}") - - -def instruction_to_expression(inst: ASTInstruction) -> MulHiExpr: - """Translate an ASTInstruction to a typed symbolic expression tree.""" - inst.validate() - - def build_operand_expr(op: ASTOperand, prefix: str) -> IntegerExpression: - if op.kind in (OperandKind.VGPR, OperandKind.SGPR): - return IntVariable(f"{prefix}_{op.reg_idx}") - elif op.kind in (OperandKind.LITERAL, OperandKind.INLINE_INT): - return IntConstant(op.imm_val) - raise ValueError(f"Unsupported operand kind: {op.kind}") - - lhs = build_operand_expr(inst.src0, "src0") - rhs = build_operand_expr(inst.src1, "src1") - return MulHiExpr(opcode=inst.opcode, lhs=lhs, rhs=rhs) - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter for v_mul_hi -# ============================================================================== - -def parse_asm_operand(tok: str) -> ASTOperand: - tok = tok.strip() - if tok.startswith("v") and tok[1:].isdigit(): - return ASTOperand(kind=OperandKind.VGPR, reg_idx=int(tok[1:])) - elif tok.startswith("s") and tok[1:].isdigit(): - return ASTOperand(kind=OperandKind.SGPR, reg_idx=int(tok[1:])) - elif tok.startswith("0x") or tok.startswith("0X"): - return ASTOperand(kind=OperandKind.LITERAL, imm_val=int(tok, 16) & MASK32) - else: - try: - val = int(tok) - return ASTOperand(kind=OperandKind.INLINE_INT, imm_val=val & MASK32) - except ValueError: - raise ValueError(f"Unrecognized assembly operand token: {tok}") - - -def parse_asm_line(line: str) -> ASTInstruction: - clean = line.split(";")[0].split("//")[0].strip() - tokens = [t for t in clean.replace(",", " ").split() if t] - if not tokens: - raise ValueError("Empty assembly line") - op_str = tokens[0] - if op_str == "v_mul_hi_u32": - opcode = Opcode.V_MUL_HI_U32 - elif op_str == "v_mul_hi_i32": - opcode = Opcode.V_MUL_HI_I32 - else: - raise ValueError(f"Expected opcode v_mul_hi_u32 or v_mul_hi_i32, got {op_str}") - - if len(tokens) != 4: - raise ValueError(f"{op_str} requires 3 operands (dst, src0, src1), got {len(tokens) - 1}: {tokens[1:]}") - - dst = parse_asm_operand(tokens[1]) - src0 = parse_asm_operand(tokens[2]) - src1 = parse_asm_operand(tokens[3]) - inst = ASTInstruction(opcode=opcode, dst=dst, src0=src0, src1=src1) - inst.validate() - return inst - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU v_mul_hi.""" - - def __init__(self, num_vgprs: int = 256, num_sgprs: int = 106) -> None: - self.vgpr = VALURegisterFile(num_vgprs=num_vgprs) - self.num_sgprs = num_sgprs - self.sgprs = [0] * num_sgprs - self.vcc = 0 - self.scc = 0 - - def get_sgpr(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: {idx}") - return self.sgprs[idx] & MASK32 - - def set_sgpr(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: {idx}") - self.sgprs[idx] = val & MASK32 - - def resolve_operand(self, op: ASTOperand) -> int: - if op.kind == OperandKind.VGPR: - return self.vgpr.get_vgpr(op.reg_idx) - elif op.kind == OperandKind.SGPR: - return self.get_sgpr(op.reg_idx) - elif op.kind in (OperandKind.LITERAL, OperandKind.INLINE_INT): - return op.imm_val & MASK32 - raise ValueError(f"Unknown operand kind: {op.kind}") - - def execute_ast(self, inst: ASTInstruction) -> int: - inst.validate() - s0 = self.resolve_operand(inst.src0) - s1 = self.resolve_operand(inst.src1) - if inst.opcode == Opcode.V_MUL_HI_U32: - res = ref_mul_hi_u32(s0, s1) - elif inst.opcode == Opcode.V_MUL_HI_I32: - res = ref_mul_hi_i32(s0, s1) - else: - raise ValueError(f"Unsupported opcode: {inst.opcode}") - self.vgpr.set_vgpr(inst.dst.reg_idx, res) - return res - - def execute_asm(self, line: str) -> int: - inst = parse_asm_line(line) - return self.execute_ast(inst) - - -# ============================================================================== -# SIMD Wavefront Execution Model (Wave32 / Wave64) for v_mul_hi -# ============================================================================== - -def ref_simd_mul_hi( - opcode: Opcode, - src0_lanes: list[int], - src1_lanes: list[int], - wave_size: int = 64, - exec_mask: int | None = None, - prev_dst: list[int] | None = None, -) -> list[int]: - """Reference SIMD execution oracle across wavefront lanes.""" - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size: {wave_size}") - if len(src0_lanes) != wave_size or len(src1_lanes) != wave_size: - raise ValueError(f"Operand length must match wave_size ({wave_size})") - - active_mask = (1 << wave_size) - 1 if exec_mask is None else (exec_mask & ((1 << wave_size) - 1)) - fallback = [0] * wave_size if prev_dst is None else prev_dst - if len(fallback) != wave_size: - raise ValueError(f"prev_dst length must match wave_size ({wave_size})") - - output = list(fallback) - fn = ref_mul_hi_u32 if opcode == Opcode.V_MUL_HI_U32 else ref_mul_hi_i32 - for lane in range(wave_size): - if (active_mask >> lane) & 1: - output[lane] = fn(src0_lanes[lane], src1_lanes[lane]) - return output - - -class SIMDWavefront: - """SIMD wavefront simulator modeling multi-lane execution and EXEC masking.""" - - def __init__(self, wave_size: int = 64, num_vgprs: int = 256) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got {wave_size}") - self.wave_size = wave_size - self.num_vgprs = num_vgprs - self.lanes = [VALURegisterFile(num_vgprs=num_vgprs) for _ in range(wave_size)] - self.exec_mask = (1 << wave_size) - 1 - self.vcc = 0 - self.sgprs = [0] * 106 - - def store_vgpr_wave(self, reg_idx: int, values: list[int]) -> None: - if len(values) != self.wave_size: - raise ValueError(f"Value count ({len(values)}) does not match wave_size ({self.wave_size})") - for lane in range(self.wave_size): - self.lanes[lane].set_vgpr(reg_idx, values[lane]) - - def load_vgpr_wave(self, reg_idx: int) -> list[int]: - return [self.lanes[lane].get_vgpr(reg_idx) for lane in range(self.wave_size)] - - def step_v_mul_hi( - self, - opcode: Opcode, - dst_reg: int, - src0_reg: int, - src1_reg: int, - ) -> list[int]: - active_mask = self.exec_mask & ((1 << self.wave_size) - 1) - fn = ref_mul_hi_u32 if opcode == Opcode.V_MUL_HI_U32 else ref_mul_hi_i32 - for lane in range(self.wave_size): - if (active_mask >> lane) & 1: - s0 = self.lanes[lane].get_vgpr(src0_reg) - s1 = self.lanes[lane].get_vgpr(src1_reg) - res = fn(s0, s1) - self.lanes[lane].set_vgpr(dst_reg, res) - return self.load_vgpr_wave(dst_reg) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Isolation for v_mul_hi -# ============================================================================== - -@dataclass -class MulHiStatusFlags: - zero: bool = False - negative: bool = False - overflow_32: bool = False - - -def compute_mul_hi_flags(opcode: Opcode, s0: int, s1: int, hi: int) -> MulHiStatusFlags: - flags = MulHiStatusFlags() - flags.zero = (hi == 0) - flags.negative = bool((hi & SIGN32) != 0) - - if opcode == Opcode.V_MUL_HI_U32: - # For unsigned, product overflows 32 bits if high dword is non-zero - flags.overflow_32 = (hi != 0) - elif opcode == Opcode.V_MUL_HI_I32: - # For signed, product overflows 32 bits if 64-bit product doesn't fit in signed 32-bit: - # which means hi is not a pure sign-extension of lo. - lo, _ = ref_mul_pair_i32(s0, s1) - expected_hi = 0xFFFFFFFF if (lo & SIGN32) else 0 - flags.overflow_32 = (hi != expected_hi) - - return flags - - -def ref_cmp_u32(op: str, s0: int, s1: int) -> bool: - u0 = s0 & MASK32 - u1 = s1 & MASK32 - if op in ("eq", "=="): - return u0 == u1 - elif op in ("ne", "!="): - return u0 != u1 - elif op in ("lt", "<"): - return u0 < u1 - elif op in ("le", "<="): - return u0 <= u1 - elif op in ("gt", ">"): - return u0 > u1 - elif op in ("ge", ">="): - return u0 >= u1 - raise ValueError(f"Unknown comparison operator: {op}") - - -def ref_cmp_i32(op: str, s0: int, s1: int) -> bool: - i0 = to_i32(s0) - i1 = to_i32(s1) - if op in ("eq", "=="): - return i0 == i1 - elif op in ("ne", "!="): - return i0 != i1 - elif op in ("lt", "<"): - return i0 < i1 - elif op in ("le", "<="): - return i0 <= i1 - elif op in ("gt", ">"): - return i0 > i1 - elif op in ("ge", ">="): - return i0 >= i1 - raise ValueError(f"Unknown comparison operator: {op}") - - -def generate_condition_mask( - op: str, is_signed: bool, s0_lanes: list[int], s1_lanes: list[int] -) -> int: - mask = 0 - fn = ref_cmp_i32 if is_signed else ref_cmp_u32 - for lane, (s0, s1) in enumerate(zip(s0_lanes, s1_lanes)): - if fn(op, s0, s1): - mask |= (1 << lane) - return mask - - -class TestVMulHiOracleAndModel(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural model.""" - - def test_mul_hi_u32_basic(self) -> None: - # 0x80000000 * 2 = 0x100000000 -> hi = 1 - self.assertEqual(ref_mul_hi_u32(0x80000000, 2), 1) - - # 0x10000 * 0x10000 = 0x100000000 -> hi = 1 - self.assertEqual(ref_mul_hi_u32(0x10000, 0x10000), 1) - - # Small products fit in 32 bits -> hi = 0 - self.assertEqual(ref_mul_hi_u32(100, 200), 0) - self.assertEqual(ref_mul_hi_u32(0xFFFF, 0xFFFF), 0) - - def test_mul_hi_u32_extremes(self) -> None: - # 0 * anything = 0 - self.assertEqual(ref_mul_hi_u32(0, UINT32_MAX), 0) - self.assertEqual(ref_mul_hi_u32(UINT32_MAX, 0), 0) - - # UINT32_MAX * 1 -> hi = 0 - self.assertEqual(ref_mul_hi_u32(UINT32_MAX, 1), 0) - - # UINT32_MAX * 2 = 0x1FFFFFFFE -> hi = 1 - self.assertEqual(ref_mul_hi_u32(UINT32_MAX, 2), 1) - - # UINT32_MAX * UINT32_MAX = 0xFFFFFFFE_00000001 -> hi = 0xFFFFFFFE - self.assertEqual(ref_mul_hi_u32(UINT32_MAX, UINT32_MAX), 0xFFFFFFFE) - - def test_mul_hi_i32_basic(self) -> None: - # (+3) * (+4) = +12 -> hi = 0 - self.assertEqual(ref_mul_hi_i32(3, 4), 0) - - # (-1) * (-1) = +1 -> 64-bit 0x00000000_00000001 -> hi = 0 - self.assertEqual(ref_mul_hi_i32(0xFFFFFFFF, 0xFFFFFFFF), 0) - - # (-1) * (+1) = -1 -> 64-bit 0xFFFFFFFF_FFFFFFFF -> hi = 0xFFFFFFFF - self.assertEqual(ref_mul_hi_i32(0xFFFFFFFF, 1), 0xFFFFFFFF) - - # (+10) * (-5) = -50 -> 64-bit negative -> hi = 0xFFFFFFFF - self.assertEqual(ref_mul_hi_i32(10, to_u32(-5)), 0xFFFFFFFF) - - def test_mul_hi_i32_extremes(self) -> None: - # INT32_MIN (-2^31) * 2 = -2^32 -> 64-bit 0xFFFFFFFF_00000000 -> hi = 0xFFFFFFFF - self.assertEqual(ref_mul_hi_i32(0x80000000, 2), 0xFFFFFFFF) - - # INT32_MIN * -1 = +2^31 (0x80000000) -> fits in 32-bit positive -> hi = 0 - self.assertEqual(ref_mul_hi_i32(0x80000000, 0xFFFFFFFF), 0) - - # INT32_MIN * INT32_MIN = (-2^31) * (-2^31) = +2^62 = 0x40000000_00000000 -> hi = 0x40000000 - self.assertEqual(ref_mul_hi_i32(0x80000000, 0x80000000), 0x40000000) - - # INT32_MAX (2^31 - 1) * INT32_MAX = (2^31 - 1)^2 = 2^62 - 2^32 + 1 - # 64-bit = 0x3FFFFFFF_00000001 -> hi = 0x3FFFFFFF - self.assertEqual(ref_mul_hi_i32(INT32_MAX, INT32_MAX), 0x3FFFFFFF) - - # INT32_MIN * INT32_MAX = (-2^31) * (2^31 - 1) = -2^62 + 2^31 - # 64-bit = 0xC0000000_80000000 -> hi = 0xC0000000 - self.assertEqual(ref_mul_hi_i32(0x80000000, INT32_MAX), 0xC0000000) - - def test_mul_pair_decomposition(self) -> None: - s0 = 0x12345678 - s1 = 0x9ABCDEF0 - - # Unsigned pair - lo_u, hi_u = ref_mul_pair_u32(s0, s1) - full_u = (hi_u << 32) | lo_u - self.assertEqual(full_u, (s0 & MASK32) * (s1 & MASK32)) - - # Signed pair - lo_i, hi_i = ref_mul_pair_i32(s0, s1) - full_i = (hi_i << 32) | lo_i - expected_i = to_u64(to_i32(s0) * to_i32(s1)) - self.assertEqual(full_i, expected_i) - - def test_register_file_access(self) -> None: - rf = VALURegisterFile(num_vgprs=64) - rf.set_vgpr(5, 0x12345678) - self.assertEqual(rf.get_vgpr(5), 0x12345678) - - with self.assertRaises(IndexError): - rf.get_vgpr(64) - with self.assertRaises(IndexError): - rf.set_vgpr(-1, 0) - - -class TestSymbolicAST(unittest.TestCase): - """Test suite for symbolic AST definitions and typed expressions.""" - - def test_ast_creation_and_formatting(self) -> None: - dst = ASTOperand(kind=OperandKind.VGPR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR, reg_idx=1) - src1 = ASTOperand(kind=OperandKind.SGPR, reg_idx=2) - - inst_u = ASTInstruction(opcode=Opcode.V_MUL_HI_U32, dst=dst, src0=src0, src1=src1) - inst_u.validate() - self.assertEqual(inst_u.format_asm(), "v_mul_hi_u32 v0, v1, s2") - - inst_i = ASTInstruction(opcode=Opcode.V_MUL_HI_I32, dst=dst, src0=src0, src1=src1) - inst_i.validate() - self.assertEqual(inst_i.format_asm(), "v_mul_hi_i32 v0, v1, s2") - - def test_typed_expression_evaluation(self) -> None: - c1 = IntConstant(0x80000000) - c2 = IntConstant(2) - - expr_u = MulHiExpr(opcode=Opcode.V_MUL_HI_U32, lhs=c1, rhs=c2) - self.assertEqual(expr_u.evaluate({}), 1) - - expr_i = MulHiExpr(opcode=Opcode.V_MUL_HI_I32, lhs=c1, rhs=c2) - # -2^31 * 2 = -2^32 -> hi = 0xFFFFFFFF - self.assertEqual(expr_i.evaluate({}), 0xFFFFFFFF) - - def test_instruction_to_expression(self) -> None: - dst = ASTOperand(kind=OperandKind.VGPR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR, reg_idx=1) - src1 = ASTOperand(kind=OperandKind.LITERAL, imm_val=UINT32_MAX) - inst = ASTInstruction(opcode=Opcode.V_MUL_HI_U32, dst=dst, src0=src0, src1=src1) - - expr = instruction_to_expression(inst) - env = {"src0_1": UINT32_MAX} - self.assertEqual(expr.evaluate(env), 0xFFFFFFFE) - - def test_ast_validation_errors(self) -> None: - # Invalid destination kind - bad_dst = ASTInstruction( - opcode=Opcode.V_MUL_HI_U32, - dst=ASTOperand(OperandKind.SGPR, reg_idx=0), - src0=ASTOperand(OperandKind.VGPR, reg_idx=1), - src1=ASTOperand(OperandKind.VGPR, reg_idx=2), - ) - with self.assertRaises(ValueError): - bad_dst.validate() - - # Destination VGPR out of bounds - oob_dst = ASTInstruction( - opcode=Opcode.V_MUL_HI_U32, - dst=ASTOperand(OperandKind.VGPR, reg_idx=256), - src0=ASTOperand(OperandKind.VGPR, reg_idx=1), - src1=ASTOperand(OperandKind.VGPR, reg_idx=2), - ) - with self.assertRaises(ValueError): - oob_dst.validate() - - -class TestScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction interpreter.""" - - def test_execute_v_mul_hi_u32_vgpr_sources(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr(1, 0x80000000) - interp.vgpr.set_vgpr(2, 2) - - dst = ASTOperand(kind=OperandKind.VGPR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR, reg_idx=1) - src1 = ASTOperand(kind=OperandKind.VGPR, reg_idx=2) - inst = ASTInstruction(opcode=Opcode.V_MUL_HI_U32, dst=dst, src0=src0, src1=src1) - - res = interp.execute_ast(inst) - self.assertEqual(res, 1) - self.assertEqual(interp.vgpr.get_vgpr(0), 1) - - def test_execute_v_mul_hi_i32_vgpr_sources(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr(1, to_u32(-10)) - interp.vgpr.set_vgpr(2, to_u32(20)) - - dst = ASTOperand(kind=OperandKind.VGPR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR, reg_idx=1) - src1 = ASTOperand(kind=OperandKind.VGPR, reg_idx=2) - inst = ASTInstruction(opcode=Opcode.V_MUL_HI_I32, dst=dst, src0=src0, src1=src1) - - res = interp.execute_ast(inst) - # -200 -> negative 64-bit product -> hi dword = 0xFFFFFFFF - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(interp.vgpr.get_vgpr(0), 0xFFFFFFFF) - - def test_execute_sgpr_and_literal_sources(self) -> None: - interp = ScalarInterpreter() - interp.set_sgpr(4, 0x10000) - interp.vgpr.set_vgpr(2, 0x20000) - - # v0 = v_mul_hi_u32 v2, s4 -> (0x20000 * 0x10000) >> 32 = 0x200000000 >> 32 = 2 - res = interp.execute_asm("v_mul_hi_u32 v0, v2, s4") - self.assertEqual(res, 2) - self.assertEqual(interp.vgpr.get_vgpr(0), 2) - - # literal multiplication - res_lit = interp.execute_asm("v_mul_hi_u32 v1, v0, 0x80000000") - # 2 * 0x80000000 = 0x100000000 -> hi = 1 - self.assertEqual(res_lit, 1) - self.assertEqual(interp.vgpr.get_vgpr(1), 1) - - def test_execute_i32_assembly(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr(5, 0x80000000) # -2^31 - interp.vgpr.set_vgpr(6, 0x80000000) # -2^31 - - # (-2^31) * (-2^31) = +2^62 = 0x40000000_00000000 -> hi = 0x40000000 - res = interp.execute_asm("v_mul_hi_i32 v0, v5, v6") - self.assertEqual(res, 0x40000000) - self.assertEqual(interp.vgpr.get_vgpr(0), 0x40000000) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_all_active_u32(self) -> None: - sim = SIMDWavefront(wave_size=32) - s0_vals = [0x10000000 * (i + 1) for i in range(32)] - s1_vals = [0x10 for _ in range(32)] - sim.store_vgpr_wave(1, s0_vals) - sim.store_vgpr_wave(2, s1_vals) - - res = sim.step_v_mul_hi(Opcode.V_MUL_HI_U32, 0, 1, 2) - for i in range(32): - expected = ref_mul_hi_u32(s0_vals[i], s1_vals[i]) - self.assertEqual(res[i], expected) - - def test_wave64_all_active_i32(self) -> None: - sim = SIMDWavefront(wave_size=64) - s0_vals = [to_u32(-1000000 * (i + 1)) for i in range(64)] - s1_vals = [to_u32(2000) for _ in range(64)] - sim.store_vgpr_wave(1, s0_vals) - sim.store_vgpr_wave(2, s1_vals) - - res = sim.step_v_mul_hi(Opcode.V_MUL_HI_I32, 0, 1, 2) - for i in range(64): - expected = ref_mul_hi_i32(s0_vals[i], s1_vals[i]) - self.assertEqual(res[i], expected) - - def test_wave32_divergent_exec_mask(self) -> None: - sim = SIMDWavefront(wave_size=32) - sim.store_vgpr_wave(0, [OLD_VGPR_SENTINEL] * 32) - s0_vals = [0x80000000] * 32 - s1_vals = [2] * 32 - sim.store_vgpr_wave(1, s0_vals) - sim.store_vgpr_wave(2, s1_vals) - - # Alternating active lanes: 0b0101... - sim.exec_mask = 0x55555555 - res = sim.step_v_mul_hi(Opcode.V_MUL_HI_U32, 0, 1, 2) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(res[lane], 1) - else: - self.assertEqual(res[lane], OLD_VGPR_SENTINEL) - - def test_wave64_divergent_exec_mask(self) -> None: - sim = SIMDWavefront(wave_size=64) - sim.store_vgpr_wave(0, [OLD_VGPR_SENTINEL] * 64) - s0_vals = [0xFFFFFFFF] * 64 - s1_vals = [0xFFFFFFFF] * 64 - sim.store_vgpr_wave(1, s0_vals) - sim.store_vgpr_wave(2, s1_vals) - - # Lower 32 lanes active, upper 32 inactive - sim.exec_mask = 0x00000000_FFFFFFFF - res = sim.step_v_mul_hi(Opcode.V_MUL_HI_U32, 0, 1, 2) - - for lane in range(32): - self.assertEqual(res[lane], 0xFFFFFFFE) - for lane in range(32, 64): - self.assertEqual(res[lane], OLD_VGPR_SENTINEL) - - def test_wave32_upper_exec_bits_ignored(self) -> None: - sim = SIMDWavefront(wave_size=32) - sim.store_vgpr_wave(0, [OLD_VGPR_SENTINEL] * 32) - sim.store_vgpr_wave(1, [0x80000000] * 32) - sim.store_vgpr_wave(2, [4] * 32) - - # Upper 32 bits should not affect wave32 - sim.exec_mask = 0xDEADBEEF_FFFFFFFF - res = sim.step_v_mul_hi(Opcode.V_MUL_HI_U32, 0, 1, 2) - for lane in range(32): - self.assertEqual(res[lane], 2) - - def test_simd_oracle_validation(self) -> None: - wave_size = 64 - s0_vals = [(i * 0x04000000 + 0x12345) & MASK32 for i in range(wave_size)] - s1_vals = [((63 - i) * 0x02000000 + 0x6789A) & MASK32 for i in range(wave_size)] - exec_mask = 0xAAAAAAAAAAAAAAAA - prev_dst = [0xCAFE0000 | i for i in range(wave_size)] - - expected = ref_simd_mul_hi( - Opcode.V_MUL_HI_U32, s0_vals, s1_vals, wave_size=wave_size, exec_mask=exec_mask, prev_dst=prev_dst - ) - - sim = SIMDWavefront(wave_size=wave_size) - sim.store_vgpr_wave(0, prev_dst) - sim.store_vgpr_wave(1, s0_vals) - sim.store_vgpr_wave(2, s1_vals) - sim.exec_mask = exec_mask - - actual = sim.step_v_mul_hi(Opcode.V_MUL_HI_U32, 0, 1, 2) - self.assertEqual(actual, expected) - - -class TestRegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def test_inplace_dst_equals_src0_u32(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr(0, 0x80000000) - interp.vgpr.set_vgpr(1, 4) - - # v0 = v_mul_hi_u32 v0, v1 -> (0x80000000 * 4) >> 32 = 0x200000000 >> 32 = 2 - res = interp.execute_asm("v_mul_hi_u32 v0, v0, v1") - self.assertEqual(res, 2) - self.assertEqual(interp.vgpr.get_vgpr(0), 2) - # v1 must remain untouched - self.assertEqual(interp.vgpr.get_vgpr(1), 4) - - def test_inplace_dst_equals_src1_u32(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr(0, 0x80000000) - interp.vgpr.set_vgpr(1, 6) - - # v1 = v_mul_hi_u32 v0, v1 -> (0x80000000 * 6) >> 32 = 3 - res = interp.execute_asm("v_mul_hi_u32 v1, v0, v1") - self.assertEqual(res, 3) - self.assertEqual(interp.vgpr.get_vgpr(1), 3) - # v0 must remain untouched - self.assertEqual(interp.vgpr.get_vgpr(0), 0x80000000) - - def test_inplace_self_squaring_u32(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr(2, UINT32_MAX) - - # v2 = v_mul_hi_u32 v2, v2 -> (0xFFFFFFFF)^2 >> 32 = 0xFFFFFFFE - res = interp.execute_asm("v_mul_hi_u32 v2, v2, v2") - self.assertEqual(res, 0xFFFFFFFE) - self.assertEqual(interp.vgpr.get_vgpr(2), 0xFFFFFFFE) - - def test_inplace_dst_equals_src0_i32(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr(3, to_u32(-2)) - interp.vgpr.set_vgpr(4, 10) - - # v3 = v_mul_hi_i32 v3, v4 -> (-2 * 10) = -20 -> hi = 0xFFFFFFFF - res = interp.execute_asm("v_mul_hi_i32 v3, v3, v4") - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(interp.vgpr.get_vgpr(3), 0xFFFFFFFF) - self.assertEqual(interp.vgpr.get_vgpr(4), 10) - - def test_inplace_self_squaring_i32(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr(5, 0x80000000) # -2^31 - - # v5 = v_mul_hi_i32 v5, v5 -> (-2^31)^2 = 2^62 = 0x40000000_00000000 -> hi = 0x40000000 - res = interp.execute_asm("v_mul_hi_i32 v5, v5, v5") - self.assertEqual(res, 0x40000000) - self.assertEqual(interp.vgpr.get_vgpr(5), 0x40000000) - - def test_simd_inplace_divergent_mask(self) -> None: - sim = SIMDWavefront(wave_size=32) - init_vals = [0x80000000 for _ in range(32)] - multiplier_vals = [i + 1 for i in range(32)] - sim.store_vgpr_wave(0, init_vals) - sim.store_vgpr_wave(1, multiplier_vals) - - # Active on even lanes only - sim.exec_mask = 0x55555555 - res = sim.step_v_mul_hi(Opcode.V_MUL_HI_U32, 0, 0, 1) - - for lane in range(32): - if lane % 2 == 0: - expected = (0x80000000 * (lane + 1)) >> 32 - self.assertEqual(res[lane], expected) - else: - self.assertEqual(res[lane], init_vals[lane]) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Test suite for condition codes, status flags, and carry/borrow isolation.""" - - def test_status_flags_zero_and_negative(self) -> None: - # High word is 0 - r0 = ref_mul_hi_u32(100, 200) - f0 = compute_mul_hi_flags(Opcode.V_MUL_HI_U32, 100, 200, r0) - self.assertTrue(f0.zero) - self.assertFalse(f0.negative) - self.assertFalse(f0.overflow_32) - - # High word has sign bit set - r1 = ref_mul_hi_i32(to_u32(-10), 2) - f1 = compute_mul_hi_flags(Opcode.V_MUL_HI_I32, to_u32(-10), 2, r1) - self.assertEqual(r1, 0xFFFFFFFF) - self.assertFalse(f1.zero) - self.assertTrue(f1.negative) - self.assertFalse(f1.overflow_32) # -20 fits in signed 32-bit! - - def test_status_flags_overflow_32(self) -> None: - # Unsigned overflow 32 bits - r_u = ref_mul_hi_u32(0x80000000, 2) - f_u = compute_mul_hi_flags(Opcode.V_MUL_HI_U32, 0x80000000, 2, r_u) - self.assertEqual(r_u, 1) - self.assertTrue(f_u.overflow_32) - - # Signed overflow 32 bits: 2^30 * 4 = 2^32, does not fit in signed 32-bit (overflows) - r_i = ref_mul_hi_i32(0x40000000, 4) - f_i = compute_mul_hi_flags(Opcode.V_MUL_HI_I32, 0x40000000, 4, r_i) - self.assertEqual(r_i, 1) - self.assertTrue(f_i.overflow_32) - - def test_vcc_and_scc_preserved(self) -> None: - interp = ScalarInterpreter() - interp.vcc = 0x12345678_9ABCDEF0 - interp.scc = 1 - interp.vgpr.set_vgpr(1, 0x80000000) - interp.vgpr.set_vgpr(2, 2) - - interp.execute_asm("v_mul_hi_u32 v0, v1, v2") - self.assertEqual(interp.vcc, 0x12345678_9ABCDEF0) - self.assertEqual(interp.scc, 1) - - sim = SIMDWavefront(wave_size=32) - sim.vcc = 0xCAFEBABE - sim.store_vgpr_wave(1, [0x80000000] * 32) - sim.store_vgpr_wave(2, [2] * 32) - sim.step_v_mul_hi(Opcode.V_MUL_HI_U32, 0, 1, 2) - self.assertEqual(sim.vcc, 0xCAFEBABE) - - def test_condition_mask_generation(self) -> None: - # Generate condition mask from high-word comparisons - hi_words = [0, 1, 0xFFFFFFFF, 0x40000000] - zeros = [0, 0, 0, 0] - - # Equal to zero -> lanes 0 - mask_eq = generate_condition_mask("==", False, hi_words, zeros) - self.assertEqual(mask_eq, 0b0001) - - # Greater than zero (unsigned) -> lanes 1, 2, 3 - mask_gt_u = generate_condition_mask(">", False, hi_words, zeros) - self.assertEqual(mask_gt_u, 0b1110) - - # Less than zero (signed) -> lane 2 (0xFFFFFFFF = -1) - mask_lt_i = generate_condition_mask("<", True, hi_words, zeros) - self.assertEqual(mask_lt_i, 0b0100) - - -class TestBoundaryExtremesAndBitPatterns(unittest.TestCase): - """Test suite for boundary extremes, signed/unsigned wrap, and bit patterns.""" - - def test_unsigned_powers_of_two_boundaries(self) -> None: - # Exactly 2^32: high word = 1, low word = 0 - self.assertEqual(ref_mul_hi_u32(1 << 16, 1 << 16), 1) - self.assertEqual(ref_mul_hi_u32(1 << 31, 2), 1) - - # 2^31 * 2^31 = 2^62 -> high word = 2^30 = 0x40000000 - self.assertEqual(ref_mul_hi_u32(1 << 31, 1 << 31), 0x40000000) - - # 2^31 - 1 with 2 -> (2^32 - 2) < 2^32 -> high word = 0 - self.assertEqual(ref_mul_hi_u32(0x7FFFFFFF, 2), 0) - - def test_unsigned_checkerboard_bit_patterns(self) -> None: - p0 = 0x55555555 - p1 = 0xAAAAAAAA - prod = p0 * p1 - expected_hi = (prod >> 32) & MASK32 - self.assertEqual(ref_mul_hi_u32(p0, p1), expected_hi) - - def test_signed_boundary_negation_and_wrap(self) -> None: - # INT32_MIN (-2^31) multiplied by -1 gives +2^31 (0x80000000) - # As 64-bit signed integer, this is +0x00000000_80000000 -> high word = 0 - self.assertEqual(ref_mul_hi_i32(0x80000000, 0xFFFFFFFF), 0) - - # INT32_MIN multiplied by 1 gives -2^31 - # As 64-bit signed integer, sign-extended to 0xFFFFFFFF_80000000 -> high word = 0xFFFFFFFF - self.assertEqual(ref_mul_hi_i32(0x80000000, 1), 0xFFFFFFFF) - - # INT32_MIN * INT32_MIN = +2^62 = 0x40000000_00000000 -> high word = 0x40000000 - self.assertEqual(ref_mul_hi_i32(0x80000000, 0x80000000), 0x40000000) - - # INT32_MIN * INT32_MAX = (-2^31) * (2^31 - 1) = -2^62 + 2^31 = 0xC0000000_80000000 - self.assertEqual(ref_mul_hi_i32(0x80000000, 0x7FFFFFFF), 0xC0000000) - - # INT32_MAX * INT32_MAX = (2^31 - 1)^2 = 2^62 - 2^32 + 1 = 0x3FFFFFFF_00000001 - self.assertEqual(ref_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF), 0x3FFFFFFF) - - def test_signed_checkerboard_patterns(self) -> None: - p0 = 0x55555555 # positive - p1 = 0xAAAAAAAA # negative in signed two's-complement - expected_hi = ((to_i32(p0) * to_i32(p1) & MASK64) >> 32) & MASK32 - self.assertEqual(ref_mul_hi_i32(p0, p1), expected_hi) - - def test_64bit_product_reconstruction_sweep(self) -> None: - # Sweep edge cases and verify high-low word reconstruction - test_values = [ - 0, 1, 2, 0x7FFF, 0xFFFF, 0x10000, 0x7FFFFFFF, 0x80000000, - 0x80000001, 0xFFFFFFFE, 0xFFFFFFFF - ] - for a in test_values: - for b in test_values[:4]: - # Unsigned reconstruction - lo_u, hi_u = ref_mul_pair_u32(a, b) - reconstructed_u = (hi_u << 32) | lo_u - self.assertEqual(reconstructed_u, a * b) - - # Signed reconstruction - lo_i, hi_i = ref_mul_pair_i32(a, b) - reconstructed_i = (hi_i << 32) | lo_i - expected_i = (to_i32(a) * to_i32(b)) & MASK64 - self.assertEqual(reconstructed_i, expected_i) - - -# ============================================================================== -# Mutants for Mutation Detection -# ============================================================================== - -def mutant_low_word_instead_of_high(opcode: Opcode, s0: int, s1: int) -> int: - """Mutant 1: Returns the low 32 bits instead of high 32 bits.""" - if opcode == Opcode.V_MUL_HI_U32: - return (s0 * s1) & MASK32 - else: - return (to_i32(s0) * to_i32(s1)) & MASK32 - - -def mutant_unsigned_for_signed(opcode: Opcode, s0: int, s1: int) -> int: - """Mutant 2: Executes unsigned multiplication even when signed is requested.""" - return ref_mul_hi_u32(s0, s1) - - -def mutant_signed_for_unsigned(opcode: Opcode, s0: int, s1: int) -> int: - """Mutant 3: Executes signed multiplication even when unsigned is requested.""" - return ref_mul_hi_i32(s0, s1) - - -def mutant_shift_31(opcode: Opcode, s0: int, s1: int) -> int: - """Mutant 4: Shifts by 31 bits instead of 32.""" - if opcode == Opcode.V_MUL_HI_U32: - return ((s0 * s1) >> 31) & MASK32 - else: - return (((to_i32(s0) * to_i32(s1)) & MASK64) >> 31) & MASK32 - - -def mutant_shift_33(opcode: Opcode, s0: int, s1: int) -> int: - """Mutant 5: Shifts by 33 bits instead of 32.""" - if opcode == Opcode.V_MUL_HI_U32: - return ((s0 * s1) >> 33) & MASK32 - else: - return (((to_i32(s0) * to_i32(s1)) & MASK64) >> 33) & MASK32 - - -def mutant_addition_operator(opcode: Opcode, s0: int, s1: int) -> int: - """Mutant 6: Replaces multiplication with addition.""" - return (s0 + s1) & MASK32 - - -class TestNegativeControlsAndMutation(unittest.TestCase): - """Test suite for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_empty_lines(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("") - with self.assertRaises(ValueError): - parse_asm_line(" ; comment only") - - def test_syntax_rejection_invalid_opcode(self) -> None: - for bad_op in ("v_mul_lo_u32", "v_mul_f32", "v_add_u32", "bad_opcode"): - with self.assertRaises(ValueError): - parse_asm_line(f"{bad_op} v0, v1, v2") - - def test_syntax_rejection_operand_count(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("v_mul_hi_u32 v0, v1") - with self.assertRaises(ValueError): - parse_asm_line("v_mul_hi_u32 v0, v1, v2, v3") - - def test_syntax_rejection_dst_sgpr(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("v_mul_hi_u32 s0, v1, v2") - - def test_syntax_rejection_out_of_bounds_registers(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("v_mul_hi_u32 v256, v1, v2") - with self.assertRaises(ValueError): - parse_asm_line("v_mul_hi_u32 v0, s110, v2") - - def test_syntax_rejection_malformed_tokens(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("v_mul_hi_u32 v0, bad_token_xyz, v2") - - def test_mutation_detects_low_word_instead_of_high(self) -> None: - s0 = 0x80000000 - s1 = 4 - # (0x80000000 * 4) = 0x200000000 -> hi = 2, lo = 0 - correct = ref_mul_hi_u32(s0, s1) - sabotaged = mutant_low_word_instead_of_high(Opcode.V_MUL_HI_U32, s0, s1) - self.assertEqual(correct, 2) - self.assertEqual(sabotaged, 0) - self.assertNotEqual(sabotaged, correct) - - def test_mutation_detects_signedness_confusion(self) -> None: - # -1 * -1 = +1: signed hi = 0, unsigned hi = 0xFFFFFFFE - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - correct_i = ref_mul_hi_i32(s0, s1) - sabotaged_i = mutant_unsigned_for_signed(Opcode.V_MUL_HI_I32, s0, s1) - self.assertEqual(correct_i, 0) - self.assertEqual(sabotaged_i, 0xFFFFFFFE) - self.assertNotEqual(sabotaged_i, correct_i) - - correct_u = ref_mul_hi_u32(s0, s1) - sabotaged_u = mutant_signed_for_unsigned(Opcode.V_MUL_HI_U32, s0, s1) - self.assertEqual(correct_u, 0xFFFFFFFE) - self.assertEqual(sabotaged_u, 0) - self.assertNotEqual(sabotaged_u, correct_u) - - def test_mutation_detects_shift_displacement_error(self) -> None: - s0 = 0x80000000 - s1 = 2 - # Product = 0x100000000 (1 << 32) - correct = ref_mul_hi_u32(s0, s1) - self.assertEqual(correct, 1) - - # Shift 31 gives 2 - sabotaged_31 = mutant_shift_31(Opcode.V_MUL_HI_U32, s0, s1) - self.assertEqual(sabotaged_31, 2) - self.assertNotEqual(sabotaged_31, correct) - - # Shift 33 gives 0 - sabotaged_33 = mutant_shift_33(Opcode.V_MUL_HI_U32, s0, s1) - self.assertEqual(sabotaged_33, 0) - self.assertNotEqual(sabotaged_33, correct) - - def test_mutation_detects_addition_instead_of_multiplication(self) -> None: - s0 = 0x10000 - s1 = 0x10000 - correct = ref_mul_hi_u32(s0, s1) - sabotaged = mutant_addition_operator(Opcode.V_MUL_HI_U32, s0, s1) - self.assertEqual(correct, 1) - self.assertEqual(sabotaged, 0x20000) - self.assertNotEqual(sabotaged, correct) - - def test_mutation_detects_exec_mask_leakage(self) -> None: - sim = SIMDWavefront(wave_size=32) - sim.store_vgpr_wave(0, [OLD_VGPR_SENTINEL] * 32) - sim.store_vgpr_wave(1, [0x80000000] * 32) - sim.store_vgpr_wave(2, [2] * 32) - - # Only lane 0 active - sim.exec_mask = 0x00000001 - res = sim.step_v_mul_hi(Opcode.V_MUL_HI_U32, 0, 1, 2) - - self.assertEqual(res[0], 1) - for lane in range(1, 32): - self.assertEqual(res[lane], OLD_VGPR_SENTINEL, f"Inactive lane {lane} was mutated!") +INT32_MIN = 0x80000000 + + +def ref_u32(a, b): + return ((a & MASK32) * (b & MASK32) >> 32) & MASK32 + + +def ref_i32(a, b): + sa = a - (1 << 32) if a & 0x80000000 else a + sb = b - (1 << 32) if b & 0x80000000 else b + return (sa * sb >> 32) & MASK32 + + +def run(op, a, b, form="vgpr"): + """Translate and run `op v0, , ` on a one-lane pixel shader; return v0 as exported to mrt0.""" + if form == "vgpr": + setup = [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}"] + srcs = "v1, v2" + elif form == "sgpr": + setup = [f"s_mov_b32 s1, {a:#x}", f"s_mov_b32 s2, {b:#x}"] + srcs = "s1, s2" + else: # inline constant or literal as the second source, v1 as the first + setup = [f"v_mov_b32 v1, {a:#x}"] + srcs = f"v1, {b:#x}" + lines = setup + [f"{op} v0, {srcs}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_mul_hi", lines))[0] + + +# (a, b, v_mul_hi_u32 word, v_mul_hi_i32 word), written by hand. +CASES = [ + (0x80000000, 2, 0x00000001, 0xFFFFFFFF), # 2^31 * 2 = 2^32; (-2^31) * 2 = -2^32 + (0x10000, 0x10000, 0x00000001, 0x00000001), # 2^32 + (100, 200, 0x00000000, 0x00000000), + (0xFFFF, 0xFFFF, 0x00000000, 0x00000000), + (0, 0xFFFFFFFF, 0x00000000, 0x00000000), + (0xFFFFFFFF, 1, 0x00000000, 0xFFFFFFFF), # u: 2^32-1 fits; i: -1 * 1 = -1 + (0xFFFFFFFF, 2, 0x00000001, 0xFFFFFFFF), # u: 0x1_FFFFFFFE; i: -1 * 2 = -2 + (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0x00000000), # u: 0xFFFFFFFE_00000001; i: (-1)*(-1) = 1 + (3, 4, 0x00000000, 0x00000000), + (10, 0xFFFFFFFB, 0x00000009, 0xFFFFFFFF), # i: 10 * -5 = -50 + (INT32_MIN, 0xFFFFFFFF, 0x7FFFFFFF, 0x00000000), # i: -2^31 * -1 = 2^31 + (INT32_MIN, INT32_MIN, 0x40000000, 0x40000000), # u: 2^62; i: (-2^31)^2 = 2^62 + (INT32_MAX, INT32_MAX, 0x3FFFFFFF, 0x3FFFFFFF), # (2^31-1)^2 = 0x3FFFFFFF_00000001 + (INT32_MIN, INT32_MAX, 0x3FFFFFFF, 0xC0000000), # i: -2^62 + 2^31 = 0xC0000000_80000000 + (0x12345678, 0x9ABCDEF0, 0x0B00EA4E, 0xF8CC93D6), # 0x12345678 * 0x9ABCDEF0 and its signed reading +] + + +class MulHi(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for a, b, u, i in CASES: + self.assertEqual(ref_u32(a, b), u, (hex(a), hex(b))) + self.assertEqual(ref_i32(a, b), i, (hex(a), hex(b))) + + def test_translated_cases(self): + for a, b, u, i in CASES: + with self.subTest(a=hex(a), b=hex(b)): + self.assertEqual(run("v_mul_hi_u32", a, b), u) + self.assertEqual(run("v_mul_hi_i32", a, b), i) + + def test_sgpr_and_literal_sources(self): + for a, b, u, i in CASES[:8]: + for form in ("sgpr", "literal"): + with self.subTest(a=hex(a), b=hex(b), form=form): + self.assertEqual(run("v_mul_hi_u32", a, b, form), u) + self.assertEqual(run("v_mul_hi_i32", a, b, form), i) + + def test_random_operands(self): + rng = random.Random(0x6D756C68) + for _ in range(60): + a, b = rng.getrandbits(32), rng.getrandbits(32) + with self.subTest(a=hex(a), b=hex(b)): + self.assertEqual(run("v_mul_hi_u32", a, b), ref_u32(a, b)) + self.assertEqual(run("v_mul_hi_i32", a, b), ref_i32(a, b)) + + def test_signedness_is_not_confused(self): + # -1 * -1: the signed high word is 0, the unsigned one 0xFFFFFFFE. + self.assertEqual(run("v_mul_hi_i32", 0xFFFFFFFF, 0xFFFFFFFF), 0) + self.assertEqual(run("v_mul_hi_u32", 0xFFFFFFFF, 0xFFFFFFFF), 0xFFFFFFFE) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_perm_b32.py b/tests/semantic/test_valu_perm_b32.py index 34e344796..5baddefdb 100644 --- a/tests/semantic/test_valu_perm_b32.py +++ b/tests/semantic/test_valu_perm_b32.py @@ -1,1631 +1,109 @@ -from __future__ import annotations +"""v_perm_b32 (RDNA2 VOP3): result byte i is picked by selector byte i from the 8 bytes {S0, S1} (S1 is the low half). -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_perm_b32. + 0..3 byte 0..3 of S1 4..7 byte 0..3 of S0 + 8..11 0xFF or 0x00 from the sign bit of S1[15], S1[31], S0[15], S0[31] (bits 15, 31, 47, 63 of {S0, S1}) + 12 0x00 >=13 0xFF -Tests the vector byte permutation instruction: - v_perm_b32 D, S0, S1, S2 -Lowered semantics: - Destination byte i (for i in 0..3) is chosen based on selector byte i (S2[8*i+7 : 8*i]): - - 0..3: selects byte 0..3 of S1 (bits [7:0], [15:8], [23:16], [31:24]) - - 4..7: selects byte 0..3 of S0 (bits [7:0], [15:8], [23:16], [31:24]) - - 8: sign-extension of S1 bit 31 (0xFF if negative, else 0x00) - - 9: sign-extension of S0 bit 15 (0xFF if negative, else 0x00) - - 10: sign-extension of S0 bit 31 (0xFF if negative, else 0x00) - - 11: sign-extension replicate (0xFF if S1 bit 7 else 0x00) - - 12: constant 0x00 - - >= 13: constant 0xFF - -Architectural model: - 32-bit vector and scalar registers (VGPRs/SGPRs) with per-byte lane slicing, - selector decoding, and bit-exact execution. Standard library only; zero game data. +Each case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +words are written by hand. (An earlier copy of this file checked a private model that picked other sign bits for +selectors 8..11 than the ISA and the translator do.) Standard library only: no GPU, no LLVM, no game data. """ - -from dataclasses import dataclass, field -from enum import Enum, auto -import struct +import os +import random import sys import unittest -from typing import List, Optional, Tuple, Union -# ============================================================================== -# Architectural Constants -# ============================================================================== +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) -MASK32: int = 0xFFFF_FFFF -BYTE_MASK: int = 0xFF -BYTE_WIDTH: int = 8 +import support # noqa: E402 -# Selector codes -SEL_SRC1_BYTE0: int = 0 -SEL_SRC1_BYTE1: int = 1 -SEL_SRC1_BYTE2: int = 2 -SEL_SRC1_BYTE3: int = 3 +MASK32 = 0xFFFFFFFF -SEL_SRC0_BYTE0: int = 4 -SEL_SRC0_BYTE1: int = 5 -SEL_SRC0_BYTE2: int = 6 -SEL_SRC0_BYTE3: int = 7 -SEL_SIGN_EXT_SRC1_B3: int = 8 # S1[31] replicated -SEL_SIGN_EXT_SRC0_B1: int = 9 # S0[15] replicated -SEL_SIGN_EXT_SRC0_B3: int = 10 # S0[31] replicated -SEL_SIGN_EXT_SRC1_B0: int = 11 # S1[7] replicated -SEL_ZERO: int = 12 # Constant 0x00 -SEL_ONES_MIN: int = 13 # Constant 0xFF (>= 13) +def sel(b0, b1, b2, b3): + return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) -# ============================================================================== -# Bit Manipulation and Byte Extraction Utilities -# ============================================================================== - -def extract_byte(val: int, idx: int) -> int: - """Extract byte idx (0..3) from an unsigned 32-bit integer.""" - if not 0 <= idx <= 3: - raise ValueError(f"Byte index out of range [0, 3]: {idx}") - return (val >> (idx * BYTE_WIDTH)) & BYTE_MASK - - -def pack_bytes(b0: int, b1: int, b2: int, b3: int) -> int: - """Pack 4 unsigned bytes (b0..b3) into an unsigned 32-bit integer.""" - return ((b0 & BYTE_MASK) | - ((b1 & BYTE_MASK) << 8) | - ((b2 & BYTE_MASK) << 16) | - ((b3 & BYTE_MASK) << 24)) & MASK32 - - -def make_selector(b0: int, b1: int, b2: int, b3: int) -> int: - """Construct a 32-bit selector word from 4 individual byte selector values.""" - return pack_bytes(b0, b1, b2, b3) - - -def permute_single_byte(src0: int, src1: int, sel_code: int) -> int: - """Evaluate a single byte according to RDNA2 v_perm_b32 hardware semantics.""" - sel = sel_code & BYTE_MASK - if 0 <= sel <= 3: - return extract_byte(src1, sel) - elif 4 <= sel <= 7: - return extract_byte(src0, sel - 4) - elif sel == SEL_SIGN_EXT_SRC1_B3: - return 0xFF if bool(src1 & 0x8000_0000) else 0x00 - elif sel == SEL_SIGN_EXT_SRC0_B1: - return 0xFF if bool(src0 & 0x0000_8000) else 0x00 - elif sel == SEL_SIGN_EXT_SRC0_B3: - return 0xFF if bool(src0 & 0x8000_0000) else 0x00 - elif sel == SEL_SIGN_EXT_SRC1_B0: - return 0xFF if bool(src1 & 0x0000_0080) else 0x00 - elif sel == SEL_ZERO: - return 0x00 - else: # sel >= SEL_ONES_MIN (13..255) - return 0xFF - - -def oracle_v_perm_b32(src0: int, src1: int, selector: int) -> int: - """Reference mathematical oracle for RDNA2 v_perm_b32. - - src0: upper 4 bytes pool (indices 4..7) - src1: lower 4 bytes pool (indices 0..3) - selector: 32-bit control word with 4 selector bytes - """ - s0 = src0 & MASK32 - s1 = src1 & MASK32 - sel = selector & MASK32 - - out_b0 = permute_single_byte(s0, s1, extract_byte(sel, 0)) - out_b1 = permute_single_byte(s0, s1, extract_byte(sel, 1)) - out_b2 = permute_single_byte(s0, s1, extract_byte(sel, 2)) - out_b3 = permute_single_byte(s0, s1, extract_byte(sel, 3)) - - return pack_bytes(out_b0, out_b1, out_b2, out_b3) - - -# ============================================================================== -# Architectural Register Models -# ============================================================================== - -class VGPRWord: - """Architectural model of a 32-bit vector register (VGPR).""" - - def __init__(self, value: int = 0) -> None: - self.raw: int = value & MASK32 - - @property - def u32(self) -> int: - return self.raw - - @u32.setter - def u32(self, val: int) -> None: - self.raw = val & MASK32 - - @property - def i32(self) -> int: - return struct.unpack(" bool: - return bool(self.raw & 0x8000_0000) - - def get_byte(self, idx: int) -> int: - return extract_byte(self.raw, idx) - - def set_byte(self, idx: int, b: int) -> None: - if not 0 <= idx <= 3: - raise ValueError(f"Byte index out of range: {idx}") - shift = idx * 8 - mask = ~(0xFF << shift) & MASK32 - self.raw = (self.raw & mask) | ((b & 0xFF) << shift) - - def __repr__(self) -> str: - return f"VGPRWord(0x{self.raw:08X})" - - def __eq__(self, other: object) -> bool: - if isinstance(other, VGPRWord): - return self.raw == other.raw - if isinstance(other, int): - return self.raw == (other & MASK32) - return NotImplemented - - -class PermSelectorWord: - """Architectural model of a 32-bit v_perm_b32 selector word.""" - - def __init__(self, raw: int = 0) -> None: - self.raw: int = raw & MASK32 - - @classmethod - def from_bytes(cls, b0: int, b1: int, b2: int, b3: int) -> PermSelectorWord: - return cls(pack_bytes(b0, b1, b2, b3)) - - @property - def sel0(self) -> int: - return extract_byte(self.raw, 0) - - @property - def sel1(self) -> int: - return extract_byte(self.raw, 1) - - @property - def sel2(self) -> int: - return extract_byte(self.raw, 2) - - @property - def sel3(self) -> int: - return extract_byte(self.raw, 3) - - @classmethod - def identity_src1(cls) -> PermSelectorWord: - """Picks bytes 0, 1, 2, 3 directly from src1.""" - return cls.from_bytes(0, 1, 2, 3) - - @classmethod - def identity_src0(cls) -> PermSelectorWord: - """Picks bytes 0, 1, 2, 3 directly from src0 (selectors 4, 5, 6, 7).""" - return cls.from_bytes(4, 5, 6, 7) - - @classmethod - def bswap_src1(cls) -> PermSelectorWord: - """Reverses byte order of src1.""" - return cls.from_bytes(3, 2, 1, 0) - - @classmethod - def bswap_src0(cls) -> PermSelectorWord: - """Reverses byte order of src0.""" - return cls.from_bytes(7, 6, 5, 4) - - @classmethod - def broadcast_byte(cls, src_byte_idx: int) -> PermSelectorWord: - """Replicates a single source byte into all 4 destination byte positions.""" - return cls.from_bytes(src_byte_idx, src_byte_idx, src_byte_idx, src_byte_idx) - - -# ============================================================================== -# Unit Tests: Reference Oracle and Architectural Model -# ============================================================================== - -class TestPermB32ReferenceOracle(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural models.""" - - def test_identity_src1_selection(self): - src0 = 0xAABBCCDD - src1 = 0x11223344 - sel = PermSelectorWord.identity_src1().raw - self.assertEqual(oracle_v_perm_b32(src0, src1, sel), 0x11223344) - - def test_identity_src0_selection(self): - src0 = 0xAABBCCDD - src1 = 0x11223344 - sel = PermSelectorWord.identity_src0().raw - self.assertEqual(oracle_v_perm_b32(src0, src1, sel), 0xAABBCCDD) - - def test_cross_source_interleaving(self): - # Pick byte 0 of src1, byte 0 of src0, byte 1 of src1, byte 1 of src0 - # src1: [44, 33, 22, 11] -> byte 0=0x44, byte 1=0x33 - # src0: [DD, CC, BB, AA] -> byte 0=0xDD, byte 1=0xCC - # Expected result bytes: [44, DD, 33, CC] -> 0xCC33DD44 - src0 = 0xAABBCCDD - src1 = 0x11223344 - sel = make_selector(0, 4, 1, 5) - self.assertEqual(oracle_v_perm_b32(src0, src1, sel), 0xCC33DD44) - - def test_endianness_bswap(self): - src1 = 0x12345678 - src0 = 0x9ABCDEF0 - # Reverse src1: [78, 56, 34, 12] -> [12, 34, 56, 78] - sel_rev1 = PermSelectorWord.bswap_src1().raw - self.assertEqual(oracle_v_perm_b32(src0, src1, sel_rev1), 0x78563412) - - # Reverse src0 - sel_rev0 = PermSelectorWord.bswap_src0().raw - self.assertEqual(oracle_v_perm_b32(src0, src1, sel_rev0), 0xF0DEBC9A) - - def test_byte_broadcast(self): - src1 = 0x01020304 # byte 0 = 0x04 - sel = PermSelectorWord.broadcast_byte(0).raw - self.assertEqual(oracle_v_perm_b32(0, src1, sel), 0x04040404) - - src0 = 0x88776655 # byte 7 (idx 3 of src0) = 0x88 - sel7 = PermSelectorWord.broadcast_byte(7).raw - self.assertEqual(oracle_v_perm_b32(src0, 0, sel7), 0x88888888) - - def test_constant_zero_fill(self): - src0 = 0xFFFFFFFF - src1 = 0xFFFFFFFF - sel = make_selector(SEL_ZERO, SEL_ZERO, SEL_ZERO, SEL_ZERO) - self.assertEqual(oracle_v_perm_b32(src0, src1, sel), 0x00000000) - - # Mix zero fill with selected bytes - sel_mix = make_selector(0, SEL_ZERO, 4, SEL_ZERO) - res = oracle_v_perm_b32(0xAABBCCDD, 0x11223344, sel_mix) - # byte 0: src1[0] = 0x44, byte 1: 0, byte 2: src0[0] = 0xDD, byte 3: 0 - self.assertEqual(res, 0x00DD0044) - - def test_constant_ones_fill(self): - src0 = 0x00000000 - src1 = 0x00000000 - # Code 13 - sel13 = make_selector(13, 14, 15, 255) - self.assertEqual(oracle_v_perm_b32(src0, src1, sel13), 0xFFFFFFFF) - - # Mix ones fill with selected bytes - sel_mix = make_selector(0, 13, 4, 255) - res = oracle_v_perm_b32(0x12345678, 0x9ABCDEF0, sel_mix) - # byte 0: src1[0]=0xF0, byte 1: 0xFF, byte 2: src0[0]=0x78, byte 3: 0xFF - self.assertEqual(res, 0xFF78FFF0) - - def test_sign_extension_modes(self): - # SEL_SIGN_EXT_SRC1_B3 (8): sign of S1 bit 31 - s1_pos = 0x7FFF_FFFF # bit 31 is 0 - s1_neg = 0x8000_0000 # bit 31 is 1 - sel8 = make_selector(8, 8, 8, 8) - self.assertEqual(oracle_v_perm_b32(0, s1_pos, sel8), 0x00000000) - self.assertEqual(oracle_v_perm_b32(0, s1_neg, sel8), 0xFFFFFFFF) - - # SEL_SIGN_EXT_SRC0_B1 (9): sign of S0 bit 15 - s0_pos15 = 0x0000_7FFF # bit 15 is 0 - s0_neg15 = 0x0000_8000 # bit 15 is 1 - sel9 = make_selector(9, 9, 9, 9) - self.assertEqual(oracle_v_perm_b32(s0_pos15, 0, sel9), 0x00000000) - self.assertEqual(oracle_v_perm_b32(s0_neg15, 0, sel9), 0xFFFFFFFF) - - # SEL_SIGN_EXT_SRC0_B3 (10): sign of S0 bit 31 - s0_pos31 = 0x7FFF_FFFF - s0_neg31 = 0x8000_0000 - sel10 = make_selector(10, 10, 10, 10) - self.assertEqual(oracle_v_perm_b32(s0_pos31, 0, sel10), 0x00000000) - self.assertEqual(oracle_v_perm_b32(s0_neg31, 0, sel10), 0xFFFFFFFF) - - def test_vgpr_word_model(self): - vw = VGPRWord(0x12345678) - self.assertEqual(vw.u32, 0x12345678) - self.assertEqual(vw.get_byte(0), 0x78) - self.assertEqual(vw.get_byte(1), 0x56) - self.assertEqual(vw.get_byte(2), 0x34) - self.assertEqual(vw.get_byte(3), 0x12) - - vw.set_byte(0, 0xAA) - self.assertEqual(vw.u32, 0x123456AA) - vw.set_byte(3, 0xFF) - self.assertEqual(vw.u32, 0xFF3456AA) - self.assertTrue(vw.is_negative) - - def test_selector_word_model(self): - sw = PermSelectorWord.from_bytes(1, 2, 3, 4) - self.assertEqual(sw.sel0, 1) - self.assertEqual(sw.sel1, 2) - self.assertEqual(sw.sel2, 3) - self.assertEqual(sw.sel3, 4) - self.assertEqual(sw.raw, 0x04030201) - - -# ============================================================================== -# Symbolic AST and Typed Expressions -# ============================================================================== - -class Opcode(Enum): - V_PERM_B32 = "v_perm_b32" - - -class OperandKind(Enum): - VGPR = auto() - SGPR = auto() - INLINE_CONST = auto() - LITERAL_CONST = auto() - - -class TypeKind(Enum): - RAW32 = "b32" - UINT32 = "u32" - INT32 = "i32" - BYTE_LANE = "u8" - - -@dataclass -class ASTOperand: - """Represents an operand in an RDNA2 instruction AST.""" - name: str - kind: OperandKind - type_kind: TypeKind = TypeKind.RAW32 - reg_index: Optional[int] = None - constant_value: Optional[int] = None - - @classmethod - def vgpr(cls, idx: int, type_kind: TypeKind = TypeKind.RAW32) -> ASTOperand: - return cls(name=f"v{idx}", kind=OperandKind.VGPR, type_kind=type_kind, reg_index=idx) - - @classmethod - def sgpr(cls, idx: int, type_kind: TypeKind = TypeKind.RAW32) -> ASTOperand: - return cls(name=f"s{idx}", kind=OperandKind.SGPR, type_kind=type_kind, reg_index=idx) - - @classmethod - def inline_const(cls, val: int, type_kind: TypeKind = TypeKind.RAW32) -> ASTOperand: - return cls(name=str(val), kind=OperandKind.INLINE_CONST, type_kind=type_kind, constant_value=val) - - @classmethod - def literal(cls, val: int, type_kind: TypeKind = TypeKind.RAW32) -> ASTOperand: - return cls(name=f"0x{val & MASK32:08X}", kind=OperandKind.LITERAL_CONST, type_kind=type_kind, constant_value=val & MASK32) - - def to_asm(self) -> str: - return self.name - - @property - def is_vgpr(self) -> bool: - return self.kind == OperandKind.VGPR - - @property - def is_sgpr(self) -> bool: - return self.kind == OperandKind.SGPR - - @property - def is_constant(self) -> bool: - return self.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST) - - -@dataclass -class ASTInstruction: - """Represents a VOP3 instruction in the symbolic AST.""" - opcode: Opcode - dst: ASTOperand - src0: ASTOperand - src1: ASTOperand - src2: ASTOperand - - def to_asm(self) -> str: - return f"{self.opcode.value} {self.dst.to_asm()}, {self.src0.to_asm()}, {self.src1.to_asm()}, {self.src2.to_asm()}" - - def validate(self) -> None: - if not self.dst.is_vgpr: - raise ValueError(f"Destination must be a VGPR, got {self.dst}") - # At most one literal constant per VOP3 instruction in RDNA2 - literal_count = sum(1 for src in (self.src0, self.src1, self.src2) if src.kind == OperandKind.LITERAL_CONST) - if literal_count > 1: - raise ValueError(f"RDNA2 VOP3 allows at most one literal constant, got {literal_count}") - - -class TypedExpr: - """Base class for symbolic typed expressions.""" - def __init__(self, type_kind: TypeKind = TypeKind.RAW32) -> None: - self.type_kind = type_kind - - def eval(self, ctx: dict[str, int]) -> int: - raise NotImplementedError - - -class VariableExpr(TypedExpr): - """Represents a variable or register reference in an expression tree.""" - def __init__(self, name: str, type_kind: TypeKind = TypeKind.RAW32) -> None: - super().__init__(type_kind) - self.name = name - - def eval(self, ctx: dict[str, int]) -> int: - if self.name not in ctx: - raise KeyError(f"Variable '{self.name}' not found in evaluation context") - return ctx[self.name] & MASK32 - - def __repr__(self) -> str: - return f"Var({self.name}:{self.type_kind.value})" - - -class ConstantExpr(TypedExpr): - """Represents a constant value in an expression tree.""" - def __init__(self, value: int, type_kind: TypeKind = TypeKind.RAW32) -> None: - super().__init__(type_kind) - self.value = value & MASK32 - - def eval(self, ctx: dict[str, int]) -> int: - return self.value - - def __repr__(self) -> str: - return f"Const(0x{self.value:08X}:{self.type_kind.value})" - - -class ExtractByteExpr(TypedExpr): - """Extracts a specific byte (0..3) from a 32-bit expression.""" - def __init__(self, source: TypedExpr, byte_idx: int) -> None: - super().__init__(TypeKind.BYTE_LANE) - self.source = source - self.byte_idx = byte_idx - - def eval(self, ctx: dict[str, int]) -> int: - val = self.source.eval(ctx) - return extract_byte(val, self.byte_idx) - - def __repr__(self) -> str: - return f"ExtractByte({self.source}, {self.byte_idx})" - - -class PermuteByteExpr(TypedExpr): - """Permutes a single byte from src0 and src1 using a selector byte expression.""" - def __init__(self, src0: TypedExpr, src1: TypedExpr, sel_byte: TypedExpr) -> None: - super().__init__(TypeKind.BYTE_LANE) - self.src0 = src0 - self.src1 = src1 - self.sel_byte = sel_byte - - def eval(self, ctx: dict[str, int]) -> int: - s0 = self.src0.eval(ctx) - s1 = self.src1.eval(ctx) - sel = self.sel_byte.eval(ctx) & BYTE_MASK - return permute_single_byte(s0, s1, sel) - - def __repr__(self) -> str: - return f"PermuteByte(src0={self.src0}, src1={self.src1}, sel={self.sel_byte})" - - -class PermB32Expr(TypedExpr): - """Symbolic expression tree representing a full v_perm_b32 operation.""" - def __init__(self, src0: TypedExpr, src1: TypedExpr, sel: TypedExpr, type_kind: TypeKind = TypeKind.RAW32) -> None: - super().__init__(type_kind) - self.src0 = src0 - self.src1 = src1 - self.sel = sel - self.byte_exprs = [ - PermuteByteExpr(src0, src1, ExtractByteExpr(sel, i)) - for i in range(4) - ] - - def eval(self, ctx: dict[str, int]) -> int: - b0 = self.byte_exprs[0].eval(ctx) - b1 = self.byte_exprs[1].eval(ctx) - b2 = self.byte_exprs[2].eval(ctx) - b3 = self.byte_exprs[3].eval(ctx) - return pack_bytes(b0, b1, b2, b3) - - def __repr__(self) -> str: - return f"v_perm_b32({self.src0}, {self.src1}, {self.sel})" - - -# ============================================================================== -# Unit Tests: Symbolic AST and Typed Expressions -# ============================================================================== - -class TestPermB32SymbolicAST(unittest.TestCase): - """Test suite for symbolic AST opcode definitions and typed expressions.""" - - def test_ast_instruction_assembly_formatting(self): - instr1 = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - self.assertEqual(instr1.to_asm(), "v_perm_b32 v0, v1, v2, v3") - - instr2 = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(5), - src0=ASTOperand.sgpr(0), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.literal(0x03020100), - ) - self.assertEqual(instr2.to_asm(), "v_perm_b32 v5, s0, v1, 0x03020100") - - def test_ast_instruction_validation(self): - # Valid instruction with 1 literal - instr_valid = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.literal(0x12345678), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.sgpr(2), - ) - instr_valid.validate() # should not raise - - # Invalid destination (SGPR not allowed as VALU destination) - instr_invalid_dst = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.sgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - instr_invalid_dst.validate() - - # Invalid: more than 1 literal constant - instr_multi_literal = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.literal(0x11111111), - src1=ASTOperand.literal(0x22222222), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - instr_multi_literal.validate() - - def test_typed_expression_evaluation(self): - v0 = VariableExpr("v0") - v1 = VariableExpr("v1") - sel_const = ConstantExpr(0x07060504) # Identity for src0 - perm_expr = PermB32Expr(v0, v1, sel_const) - - ctx = {"v0": 0xDEADBEEF, "v1": 0xCAFEBABE} - result = perm_expr.eval(ctx) - self.assertEqual(result, 0xDEADBEEF) - - def test_symbolic_byte_slicing_and_reassembly(self): - v0 = VariableExpr("v0") - b1_expr = ExtractByteExpr(v0, 1) - ctx = {"v0": 0x12345678} - self.assertEqual(b1_expr.eval(ctx), 0x56) - - v1 = VariableExpr("v1") - # Selector picks byte 0 from v1 (which is index 0) - sel_expr = ConstantExpr(0) - p_byte = PermuteByteExpr(v0, v1, sel_expr) - ctx2 = {"v0": 0x12345678, "v1": 0x9ABCDEF0} - self.assertEqual(p_byte.eval(ctx2), 0xF0) - - def test_expression_type_checking(self): - c = ConstantExpr(0x12345678, TypeKind.UINT32) - self.assertEqual(c.type_kind, TypeKind.UINT32) - v = VariableExpr("x", TypeKind.INT32) - self.assertEqual(v.type_kind, TypeKind.INT32) - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -class ScalarRegisterFile: - """Architectural register file for deterministic scalar simulation.""" - - def __init__(self) -> None: - self.vgprs: dict[int, int] = {i: 0 for i in range(256)} - self.sgprs: dict[int, int] = {i: 0 for i in range(106)} - - def get_vgpr(self, idx: int) -> int: - if not 0 <= idx < 256: - raise IndexError(f"VGPR index out of range [0, 255]: {idx}") - return self.vgprs.get(idx, 0) & MASK32 - - def set_vgpr(self, idx: int, val: int) -> None: - if not 0 <= idx < 256: - raise IndexError(f"VGPR index out of range [0, 255]: {idx}") - self.vgprs[idx] = val & MASK32 - - def get_sgpr(self, idx: int) -> int: - if not 0 <= idx < 106: - raise IndexError(f"SGPR index out of range [0, 105]: {idx}") - return self.sgprs.get(idx, 0) & MASK32 - - def set_sgpr(self, idx: int, val: int) -> None: - if not 0 <= idx < 106: - raise IndexError(f"SGPR index out of range [0, 105]: {idx}") - self.sgprs[idx] = val & MASK32 - - def read_operand(self, op: ASTOperand) -> int: - if op.kind == OperandKind.VGPR: - assert op.reg_index is not None - return self.get_vgpr(op.reg_index) - elif op.kind == OperandKind.SGPR: - assert op.reg_index is not None - return self.get_sgpr(op.reg_index) - elif op.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST): - assert op.constant_value is not None - return op.constant_value & MASK32 - else: - raise ValueError(f"Unknown operand kind: {op.kind}") - - def write_operand(self, op: ASTOperand, val: int) -> None: - if op.kind == OperandKind.VGPR: - assert op.reg_index is not None - self.set_vgpr(op.reg_index, val) - else: - raise ValueError(f"Cannot write VALU result to non-VGPR operand: {op}") - - -class PermB32ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_perm_b32.""" - - def __init__(self, rf: Optional[ScalarRegisterFile] = None) -> None: - self.rf: ScalarRegisterFile = rf if rf is not None else ScalarRegisterFile() - - def step(self, instr: ASTInstruction) -> None: - instr.validate() - if instr.opcode != Opcode.V_PERM_B32: - raise NotImplementedError(f"Unsupported opcode: {instr.opcode}") - - s0 = self.rf.read_operand(instr.src0) - s1 = self.rf.read_operand(instr.src1) - s2 = self.rf.read_operand(instr.src2) - - res = oracle_v_perm_b32(s0, s1, s2) - self.rf.write_operand(instr.dst, res) - - def run_program(self, instructions: list[ASTInstruction]) -> None: - for instr in instructions: - self.step(instr) - - -# ============================================================================== -# Unit Tests: Deterministic Scalar Interpreter -# ============================================================================== - -class TestPermB32ScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction interpreter.""" - - def test_scalar_execution_all_vgpr(self): - rf = ScalarRegisterFile() - rf.set_vgpr(1, 0x11223344) # src0 - rf.set_vgpr(2, 0x55667788) # src1 - rf.set_vgpr(3, PermSelectorWord.bswap_src1().raw) # src2 (selector) - - interp = PermB32ScalarInterpreter(rf) - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - interp.step(instr) - - # src1 bytes: [88, 77, 66, 55], reversed: [55, 66, 77, 88] -> 0x88776655 - self.assertEqual(rf.get_vgpr(0), 0x88776655) - - def test_scalar_execution_mixed_sgpr_vgpr_literal(self): - rf = ScalarRegisterFile() - rf.set_sgpr(0, 0xAABBCCDD) # src0 from SGPR - rf.set_vgpr(1, 0x11223344) # src1 from VGPR - - interp = PermB32ScalarInterpreter(rf) - # Select identity of src0 using literal constant 0x07060504 - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(2), - src0=ASTOperand.sgpr(0), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.literal(0x07060504), - ) - interp.step(instr) - self.assertEqual(rf.get_vgpr(2), 0xAABBCCDD) - - def test_scalar_execution_inline_constants(self): - rf = ScalarRegisterFile() - rf.set_vgpr(0, 0x12345678) - interp = PermB32ScalarInterpreter(rf) - - # src0=0 (inline), src1=v0, src2=literal 0x0C0C0100 (zero extend low 16 bits of src1) - # byte 0 = src1[0] = 0x78, byte 1 = src1[1] = 0x56, byte 2 = 0x00, byte 3 = 0x00 - # Result: 0x00005678 - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(1), - src0=ASTOperand.inline_const(0), - src1=ASTOperand.vgpr(0), - src2=ASTOperand.literal(make_selector(0, 1, SEL_ZERO, SEL_ZERO)), - ) - interp.step(instr) - self.assertEqual(rf.get_vgpr(1), 0x00005678) - - def test_sequential_pipeline_execution(self): - rf = ScalarRegisterFile() - rf.set_vgpr(0, 0x12345678) - rf.set_vgpr(1, 0x9ABCDEF0) - - interp = PermB32ScalarInterpreter(rf) - # Program: - # 1. v2 = perm(v0, v1, 0x04040404) -> broadcasts byte 4 (src0[0] = 0x78) - # 2. v3 = perm(v2, v1, 0x03020104) -> replace byte 0 with broadcasted 0x78 - prog = [ - ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(2), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.literal(0x04040404), - ), - ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(3), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.literal(make_selector(4, 1, 2, 3)), - ), - ] - interp.run_program(prog) - - self.assertEqual(rf.get_vgpr(2), 0x78787878) - # v3 byte 0 is v2[0] = 0x78; bytes 1..3 are v1[1..3] = 0x9ABCDE - self.assertEqual(rf.get_vgpr(3), 0x9ABCDE78) - - def test_state_preservation_unmodified_registers(self): - rf = ScalarRegisterFile() - rf.set_vgpr(10, 0xCAFEBABE) - rf.set_sgpr(5, 0xFEEDFACE) - - interp = PermB32ScalarInterpreter(rf) - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.inline_const(0), - src1=ASTOperand.inline_const(0), - src2=ASTOperand.inline_const(0), - ) - interp.step(instr) - - self.assertEqual(rf.get_vgpr(10), 0xCAFEBABE) - self.assertEqual(rf.get_sgpr(5), 0xFEEDFACE) - - -# ============================================================================== -# SIMD Multi-Lane Divergence and 32/64-bit EXEC Masking -# ============================================================================== - -class SIMDWaveState: - """Architectural model of a SIMD Wavefront (Wave32 or Wave64).""" - - def __init__(self, num_lanes: int = 32, exec_mask: Optional[int] = None) -> None: - if num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {num_lanes}") - self.num_lanes = num_lanes - default_mask = (1 << num_lanes) - 1 - self.exec_mask: int = (exec_mask if exec_mask is not None else default_mask) & default_mask - self.vgprs: dict[int, list[int]] = {i: [0] * num_lanes for i in range(256)} - self.sgprs: dict[int, int] = {i: 0 for i in range(106)} - - def get_lane_vgpr(self, reg_idx: int, lane: int) -> int: - if not 0 <= lane < self.num_lanes: - raise IndexError(f"Lane {lane} out of range [0, {self.num_lanes})") - return self.vgprs[reg_idx][lane] & MASK32 - - def set_lane_vgpr(self, reg_idx: int, lane: int, val: int) -> None: - if not 0 <= lane < self.num_lanes: - raise IndexError(f"Lane {lane} out of range [0, {self.num_lanes})") - self.vgprs[reg_idx][lane] = val & MASK32 - - def set_wave_vgpr(self, reg_idx: int, vals: list[int]) -> None: - if len(vals) != self.num_lanes: - raise ValueError(f"Expected {self.num_lanes} values, got {len(vals)}") - self.vgprs[reg_idx] = [v & MASK32 for v in vals] - - def set_sgpr(self, idx: int, val: int) -> None: - self.sgprs[idx] = val & MASK32 - - def get_sgpr(self, idx: int) -> int: - return self.sgprs.get(idx, 0) & MASK32 - - def read_lane_operand(self, op: ASTOperand, lane: int) -> int: - if op.kind == OperandKind.VGPR: - assert op.reg_index is not None - return self.get_lane_vgpr(op.reg_index, lane) - elif op.kind == OperandKind.SGPR: - assert op.reg_index is not None - return self.get_sgpr(op.reg_index) - elif op.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST): - assert op.constant_value is not None - return op.constant_value & MASK32 - else: - raise ValueError(f"Unknown operand kind: {op.kind}") - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def execute_instruction(self, instr: ASTInstruction) -> None: - instr.validate() - if instr.opcode != Opcode.V_PERM_B32: - raise NotImplementedError(f"Unsupported opcode: {instr.opcode}") - - dst_idx = instr.dst.reg_index - assert dst_idx is not None - - for lane in range(self.num_lanes): - if self.is_lane_active(lane): - s0 = self.read_lane_operand(instr.src0, lane) - s1 = self.read_lane_operand(instr.src1, lane) - s2 = self.read_lane_operand(instr.src2, lane) - res = oracle_v_perm_b32(s0, s1, s2) - self.set_lane_vgpr(dst_idx, lane, res) - # Inactive lanes strictly preserve prior contents - - -# ============================================================================== -# Unit Tests: SIMD Multi-Lane Divergence and EXEC Masking -# ============================================================================== - -class TestPermB32SIMDMultiLane(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_uniform_selector_divergent_data(self): - wave = SIMDWaveState(num_lanes=32) - # Each lane has distinct src0 and src1 data - src0_vals = [0x10000000 + i for i in range(32)] - src1_vals = [0x20000000 + i for i in range(32)] - wave.set_wave_vgpr(1, src0_vals) - wave.set_wave_vgpr(2, src1_vals) - - # Uniform selector: bswap src1 - sel = PermSelectorWord.bswap_src1().raw - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.literal(sel), - ) - wave.execute_instruction(instr) - - for lane in range(32): - expected = oracle_v_perm_b32(src0_vals[lane], src1_vals[lane], sel) - self.assertEqual(wave.get_lane_vgpr(0, lane), expected) - - def test_wave32_divergent_selectors(self): - wave = SIMDWaveState(num_lanes=32) - src0_data = [0xAABBCCDD] * 32 - src1_data = [0x11223344] * 32 - # Divergent selectors: lane k broadcasts byte (k % 8) - sel_vals = [PermSelectorWord.broadcast_byte(k % 8).raw for k in range(32)] - wave.set_wave_vgpr(1, src0_data) - wave.set_wave_vgpr(2, src1_data) - wave.set_wave_vgpr(3, sel_vals) - - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - wave.execute_instruction(instr) - - for lane in range(32): - expected = oracle_v_perm_b32(src0_data[lane], src1_data[lane], sel_vals[lane]) - self.assertEqual(wave.get_lane_vgpr(0, lane), expected) - - def test_wave64_execution_all_lanes(self): - wave = SIMDWaveState(num_lanes=64) - src0_vals = [0x55000000 + i for i in range(64)] - src1_vals = [0xAA000000 + i for i in range(64)] - wave.set_wave_vgpr(0, [0xCAFE0000] * 64) # initial dst - wave.set_wave_vgpr(1, src0_vals) - wave.set_wave_vgpr(2, src1_vals) - - sel = PermSelectorWord.identity_src0().raw - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.literal(sel), - ) - wave.execute_instruction(instr) - - for lane in range(64): - self.assertEqual(wave.get_lane_vgpr(0, lane), src0_vals[lane]) - - def test_exec_masking_partial_lanes(self): - # Alternating even lanes enabled in Wave32: 0x55555555 - exec_mask = 0x55555555 - wave = SIMDWaveState(num_lanes=32, exec_mask=exec_mask) - prior_dst = [0xEEEE0000 + i for i in range(32)] - wave.set_wave_vgpr(0, prior_dst) - wave.set_wave_vgpr(1, [0x11111111] * 32) - wave.set_wave_vgpr(2, [0x22222222] * 32) - - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.literal(PermSelectorWord.identity_src1().raw), - ) - wave.execute_instruction(instr) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(wave.get_lane_vgpr(0, lane), 0x22222222) - else: - self.assertEqual(wave.get_lane_vgpr(0, lane), prior_dst[lane]) - - def test_exec_masking_contiguous_blocks(self): - # Lower 16 lanes active, upper 16 lanes inactive: 0x0000FFFF - exec_mask = 0x0000FFFF - wave = SIMDWaveState(num_lanes=32, exec_mask=exec_mask) - prior_dst = [0xDEADBEEF] * 32 - wave.set_wave_vgpr(0, prior_dst) - wave.set_wave_vgpr(1, [0x44332211] * 32) - wave.set_wave_vgpr(2, [0x88776655] * 32) - - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.literal(PermSelectorWord.identity_src0().raw), - ) - wave.execute_instruction(instr) - - for lane in range(16): - self.assertEqual(wave.get_lane_vgpr(0, lane), 0x44332211) - for lane in range(16, 32): - self.assertEqual(wave.get_lane_vgpr(0, lane), 0xDEADBEEF) - - def test_all_lanes_disabled_preserves_dst(self): - wave = SIMDWaveState(num_lanes=32, exec_mask=0) - prior_dst = [0xFEEDC0DE + i for i in range(32)] - wave.set_wave_vgpr(0, prior_dst) - wave.set_wave_vgpr(1, [0x00000000] * 32) - - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.literal(0), - ) - wave.execute_instruction(instr) - - for lane in range(32): - self.assertEqual(wave.get_lane_vgpr(0, lane), prior_dst[lane]) - - -# ============================================================================== -# Register Aliasing and In-Place Operand Preservation -# ============================================================================== - -class TestPermB32RegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def test_dst_aliases_src0(self): - # v0 = perm(v0, v1, v2) - # v0 holds src0 (indices 4..7). In-place update must read old v0 bytes accurately. - rf = ScalarRegisterFile() - rf.set_vgpr(0, 0x11223344) # src0 and dst - rf.set_vgpr(1, 0xAABBCCDD) # src1 - # Selector picks byte 0 of src1, byte 0 of src0, byte 1 of src1, byte 1 of src0 - # src1[0]=0xDD, src0[0]=0x44, src1[1]=0xCC, src0[1]=0x33 -> 0x33CC44DD - sel = make_selector(0, 4, 1, 5) - rf.set_vgpr(2, sel) - - interp = PermB32ScalarInterpreter(rf) - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.vgpr(2), - ) - interp.step(instr) - self.assertEqual(rf.get_vgpr(0), 0x33CC44DD) - - def test_dst_aliases_src1(self): - # v1 = perm(v0, v1, v2) - # v1 holds src1 (indices 0..3) - rf = ScalarRegisterFile() - rf.set_vgpr(0, 0x11223344) # src0 - rf.set_vgpr(1, 0xAABBCCDD) # src1 and dst - # Reverse src1: [DD, CC, BB, AA] -> [AA, BB, CC, DD] -> 0xDDCCBBAA - sel = PermSelectorWord.bswap_src1().raw - rf.set_vgpr(2, sel) - - interp = PermB32ScalarInterpreter(rf) - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(1), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.vgpr(2), - ) - interp.step(instr) - self.assertEqual(rf.get_vgpr(1), 0xDDCCBBAA) - - def test_dst_aliases_src2_selector(self): - # v2 = perm(v0, v1, v2) - # Selector register is overwritten by the result - rf = ScalarRegisterFile() - rf.set_vgpr(0, 0x12345678) - rf.set_vgpr(1, 0x9ABCDEF0) - # Identity of src0: 0x07060504 - sel = PermSelectorWord.identity_src0().raw - rf.set_vgpr(2, sel) - - interp = PermB32ScalarInterpreter(rf) - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(2), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.vgpr(2), - ) - interp.step(instr) - self.assertEqual(rf.get_vgpr(2), 0x12345678) - - def test_full_aliasing_all_operands(self): - # v0 = perm(v0, v0, v0) - # All operands are the same register v0 - rf = ScalarRegisterFile() - # Choose a value that serves as both data and selector: - # byte 0 = 0x01, byte 1 = 0x02, byte 2 = 0x03, byte 3 = 0x00 -> 0x00030201 - val = 0x00030201 - rf.set_vgpr(0, val) - - # Expected: - # data pool: src0=val (bytes 4..7), src1=val (bytes 0..3) - # selector bytes: sel0=1, sel1=2, sel2=3, sel3=0 - # byte 0: val[1] = 0x02 - # byte 1: val[2] = 0x03 - # byte 2: val[3] = 0x00 - # byte 3: val[0] = 0x01 - # Pack: [0x02, 0x03, 0x00, 0x01] -> 0x01000302 - interp = PermB32ScalarInterpreter(rf) - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(0), - src2=ASTOperand.vgpr(0), - ) - interp.step(instr) - self.assertEqual(rf.get_vgpr(0), 0x01000302) - - def test_src0_aliases_src1_self_swizzle(self): - # v2 = perm(v0, v0, literal) - rf = ScalarRegisterFile() - rf.set_vgpr(0, 0x12345678) - - # Select bytes from same register using indices 0..3 or 4..7 - # Index 0 and 4 are both byte 0 (0x78) - sel = make_selector(0, 4, 1, 5) # [0x78, 0x78, 0x56, 0x56] -> 0x56567878 - interp = PermB32ScalarInterpreter(rf) - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(2), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(0), - src2=ASTOperand.literal(sel), - ) - interp.step(instr) - self.assertEqual(rf.get_vgpr(2), 0x56567878) - - def test_simd_wave_aliasing_with_exec_mask(self): - # Wave32: v1 = perm(v0, v1, v2) with half EXEC mask - wave = SIMDWaveState(num_lanes=32, exec_mask=0x0000FFFF) - src0_init = [0x11111111] * 32 - src1_init = [0x22222222 + i for i in range(32)] - sel_bswap = [PermSelectorWord.bswap_src1().raw] * 32 - - wave.set_wave_vgpr(0, src0_init) - wave.set_wave_vgpr(1, src1_init) - wave.set_wave_vgpr(2, sel_bswap) - - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(1), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.vgpr(2), - ) - wave.execute_instruction(instr) - - for lane in range(16): - expected = oracle_v_perm_b32(src0_init[lane], src1_init[lane], sel_bswap[lane]) - self.assertEqual(wave.get_lane_vgpr(1, lane), expected) - for lane in range(16, 32): - self.assertEqual(wave.get_lane_vgpr(1, lane), src1_init[lane]) - - def test_unwritten_registers_unaffected(self): - rf = ScalarRegisterFile() - rf.set_vgpr(3, 0x11111111) - rf.set_vgpr(4, 0x22222222) - rf.set_vgpr(5, 0x33333333) - rf.set_vgpr(6, 0x44444444) - - interp = PermB32ScalarInterpreter(rf) - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(4), - src0=ASTOperand.vgpr(3), - src1=ASTOperand.vgpr(3), - src2=ASTOperand.literal(0), - ) - interp.step(instr) - - self.assertEqual(rf.get_vgpr(3), 0x11111111) - self.assertEqual(rf.get_vgpr(5), 0x33333333) - self.assertEqual(rf.get_vgpr(6), 0x44444444) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass -class StatusFlags: - """Architectural status flags and condition codes for 32-bit execution.""" - zero: bool = False - negative: bool = False - parity_even: bool = False - byte_zeros: Tuple[bool, bool, bool, bool] = (False, False, False, False) - byte_negatives: Tuple[bool, bool, bool, bool] = (False, False, False, False) - carry: bool = False - overflow: bool = False - - @classmethod - def from_result(cls, res: int, addend: int = 0, is_sub: bool = False) -> StatusFlags: - val = res & MASK32 - zero = (val == 0) - negative = bool(val & 0x8000_0000) - - # Bit parity of low byte - popcount = bin(val & 0xFF).count("1") - parity_even = (popcount % 2 == 0) - - b_zeros = ( - extract_byte(val, 0) == 0, - extract_byte(val, 1) == 0, - extract_byte(val, 2) == 0, - extract_byte(val, 3) == 0, - ) - b_negs = ( - bool(extract_byte(val, 0) & 0x80), - bool(extract_byte(val, 1) & 0x80), - bool(extract_byte(val, 2) & 0x80), - bool(extract_byte(val, 3) & 0x80), - ) - - carry = False - overflow = False - if is_sub: - # Emulate subtraction borrow: addend - val - diff = addend - val - carry = (diff < 0) # Borrow - sa = (addend >> 31) & 1 - sb = (val >> 31) & 1 - sr = ((diff & MASK32) >> 31) & 1 - overflow = bool((sa ^ sb) & (sa ^ sr)) - elif addend != 0: - # Emulate addition carry: addend + val - total = addend + val - carry = bool(total > MASK32) - sa = (addend >> 31) & 1 - sb = (val >> 31) & 1 - sr = ((total & MASK32) >> 31) & 1 - overflow = bool(not (sa ^ sb) & (sa ^ sr)) - - return cls( - zero=zero, - negative=negative, - parity_even=parity_even, - byte_zeros=b_zeros, - byte_negatives=b_negs, - carry=carry, - overflow=overflow, - ) - - -def compute_wave_vcc_mask(wave: SIMDWaveState, reg_idx: int, predicate: str = "ne_zero") -> int: - """Evaluate lane condition codes across active lanes to produce a 32/64-bit VCC mask.""" - vcc_mask = 0 - for lane in range(wave.num_lanes): - if wave.is_lane_active(lane): - val = wave.get_lane_vgpr(reg_idx, lane) - cond = False - if predicate == "ne_zero": - cond = (val != 0) - elif predicate == "eq_zero": - cond = (val == 0) - elif predicate == "negative": - cond = bool(val & 0x8000_0000) - elif predicate == "byte0_zero": - cond = (extract_byte(val, 0) == 0) - elif predicate == "byte3_neg": - cond = bool(extract_byte(val, 3) & 0x80) - else: - raise ValueError(f"Unknown predicate: {predicate}") - - if cond: - vcc_mask |= (1 << lane) - return vcc_mask - - -# ============================================================================== -# Unit Tests: Condition Codes and Status Flags -# ============================================================================== - -class TestPermB32StatusFlagsAndConditionCodes(unittest.TestCase): - """Test suite for condition codes, status flags, and carry/borrow generation.""" - - def test_zero_flag_detection(self): - # Permutation producing all zero bytes - res = oracle_v_perm_b32(0xFFFFFFFF, 0xFFFFFFFF, make_selector(SEL_ZERO, SEL_ZERO, SEL_ZERO, SEL_ZERO)) - flags = StatusFlags.from_result(res) - self.assertTrue(flags.zero) - self.assertFalse(flags.negative) - self.assertEqual(flags.byte_zeros, (True, True, True, True)) - - def test_negative_sign_flag_detection(self): - # Permutation selecting sign-extended 1s into MSB (byte 3) - res = oracle_v_perm_b32(0x80000000, 0, make_selector(0, 0, 0, SEL_SIGN_EXT_SRC0_B3)) - flags = StatusFlags.from_result(res) - self.assertFalse(flags.zero) - self.assertTrue(flags.negative) - self.assertTrue(flags.byte_negatives[3]) - self.assertFalse(flags.byte_negatives[0]) - - def test_byte_level_flags(self): - # Result = 0x8000007F: byte 0=0x7F, byte 1=0x00, byte 2=0x00, byte 3=0x80 - res = 0x8000007F - flags = StatusFlags.from_result(res) - self.assertEqual(flags.byte_zeros, (False, True, True, False)) - self.assertEqual(flags.byte_negatives, (False, False, False, True)) - - def test_parity_flag_calculation(self): - # Byte 0 = 0x03 (binary 00000011 -> 2 bits set -> even parity) - flags_even = StatusFlags.from_result(0x00000003) - self.assertTrue(flags_even.parity_even) - - # Byte 0 = 0x07 (binary 00000111 -> 3 bits set -> odd parity) - flags_odd = StatusFlags.from_result(0x00000007) - self.assertFalse(flags_odd.parity_even) - - def test_wave_vcc_mask_generation(self): - # Wave32 where even lanes have non-zero results and odd lanes have zero results - wave = SIMDWaveState(num_lanes=32, exec_mask=0xFFFFFFFF) - vals = [0x12345678 if i % 2 == 0 else 0 for i in range(32)] - wave.set_wave_vgpr(0, vals) - - vcc_ne = compute_wave_vcc_mask(wave, 0, predicate="ne_zero") - # Even bits set: 0x55555555 - self.assertEqual(vcc_ne, 0x55555555) - - vcc_eq = compute_wave_vcc_mask(wave, 0, predicate="eq_zero") - # Odd bits set: 0xAAAAAAAA - self.assertEqual(vcc_eq, 0xAAAAAAAA) - - def test_wave_vcc_mask_respects_inactive_lanes(self): - # EXEC mask has only lower 16 lanes active - wave = SIMDWaveState(num_lanes=32, exec_mask=0x0000FFFF) - wave.set_wave_vgpr(0, [0xFFFFFFFF] * 32) - - vcc = compute_wave_vcc_mask(wave, 0, predicate="ne_zero") - # Upper 16 lanes inactive, so VCC bits must not be set - self.assertEqual(vcc, 0x0000FFFF) - - def test_carry_borrow_generation_from_permuted_operands(self): - # Unpack byte 0 using v_perm_b32 into a register, then add to trigger carry - val = oracle_v_perm_b32(0, 0x000000FF, make_selector(0, SEL_ZERO, SEL_ZERO, SEL_ZERO)) - self.assertEqual(val, 0x000000FF) - - # Add 0xFFFFFFFF + 0x000000FF -> generates unsigned carry - flags_add = StatusFlags.from_result(val, addend=0xFFFFFFFF) - self.assertTrue(flags_add.carry) - - # Subtract 0x00000010 - 0x000000FF -> generates borrow - flags_sub = StatusFlags.from_result(val, addend=0x00000010, is_sub=True) - self.assertTrue(flags_sub.carry) - - -# ============================================================================== -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# ============================================================================== - -# IEEE 754 Binary32 (single precision) architectural constants -F32_POS_ZERO: int = 0x0000_0000 -F32_NEG_ZERO: int = 0x8000_0000 -F32_POS_INF: int = 0x7F80_0000 -F32_NEG_INF: int = 0xFF80_0000 -F32_QNAN: int = 0x7FC0_0000 -F32_SNAN: int = 0x7F80_0001 -F32_NEG_QNAN: int = 0xFFC0_0000 - -F32_POS_MIN_NORMAL: int = 0x0080_0000 -F32_POS_MAX_NORMAL: int = 0x7F7F_FFFF -F32_POS_MIN_SUBNORM: int = 0x0000_0001 -F32_POS_MAX_SUBNORM: int = 0x007F_FFFF - -# IEEE 754 Binary16 (half precision) constants -F16_POS_ZERO: int = 0x0000 -F16_NEG_ZERO: int = 0x8000 -F16_POS_INF: int = 0x7C00 -F16_NEG_INF: int = 0xFC00 -F16_QNAN: int = 0x7E00 -F16_SNAN: int = 0x7D00 - - -def bswap_f32_bits(f_bits: int) -> int: - """Byte-swap an IEEE 754 float32 using v_perm_b32.""" - sel = PermSelectorWord.bswap_src1().raw - return oracle_v_perm_b32(0, f_bits, sel) - - -def unpack_pk_f16_lo(packed: int) -> int: - """Unpack lower 16-bit float into 32-bit register with zero-extension using v_perm_b32.""" - sel = make_selector(0, 1, SEL_ZERO, SEL_ZERO) - return oracle_v_perm_b32(0, packed, sel) - - -def unpack_pk_f16_hi(packed: int) -> int: - """Unpack upper 16-bit float into 32-bit register with zero-extension using v_perm_b32.""" - sel = make_selector(2, 3, SEL_ZERO, SEL_ZERO) - return oracle_v_perm_b32(0, packed, sel) - - -class TestPermB32IEEE754Boundaries(unittest.TestCase): - """Test suite for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_f32_endian_swapping_preserves_nan_payloads(self): - # Signaling NaN with custom payload - snan = 0x7F80_1234 - swapped = bswap_f32_bits(snan) - restored = bswap_f32_bits(swapped) - self.assertEqual(restored, snan) - - # Quiet NaN - qnan = F32_QNAN - self.assertEqual(bswap_f32_bits(bswap_f32_bits(qnan)), qnan) - - # Negative Quiet NaN - neg_qnan = F32_NEG_QNAN - self.assertEqual(bswap_f32_bits(bswap_f32_bits(neg_qnan)), neg_qnan) - - def test_f32_subnormal_byte_manipulation(self): - # Smallest positive subnormal: 0x00000001 (byte 0 has bit 0 set) - min_sub = F32_POS_MIN_SUBNORM - swapped = bswap_f32_bits(min_sub) - # In big endian, bit 0 is in byte 3 (MSB position of word): 0x01000000 - self.assertEqual(swapped, 0x0100_0000) - self.assertEqual(bswap_f32_bits(swapped), min_sub) - - # Largest subnormal: 0x007FFFFF - max_sub = F32_POS_MAX_SUBNORM - self.assertEqual(bswap_f32_bits(bswap_f32_bits(max_sub)), max_sub) - - def test_f32_infinity_and_zero_byte_isolation(self): - # Positive and negative zero - self.assertEqual(bswap_f32_bits(bswap_f32_bits(F32_POS_ZERO)), F32_POS_ZERO) - self.assertEqual(bswap_f32_bits(bswap_f32_bits(F32_NEG_ZERO)), F32_NEG_ZERO) - - # Positive and negative infinity - self.assertEqual(bswap_f32_bits(bswap_f32_bits(F32_POS_INF)), F32_POS_INF) - self.assertEqual(bswap_f32_bits(bswap_f32_bits(F32_NEG_INF)), F32_NEG_INF) - - # Extract exponent byte (bits 30..23 span byte 2 and byte 3) - # Using v_perm_b32 to extract byte 2 and byte 3 into lower 16 bits - sel_exp = make_selector(2, 3, SEL_ZERO, SEL_ZERO) - exp_words = oracle_v_perm_b32(0, F32_POS_INF, sel_exp) - # F32_POS_INF = 0x7F800000 -> byte 2=0x80, byte 3=0x7F -> 0x00007F80 - self.assertEqual(exp_words, 0x00007F80) - - def test_f16_unpacking_and_zero_extension(self): - # Packed pair of f16 values: lo = +1.0 (0x3C00), hi = -1.0 (0xBC00) - # packed dword: 0xBC00_3C00 - packed = 0xBC00_3C00 - unpacked_lo = unpack_pk_f16_lo(packed) - self.assertEqual(unpacked_lo, 0x0000_3C00) - - unpacked_hi = unpack_pk_f16_hi(packed) - self.assertEqual(unpacked_hi, 0x0000_BC00) - - def test_f32_sign_bit_sign_extension(self): - # Sign-extend sign bit of float: bit 31 is in byte 3 - # Selector 8 performs sign extension of S1 bit 31 - sel_sign = make_selector(8, 8, 8, 8) - - # Positive float: sign bit 0 -> 0x00000000 - pos_float = 0x3F80_0000 # +1.0f - mask_pos = oracle_v_perm_b32(0, pos_float, sel_sign) - self.assertEqual(mask_pos, 0x0000_0000) - - # Negative float: sign bit 1 -> 0xFFFFFFFF - neg_float = 0xBF80_0000 # -1.0f - mask_neg = oracle_v_perm_b32(0, neg_float, sel_sign) - self.assertEqual(mask_neg, 0xFFFF_FFFF) - - # Negative Quiet NaN - mask_nan = oracle_v_perm_b32(0, F32_NEG_QNAN, sel_sign) - self.assertEqual(mask_nan, 0xFFFF_FFFF) - - -# ============================================================================== -# Negative Controls, Syntax Rejection, and Mutation Detection -# ============================================================================== - -def mutated_perm_off_by_one(src0: int, src1: int, selector: int) -> int: - """Mutant 1: shifts selector index by +1.""" - s0 = src0 & MASK32 - s1 = src1 & MASK32 - sel = selector & MASK32 - b0 = permute_single_byte(s0, s1, (extract_byte(sel, 0) + 1) & 0xFF) - b1 = permute_single_byte(s0, s1, (extract_byte(sel, 1) + 1) & 0xFF) - b2 = permute_single_byte(s0, s1, (extract_byte(sel, 2) + 1) & 0xFF) - b3 = permute_single_byte(s0, s1, (extract_byte(sel, 3) + 1) & 0xFF) - return pack_bytes(b0, b1, b2, b3) - - -def mutated_perm_inverted_sources(src0: int, src1: int, selector: int) -> int: - """Mutant 2: inverts src0 and src1 mapping.""" - return oracle_v_perm_b32(src1, src0, selector) - - -def mutated_perm_ignore_zero_fill(src0: int, src1: int, selector: int) -> int: - """Mutant 3: treats selector 12 as picking from src1 byte 0 instead of 0x00.""" - s0 = src0 & MASK32 - s1 = src1 & MASK32 - sel = selector & MASK32 - bytes_out = [] +def ref_perm(s0, s1, selector): + """Plain-Python reference of the table in the module docstring.""" + pool = [(s1 >> (8 * i)) & 0xFF for i in range(4)] + [(s0 >> (8 * i)) & 0xFF for i in range(4)] + out = 0 for i in range(4): - b = extract_byte(sel, i) - if b == SEL_ZERO: - bytes_out.append(extract_byte(s1, 0)) # Buggy replacement + c = (selector >> (8 * i)) & 0xFF + if c < 8: + v = pool[c] + elif c < 12: + w, b = [(s1, 15), (s1, 31), (s0, 15), (s0, 31)][c - 8] + v = 0xFF if (w >> b) & 1 else 0 else: - bytes_out.append(permute_single_byte(s0, s1, b)) - return pack_bytes(bytes_out[0], bytes_out[1], bytes_out[2], bytes_out[3]) + v = 0 if c == 12 else 0xFF + out |= v << (8 * i) + return out -def mutated_perm_ignore_ones_fill(src0: int, src1: int, selector: int) -> int: - """Mutant 4: returns 0x00 instead of 0xFF for selector >= 13.""" - s0 = src0 & MASK32 - s1 = src1 & MASK32 - sel = selector & MASK32 - bytes_out = [] - for i in range(4): - b = extract_byte(sel, i) - if b >= SEL_ONES_MIN: - bytes_out.append(0x00) # Buggy replacement - else: - bytes_out.append(permute_single_byte(s0, s1, b)) - return pack_bytes(bytes_out[0], bytes_out[1], bytes_out[2], bytes_out[3]) +def run(s0, s1, selector, form="vgpr"): + if form == "vgpr": + setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {selector:#x}"] + srcs = "v1, v2, v3" + else: + setup = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {selector:#x}"] + srcs = "s1, s2, s3" + lines = setup + [f"v_perm_b32 v0, {srcs}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_perm", lines))[0] -def mutated_perm_wrong_endianness(src0: int, src1: int, selector: int) -> int: - """Mutant 5: packs output bytes in big-endian order instead of little-endian.""" - s0 = src0 & MASK32 - s1 = src1 & MASK32 - sel = selector & MASK32 - b0 = permute_single_byte(s0, s1, extract_byte(sel, 0)) - b1 = permute_single_byte(s0, s1, extract_byte(sel, 1)) - b2 = permute_single_byte(s0, s1, extract_byte(sel, 2)) - b3 = permute_single_byte(s0, s1, extract_byte(sel, 3)) - # Big-endian packing - return ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) & MASK32 +S0, S1 = 0xAABBCCDD, 0x11223344 + +# (name, S0, S1, selector, expected word), written by hand. +CASES = [ + ("identity S1", S0, S1, sel(0, 1, 2, 3), 0x11223344), + ("identity S0", S0, S1, sel(4, 5, 6, 7), 0xAABBCCDD), + ("interleave", S0, S1, sel(0, 4, 1, 5), 0xCC33DD44), + ("bswap S1", 0x9ABCDEF0, 0x12345678, sel(3, 2, 1, 0), 0x78563412), + ("bswap S0", 0x9ABCDEF0, 0x12345678, sel(7, 6, 5, 4), 0xF0DEBC9A), + ("broadcast S1 byte 0", 0, 0x01020304, sel(0, 0, 0, 0), 0x04040404), + ("broadcast S0 byte 3", 0x88776655, 0, sel(7, 7, 7, 7), 0x88888888), + ("zero fill", 0xFFFFFFFF, 0xFFFFFFFF, sel(12, 12, 12, 12), 0x00000000), + ("zero mixed", S0, S1, sel(0, 12, 4, 12), 0x00DD0044), + ("ones fill 13..255", 0, 0, sel(13, 14, 15, 255), 0xFFFFFFFF), + ("ones mixed", 0x12345678, 0x9ABCDEF0, sel(0, 13, 4, 255), 0xFF78FFF0), + # 8: S1 bit 15, 9: S1 bit 31, 10: S0 bit 15, 11: S0 bit 31 + ("sel 8 set", 0, 0x00008000, sel(8, 12, 12, 12), 0x000000FF), + ("sel 8 clear (S1 bit 31 does not count)", 0, 0x80000000, sel(8, 12, 12, 12), 0x00000000), + ("sel 9 set", 0, 0x80000000, sel(12, 9, 12, 12), 0x0000FF00), + ("sel 9 clear", 0, 0x7FFFFFFF, sel(12, 9, 12, 12), 0x00000000), + ("sel 10 set", 0x00008000, 0, sel(12, 12, 10, 12), 0x00FF0000), + ("sel 10 clear (S0 bit 31 does not count)", 0x80000000, 0, sel(12, 12, 10, 12), 0x00000000), + ("sel 11 set", 0x80000000, 0, sel(12, 12, 12, 11), 0xFF000000), + ("sel 11 clear (S1 bit 7 does not count)", 0, 0x00000080, sel(12, 12, 12, 11), 0x00000000), + ("all four sign bits set", 0x80008000, 0x80008000, sel(8, 9, 10, 11), 0xFFFFFFFF), + ("selector bytes use all 8 bits", S0, S1, sel(0x10, 0x7F, 0x80, 0xFF), 0xFFFFFFFF), +] -class TestPermB32NegativeControlsAndMutations(unittest.TestCase): - """Test suite for negative controls, syntax rejection, and mutation detection.""" +class PermB32(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for name, s0, s1, selector, want in CASES: + self.assertEqual(ref_perm(s0, s1, selector), want, name) - def test_negative_sgpr_destination_rejected(self): - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.sgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - instr.validate() + def test_translated_cases(self): + for name, s0, s1, selector, want in CASES: + with self.subTest(name): + self.assertEqual(run(s0, s1, selector), want) - def test_negative_multiple_literals_rejected(self): - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.literal(0x11111111), - src1=ASTOperand.literal(0x22222222), - src2=ASTOperand.vgpr(3), - ) - with self.assertRaises(ValueError): - instr.validate() + def test_sgpr_sources(self): + for name, s0, s1, selector, want in CASES[:8]: + with self.subTest(name): + self.assertEqual(run(s0, s1, selector, "sgpr"), want) - def test_negative_register_index_bounds(self): - rf = ScalarRegisterFile() - with self.assertRaises(IndexError): - rf.get_vgpr(256) - with self.assertRaises(IndexError): - rf.set_vgpr(-1, 0) - with self.assertRaises(IndexError): - rf.get_sgpr(106) - with self.assertRaises(IndexError): - rf.set_sgpr(-1, 0) - - def test_negative_byte_index_bounds(self): - with self.assertRaises(ValueError): - extract_byte(0x12345678, 4) - with self.assertRaises(ValueError): - extract_byte(0x12345678, -1) - - def test_negative_wave_size_rejected(self): - with self.assertRaises(ValueError): - SIMDWaveState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDWaveState(num_lanes=128) - - def test_mutation_off_by_one_detected(self): - src0 = 0xAABBCCDD - src1 = 0x11223344 - sel = PermSelectorWord.identity_src1().raw - expected = oracle_v_perm_b32(src0, src1, sel) - mutated = mutated_perm_off_by_one(src0, src1, sel) - self.assertNotEqual(expected, mutated) - - def test_mutation_inverted_sources_detected(self): - src0 = 0xAABBCCDD - src1 = 0x11223344 - sel = PermSelectorWord.identity_src1().raw - expected = oracle_v_perm_b32(src0, src1, sel) - mutated = mutated_perm_inverted_sources(src0, src1, sel) - self.assertNotEqual(expected, mutated) - - def test_mutation_constant_zero_ignored_detected(self): - src0 = 0xFFFFFFFF - src1 = 0x55667788 - sel = make_selector(SEL_ZERO, SEL_ZERO, SEL_ZERO, SEL_ZERO) - expected = oracle_v_perm_b32(src0, src1, sel) - mutated = mutated_perm_ignore_zero_fill(src0, src1, sel) - self.assertNotEqual(expected, mutated) - - def test_mutation_constant_ones_ignored_detected(self): - src0 = 0x00000000 - src1 = 0x00000000 - sel = make_selector(SEL_ONES_MIN, SEL_ONES_MIN, SEL_ONES_MIN, SEL_ONES_MIN) - expected = oracle_v_perm_b32(src0, src1, sel) - mutated = mutated_perm_ignore_ones_fill(src0, src1, sel) - self.assertNotEqual(expected, mutated) - - def test_mutation_exec_mask_ignored_detected(self): - # A buggy execution engine that ignores EXEC mask writes all lanes - wave = SIMDWaveState(num_lanes=32, exec_mask=0x00000001) # Only lane 0 active - wave.set_wave_vgpr(0, [0xCAFE0000] * 32) - wave.set_wave_vgpr(1, [0x12345678] * 32) - - instr = ASTInstruction( - opcode=Opcode.V_PERM_B32, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(1), - src1=ASTOperand.vgpr(1), - src2=ASTOperand.literal(0), - ) - wave.execute_instruction(instr) - - # Inactive lanes (1..31) must remain 0xCAFE0000 - for lane in range(1, 32): - self.assertEqual(wave.get_lane_vgpr(0, lane), 0xCAFE0000) - - def test_mutation_wrong_endianness_detected(self): - src0 = 0x12345678 - src1 = 0x9ABCDEF0 - sel = make_selector(0, 1, 2, 3) - expected = oracle_v_perm_b32(src0, src1, sel) - mutated = mutated_perm_wrong_endianness(src0, src1, sel) - self.assertNotEqual(expected, mutated) + def test_random_operands(self): + rng = random.Random(0x7065726D) + for _ in range(60): + s0, s1, selector = (rng.getrandbits(32) for _ in range(3)) + with self.subTest(s0=hex(s0), s1=hex(s1), selector=hex(selector)): + self.assertEqual(run(s0, s1, selector), ref_perm(s0, s1, selector)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_pk_add_f16.py b/tests/semantic/test_valu_pk_add_f16.py index bd6807fad..a4f9e2145 100644 --- a/tests/semantic/test_valu_pk_add_f16.py +++ b/tests/semantic/test_valu_pk_add_f16.py @@ -1,1447 +1,168 @@ -from __future__ import annotations +"""v_pk_add_f16 (RDNA2 VOP3P): D.f16[i] = S0.f16[i] + S1.f16[i] for both halves, binary16 with round to nearest even. -import math -import struct +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py. The expected +words are written down by hand (from the ISA) next to each case; the plain-Python binary16 reference in +tests/semantic/f16_ref.py rechecks them lane by lane and drives seeded random operands and modifier combinations. +Covers per-lane results, op_sel / op_sel_hi half selection, neg_lo / neg_hi, clamp and SGPR sources. +Standard library only: no GPU, no LLVM, no game data. +""" +import os +import random +import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from fractions import Fraction -from typing import List, Optional, Tuple, Union -# IEEE 754 binary16 (half-precision) architectural constants -SIGN_MASK_F16: int = 0x8000 -EXP_MASK_F16: int = 0x7C00 -FRAC_MASK_F16: int = 0x03FF -QNAN_BIT_F16: int = 0x0200 -CANONICAL_QNAN_F16: int = 0x7E00 - -POS_ZERO_F16: int = 0x0000 -NEG_ZERO_F16: int = 0x8000 -POS_INF_F16: int = 0x7C00 -NEG_INF_F16: int = 0xFC00 -ONE_F16: int = 0x3C00 -HALF_F16: int = 0x3800 -TWO_F16: int = 0x4000 - - -def f16_to_bits(val: float) -> int: - """Convert a Python float to 16-bit IEEE 754 half-precision bits.""" - if math.isnan(val): - return CANONICAL_QNAN_F16 - try: - return struct.unpack(" 0 else NEG_INF_F16 - - -def bits_to_f16(bits: int) -> float: - """Convert 16-bit integer bits to a Python float (IEEE 754 half precision).""" - return struct.unpack(" int: - """Pack two 16-bit halfwords into a 32-bit dword.""" - return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) - - -def unpack_2xf16(dword: int) -> Tuple[int, int]: - """Unpack a 32-bit dword into two 16-bit halfwords (lo, hi).""" - return dword & 0xFFFF, (dword >> 16) & 0xFFFF - - -def split_f16_bits(bits: int) -> Tuple[int, int, int]: - """Unpack bits into (sign, exponent, fraction) components.""" - sign = (bits & SIGN_MASK_F16) >> 15 - exponent = (bits & EXP_MASK_F16) >> 10 - fraction = bits & FRAC_MASK_F16 - return sign, exponent, fraction - - -def is_nan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 half-precision NaN.""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & FRAC_MASK_F16) != 0) - - -def is_qnan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Quiet NaN.""" - return is_nan_f16(bits) and bool(bits & QNAN_BIT_F16) - - -def is_snan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Signaling NaN.""" - return is_nan_f16(bits) and not bool(bits & QNAN_BIT_F16) - - -def is_inf_f16(bits: int) -> bool: - """Return True if bits represent IEEE 754 positive or negative infinity.""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & FRAC_MASK_F16) == 0) - - -def is_subnormal_f16(bits: int) -> bool: - """Return True if bits represent a subnormal (denormal) half-precision float.""" - return ((bits & EXP_MASK_F16) == 0) and ((bits & FRAC_MASK_F16) != 0) - - -def is_zero_f16(bits: int) -> bool: - """Return True if bits represent positive or negative zero.""" - return (bits & ~SIGN_MASK_F16) == 0 - - -def apply_f16_modifiers(bits: int, abs_mod: bool = False, neg_mod: bool = False) -> int: - """Apply VOP3P input modifiers: abs clears sign bit; neg toggles sign bit.""" - res = bits & 0xFFFF - if abs_mod: - res &= ~SIGN_MASK_F16 - if neg_mod: - res ^= SIGN_MASK_F16 - return res - - -def oracle_add_f16( - s0_bits: int, - s1_bits: int, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> int: - """Reference mathematical oracle for scalar IEEE 754 half-precision addition with clamp.""" - s0 = apply_f16_modifiers(s0_bits, abs_mod=abs0, neg_mod=neg0) - s1 = apply_f16_modifiers(s1_bits, abs_mod=abs1, neg_mod=neg1) - - # 1. NaN handling - if is_nan_f16(s0) or is_nan_f16(s1): - if clamp: - # Clamping NaN in RDNA2 produces +0.0 - return POS_ZERO_F16 - # Prefer quietening signaling NaN or propagating quiet NaN - nan_bits = s0 if is_nan_f16(s0) else s1 - return nan_bits | QNAN_BIT_F16 - - # 2. Infinity handling - s0_inf = is_inf_f16(s0) - s1_inf = is_inf_f16(s1) - if s0_inf and s1_inf: - s0_sign = (s0 & SIGN_MASK_F16) - s1_sign = (s1 & SIGN_MASK_F16) - if s0_sign != s1_sign: - # (+inf) + (-inf) -> Invalid operation -> Canonical Quiet NaN - return POS_ZERO_F16 if clamp else CANONICAL_QNAN_F16 - if clamp: - return ONE_F16 if s0 == POS_INF_F16 else POS_ZERO_F16 - return s0 - if s0_inf: - if clamp: - return ONE_F16 if s0 == POS_INF_F16 else POS_ZERO_F16 - return s0 - if s1_inf: - if clamp: - return ONE_F16 if s1 == POS_INF_F16 else POS_ZERO_F16 - return s1 - - # 3. Signed zero handling - if is_zero_f16(s0) and is_zero_f16(s1): - s0_is_neg = (s0 == NEG_ZERO_F16) - s1_is_neg = (s1 == NEG_ZERO_F16) - if s0_is_neg and s1_is_neg: - res = NEG_ZERO_F16 - else: - res = POS_ZERO_F16 - if clamp and res == NEG_ZERO_F16: - return POS_ZERO_F16 - return res - - # 4. Finite addition - f0 = bits_to_f16(s0) - f1 = bits_to_f16(s1) - f_res = f0 + f1 - res = f16_to_bits(f_res) - - # In round-to-nearest-even, x + (-x) produces +0.0 - if f_res == 0.0 and not (s0 == NEG_ZERO_F16 and s1 == NEG_ZERO_F16): - res = POS_ZERO_F16 - - # 5. Clamp modifier ([0.0, 1.0]) - if clamp: - if f_res < 0.0 or res == NEG_ZERO_F16: - res = POS_ZERO_F16 - elif f_res > 1.0 or res == POS_INF_F16: - res = ONE_F16 - - return res - - -def oracle_v_pk_add_f16( - src0_dword: int, - src1_dword: int, - op_sel: Tuple[int, int] = (0, 0), - op_sel_hi: Tuple[int, int] = (1, 1), - neg_lo: Tuple[bool, bool] = (False, False), - neg_hi: Tuple[bool, bool] = (False, False), - abs_lo: Tuple[bool, bool] = (False, False), - abs_hi: Tuple[bool, bool] = (False, False), - clamp: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_pk_add_f16 packed addition. - - Computes packed 2xf16 addition: - lo = src0[op_sel[0]] + src1[op_sel[1]] - hi = src0[op_sel_hi[0]] + src1[op_sel_hi[1]] - applying neg, abs, and clamp modifiers. - """ - s0_halves = unpack_2xf16(src0_dword) - s1_halves = unpack_2xf16(src1_dword) - - s0_lo_in = s0_halves[op_sel[0]] - s1_lo_in = s1_halves[op_sel[1]] - res_lo = oracle_add_f16( - s0_lo_in, - s1_lo_in, - abs0=abs_lo[0], - neg0=neg_lo[0], - abs1=abs_lo[1], - neg1=neg_lo[1], - clamp=clamp, - ) - - s0_hi_in = s0_halves[op_sel_hi[0]] - s1_hi_in = s1_halves[op_sel_hi[1]] - res_hi = oracle_add_f16( - s0_hi_in, - s1_hi_in, - abs0=abs_hi[0], - neg0=neg_hi[0], - abs1=abs_hi[1], - neg1=neg_hi[1], - clamp=clamp, - ) - - return pack_2xf16(res_lo, res_hi) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - VGPR = auto() - SGPR = auto() - - -@dataclass(frozen=True) -class Reg32: - """Represents an architectural 32-bit register (VGPR or SGPR).""" - index: int - reg_type: RegType - - def __post_init__(self) -> None: - if not (0 <= self.index <= 255): - raise ValueError(f"Register index {self.index} out of range [0, 255]") - - @property - def name(self) -> str: - prefix = "v" if self.reg_type == RegType.VGPR else "s" - return f"{prefix}{self.index}" - - -@dataclass(frozen=True) -class Literal32: - """Represents a 32-bit literal or inline constant holding packed 2xf16 values.""" - dword: int - - @classmethod - def from_floats(cls, lo: float, hi: float) -> Literal32: - return cls(pack_2xf16(f16_to_bits(lo), f16_to_bits(hi))) - - @property - def lo_float(self) -> float: - return bits_to_f16(self.dword & 0xFFFF) - - @property - def hi_float(self) -> float: - return bits_to_f16((self.dword >> 16) & 0xFFFF) - - @property - def name(self) -> str: - return f"0x{self.dword:08x}" - - -@dataclass(frozen=True) -class VOP3POperand: - """Typed VOP3P operand with op_sel, neg, and abs modifiers.""" - source: Union[Reg32, Literal32] - op_sel_lo: int = 0 # 0 for lo half, 1 for hi half - op_sel_hi: int = 1 # 0 for lo half, 1 for hi half - neg_lo: bool = False - neg_hi: bool = False - abs_lo: bool = False - abs_hi: bool = False - - def __post_init__(self) -> None: - if self.op_sel_lo not in (0, 1) or self.op_sel_hi not in (0, 1): - raise ValueError(f"Invalid op_sel values ({self.op_sel_lo}, {self.op_sel_hi}), must be 0 or 1") - - def disassemble(self) -> str: - s = self.source.name - mods = [] - if self.abs_lo or self.abs_hi: - mods.append(f"abs:[{int(self.abs_lo)},{int(self.abs_hi)}]") - if self.neg_lo or self.neg_hi: - mods.append(f"neg:[{int(self.neg_lo)},{int(self.neg_hi)}]") - if self.op_sel_lo != 0 or self.op_sel_hi != 1: - mods.append(f"op_sel:[{self.op_sel_lo},{self.op_sel_hi}]") - if mods: - return f"{s} {' '.join(mods)}" - return s - - -@dataclass(frozen=True) -class VPkAddF16Instruction: - """Symbolic AST node representing a RDNA2 v_pk_add_f16 VOP3P instruction.""" - dst: Reg32 - src0: VOP3POperand - src1: VOP3POperand - clamp: bool = False - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination of VALU instruction must be VGPR, got {self.dst.reg_type}") - - def disassemble(self) -> str: - s = f"v_pk_add_f16 {self.dst.name}, {self.src0.disassemble()}, {self.src1.disassemble()}" - if self.clamp: - s += " clamp" - return s - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register file for a single wavefront lane (256 VGPRs, 256 SGPRs).""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def get_vgpr(self, index: int) -> int: - return self.vgprs[index] & 0xFFFF_FFFF - - def set_vgpr(self, index: int, value: int) -> None: - self.vgprs[index] = value & 0xFFFF_FFFF - - def get_sgpr(self, index: int) -> int: - return self.sgprs[index] & 0xFFFF_FFFF - - def set_sgpr(self, index: int, value: int) -> None: - self.sgprs[index] = value & 0xFFFF_FFFF - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_pk_add_f16.""" - - def resolve_operand(self, op: VOP3POperand, state: ScalarMachineState) -> int: - if isinstance(op.source, Reg32): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr(op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal32): - return op.source.dword - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VPkAddF16Instruction, state: ScalarMachineState) -> int: - # Atomic read phase - s0_raw = self.resolve_operand(instr.src0, state) - s1_raw = self.resolve_operand(instr.src1, state) - - # Computation phase - result_dword = oracle_v_pk_add_f16( - src0_dword=s0_raw, - src1_dword=s1_raw, - op_sel=(instr.src0.op_sel_lo, instr.src1.op_sel_lo), - op_sel_hi=(instr.src0.op_sel_hi, instr.src1.op_sel_hi), - neg_lo=(instr.src0.neg_lo, instr.src1.neg_lo), - neg_hi=(instr.src0.neg_hi, instr.src1.neg_hi), - abs_lo=(instr.src0.abs_lo, instr.src1.abs_lo), - abs_hi=(instr.src0.abs_hi, instr.src1.abs_hi), - clamp=instr.clamp, - ) - - # Write-back phase - state.set_vgpr(instr.dst.index, result_dword) - return result_dword - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64 execution.""" - num_lanes: int - exec_mask: Optional[int] = None - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - - def get_vgpr(self, lane: int, index: int) -> int: - return self.vgprs[lane][index] & 0xFFFF_FFFF - - def set_vgpr(self, lane: int, index: int, value: int) -> None: - self.vgprs[lane][index] = value & 0xFFFF_FFFF - - def get_sgpr(self, index: int) -> int: - return self.sgprs[index] & 0xFFFF_FFFF - - def set_sgpr(self, index: int, value: int) -> None: - self.sgprs[index] = value & 0xFFFF_FFFF - - -class SIMDInterpreter: - """SIMD instruction interpreter handling multi-lane divergence and EXEC masking.""" - - def resolve_lane_operand(self, op: VOP3POperand, state: SIMDState, lane: int) -> int: - if isinstance(op.source, Reg32): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr(lane, op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal32): - return op.source.dword - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VPkAddF16Instruction, state: SIMDState) -> List[Optional[int]]: - results: List[Optional[int]] = [None] * state.num_lanes - - # Atomic read phase across all lanes - s0_vals = [ - self.resolve_lane_operand(instr.src0, state, lane) - for lane in range(state.num_lanes) - ] - s1_vals = [ - self.resolve_lane_operand(instr.src1, state, lane) - for lane in range(state.num_lanes) - ] - - # Execution phase - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - res = oracle_v_pk_add_f16( - src0_dword=s0_vals[lane], - src1_dword=s1_vals[lane], - op_sel=(instr.src0.op_sel_lo, instr.src1.op_sel_lo), - op_sel_hi=(instr.src0.op_sel_hi, instr.src1.op_sel_hi), - neg_lo=(instr.src0.neg_lo, instr.src1.neg_lo), - neg_hi=(instr.src0.neg_hi, instr.src1.neg_hi), - abs_lo=(instr.src0.abs_lo, instr.src1.abs_lo), - abs_hi=(instr.src0.abs_hi, instr.src1.abs_hi), - clamp=instr.clamp, - ) - state.set_vgpr(lane, instr.dst.index, res) - results[lane] = res - - return results - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry Generation -# ============================================================================== - -@dataclass(frozen=True) -class FPStatusFlags16: - """Architectural floating-point condition codes and IEEE 754 status flags for 16-bit float.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -@dataclass(frozen=True) -class PackedFPStatusFlags16: - """Architectural status flags for both packed 16-bit halves.""" - lo: FPStatusFlags16 - hi: FPStatusFlags16 - - -def evaluate_f16_flags( - s0_bits: int, - s1_bits: int, - res_bits: int, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> FPStatusFlags16: - """Evaluate IEEE 754 architectural flags and condition codes for a single f16 lane.""" - s0 = apply_f16_modifiers(s0_bits, abs_mod=abs0, neg_mod=neg0) - s1 = apply_f16_modifiers(s1_bits, abs_mod=abs1, neg_mod=neg1) - - s0_nan = is_nan_f16(s0) - s1_nan = is_nan_f16(s1) - s0_snan = is_snan_f16(s0) - s1_snan = is_snan_f16(s1) - s0_inf = is_inf_f16(s0) - s1_inf = is_inf_f16(s1) - - invalid = False - if s0_snan or s1_snan: - invalid = True - elif s0_inf and s1_inf and ((s0 & SIGN_MASK_F16) != (s1 & SIGN_MASK_F16)): - invalid = True - - nan_flag = is_nan_f16(res_bits) - inf_flag = is_inf_f16(res_bits) - zero_flag = is_zero_f16(res_bits) - neg_flag = bool(res_bits & SIGN_MASK_F16) - denorm_flag = is_subnormal_f16(res_bits) - - overflow = False - if not (s0_nan or s1_nan or s0_inf or s1_inf) and inf_flag: - overflow = True - - underflow = False - if denorm_flag: - underflow = True - - inexact = False - if overflow: - inexact = True - elif not (s0_nan or s1_nan or s0_inf or s1_inf or nan_flag or inf_flag): - f0 = bits_to_f16(s0) - f1 = bits_to_f16(s1) - res_f = bits_to_f16(res_bits) - if not clamp: - if Fraction(f0) + Fraction(f1) != Fraction(res_f): - inexact = True - else: - clamped_math = min(1.0, max(0.0, float(Fraction(f0) + Fraction(f1)))) - if Fraction(clamped_math) != Fraction(res_f): - inexact = True - - return FPStatusFlags16( - invalid=invalid, - overflow=overflow, - underflow=underflow, - inexact=inexact, - zero=zero_flag, - negative=neg_flag, - denormal=denorm_flag, - infinite=inf_flag, - nan=nan_flag, - ) - - -def evaluate_v_pk_add_f16_flags( - src0_dword: int, - src1_dword: int, - res_dword: int, - op_sel: Tuple[int, int] = (0, 0), - op_sel_hi: Tuple[int, int] = (1, 1), - neg_lo: Tuple[bool, bool] = (False, False), - neg_hi: Tuple[bool, bool] = (False, False), - abs_lo: Tuple[bool, bool] = (False, False), - abs_hi: Tuple[bool, bool] = (False, False), - clamp: bool = False, -) -> PackedFPStatusFlags16: - """Evaluate packed status flags for both low and high 16-bit halves.""" - s0_halves = unpack_2xf16(src0_dword) - s1_halves = unpack_2xf16(src1_dword) - res_halves = unpack_2xf16(res_dword) - - lo_flags = evaluate_f16_flags( - s0_halves[op_sel[0]], - s1_halves[op_sel[1]], - res_halves[0], - abs0=abs_lo[0], - neg0=neg_lo[0], - abs1=abs_lo[1], - neg1=neg_lo[1], - clamp=clamp, - ) - - hi_flags = evaluate_f16_flags( - s0_halves[op_sel_hi[0]], - s1_halves[op_sel_hi[1]], - res_halves[1], - abs0=abs_hi[0], - neg0=neg_hi[0], - abs1=abs_hi[1], - neg1=neg_hi[1], - clamp=clamp, - ) - - return PackedFPStatusFlags16(lo=lo_flags, hi=hi_flags) - - -def compute_f16_mantissa_carry(s0_bits: int, s1_bits: int) -> Tuple[int, int]: - """Demonstrate IEEE 754 11-bit mantissa carry generation during half-precision addition.""" - _, exp0, frac0 = split_f16_bits(s0_bits) - _, exp1, frac1 = split_f16_bits(s1_bits) - m0 = (1 << 10) | frac0 if exp0 != 0 else frac0 - m1 = (1 << 10) | frac1 if exp1 != 0 else frac1 - if exp0 > exp1: - m1 >>= (exp0 - exp1) - elif exp1 > exp0: - m0 >>= (exp1 - exp0) - mant_sum = m0 + m1 - carry_out = 1 if mant_sum >= (1 << 11) else 0 - return mant_sum, carry_out - - -# ============================================================================== -# Unit Tests -# ============================================================================== - -class TestF16ModelAndOracle(unittest.TestCase): - """Unit tests for binary16 / packed 2xf16 bit model and reference oracle.""" - - def test_bit_representation_roundtrip(self) -> None: - values = [0.0, -0.0, 1.0, -1.0, 0.5, -2.5, 65504.0, -65504.0] - for val in values: - with self.subTest(val=val): - bits = f16_to_bits(val) - recovered = bits_to_f16(bits) - self.assertEqual(val, recovered) - self.assertEqual(math.copysign(1.0, val), math.copysign(1.0, recovered)) - - def test_dword_packing_and_unpacking(self) -> None: - lo = f16_to_bits(1.5) - hi = f16_to_bits(-3.0) - packed = pack_2xf16(lo, hi) - unpacked_lo, unpacked_hi = unpack_2xf16(packed) - self.assertEqual(unpacked_lo, lo) - self.assertEqual(unpacked_hi, hi) - self.assertEqual(bits_to_f16(unpacked_lo), 1.5) - self.assertEqual(bits_to_f16(unpacked_hi), -3.0) - - def test_classification_predicates(self) -> None: - self.assertTrue(f16_to_bits(0.0) == POS_ZERO_F16) - self.assertTrue(f16_to_bits(-0.0) == NEG_ZERO_F16) - self.assertTrue(is_zero_f16(POS_ZERO_F16)) - self.assertTrue(is_zero_f16(NEG_ZERO_F16)) - self.assertFalse(is_zero_f16(f16_to_bits(1.0))) - - self.assertTrue(is_inf_f16(POS_INF_F16)) - self.assertTrue(is_inf_f16(NEG_INF_F16)) - self.assertFalse(is_inf_f16(POS_ZERO_F16)) - - snan_bits = 0x7C01 - qnan_bits = CANONICAL_QNAN_F16 - self.assertTrue(is_nan_f16(snan_bits)) - self.assertTrue(is_snan_f16(snan_bits)) - self.assertFalse(is_qnan_f16(snan_bits)) - - self.assertTrue(is_nan_f16(qnan_bits)) - self.assertTrue(is_qnan_f16(qnan_bits)) - self.assertFalse(is_snan_f16(qnan_bits)) - - subnorm_bits = 0x0001 - self.assertTrue(is_subnormal_f16(subnorm_bits)) - self.assertFalse(is_subnormal_f16(POS_ZERO_F16)) - self.assertFalse(is_subnormal_f16(f16_to_bits(1.0))) - - def test_exact_finite_addition(self) -> None: - # lo: 1.5 + 2.5 = 4.0; hi: 0.25 + 0.75 = 1.0 - s0 = pack_2xf16(f16_to_bits(1.5), f16_to_bits(0.25)) - s1 = pack_2xf16(f16_to_bits(2.5), f16_to_bits(0.75)) - res = oracle_v_pk_add_f16(s0, s1) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(bits_to_f16(r_lo), 4.0) - self.assertEqual(bits_to_f16(r_hi), 1.0) - - def test_signed_zero_rules(self) -> None: - self.assertEqual(oracle_add_f16(POS_ZERO_F16, POS_ZERO_F16), POS_ZERO_F16) - self.assertEqual(oracle_add_f16(NEG_ZERO_F16, NEG_ZERO_F16), NEG_ZERO_F16) - self.assertEqual(oracle_add_f16(POS_ZERO_F16, NEG_ZERO_F16), POS_ZERO_F16) - self.assertEqual(oracle_add_f16(NEG_ZERO_F16, POS_ZERO_F16), POS_ZERO_F16) - self.assertEqual(oracle_add_f16(f16_to_bits(5.0), f16_to_bits(-5.0)), POS_ZERO_F16) - - def test_input_modifiers_abs_neg(self) -> None: - val_pos = f16_to_bits(4.0) - val_neg = f16_to_bits(-4.0) - s0 = pack_2xf16(val_neg, val_pos) - s1 = pack_2xf16(f16_to_bits(2.0), f16_to_bits(2.0)) - - # lo: |-4.0| + 2.0 = 6.0; hi: -(4.0) + 2.0 = -2.0 - res = oracle_v_pk_add_f16( - s0, s1, - abs_lo=(True, False), - neg_hi=(True, False), - ) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(bits_to_f16(r_lo), 6.0) - self.assertEqual(bits_to_f16(r_hi), -2.0) - - def test_op_sel_cross_and_broadcast(self) -> None: - # s0 = [lo: 10.0, hi: 20.0], s1 = [lo: 1.0, hi: 2.0] - s0 = pack_2xf16(f16_to_bits(10.0), f16_to_bits(20.0)) - s1 = pack_2xf16(f16_to_bits(1.0), f16_to_bits(2.0)) - - # Cross add: lo uses s0.hi + s1.lo (20 + 1 = 21), hi uses s0.lo + s1.hi (10 + 2 = 12) - res_cross = oracle_v_pk_add_f16(s0, s1, op_sel=(1, 0), op_sel_hi=(0, 1)) - r_lo, r_hi = unpack_2xf16(res_cross) - self.assertEqual(bits_to_f16(r_lo), 21.0) - self.assertEqual(bits_to_f16(r_hi), 12.0) - - # Broadcast hi: lo and hi both use s0.hi + s1.hi (20 + 2 = 22) - res_bcast = oracle_v_pk_add_f16(s0, s1, op_sel=(1, 1), op_sel_hi=(1, 1)) - b_lo, b_hi = unpack_2xf16(res_bcast) - self.assertEqual(bits_to_f16(b_lo), 22.0) - self.assertEqual(bits_to_f16(b_hi), 22.0) - - def test_clamp_modifier(self) -> None: - # lo: 0.5 + 0.8 = 1.3 -> clamped to 1.0 - # hi: -1.0 + 0.4 = -0.6 -> clamped to 0.0 - s0 = pack_2xf16(f16_to_bits(0.5), f16_to_bits(-1.0)) - s1 = pack_2xf16(f16_to_bits(0.8), f16_to_bits(0.4)) - res = oracle_v_pk_add_f16(s0, s1, clamp=True) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo, ONE_F16) - self.assertEqual(r_hi, POS_ZERO_F16) - - def test_infinity_and_nan_addition(self) -> None: - self.assertEqual(oracle_add_f16(POS_INF_F16, f16_to_bits(1.0)), POS_INF_F16) - self.assertEqual(oracle_add_f16(NEG_INF_F16, f16_to_bits(1.0)), NEG_INF_F16) - self.assertEqual(oracle_add_f16(POS_INF_F16, NEG_INF_F16), CANONICAL_QNAN_F16) - - snan = 0x7C05 - res_nan = oracle_add_f16(snan, f16_to_bits(1.0)) - self.assertTrue(is_qnan_f16(res_nan)) - self.assertEqual(res_nan, snan | QNAN_BIT_F16) - - # Clamping NaN yields +0.0 - res_clamped_nan = oracle_add_f16(snan, f16_to_bits(1.0), clamp=True) - self.assertEqual(res_clamped_nan, POS_ZERO_F16) - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_reg32_validation_and_naming(self) -> None: - v0 = Reg32(0, RegType.VGPR) - self.assertEqual(v0.name, "v0") - self.assertEqual(v0.index, 0) - - s15 = Reg32(15, RegType.SGPR) - self.assertEqual(s15.name, "s15") - self.assertEqual(s15.index, 15) - - with self.assertRaises(ValueError): - Reg32(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(-1, RegType.VGPR) - - def test_literal32_representation(self) -> None: - lit = Literal32.from_floats(1.0, 2.0) - self.assertAlmostEqual(lit.lo_float, 1.0) - self.assertAlmostEqual(lit.hi_float, 2.0) - self.assertTrue(lit.name.startswith("0x")) - - def test_vop3p_operand_disassembly(self) -> None: - v1 = Reg32(1, RegType.VGPR) - op_plain = VOP3POperand(v1) - self.assertEqual(op_plain.disassemble(), "v1") - - op_mods = VOP3POperand(v1, op_sel_lo=1, op_sel_hi=0, neg_lo=True, abs_hi=True) - self.assertIn("abs:[0,1]", op_mods.disassemble()) - self.assertIn("neg:[1,0]", op_mods.disassemble()) - self.assertIn("op_sel:[1,0]", op_mods.disassemble()) - - with self.assertRaises(ValueError): - VOP3POperand(v1, op_sel_lo=2) - - def test_v_pk_add_f16_instruction_ast(self) -> None: - dst = Reg32(0, RegType.VGPR) - src0 = VOP3POperand(Reg32(2, RegType.VGPR), neg_lo=True) - src1 = VOP3POperand(Reg32(4, RegType.SGPR)) - instr = VPkAddF16Instruction(dst=dst, src0=src0, src1=src1, clamp=True) - dis = instr.disassemble() - self.assertTrue(dis.startswith("v_pk_add_f16 v0, v2 neg:[1,0], s4 clamp")) - - # Destination must be VGPR - with self.assertRaises(TypeError): - VPkAddF16Instruction(dst=Reg32(0, RegType.SGPR), src0=src0, src1=src1) - - def test_structural_equality(self) -> None: - i1 = VPkAddF16Instruction( - Reg32(0, RegType.VGPR), - VOP3POperand(Reg32(1, RegType.VGPR)), - VOP3POperand(Literal32(0)), - ) - i2 = VPkAddF16Instruction( - Reg32(0, RegType.VGPR), - VOP3POperand(Reg32(1, RegType.VGPR)), - VOP3POperand(Literal32(0)), - ) - self.assertEqual(i1, i2) - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_scalar_vgpr_vgpr_addition(self) -> None: - # v2 = [lo: 2.0, hi: 3.0], v4 = [lo: 0.5, hi: 1.5] - s0 = pack_2xf16(f16_to_bits(2.0), f16_to_bits(3.0)) - s1 = pack_2xf16(f16_to_bits(0.5), f16_to_bits(1.5)) - self.state.set_vgpr(2, s0) - self.state.set_vgpr(4, s1) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(2, RegType.VGPR)), - src1=VOP3POperand(Reg32(4, RegType.VGPR)), - ) - res = self.interp.step(instr, self.state) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(bits_to_f16(r_lo), 2.5) - self.assertEqual(bits_to_f16(r_hi), 4.5) - self.assertEqual(self.state.get_vgpr(0), res) - - def test_scalar_vgpr_sgpr_addition(self) -> None: - # v1 = [10.0, 20.0], s8 = [1.0, 2.0] - self.state.set_vgpr(1, pack_2xf16(f16_to_bits(10.0), f16_to_bits(20.0))) - self.state.set_sgpr(8, pack_2xf16(f16_to_bits(1.0), f16_to_bits(2.0))) - - instr = VPkAddF16Instruction( - dst=Reg32(3, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(8, RegType.SGPR)), - ) - res = self.interp.step(instr, self.state) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(bits_to_f16(r_lo), 11.0) - self.assertEqual(bits_to_f16(r_hi), 22.0) - self.assertEqual(self.state.get_vgpr(3), res) - - def test_scalar_vgpr_literal_addition(self) -> None: - self.state.set_vgpr(5, pack_2xf16(f16_to_bits(5.0), f16_to_bits(15.0))) - lit = Literal32.from_floats(2.0, 3.0) - - instr = VPkAddF16Instruction( - dst=Reg32(6, RegType.VGPR), - src0=VOP3POperand(Reg32(5, RegType.VGPR)), - src1=VOP3POperand(lit), - ) - res = self.interp.step(instr, self.state) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(bits_to_f16(r_lo), 7.0) - self.assertEqual(bits_to_f16(r_hi), 18.0) - self.assertEqual(self.state.get_vgpr(6), res) - - def test_scalar_with_modifiers_and_clamp(self) -> None: - # v0 = [lo: -0.5, hi: 1.2], v2 = [lo: 0.2, hi: 0.3] - # lo: -|-0.5| + 0.2 = -0.5 + 0.2 = -0.3 -> clamped to +0.0 - # hi: 1.2 + 0.3 = 1.5 -> clamped to 1.0 - self.state.set_vgpr(0, pack_2xf16(f16_to_bits(-0.5), f16_to_bits(1.2))) - self.state.set_vgpr(2, pack_2xf16(f16_to_bits(0.2), f16_to_bits(0.3))) - - instr = VPkAddF16Instruction( - dst=Reg32(4, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR), abs_lo=True, neg_lo=True), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - clamp=True, - ) - res = self.interp.step(instr, self.state) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo, POS_ZERO_F16) - self.assertEqual(r_hi, ONE_F16) - - def test_scalar_determinism(self) -> None: - runs = [] - for _ in range(30): - st = ScalarMachineState() - st.set_vgpr(0, pack_2xf16(0x3C00, 0x4000)) - st.set_vgpr(1, pack_2xf16(0x3800, 0x4200)) - instr = VPkAddF16Instruction( - dst=Reg32(2, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - runs.append(self.interp.step(instr, st)) - self.assertTrue(all(r == runs[0] for r in runs)) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD execution, lane divergence, and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.interp = SIMDInterpreter() - - def test_wave32_full_exec(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - s0 = pack_2xf16(f16_to_bits(float(lane)), f16_to_bits(float(lane) * 2.0)) - s1 = pack_2xf16(f16_to_bits(1.0), f16_to_bits(2.0)) - state.set_vgpr(lane, 0, s0) - state.set_vgpr(lane, 1, s1) - - instr = VPkAddF16Instruction( - dst=Reg32(2, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - self.assertIsNotNone(results[lane]) - r_lo, r_hi = unpack_2xf16(state.get_vgpr(lane, 2)) - self.assertEqual(bits_to_f16(r_lo), float(lane) + 1.0) - self.assertEqual(bits_to_f16(r_hi), float(lane) * 2.0 + 2.0) - - def test_wave32_divergent_masking(self) -> None: - sentinel = 0xDEAD_BEEF - state = SIMDState(num_lanes=32, exec_mask=0x5555_5555) # even lanes active - for lane in range(32): - s0 = pack_2xf16(f16_to_bits(float(lane)), f16_to_bits(10.0)) - s1 = pack_2xf16(f16_to_bits(1.0), f16_to_bits(5.0)) - state.set_vgpr(lane, 0, s0) - state.set_vgpr(lane, 1, s1) - state.set_vgpr(lane, 2, sentinel) - - instr = VPkAddF16Instruction( - dst=Reg32(2, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - if lane % 2 == 0: - self.assertIsNotNone(results[lane]) - r_lo, r_hi = unpack_2xf16(state.get_vgpr(lane, 2)) - self.assertEqual(bits_to_f16(r_lo), float(lane) + 1.0) - self.assertEqual(bits_to_f16(r_hi), 15.0) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr(lane, 2), sentinel) - - def test_wave64_full_exec(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=0xFFFF_FFFF_FFFF_FFFF) - for lane in range(64): - state.set_vgpr(lane, 0, pack_2xf16(f16_to_bits(float(lane)), f16_to_bits(0.5))) - state.set_vgpr(lane, 1, pack_2xf16(f16_to_bits(2.0), f16_to_bits(1.5))) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - self.interp.step(instr, state) - for lane in range(64): - r_lo, r_hi = unpack_2xf16(state.get_vgpr(lane, 0)) - self.assertEqual(bits_to_f16(r_lo), float(lane) + 2.0) - self.assertEqual(bits_to_f16(r_hi), 2.0) - - def test_wave64_half_disabled(self) -> None: - sentinel = 0xCAFE_BABE - state = SIMDState(num_lanes=64, exec_mask=0x0000_0000_FFFF_FFFF) # lower 32 lanes - for lane in range(64): - state.set_vgpr(lane, 0, pack_2xf16(f16_to_bits(4.0), f16_to_bits(6.0))) - state.set_vgpr(lane, 1, pack_2xf16(f16_to_bits(1.0), f16_to_bits(2.0))) - state.set_vgpr(lane, 2, sentinel) - - instr = VPkAddF16Instruction( - dst=Reg32(2, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(64): - if lane < 32: - self.assertIsNotNone(results[lane]) - r_lo, r_hi = unpack_2xf16(state.get_vgpr(lane, 2)) - self.assertEqual(bits_to_f16(r_lo), 5.0) - self.assertEqual(bits_to_f16(r_hi), 8.0) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr(lane, 2), sentinel) - - def test_wave_exec_all_zero(self) -> None: - sentinel = 0x1234_5678 - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) - for lane in range(32): - state.set_vgpr(lane, 0, sentinel) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Literal32.from_floats(1.0, 1.0)), - src1=VOP3POperand(Literal32.from_floats(2.0, 2.0)), - ) - results = self.interp.step(instr, state) - self.assertTrue(all(r is None for r in results)) - for lane in range(32): - self.assertEqual(state.get_vgpr(lane, 0), sentinel) - - def test_simd_sgpr_uniform_broadcast(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - state.set_sgpr(5, pack_2xf16(f16_to_bits(100.0), f16_to_bits(200.0))) - for lane in range(32): - state.set_vgpr(lane, 0, pack_2xf16(f16_to_bits(float(lane)), f16_to_bits(float(lane)))) - - instr = VPkAddF16Instruction( - dst=Reg32(1, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(5, RegType.SGPR)), - ) - self.interp.step(instr, state) - for lane in range(32): - r_lo, r_hi = unpack_2xf16(state.get_vgpr(lane, 1)) - self.assertEqual(bits_to_f16(r_lo), 100.0 + float(lane)) - self.assertEqual(bits_to_f16(r_hi), 200.0 + float(lane)) - - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_dst_alias_src0(self) -> None: - state = ScalarMachineState() - state.set_vgpr(0, pack_2xf16(f16_to_bits(1.5), f16_to_bits(2.5))) - state.set_vgpr(1, pack_2xf16(f16_to_bits(0.5), f16_to_bits(1.0))) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - self.scalar_interp.step(instr, state) - r_lo, r_hi = unpack_2xf16(state.get_vgpr(0)) - self.assertEqual(bits_to_f16(r_lo), 2.0) - self.assertEqual(bits_to_f16(r_hi), 3.5) - # src1 untouched - s1_lo, s1_hi = unpack_2xf16(state.get_vgpr(1)) - self.assertEqual(bits_to_f16(s1_lo), 0.5) - self.assertEqual(bits_to_f16(s1_hi), 1.0) - - def test_dst_alias_src1(self) -> None: - state = ScalarMachineState() - state.set_vgpr(0, pack_2xf16(f16_to_bits(1.5), f16_to_bits(2.5))) - state.set_vgpr(1, pack_2xf16(f16_to_bits(0.5), f16_to_bits(1.0))) - - instr = VPkAddF16Instruction( - dst=Reg32(1, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - self.scalar_interp.step(instr, state) - r_lo, r_hi = unpack_2xf16(state.get_vgpr(1)) - self.assertEqual(bits_to_f16(r_lo), 2.0) - self.assertEqual(bits_to_f16(r_hi), 3.5) - # src0 untouched - s0_lo, s0_hi = unpack_2xf16(state.get_vgpr(0)) - self.assertEqual(bits_to_f16(s0_lo), 1.5) - self.assertEqual(bits_to_f16(s0_hi), 2.5) - - def test_dst_alias_both_srcs(self) -> None: - state = ScalarMachineState() - state.set_vgpr(0, pack_2xf16(f16_to_bits(3.0), f16_to_bits(4.0))) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(0, RegType.VGPR)), - ) - self.scalar_interp.step(instr, state) - r_lo, r_hi = unpack_2xf16(state.get_vgpr(0)) - self.assertEqual(bits_to_f16(r_lo), 6.0) - self.assertEqual(bits_to_f16(r_hi), 8.0) - - def test_inplace_iterative_accumulation(self) -> None: - state = ScalarMachineState() - state.set_vgpr(0, pack_2xf16(f16_to_bits(0.0), f16_to_bits(0.0))) - state.set_vgpr(1, pack_2xf16(f16_to_bits(0.5), f16_to_bits(1.0))) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - for _ in range(40): - self.scalar_interp.step(instr, state) - r_lo, r_hi = unpack_2xf16(state.get_vgpr(0)) - self.assertEqual(bits_to_f16(r_lo), 20.0) - self.assertEqual(bits_to_f16(r_hi), 40.0) - - def test_non_aliased_registers_preserved(self) -> None: - state = ScalarMachineState() - sentinel_v2 = 0x1111_2222 - sentinel_v3 = 0x3333_4444 - state.set_vgpr(0, pack_2xf16(f16_to_bits(1.0), f16_to_bits(1.0))) - state.set_vgpr(1, pack_2xf16(f16_to_bits(2.0), f16_to_bits(2.0))) - state.set_vgpr(2, sentinel_v2) - state.set_vgpr(3, sentinel_v3) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(state.get_vgpr(2), sentinel_v2) - self.assertEqual(state.get_vgpr(3), sentinel_v3) - - def test_simd_multi_lane_aliasing(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_vgpr(lane, 0, pack_2xf16(f16_to_bits(float(lane)), f16_to_bits(1.0))) - state.set_vgpr(lane, 1, pack_2xf16(f16_to_bits(2.0), f16_to_bits(3.0))) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - ) - self.simd_interp.step(instr, state) - for lane in range(32): - r_lo, r_hi = unpack_2xf16(state.get_vgpr(lane, 0)) - self.assertEqual(bits_to_f16(r_lo), float(lane) + 2.0) - self.assertEqual(bits_to_f16(r_hi), 4.0) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for status flags, condition codes, and carry generation.""" - - def test_exact_finite_flags(self) -> None: - s0 = pack_2xf16(f16_to_bits(1.0), f16_to_bits(2.0)) - s1 = pack_2xf16(f16_to_bits(2.0), f16_to_bits(3.0)) - res = oracle_v_pk_add_f16(s0, s1) - flags = evaluate_v_pk_add_f16_flags(s0, s1, res) - - self.assertFalse(flags.lo.invalid) - self.assertFalse(flags.lo.overflow) - self.assertFalse(flags.lo.underflow) - self.assertFalse(flags.lo.inexact) - self.assertFalse(flags.lo.zero) - self.assertFalse(flags.lo.negative) - - self.assertFalse(flags.hi.invalid) - self.assertFalse(flags.hi.overflow) - self.assertFalse(flags.hi.underflow) - self.assertFalse(flags.hi.inexact) - self.assertFalse(flags.hi.zero) - self.assertFalse(flags.hi.negative) - - def test_inexact_flag(self) -> None: - # In half-precision, 1.0 + 2^-11 has a fractional bit beyond 10-bit precision - ulp_half = 2.0 ** -11 - s0 = pack_2xf16(f16_to_bits(1.0), f16_to_bits(0.0)) - s1 = pack_2xf16(f16_to_bits(ulp_half), f16_to_bits(0.0)) - res = oracle_v_pk_add_f16(s0, s1) - flags = evaluate_v_pk_add_f16_flags(s0, s1, res) - self.assertTrue(flags.lo.inexact) - self.assertFalse(flags.hi.inexact) - - def test_overflow_flag(self) -> None: - max_f16 = 0x7BFF # 65504.0 - s0 = pack_2xf16(max_f16, f16_to_bits(1.0)) - s1 = pack_2xf16(max_f16, f16_to_bits(1.0)) - res = oracle_v_pk_add_f16(s0, s1) - flags = evaluate_v_pk_add_f16_flags(s0, s1, res) - self.assertTrue(flags.lo.overflow) - self.assertTrue(flags.lo.infinite) - self.assertTrue(flags.lo.inexact) - self.assertFalse(flags.hi.overflow) - - def test_underflow_and_denorm_flags(self) -> None: - subnorm = 0x0001 - s0 = pack_2xf16(subnorm, f16_to_bits(1.0)) - s1 = pack_2xf16(subnorm, f16_to_bits(1.0)) - res = oracle_v_pk_add_f16(s0, s1) - flags = evaluate_v_pk_add_f16_flags(s0, s1, res) - self.assertTrue(flags.lo.denormal) - self.assertTrue(flags.lo.underflow) - self.assertFalse(flags.hi.denormal) - - def test_invalid_operation_flag(self) -> None: - s0 = pack_2xf16(POS_INF_F16, 0x7C01) # lo: +inf, hi: signaling NaN - s1 = pack_2xf16(NEG_INF_F16, f16_to_bits(1.0)) - res = oracle_v_pk_add_f16(s0, s1) - flags = evaluate_v_pk_add_f16_flags(s0, s1, res) - self.assertTrue(flags.lo.invalid) # +inf + -inf - self.assertTrue(flags.hi.invalid) # signaling NaN - - def test_zero_and_negative_flags(self) -> None: - s0 = pack_2xf16(POS_ZERO_F16, NEG_ZERO_F16) - s1 = pack_2xf16(POS_ZERO_F16, NEG_ZERO_F16) - res = oracle_v_pk_add_f16(s0, s1) - flags = evaluate_v_pk_add_f16_flags(s0, s1, res) - self.assertTrue(flags.lo.zero) - self.assertFalse(flags.lo.negative) - self.assertTrue(flags.hi.zero) - self.assertTrue(flags.hi.negative) - - def test_mantissa_carry_generation(self) -> None: - # 1.0 + 1.0: mantissas 1.000 + 1.000 = 2.000 -> carry_out = 1 - _, carry1 = compute_f16_mantissa_carry(f16_to_bits(1.0), f16_to_bits(1.0)) - self.assertEqual(carry1, 1) - - # 1.0 + 0.25: mantissas sum < 2.0 -> carry_out = 0 - _, carry0 = compute_f16_mantissa_carry(f16_to_bits(1.0), f16_to_bits(0.25)) - self.assertEqual(carry0, 0) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_addition_without_carry(self) -> None: - sub1 = 0x0001 - sub2 = 0x0002 - s0 = pack_2xf16(sub1, sub2) - s1 = pack_2xf16(sub2, sub1) - res = oracle_v_pk_add_f16(s0, s1) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo, 0x0003) - self.assertEqual(r_hi, 0x0003) - self.assertTrue(is_subnormal_f16(r_lo)) - self.assertTrue(is_subnormal_f16(r_hi)) - - def test_subnormal_to_normal_transition(self) -> None: - # Max subnormal: 0x03FF; min subnormal: 0x0001 - # Sum = 0x0400 = min normal (2^-14) - max_sub = 0x03FF - min_sub = 0x0001 - s0 = pack_2xf16(max_sub, min_sub) - s1 = pack_2xf16(min_sub, max_sub) - res = oracle_v_pk_add_f16(s0, s1) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo, 0x0400) - self.assertEqual(r_hi, 0x0400) - self.assertFalse(is_subnormal_f16(r_lo)) - self.assertEqual(split_f16_bits(r_lo)[1], 1) # exponent = 1 - self.assertEqual(split_f16_bits(r_lo)[2], 0) # fraction = 0 - - def test_subnormal_cancellation(self) -> None: - sub = 0x0042 - neg_sub = sub | SIGN_MASK_F16 - s0 = pack_2xf16(sub, neg_sub) - s1 = pack_2xf16(neg_sub, sub) - res = oracle_v_pk_add_f16(s0, s1) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo, POS_ZERO_F16) - self.assertEqual(r_hi, POS_ZERO_F16) - - def test_nan_signaling_to_quiet_conversion(self) -> None: - snan = 0x7C05 # signaling NaN: exp = 0x1F, fraction != 0, quiet bit 9 is 0 - self.assertTrue(is_snan_f16(snan)) - s0 = pack_2xf16(snan, f16_to_bits(1.0)) - s1 = pack_2xf16(f16_to_bits(2.0), snan) - res = oracle_v_pk_add_f16(s0, s1) - r_lo, r_hi = unpack_2xf16(res) - self.assertTrue(is_qnan_f16(r_lo)) - self.assertTrue(is_qnan_f16(r_hi)) - self.assertEqual(r_lo, snan | QNAN_BIT_F16) - self.assertEqual(r_hi, snan | QNAN_BIT_F16) - - def test_nan_payload_preservation(self) -> None: - payload = 0x7E35 # Quiet NaN with payload 0x035 - s0 = pack_2xf16(payload, f16_to_bits(0.0)) - s1 = pack_2xf16(f16_to_bits(5.0), payload) - res = oracle_v_pk_add_f16(s0, s1) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo, payload) - self.assertEqual(r_hi, payload) - - def test_nan_with_modifiers(self) -> None: - qnan = 0x7E01 - # abs should clear sign bit - s0 = pack_2xf16(qnan | SIGN_MASK_F16, qnan) - s1 = pack_2xf16(f16_to_bits(0.0), f16_to_bits(0.0)) - res = oracle_v_pk_add_f16(s0, s1, abs_lo=(True, False), neg_hi=(True, False)) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo & SIGN_MASK_F16, 0) - self.assertEqual(r_hi & SIGN_MASK_F16, SIGN_MASK_F16) - - def test_nan_with_clamp(self) -> None: - qnan = CANONICAL_QNAN_F16 - s0 = pack_2xf16(qnan, qnan) - s1 = pack_2xf16(f16_to_bits(1.0), f16_to_bits(2.0)) - res = oracle_v_pk_add_f16(s0, s1, clamp=True) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo, POS_ZERO_F16) - self.assertEqual(r_hi, POS_ZERO_F16) - - def test_infinity_arithmetic_boundaries(self) -> None: - s0 = pack_2xf16(POS_INF_F16, NEG_INF_F16) - s1 = pack_2xf16(POS_INF_F16, NEG_INF_F16) - res = oracle_v_pk_add_f16(s0, s1) - r_lo, r_hi = unpack_2xf16(res) - self.assertEqual(r_lo, POS_INF_F16) - self.assertEqual(r_hi, NEG_INF_F16) - - # (+inf) + (-inf) -> Canonical NaN - s_cross0 = pack_2xf16(POS_INF_F16, NEG_INF_F16) - s_cross1 = pack_2xf16(NEG_INF_F16, POS_INF_F16) - res_cross = oracle_v_pk_add_f16(s_cross0, s_cross1) - rc_lo, rc_hi = unpack_2xf16(res_cross) - self.assertEqual(rc_lo, CANONICAL_QNAN_F16) - self.assertEqual(rc_hi, CANONICAL_QNAN_F16) - - # Infinity with clamp - res_clamped = oracle_v_pk_add_f16(s0, s1, clamp=True) - rcl_lo, rcl_hi = unpack_2xf16(res_clamped) - self.assertEqual(rcl_lo, ONE_F16) - self.assertEqual(rcl_hi, POS_ZERO_F16) - - def test_round_to_nearest_even_ties(self) -> None: - # 1.0 is 0x3C00 (even LSB) - # 1.0 + 2^-10 is 0x3C01 (odd LSB) - # 2^-11 is halfway between representable numbers - half_ulp = 2.0 ** -11 - one = 1.0 - one_plus_ulp = bits_to_f16(0x3C01) - - # Case 1: 1.0 (even LSB) + 2^-11: tie rounds to even (1.0 = 0x3C00) - res1 = oracle_add_f16(f16_to_bits(one), f16_to_bits(half_ulp)) - self.assertEqual(res1, 0x3C00) - - # Case 2: (1.0 + 2^-10) (odd LSB) + 2^-11: tie rounds to even (1.0 + 2^-9 = 0x3C02) - res2 = oracle_add_f16(f16_to_bits(one_plus_ulp), f16_to_bits(half_ulp)) - self.assertEqual(res2, 0x3C02) - - def test_dual_half_independence(self) -> None: - # lo is NaN, hi is exact finite addition - s0 = pack_2xf16(CANONICAL_QNAN_F16, f16_to_bits(3.0)) - s1 = pack_2xf16(f16_to_bits(1.0), f16_to_bits(4.0)) - res = oracle_v_pk_add_f16(s0, s1) - r_lo, r_hi = unpack_2xf16(res) - self.assertTrue(is_qnan_f16(r_lo)) - self.assertEqual(bits_to_f16(r_hi), 7.0) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and mutation detection.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_negative_control_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Reg32(-1, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(-5, RegType.SGPR) - with self.assertRaises(ValueError): - Reg32(300, RegType.SGPR) - - def test_negative_control_sgpr_destination_rejected(self) -> None: - with self.assertRaises(TypeError): - VPkAddF16Instruction( - dst=Reg32(0, RegType.SGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - ) - - def test_negative_control_invalid_op_sel(self) -> None: - v = Reg32(0, RegType.VGPR) - with self.assertRaises(ValueError): - VOP3POperand(v, op_sel_lo=-1) - with self.assertRaises(ValueError): - VOP3POperand(v, op_sel_hi=2) - - def test_negative_control_invalid_simd_lane_count(self) -> None: - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDState(num_lanes=48) - with self.assertRaises(ValueError): - SIMDState(num_lanes=128) - - def test_negative_control_unsupported_operand_type(self) -> None: - state = ScalarMachineState() - dummy_op = VOP3POperand(source=None) # type: ignore - with self.assertRaises(TypeError): - self.interp.resolve_operand(dummy_op, state) - - def test_mutation_detection_subtraction_vs_addition(self) -> None: - s0 = pack_2xf16(f16_to_bits(10.0), f16_to_bits(20.0)) - s1 = pack_2xf16(f16_to_bits(4.0), f16_to_bits(5.0)) - oracle_res = oracle_v_pk_add_f16(s0, s1) - - # Mutate to subtraction - mutated_lo = f16_to_bits(10.0 - 4.0) - mutated_hi = f16_to_bits(20.0 - 5.0) - mutated_res = pack_2xf16(mutated_lo, mutated_hi) - self.assertNotEqual(oracle_res, mutated_res) - - def test_mutation_detection_clamp_omission(self) -> None: - # Results exceed 1.0 - s0 = pack_2xf16(f16_to_bits(0.8), f16_to_bits(0.9)) - s1 = pack_2xf16(f16_to_bits(0.5), f16_to_bits(0.5)) - clamped_oracle = oracle_v_pk_add_f16(s0, s1, clamp=True) - unclamped = oracle_v_pk_add_f16(s0, s1, clamp=False) - self.assertNotEqual(clamped_oracle, unclamped) - c_lo, c_hi = unpack_2xf16(clamped_oracle) - self.assertEqual(c_lo, ONE_F16) - self.assertEqual(c_hi, ONE_F16) - - def test_mutation_detection_op_sel_swapping(self) -> None: - s0 = pack_2xf16(f16_to_bits(1.0), f16_to_bits(50.0)) - s1 = pack_2xf16(f16_to_bits(2.0), f16_to_bits(100.0)) - res_default = oracle_v_pk_add_f16(s0, s1, op_sel=(0, 0), op_sel_hi=(1, 1)) - res_swapped = oracle_v_pk_add_f16(s0, s1, op_sel=(1, 1), op_sel_hi=(0, 0)) - self.assertNotEqual(res_default, res_swapped) - - def test_mutation_detection_negation_omission(self) -> None: - s0 = pack_2xf16(f16_to_bits(5.0), f16_to_bits(5.0)) - s1 = pack_2xf16(f16_to_bits(2.0), f16_to_bits(2.0)) - res_neg = oracle_v_pk_add_f16(s0, s1, neg_lo=(True, False)) - res_no_neg = oracle_v_pk_add_f16(s0, s1, neg_lo=(False, False)) - self.assertNotEqual(res_neg, res_no_neg) - r_lo, _ = unpack_2xf16(res_neg) - self.assertEqual(bits_to_f16(r_lo), -3.0) # -5.0 + 2.0 = -3.0 - - def test_mutation_detection_nan_quietening_omission(self) -> None: - snan = 0x7C03 - res = oracle_add_f16(snan, f16_to_bits(1.0)) - # Omitting quietening keeps snan untouched, which must diverge from oracle - self.assertNotEqual(res, snan) - self.assertEqual(res, snan | QNAN_BIT_F16) - - def test_mutation_detection_inactive_lane_write(self) -> None: - sentinel = 0x55AA_55AA - state = SIMDState(num_lanes=32, exec_mask=0x0000_0001) # only lane 0 active - for lane in range(32): - state.set_vgpr(lane, 0, sentinel) - - instr = VPkAddF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Literal32.from_floats(1.0, 1.0)), - src1=VOP3POperand(Literal32.from_floats(1.0, 1.0)), - ) - self.simd_interp.step(instr, state) - self.assertNotEqual(state.get_vgpr(0, 0), sentinel) - # Inactive lanes must remain exactly sentinel - for lane in range(1, 32): - self.assertEqual(state.get_vgpr(lane, 0), sentinel) +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import clamp01, ref_add, same_f16 # noqa: E402 + +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF + + +def P(lo, hi): + """A dword holding two binary16 values.""" + return (hi << 16) | lo + + +def run(line, seeds, old=0xDEADBEEF): + """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0 (seeds map reg -> dword).""" + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_pk_add_f16", prog))[0] + + +def half(w, i): + return (w >> (16 * i)) & 0xFFFF + + +def pk_ref(fn, srcs, op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): + """Reference for one packed op: the low result reads half op_sel[i] of source i (negated by neg_lo[i]), the high + result half op_sel_hi[i] (negated by neg_hi[i]); defaults are op_sel 0, op_sel_hi 1, no negation.""" + n = len(srcs) + op_sel, op_sel_hi = op_sel or [0] * n, op_sel_hi or [1] * n + neg_lo, neg_hi = neg_lo or [0] * n, neg_hi or [0] * n + out = [] + for sel, ng in ((op_sel, neg_lo), (op_sel_hi, neg_hi)): + r = fn(*[half(s, h) ^ (0x8000 if g else 0) for s, h, g in zip(srcs, sel, ng)]) + out.append(clamp01(r) if clamp else r) + return P(out[0], out[1]) + + +def same_pk(a, b): + return same_f16(a & 0xFFFF, b & 0xFFFF) and same_f16(a >> 16, b >> 16) + + +def mods_text(op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): + t = "" + for name, v in (("op_sel", op_sel), ("op_sel_hi", op_sel_hi), ("neg_lo", neg_lo), ("neg_hi", neg_hi)): + if v is not None: + t += f" {name}:[{','.join(map(str, v))}]" + return t + (" clamp" if clamp else "") + + +def regs(n): + return ", ".join(f"v{i}" for i in range(1, n + 1)) + + +# mnemonic -> (source count, reference for one lane) +OPS = {"v_pk_add_f16": (2, ref_add)} + +# mnemonic -> rows of (source dwords..., D), written by hand; lane 0 is the low half +CASES = { + 'v_pk_add_f16': [ + (P(ONE, TWO), P(TWO, THREE), P(THREE, 0x4500)), # (1 + 2, 2 + 3) = (3, 5) + (P(HALF, 0x8000), P(QUARTER, 0x8000), P(0x3A00, 0x8000)), # (0.5 + 0.25, -0 + -0) = (0.75, -0) + (P(MAXH, ONE), P(MAXH, MIN_SUB), P(INF, ONE)), # lanes are independent: overflow / 1 + 2^-24 = 1 + (P(0x3E00, INF), P(0xBE00, NINF), P(0x0000, QNAN)), # (1.5 - 1.5 = +0, inf + -inf = NaN) + (P(MIN_NORMAL, 0x6800), P(0x8001, ONE), P(MAX_SUB, 0x6800)), # (2^-14 - 2^-24 = largest subnormal, 2048 + 1 ties to even) + (P(ONE, 0x6801), P(0x1000, ONE), P(ONE, 0x6802)), # (1 + 2^-11 ties to 1, 2050 + 1 ties to 2052) + (P(0x8000, 0x0000), P(0x0000, 0x8000), P(0x0000, 0x0000)), # (-0 + +0, +0 + -0) = (+0, +0) + (P(MIN_SUB, 0xFBFF), P(MIN_SUB, 0xFBFF), P(0x0002, NINF)), # (2^-23, -65504 * 2 overflows) + ], + +} + +# mnemonic -> (sources, modifier text, D), by hand. S0 = (1.0, 3.0), S1 = (0.5, -0.25), S2 = (0.25, -1.0) as +# (low, high) halves. +S0, S1, S2 = P(ONE, THREE), P(HALF, 0xB400), P(QUARTER, 0xBC00) +MODS = { + 'v_pk_add_f16': [ + ((S0, S1), "", P(0x3E00, 0x4180)), # (1 + 0.5, 3 - 0.25) = (1.5, 2.75) + ((S0, S1), " op_sel:[1,0]", P(0x4300, 0x4180)), # low: S0.hi + S1.lo = 3.5 + ((S0, S1), " op_sel:[0,1] op_sel_hi:[0,0]", P(0x3A00, 0x3E00)), # low: 1 + -0.25 = 0.75; high: 1 + 0.5 + ((S0, S1), " op_sel:[1,1] op_sel_hi:[0,0]", P(0x4180, 0x3E00)), # low: 3 + -0.25 = 2.75; high: 1 + 0.5 + ((S0, S1), " neg_lo:[1,0]", P(0xB800, 0x4180)), # low: -1 + 0.5 + ((S0, S1), " neg_hi:[0,1]", P(0x3E00, 0x4280)), # high: 3 - -0.25 = 3.25 + ((S0, S1), " neg_lo:[1,1] neg_hi:[1,1]", P(0xBE00, 0xC180)), # both negated: (-1.5, -2.75) + ((P(0x3E00, 0xBC00), P(HALF, QUARTER)), " clamp", P(ONE, 0x0000)), # (2.0, -0.75) -> (1, 0) + ((P(HALF, QUARTER), P(QUARTER, QUARTER)), " clamp", P(0x3A00, HALF)), # inside [0, 1]: unchanged + ], + +} + + +class PkAddF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for op, rows in CASES.items(): + for *src, want in rows: + with self.subTest(op=op, src=[hex(s) for s in src]): + self.assertTrue(same_pk(pk_ref(OPS[op][1], src), want), hex(pk_ref(OPS[op][1], src))) + + def test_per_lane_results(self): + for op, rows in CASES.items(): + for *src, want in rows: + with self.subTest(op=op, src=[hex(s) for s in src]): + got = run(f"{op} v0, {regs(len(src))}", {f"v{i}": s for i, s in enumerate(src, 1)}) + self.assertTrue(same_pk(got, want), hex(got)) + + def test_sgpr_sources(self): + for op, rows in CASES.items(): + for *src, want in rows[:6]: + n = len(src) + forms = [("all sgpr", ", ".join(f"s{i}" for i in range(1, n + 1)), {f"s{i}": s for i, s in enumerate(src, 1)}), + ("sgpr src0", ", ".join(["s1"] + [f"v{i}" for i in range(2, n + 1)]), + {"s1": src[0], **{f"v{i}": s for i, s in enumerate(src[1:], 2)}})] + for form, text, seeds in forms: + with self.subTest(op=op, src=[hex(s) for s in src], form=form): + self.assertTrue(same_pk(run(f"{op} v0, {text}", seeds), want)) + + def test_hand_written_modifier_cases(self): + for op, rows in MODS.items(): + for srcs, mods, want in rows: + with self.subTest(op=op, mods=mods): + got = run(f"{op} v0, {regs(len(srcs))}{mods}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, want), hex(got)) + + def test_every_op_sel_and_op_sel_hi_combination(self): + a, b, c = P(0x3E00, 0xC400), P(0x4900, 0x3A00), P(0xB800, 0x4D00) # distinct halves: 1.5/-4, 10/.75, -.5/20 + for op, (n, fn) in OPS.items(): + srcs = [a, b, c][:n] + for sel in range(1 << n): + for selhi in range(1 << n): + os_, oh = [(sel >> i) & 1 for i in range(n)], [(selhi >> i) & 1 for i in range(n)] + with self.subTest(op=op, op_sel=os_, op_sel_hi=oh): + got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh)), hex(got)) + + def test_random_operands_and_modifiers(self): + rng = random.Random(0xADD2) + pool = [0x0000, 0x8000, ONE, 0xBC00, TWO, HALF, THREE, MAXH, 0xFBFF, INF, NINF, QNAN, MIN_NORMAL, MIN_SUB, + 0x8001, MAX_SUB, 0x3C01, 0x6800, 0x6801, 0x4C00, 0x1000, 0x9000] + for _ in range(150): + op = rng.choice(sorted(OPS)) + n, fn = OPS[op] + srcs = [P(*[rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(2)]) + for _ in range(n)] + os_, oh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] + nl, nh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] + with self.subTest(op=op, src=[hex(s) for s in srcs], mods=(os_, oh, nl, nh)): + got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh, nl, nh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh, nl, nh)), hex(got)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_pk_fma_f16.py b/tests/semantic/test_valu_pk_fma_f16.py index e5d30942f..c8d2f2617 100644 --- a/tests/semantic/test_valu_pk_fma_f16.py +++ b/tests/semantic/test_valu_pk_fma_f16.py @@ -1,1800 +1,164 @@ -from __future__ import annotations +"""v_pk_fma_f16 (RDNA2 VOP3P): D.f16[i] = S0.f16[i] * S1.f16[i] + S2.f16[i] for both halves, one rounding per half. -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_pk_fma_f16. - -Tests the packed 16-bit floating-point fused multiply-add instruction: - v_pk_fma_f16 D, S0, S1, S2 [op_sel] [op_sel_hi] [neg_lo] [neg_hi] [clamp] -Architecture: VOP3P (GFX10 / RDNA2). -Lowered semantics: - D.lo = (S0_selected_lo * S1_selected_lo) + S2_selected_lo - D.hi = (S0_selected_hi * S1_selected_hi) + S2_selected_hi -where: - - op_sel[i] selects source half for lo computation (0 = lo half [15:0], 1 = hi half [31:16]) - - op_sel_hi[i] selects source half for hi computation (0 = lo half [15:0], 1 = hi half [31:16]) - - neg_lo[i] negates operand i for lo computation - - neg_hi[i] negates operand i for hi computation - - clamp saturates each 16-bit result to [0.0, 1.0], with NaN clamped to +0.0 -Each lane computes fused multiply-add with single rounding per IEEE 754-2008 binary16. +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py. The expected +words are written down by hand (from the ISA) next to each case; the plain-Python binary16 reference in +tests/semantic/f16_ref.py rechecks them lane by lane and drives seeded random operands and modifier combinations. +Covers per-lane results, op_sel / op_sel_hi half selection, neg_lo / neg_hi, clamp and SGPR sources. +Standard library only: no GPU, no LLVM, no game data. """ - -from dataclasses import dataclass, field -from enum import Enum, auto -from fractions import Fraction -import math -import struct +import os +import random +import sys import unittest -from typing import Dict, List, Optional, Tuple, Union -# ============================================================================== -# IEEE 754 binary16 (Half-Precision) Architectural Constants -# ============================================================================== +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import clamp01, ref_fma, same_f16 # noqa: E402 -MASK16: int = 0xFFFF -MASK32: int = 0xFFFF_FFFF - -SIGN_MASK16: int = 0x8000 -EXP_MASK16: int = 0x7C00 -FRAC_MASK16: int = 0x03FF -QNAN_BIT16: int = 0x0200 - -# Canonical and special binary16 values -POS_ZERO: int = 0x0000 # +0.0 -NEG_ZERO: int = 0x8000 # -0.0 -POS_ONE: int = 0x3C00 # +1.0 -NEG_ONE: int = 0xBC00 # -1.0 -POS_HALF: int = 0x3800 # +0.5 -NEG_HALF: int = 0xB800 # -0.5 -POS_TWO: int = 0x4000 # +2.0 -NEG_TWO: int = 0xC000 # -2.0 -POS_INF: int = 0x7C00 # +inf -NEG_INF: int = 0xFC00 # -inf -QNAN_CANONICAL: int = 0x7E00 # Canonical quiet NaN -SNAN_DEFAULT: int = 0x7D00 # Signaling NaN default -NEG_QNAN: int = 0xFE00 # Negative quiet NaN - -# Subnormal (denormal) binary16 constants -POS_MIN_SUBNORM: int = 0x0001 # +2^-24, smallest positive subnormal -POS_MAX_SUBNORM: int = 0x03FF # largest positive subnormal ((1023/1024) * 2^-14) -NEG_MIN_SUBNORM: int = 0x8001 # -2^-24, smallest negative subnormal -NEG_MAX_SUBNORM: int = 0x83FF # largest negative subnormal - -# Normal binary16 boundaries -POS_MIN_NORMAL: int = 0x0400 # +2^-14, smallest positive normal -POS_MAX_NORMAL: int = 0x7BFF # +65504.0, largest finite binary16 -NEG_MAX_NORMAL: int = 0xFBFF # -65504.0, largest negative finite binary16 - - -# ============================================================================== -# Bit Manipulation and Conversion Utilities -# ============================================================================== - -def f16_to_bits(val: float) -> int: - """Convert a Python float to an IEEE 754 binary16 16-bit integer.""" - if math.isnan(val): - return QNAN_CANONICAL - try: - return struct.unpack(" 0 else NEG_INF - - -def bits_to_f16(bits: int) -> float: - """Convert an IEEE 754 binary16 16-bit integer to a Python float.""" - return struct.unpack(" Tuple[int, int]: - """Unpack a 32-bit dword into two 16-bit half words (lo, hi).""" - lo = packed & MASK16 - hi = (packed >> 16) & MASK16 - return lo, hi - - -def pack_pk_f16(lo: int, hi: int) -> int: - """Pack two 16-bit half words (lo, hi) into a single 32-bit dword.""" - return ((hi & MASK16) << 16) | (lo & MASK16) - - -def split_f16_bits(bits: int) -> Tuple[int, int, int]: - """Split 16-bit float bits into (sign, exponent, fraction).""" - b = bits & MASK16 - sign = (b >> 15) & 1 - exp = (b >> 10) & 0x1F - frac = b & FRAC_MASK16 - return sign, exp, frac - - -def is_nan16(bits: int) -> bool: - """Check if 16-bit word represents an IEEE 754 binary16 NaN.""" - return ((bits & EXP_MASK16) == EXP_MASK16) and ((bits & FRAC_MASK16) != 0) - - -def is_qnan16(bits: int) -> bool: - """Check if 16-bit word represents a Quiet NaN.""" - return is_nan16(bits) and bool(bits & QNAN_BIT16) - - -def is_snan16(bits: int) -> bool: - """Check if 16-bit word represents a Signaling NaN.""" - return is_nan16(bits) and not bool(bits & QNAN_BIT16) - - -def is_inf16(bits: int) -> bool: - """Check if 16-bit word represents positive or negative infinity.""" - return ((bits & EXP_MASK16) == EXP_MASK16) and ((bits & FRAC_MASK16) == 0) - - -def is_subnormal16(bits: int) -> bool: - """Check if 16-bit word represents a subnormal (denormal) half-float.""" - return ((bits & EXP_MASK16) == 0) and ((bits & FRAC_MASK16) != 0) - - -def is_zero16(bits: int) -> bool: - """Check if 16-bit word represents positive or negative zero.""" - return (bits & ~SIGN_MASK16) == 0 - - -def apply_f16_modifiers(bits: int, abs_mod: bool = False, neg_mod: bool = False) -> int: - """Apply half-float input modifiers (abs, neg).""" - res = bits & MASK16 - if abs_mod: - res &= ~SIGN_MASK16 - if neg_mod: - res ^= SIGN_MASK16 - return res - - -def apply_f16_clamp(val: float) -> float: - """Apply RDNA2 clamp modifier [0.0, 1.0] to float, mapping NaNs to +0.0.""" - if math.isnan(val): - return 0.0 - if val < 0.0: - return 0.0 - if val > 1.0: - return 1.0 - return val - - -# ============================================================================== -# Reference Mathematical Oracles for Scalar & Packed f16 FMA -# ============================================================================== - -def raw_fma_f16_float(v0: float, v1: float, v2: float) -> float: - """Compute fused multiply-add (v0 * v1) + v2 with exact mathematical single rounding.""" - if math.isnan(v0) or math.isnan(v1) or math.isnan(v2): - return math.nan - - if (math.isinf(v0) and v1 == 0.0) or (v0 == 0.0 and math.isinf(v1)): - return math.nan - - p_inf = math.isinf(v0) or math.isinf(v1) - if p_inf: - p_sign = -1.0 if (math.copysign(1.0, v0) * math.copysign(1.0, v1) < 0) else 1.0 - if math.isinf(v2): - v2_sign = math.copysign(1.0, v2) - if p_sign != v2_sign: - return math.nan - return math.copysign(float("inf"), p_sign) - - if math.isinf(v2): - return v2 - - if v0 == 0.0 or v1 == 0.0: - prod_sign = -1.0 if (math.copysign(1.0, v0) * math.copysign(1.0, v1) < 0) else 1.0 - if v2 == 0.0: - v2_sign = math.copysign(1.0, v2) - if prod_sign < 0 and v2_sign < 0: - return -0.0 - return 0.0 - return v2 - - # High precision exact arithmetic for single rounding to binary16 - frac = Fraction(v0) * Fraction(v1) + Fraction(v2) - if frac == 0: - return 0.0 - try: - return float(frac) - except OverflowError: - return math.copysign(float("inf"), 1.0 if frac > 0 else -1.0) - - -def compute_scalar_fma_f16_bits( - s0_bits: int, - s1_bits: int, - s2_bits: int, - clamp: bool = False, -) -> int: - """Compute exact IEEE 754 binary16 FMA on 16-bit integer patterns.""" - # Check for signaling NaNs first -> quieten - if is_snan16(s0_bits): - return (s0_bits | QNAN_BIT16) if not clamp else POS_ZERO - if is_snan16(s1_bits): - return (s1_bits | QNAN_BIT16) if not clamp else POS_ZERO - if is_snan16(s2_bits): - return (s2_bits | QNAN_BIT16) if not clamp else POS_ZERO - - # Quiet NaNs propagate payload - if is_qnan16(s0_bits): - return s0_bits if not clamp else POS_ZERO - if is_qnan16(s1_bits): - return s1_bits if not clamp else POS_ZERO - if is_qnan16(s2_bits): - return s2_bits if not clamp else POS_ZERO - - v0 = bits_to_f16(s0_bits) - v1 = bits_to_f16(s1_bits) - v2 = bits_to_f16(s2_bits) - - res_f = raw_fma_f16_float(v0, v1, v2) - - if clamp: - res_f = apply_f16_clamp(res_f) - if math.isnan(res_f): - return POS_ZERO - - return f16_to_bits(res_f) - - -def oracle_v_pk_fma_f16( - src0_bits: int, - src1_bits: int, - src2_bits: int, - op_sel: Tuple[int, int, int] = (0, 0, 0), - op_sel_hi: Tuple[int, int, int] = (1, 1, 1), - neg_lo: Tuple[int, int, int] = (0, 0, 0), - neg_hi: Tuple[int, int, int] = (0, 0, 0), - clamp: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_pk_fma_f16 packed instruction.""" - s0_lo, s0_hi = unpack_pk_f16(src0_bits) - s1_lo, s1_hi = unpack_pk_f16(src1_bits) - s2_lo, s2_hi = unpack_pk_f16(src2_bits) - - # Route low-half inputs according to op_sel and neg_lo - in0_lo = apply_f16_modifiers(s0_hi if op_sel[0] else s0_lo, neg_mod=bool(neg_lo[0])) - in1_lo = apply_f16_modifiers(s1_hi if op_sel[1] else s1_lo, neg_mod=bool(neg_lo[1])) - in2_lo = apply_f16_modifiers(s2_hi if op_sel[2] else s2_lo, neg_mod=bool(neg_lo[2])) - - # Route high-half inputs according to op_sel_hi and neg_hi - in0_hi = apply_f16_modifiers(s0_hi if op_sel_hi[0] else s0_lo, neg_mod=bool(neg_hi[0])) - in1_hi = apply_f16_modifiers(s1_hi if op_sel_hi[1] else s1_lo, neg_mod=bool(neg_hi[1])) - in2_hi = apply_f16_modifiers(s2_hi if op_sel_hi[2] else s2_lo, neg_mod=bool(neg_hi[2])) - - res_lo = compute_scalar_fma_f16_bits(in0_lo, in1_lo, in2_lo, clamp=clamp) - res_hi = compute_scalar_fma_f16_bits(in0_hi, in1_hi, in2_hi, clamp=clamp) - - return pack_pk_f16(res_lo, res_hi) - - -# ============================================================================== -# Architectural Register Model -# ============================================================================== - -class PackedVGPR: - """Architectural model of a 32-bit VGPR storing two packed binary16 floats.""" - - def __init__(self, lo: int = 0, hi: int = 0) -> None: - self.lo = lo & MASK16 - self.hi = hi & MASK16 - - @classmethod - def from_u32(cls, val: int) -> PackedVGPR: - lo, hi = unpack_pk_f16(val) - return cls(lo, hi) - - @classmethod - def from_floats(cls, lo_f: float, hi_f: float) -> PackedVGPR: - return cls(f16_to_bits(lo_f), f16_to_bits(hi_f)) - - @property - def as_u32(self) -> int: - return pack_pk_f16(self.lo, self.hi) - - @property - def lo_float(self) -> float: - return bits_to_f16(self.lo) - - @property - def hi_float(self) -> float: - return bits_to_f16(self.hi) - - def set_u32(self, val: int) -> None: - self.lo, self.hi = unpack_pk_f16(val) - - def __repr__(self) -> str: - return ( - f"PackedVGPR(lo={self.lo:#06x} ({self.lo_float:g}), " - f"hi={self.hi:#06x} ({self.hi_float:g}))" - ) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, PackedVGPR): - return NotImplemented - return self.lo == other.lo and self.hi == other.hi - - -# ============================================================================== -# Phase 1 Unit Tests: Mathematical Oracle & Architectural Model -# ============================================================================== - -class TestPkFmaF16MathematicalOracle(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural register model.""" - - def test_binary16_bit_conversions_and_predicates(self) -> None: - test_vals = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 65504.0, -65504.0] - for val in test_vals: - with self.subTest(val=val): - b = f16_to_bits(val) - rec = bits_to_f16(b) - self.assertEqual(val, rec) - self.assertEqual(math.copysign(1.0, val), math.copysign(1.0, rec)) - - self.assertTrue(is_zero16(POS_ZERO)) - self.assertTrue(is_zero16(NEG_ZERO)) - self.assertFalse(is_zero16(POS_ONE)) - - self.assertTrue(is_inf16(POS_INF)) - self.assertTrue(is_inf16(NEG_INF)) - self.assertFalse(is_inf16(POS_ONE)) - - self.assertTrue(is_subnormal16(POS_MIN_SUBNORM)) - self.assertTrue(is_subnormal16(POS_MAX_SUBNORM)) - self.assertFalse(is_subnormal16(POS_MIN_NORMAL)) - self.assertFalse(is_subnormal16(POS_ZERO)) - - self.assertTrue(is_nan16(QNAN_CANONICAL)) - self.assertTrue(is_qnan16(QNAN_CANONICAL)) - self.assertFalse(is_snan16(QNAN_CANONICAL)) - - self.assertTrue(is_nan16(SNAN_DEFAULT)) - self.assertTrue(is_snan16(SNAN_DEFAULT)) - self.assertFalse(is_qnan16(SNAN_DEFAULT)) - - def test_pack_unpack_pk_f16(self) -> None: - p = pack_pk_f16(POS_ONE, POS_TWO) - self.assertEqual(p, (POS_TWO << 16) | POS_ONE) - lo, hi = unpack_pk_f16(p) - self.assertEqual(lo, POS_ONE) - self.assertEqual(hi, POS_TWO) - - def test_basic_fma_identities_scalar(self) -> None: - # 1.0 * 1.0 + 0.0 == 1.0 - self.assertEqual(compute_scalar_fma_f16_bits(POS_ONE, POS_ONE, POS_ZERO), POS_ONE) - # 2.0 * 3.0 + 4.0 == 10.0 - s3 = f16_to_bits(3.0) - s4 = f16_to_bits(4.0) - s10 = f16_to_bits(10.0) - self.assertEqual(compute_scalar_fma_f16_bits(POS_TWO, s3, s4), s10) - # 0.5 * 2.0 + (-1.0) == 0.0 - self.assertEqual(compute_scalar_fma_f16_bits(POS_HALF, POS_TWO, NEG_ONE), POS_ZERO) - - def test_packed_fma_dual_lane_independence(self) -> None: - # lo: 1.0 * 2.0 + 3.0 = 5.0 - # hi: 2.0 * 4.0 + 1.0 = 9.0 - v0 = pack_pk_f16(POS_ONE, POS_TWO) - v1 = pack_pk_f16(POS_TWO, f16_to_bits(4.0)) - v2 = pack_pk_f16(f16_to_bits(3.0), POS_ONE) - expected_lo = f16_to_bits(5.0) - expected_hi = f16_to_bits(9.0) - res = oracle_v_pk_fma_f16(v0, v1, v2) - r_lo, r_hi = unpack_pk_f16(res) - self.assertEqual(r_lo, expected_lo) - self.assertEqual(r_hi, expected_hi) - - def test_op_sel_and_op_sel_hi_half_selection(self) -> None: - # v0 has lo = 1.0, hi = 2.0 - # v1 has lo = 3.0, hi = 4.0 - # v2 has lo = 0.5, hi = 1.5 - v0 = pack_pk_f16(POS_ONE, POS_TWO) - v1 = pack_pk_f16(f16_to_bits(3.0), f16_to_bits(4.0)) - v2 = pack_pk_f16(POS_HALF, f16_to_bits(1.5)) - - # Default: lo takes (s0.lo * s1.lo + s2.lo) = 1*3 + 0.5 = 3.5 - # hi takes (s0.hi * s1.hi + s2.hi) = 2*4 + 1.5 = 9.5 - res_def = oracle_v_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 1)) - self.assertEqual(unpack_pk_f16(res_def), (f16_to_bits(3.5), f16_to_bits(9.5))) - - # Swapped op_sel: lo takes s0.hi, s1.lo, s2.hi = 2*3 + 1.5 = 7.5 - # Swapped op_sel_hi: hi takes s0.lo, s1.hi, s2.lo = 1*4 + 0.5 = 4.5 - res_swap = oracle_v_pk_fma_f16(v0, v1, v2, op_sel=(1, 0, 1), op_sel_hi=(0, 1, 0)) - self.assertEqual(unpack_pk_f16(res_swap), (f16_to_bits(7.5), f16_to_bits(4.5))) - - def test_neg_lo_and_neg_hi_modifiers(self) -> None: - v0 = pack_pk_f16(POS_ONE, POS_TWO) - v1 = pack_pk_f16(POS_TWO, POS_TWO) - v2 = pack_pk_f16(f16_to_bits(5.0), f16_to_bits(5.0)) - - # lo: -(1.0) * 2.0 + 5.0 = 3.0 - # hi: 2.0 * -(2.0) + 5.0 = 1.0 - res = oracle_v_pk_fma_f16( - v0, v1, v2, - op_sel=(0, 0, 0), op_sel_hi=(1, 1, 1), - neg_lo=(1, 0, 0), neg_hi=(0, 1, 0), - ) - self.assertEqual(unpack_pk_f16(res), (f16_to_bits(3.0), POS_ONE)) - - def test_clamp_modifier(self) -> None: - # lo: 1.0 * 2.0 + 0.0 = 2.0 -> clamp -> 1.0 - # hi: -2.0 * 1.0 + 0.0 = -2.0 -> clamp -> +0.0 - v0 = pack_pk_f16(POS_ONE, NEG_TWO) - v1 = pack_pk_f16(POS_TWO, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2, clamp=True) - self.assertEqual(unpack_pk_f16(res), (POS_ONE, POS_ZERO)) - - def test_signed_zero_identities(self) -> None: - # (+0) * (+0) + (+0) = +0 - res_pz = compute_scalar_fma_f16_bits(POS_ZERO, POS_ZERO, POS_ZERO) - self.assertEqual(res_pz, POS_ZERO) - - # (-0) * (+1) + (-0) = -0 - res_nz = compute_scalar_fma_f16_bits(NEG_ZERO, POS_ONE, NEG_ZERO) - self.assertEqual(res_nz, NEG_ZERO) - - def test_infinity_identities(self) -> None: - # +inf * 1.0 + 0.0 = +inf - self.assertEqual(compute_scalar_fma_f16_bits(POS_INF, POS_ONE, POS_ZERO), POS_INF) - # +inf * 0.0 + 1.0 = NaN - self.assertTrue(is_nan16(compute_scalar_fma_f16_bits(POS_INF, POS_ZERO, POS_ONE))) - # +inf * 1.0 + (-inf) = NaN - self.assertTrue(is_nan16(compute_scalar_fma_f16_bits(POS_INF, POS_ONE, NEG_INF))) - - def test_nan_quietening_and_propagation(self) -> None: - # Signaling NaN quietened to QNaN - res = compute_scalar_fma_f16_bits(SNAN_DEFAULT, POS_ONE, POS_ZERO) - self.assertTrue(is_qnan16(res)) - self.assertEqual(res, SNAN_DEFAULT | QNAN_BIT16) - - def test_architectural_packed_vgpr_model(self) -> None: - reg = PackedVGPR.from_floats(1.5, -2.5) - self.assertAlmostEqual(reg.lo_float, 1.5) - self.assertAlmostEqual(reg.hi_float, -2.5) - u32_val = reg.as_u32 - reg2 = PackedVGPR.from_u32(u32_val) - self.assertEqual(reg, reg2) - self.assertEqual(reg.lo, f16_to_bits(1.5)) - self.assertEqual(reg.hi, f16_to_bits(-2.5)) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - VGPR = auto() - SGPR = auto() - - -@dataclass(frozen=True) -class Reg32: - """Represents a 32-bit architectural register (VGPR or SGPR).""" - index: int - reg_type: RegType - - def __post_init__(self) -> None: - if not (0 <= self.index <= 255): - raise ValueError(f"Register index {self.index} out of range [0, 255]") - - @property - def name(self) -> str: - prefix = "v" if self.reg_type == RegType.VGPR else "s" - return f"{prefix}{self.index}" - - -@dataclass(frozen=True) -class Literal32: - """Represents a 32-bit literal constant (packed f16x2 or raw bits).""" - bits: int - - def __post_init__(self) -> None: - if not (0 <= self.bits <= MASK32): - raise ValueError(f"Literal constant {self.bits:#x} out of range [0, 0xFFFFFFFF]") - - @classmethod - def from_floats(cls, lo: float, hi: float) -> Literal32: - return cls(pack_pk_f16(f16_to_bits(lo), f16_to_bits(hi))) - - @classmethod - def from_bits(cls, lo: int, hi: int) -> Literal32: - return cls(pack_pk_f16(lo, hi)) - - @property - def name(self) -> str: - lo, hi = unpack_pk_f16(self.bits) - return f"[{bits_to_f16(lo):g}, {bits_to_f16(hi):g}] ({self.bits:#010x})" - - -@dataclass(frozen=True) -class VOP3POperand: - """Operand in a VOP3P instruction (Reg32 or Literal32).""" - source: Union[Reg32, Literal32] - - def disassemble(self) -> str: - if isinstance(self.source, Reg32): - return self.source.name - return f"{self.source.bits:#010x}" - - -@dataclass(frozen=True) -class VPkFmaF16Instruction: - """Symbolic AST node representing a RDNA2 v_pk_fma_f16 instruction.""" - dst: Reg32 - src0: VOP3POperand - src1: VOP3POperand - src2: VOP3POperand - op_sel: Tuple[int, int, int] = (0, 0, 0) - op_sel_hi: Tuple[int, int, int] = (1, 1, 1) - neg_lo: Tuple[int, int, int] = (0, 0, 0) - neg_hi: Tuple[int, int, int] = (0, 0, 0) - clamp: bool = False - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination of VALU instruction must be VGPR, got {self.dst.reg_type}") - for name, tup in ( - ("op_sel", self.op_sel), - ("op_sel_hi", self.op_sel_hi), - ("neg_lo", self.neg_lo), - ("neg_hi", self.neg_hi), - ): - if len(tup) != 3: - raise ValueError(f"{name} must have 3 elements, got {len(tup)}") - if any(x not in (0, 1) for x in tup): - raise ValueError(f"{name} elements must be 0 or 1, got {tup}") - - def disassemble(self) -> str: - s = ( - f"v_pk_fma_f16 {self.dst.name}, {self.src0.disassemble()}, " - f"{self.src1.disassemble()}, {self.src2.disassemble()}" - ) - if self.op_sel != (0, 0, 0): - s += f" op_sel:[{self.op_sel[0]},{self.op_sel[1]},{self.op_sel[2]}]" - if self.op_sel_hi != (1, 1, 1): - s += f" op_sel_hi:[{self.op_sel_hi[0]},{self.op_sel_hi[1]},{self.op_sel_hi[2]}]" - if any(self.neg_lo): - s += f" neg_lo:[{self.neg_lo[0]},{self.neg_lo[1]},{self.neg_lo[2]}]" - if any(self.neg_hi): - s += f" neg_hi:[{self.neg_hi[0]},{self.neg_hi[1]},{self.neg_hi[2]}]" - if self.clamp: - s += " clamp" - return s - - -# Typed Expressions for Symbolic Execution -class TypedExpr: - """Abstract base class for typed expressions.""" - def eval(self, env: Dict[str, int]) -> int: - raise NotImplementedError - - -@dataclass(frozen=True) -class VariableExpr(TypedExpr): - """Named variable evaluating to an architectural register or value in env.""" - name: str - - def eval(self, env: Dict[str, int]) -> int: - if self.name not in env: - raise KeyError(f"Variable '{self.name}' not found in environment") - return env[self.name] & MASK32 - - -@dataclass(frozen=True) -class ConstantExpr(TypedExpr): - """Constant 32-bit packed float literal.""" - value: int - - def eval(self, env: Dict[str, int]) -> int: - return self.value & MASK32 - - -@dataclass(frozen=True) -class PackedF16FMAExpr(TypedExpr): - """Symbolic typed expression for packed f16 FMA operation.""" - src0: TypedExpr - src1: TypedExpr - src2: TypedExpr - op_sel: Tuple[int, int, int] = (0, 0, 0) - op_sel_hi: Tuple[int, int, int] = (1, 1, 1) - neg_lo: Tuple[int, int, int] = (0, 0, 0) - neg_hi: Tuple[int, int, int] = (0, 0, 0) - clamp: bool = False - - def eval(self, env: Dict[str, int]) -> int: - v0 = self.src0.eval(env) - v1 = self.src1.eval(env) - v2 = self.src2.eval(env) - return oracle_v_pk_fma_f16( - v0, v1, v2, - op_sel=self.op_sel, - op_sel_hi=self.op_sel_hi, - neg_lo=self.neg_lo, - neg_hi=self.neg_hi, - clamp=self.clamp, - ) - - -class TestPkFmaF16SymbolicAST(unittest.TestCase): - """Test suite for symbolic AST opcode definitions and typed expressions.""" - - def test_reg32_naming_and_bounds(self) -> None: - v0 = Reg32(0, RegType.VGPR) - self.assertEqual(v0.name, "v0") - self.assertEqual(v0.index, 0) - - s255 = Reg32(255, RegType.SGPR) - self.assertEqual(s255.name, "s255") - - with self.assertRaises(ValueError): - Reg32(-1, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(256, RegType.SGPR) - - def test_literal32_representation(self) -> None: - lit = Literal32.from_floats(1.0, 2.0) - self.assertEqual(lit.bits, pack_pk_f16(POS_ONE, POS_TWO)) - self.assertIn("0x40003c00", lit.name) - - with self.assertRaises(ValueError): - Literal32(-1) - with self.assertRaises(ValueError): - Literal32(0x1_0000_0000) - - def test_vop3p_operand_disassembly(self) -> None: - op_v = VOP3POperand(Reg32(5, RegType.VGPR)) - self.assertEqual(op_v.disassemble(), "v5") - - op_s = VOP3POperand(Reg32(12, RegType.SGPR)) - self.assertEqual(op_s.disassemble(), "s12") - - op_lit = VOP3POperand(Literal32.from_floats(1.0, 1.0)) - self.assertEqual(op_lit.disassemble(), f"{pack_pk_f16(POS_ONE, POS_ONE):#010x}") - - def test_instruction_disassembly(self) -> None: - instr_def = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - ) - self.assertEqual(instr_def.disassemble(), "v_pk_fma_f16 v0, v1, v2, v3") - - instr_mods = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.SGPR)), - src2=VOP3POperand(Literal32(0)), - op_sel=(1, 0, 1), - op_sel_hi=(0, 1, 0), - neg_lo=(1, 0, 0), - neg_hi=(0, 1, 1), - clamp=True, - ) - dis = instr_mods.disassemble() - self.assertIn("op_sel:[1,0,1]", dis) - self.assertIn("op_sel_hi:[0,1,0]", dis) - self.assertIn("neg_lo:[1,0,0]", dis) - self.assertIn("neg_hi:[0,1,1]", dis) - self.assertTrue(dis.endswith("clamp")) - - def test_instruction_validation(self) -> None: - v = VOP3POperand(Reg32(1, RegType.VGPR)) - # Destination must be VGPR - with self.assertRaises(TypeError): - VPkFmaF16Instruction(dst=Reg32(0, RegType.SGPR), src0=v, src1=v, src2=v) - - # Invalid tuple lengths - with self.assertRaises(ValueError): - VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), src0=v, src1=v, src2=v, - op_sel=(0, 0), # type: ignore[arg-type] - ) - - # Invalid tuple element values - with self.assertRaises(ValueError): - VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), src0=v, src1=v, src2=v, - neg_lo=(0, 2, 0), - ) - - def test_structural_equality_and_immutability(self) -> None: - v1 = VOP3POperand(Reg32(1, RegType.VGPR)) - v2 = VOP3POperand(Reg32(2, RegType.VGPR)) - v3 = VOP3POperand(Reg32(3, RegType.VGPR)) - i1 = VPkFmaF16Instruction(Reg32(0, RegType.VGPR), v1, v2, v3, clamp=True) - i2 = VPkFmaF16Instruction(Reg32(0, RegType.VGPR), v1, v2, v3, clamp=True) - self.assertEqual(i1, i2) - self.assertEqual(hash(i1), hash(i2)) - - def test_typed_expressions_evaluation(self) -> None: - env = { - "v0": pack_pk_f16(POS_ONE, POS_TWO), - "v1": pack_pk_f16(POS_TWO, POS_TWO), - "v2": pack_pk_f16(POS_HALF, POS_HALF), - } - # expr: v0 * v1 + v2 - # lo: 1*2 + 0.5 = 2.5 - # hi: 2*2 + 0.5 = 4.5 - fma_expr = PackedF16FMAExpr( - src0=VariableExpr("v0"), - src1=VariableExpr("v1"), - src2=VariableExpr("v2"), - ) - res = fma_expr.eval(env) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, f16_to_bits(2.5)) - self.assertEqual(hi, f16_to_bits(4.5)) - - # Test constant expr - const_expr = ConstantExpr(pack_pk_f16(POS_ONE, POS_ONE)) - self.assertEqual(const_expr.eval(env), pack_pk_f16(POS_ONE, POS_ONE)) - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register file for a single wavefront lane.""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def get_vgpr(self, index: int) -> int: - return self.vgprs[index] & MASK32 - - def set_vgpr(self, index: int, val: int) -> None: - self.vgprs[index] = val & MASK32 - - def get_sgpr(self, index: int) -> int: - return self.sgprs[index] & MASK32 - - def set_sgpr(self, index: int, val: int) -> None: - self.sgprs[index] = val & MASK32 - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_pk_fma_f16.""" - - def resolve_operand(self, op: VOP3POperand, state: ScalarMachineState) -> int: - if isinstance(op.source, Reg32): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr(op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal32): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VPkFmaF16Instruction, state: ScalarMachineState) -> int: - # Atomic read phase - s0 = self.resolve_operand(instr.src0, state) - s1 = self.resolve_operand(instr.src1, state) - s2 = self.resolve_operand(instr.src2, state) - - # Computation phase - res = oracle_v_pk_fma_f16( - s0, s1, s2, - op_sel=instr.op_sel, - op_sel_hi=instr.op_sel_hi, - neg_lo=instr.neg_lo, - neg_hi=instr.neg_hi, - clamp=instr.clamp, - ) - - # Write-back phase - state.set_vgpr(instr.dst.index, res) - return res - - -class TestPkFmaF16ScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_scalar_vgpr_sources(self) -> None: - # v1: lo=1.0, hi=2.0 - # v2: lo=3.0, hi=4.0 - # v3: lo=0.5, hi=1.0 - self.state.set_vgpr(1, pack_pk_f16(POS_ONE, POS_TWO)) - self.state.set_vgpr(2, pack_pk_f16(f16_to_bits(3.0), f16_to_bits(4.0))) - self.state.set_vgpr(3, pack_pk_f16(POS_HALF, POS_ONE)) - - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - ) - res = self.interp.step(instr, self.state) - # lo: 1*3 + 0.5 = 3.5 - # hi: 2*4 + 1.0 = 9.0 - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, f16_to_bits(3.5)) - self.assertEqual(hi, f16_to_bits(9.0)) - self.assertEqual(self.state.get_vgpr(0), res) - - def test_scalar_mixed_sources(self) -> None: - # src0 from VGPR, src1 from SGPR, src2 from Literal - self.state.set_vgpr(5, pack_pk_f16(POS_TWO, POS_TWO)) - self.state.set_sgpr(10, pack_pk_f16(f16_to_bits(3.0), f16_to_bits(5.0))) - lit = Literal32.from_floats(1.0, -2.0) - - instr = VPkFmaF16Instruction( - dst=Reg32(4, RegType.VGPR), - src0=VOP3POperand(Reg32(5, RegType.VGPR)), - src1=VOP3POperand(Reg32(10, RegType.SGPR)), - src2=VOP3POperand(lit), - ) - res = self.interp.step(instr, self.state) - # lo: 2*3 + 1.0 = 7.0 - # hi: 2*5 + (-2.0) = 8.0 - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, f16_to_bits(7.0)) - self.assertEqual(hi, f16_to_bits(8.0)) - - def test_scalar_half_selection_and_negation(self) -> None: - self.state.set_vgpr(1, pack_pk_f16(POS_ONE, POS_TWO)) - self.state.set_vgpr(2, pack_pk_f16(f16_to_bits(3.0), f16_to_bits(4.0))) - self.state.set_vgpr(3, pack_pk_f16(f16_to_bits(5.0), f16_to_bits(6.0))) - - # lo uses op_sel (1, 0, 0) -> (s0.hi * s1.lo + s2.lo) = 2*3 + 5 = 11 - # neg_lo (1, 0, 0) -> -(2)*3 + 5 = -1 - # hi uses op_sel_hi (0, 1, 1) -> (s0.lo * s1.hi + s2.hi) = 1*4 + 6 = 10 - # neg_hi (0, 1, 0) -> 1*(-4) + 6 = 2 - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - op_sel=(1, 0, 0), - op_sel_hi=(0, 1, 1), - neg_lo=(1, 0, 0), - neg_hi=(0, 1, 0), - ) - res = self.interp.step(instr, self.state) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, f16_to_bits(-1.0)) - self.assertEqual(hi, f16_to_bits(2.0)) - - def test_scalar_clamp_execution(self) -> None: - # lo: 1.0 * 2.0 + 0.0 = 2.0 -> clamp -> 1.0 - # hi: -1.0 * 2.0 + 0.0 = -2.0 -> clamp -> 0.0 - self.state.set_vgpr(1, pack_pk_f16(POS_ONE, NEG_ONE)) - self.state.set_vgpr(2, pack_pk_f16(POS_TWO, POS_TWO)) - self.state.set_vgpr(3, pack_pk_f16(POS_ZERO, POS_ZERO)) - - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - clamp=True, - ) - res = self.interp.step(instr, self.state) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, POS_ONE) - self.assertEqual(hi, POS_ZERO) - - def test_scalar_determinism(self) -> None: - runs = [] - for _ in range(100): - st = ScalarMachineState() - st.set_vgpr(1, 0x3C004000) - st.set_vgpr(2, 0x38003C00) - st.set_vgpr(3, 0x00003800) - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - ) - runs.append(self.interp.step(instr, st)) - self.assertTrue(all(r == runs[0] for r in runs)) - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - num_lanes: int - exec_mask: Optional[int] = None - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - - def get_vgpr(self, lane: int, index: int) -> int: - return self.vgprs[lane][index] & MASK32 - - def set_vgpr(self, lane: int, index: int, val: int) -> None: - self.vgprs[lane][index] = val & MASK32 - - def get_sgpr(self, index: int) -> int: - return self.sgprs[index] & MASK32 - - def set_sgpr(self, index: int, val: int) -> None: - self.sgprs[index] = val & MASK32 - - -class SIMDInterpreter: - """SIMD instruction interpreter handling multi-lane divergence and EXEC masking.""" - - def resolve_lane_operand(self, op: VOP3POperand, state: SIMDState, lane: int) -> int: - if isinstance(op.source, Reg32): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr(lane, op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal32): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VPkFmaF16Instruction, state: SIMDState) -> List[Optional[int]]: - results: List[Optional[int]] = [None] * state.num_lanes - # Atomic read phase across all lanes - s0_vals = [ - self.resolve_lane_operand(instr.src0, state, lane) - for lane in range(state.num_lanes) - ] - s1_vals = [ - self.resolve_lane_operand(instr.src1, state, lane) - for lane in range(state.num_lanes) - ] - s2_vals = [ - self.resolve_lane_operand(instr.src2, state, lane) - for lane in range(state.num_lanes) - ] - - # Execution phase - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - res = oracle_v_pk_fma_f16( - s0_vals[lane], - s1_vals[lane], - s2_vals[lane], - op_sel=instr.op_sel, - op_sel_hi=instr.op_sel_hi, - neg_lo=instr.neg_lo, - neg_hi=instr.neg_hi, - clamp=instr.clamp, - ) - state.set_vgpr(lane, instr.dst.index, res) - results[lane] = res - - return results - - -class TestPkFmaF16SIMDMultiLane(unittest.TestCase): - """Test suite for SIMD execution, lane divergence, and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.interp = SIMDInterpreter() - - def test_wave32_full_exec(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - # lo: lane * 2.0 + 1.0, hi: (lane + 1) * 1.0 + 2.0 - state.set_vgpr(lane, 1, pack_pk_f16(f16_to_bits(float(lane)), f16_to_bits(float(lane + 1)))) - state.set_vgpr(lane, 2, pack_pk_f16(POS_TWO, POS_ONE)) - state.set_vgpr(lane, 3, pack_pk_f16(POS_ONE, POS_TWO)) - - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - self.assertIsNotNone(results[lane]) - lo, hi = unpack_pk_f16(state.get_vgpr(lane, 0)) - self.assertEqual(lo, f16_to_bits(float(lane) * 2.0 + 1.0)) - self.assertEqual(hi, f16_to_bits(float(lane + 1) * 1.0 + 2.0)) - - def test_wave32_divergent_masking(self) -> None: - sentinel = 0xDEAD_BEEF - state = SIMDState(num_lanes=32, exec_mask=0x5555_5555) # even lanes active - for lane in range(32): - state.set_vgpr(lane, 1, pack_pk_f16(f16_to_bits(float(lane)), POS_ONE)) - state.set_vgpr(lane, 2, pack_pk_f16(POS_ONE, POS_ONE)) - state.set_vgpr(lane, 3, pack_pk_f16(POS_ZERO, POS_ZERO)) - state.set_vgpr(lane, 4, sentinel) - - instr = VPkFmaF16Instruction( - dst=Reg32(4, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - if lane % 2 == 0: - self.assertIsNotNone(results[lane]) - lo, hi = unpack_pk_f16(state.get_vgpr(lane, 4)) - self.assertEqual(lo, f16_to_bits(float(lane))) - self.assertEqual(hi, POS_ONE) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr(lane, 4), sentinel) - - def test_wave64_full_exec(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=0xFFFF_FFFF_FFFF_FFFF) - for lane in range(64): - state.set_vgpr(lane, 1, pack_pk_f16(POS_ONE, POS_TWO)) - state.set_vgpr(lane, 2, pack_pk_f16(f16_to_bits(float(lane)), POS_ONE)) - state.set_vgpr(lane, 3, pack_pk_f16(POS_ZERO, POS_ZERO)) - - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - ) - self.interp.step(instr, state) - for lane in range(64): - lo, hi = unpack_pk_f16(state.get_vgpr(lane, 0)) - self.assertEqual(lo, f16_to_bits(float(lane))) - self.assertEqual(hi, POS_TWO) - - def test_wave64_half_disabled(self) -> None: - sentinel = 0xCAFE_BABE - state = SIMDState(num_lanes=64, exec_mask=0x0000_0000_FFFF_FFFF) # lanes 0-31 active - for lane in range(64): - state.set_vgpr(lane, 1, pack_pk_f16(POS_TWO, POS_TWO)) - state.set_vgpr(lane, 2, pack_pk_f16(POS_TWO, POS_TWO)) - state.set_vgpr(lane, 3, pack_pk_f16(POS_ONE, POS_ONE)) - state.set_vgpr(lane, 4, sentinel) - - instr = VPkFmaF16Instruction( - dst=Reg32(4, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(3, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(64): - if lane < 32: - self.assertIsNotNone(results[lane]) - lo, hi = unpack_pk_f16(state.get_vgpr(lane, 4)) - # 2*2 + 1 = 5 - self.assertEqual(lo, f16_to_bits(5.0)) - self.assertEqual(hi, f16_to_bits(5.0)) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr(lane, 4), sentinel) - - def test_wave_exec_all_zero(self) -> None: - sentinel = 0xAA55_AA55 - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) - for lane in range(32): - state.set_vgpr(lane, 0, sentinel) - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Literal32.from_floats(1.0, 1.0)), - src1=VOP3POperand(Literal32.from_floats(2.0, 2.0)), - src2=VOP3POperand(Literal32.from_floats(3.0, 3.0)), - ) - results = self.interp.step(instr, state) - self.assertTrue(all(r is None for r in results)) - for lane in range(32): - self.assertEqual(state.get_vgpr(lane, 0), sentinel) - - def test_simd_sgpr_uniform_broadcast(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - # Broadcast SGPR s10 = (10.0, 20.0) - state.set_sgpr(10, pack_pk_f16(f16_to_bits(10.0), f16_to_bits(20.0))) - for lane in range(32): - state.set_vgpr(lane, 1, pack_pk_f16(POS_ONE, POS_ONE)) - state.set_vgpr(lane, 2, pack_pk_f16(f16_to_bits(float(lane)), f16_to_bits(float(lane)))) - - # v0 = v1 * s10 + v2 -> lo: 1.0 * 10.0 + lane, hi: 1.0 * 20.0 + lane - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(10, RegType.SGPR)), - src2=VOP3POperand(Reg32(2, RegType.VGPR)), - ) - self.interp.step(instr, state) - for lane in range(32): - lo, hi = unpack_pk_f16(state.get_vgpr(lane, 0)) - self.assertEqual(lo, f16_to_bits(10.0 + float(lane))) - self.assertEqual(hi, f16_to_bits(20.0 + float(lane))) - - -# ============================================================================== -# Register Aliasing and In-Place Operand Preservation -# ============================================================================== - -class TestPkFmaF16RegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_dst_alias_src0(self) -> None: - state = ScalarMachineState() - # v0 = (2.0, 3.0), v1 = (4.0, 5.0), v2 = (1.0, 2.0) - state.set_vgpr(0, pack_pk_f16(POS_TWO, f16_to_bits(3.0))) - state.set_vgpr(1, pack_pk_f16(f16_to_bits(4.0), f16_to_bits(5.0))) - state.set_vgpr(2, pack_pk_f16(POS_ONE, POS_TWO)) - - # v0 = v0 * v1 + v2 -> lo: 2*4 + 1 = 9.0, hi: 3*5 + 2 = 17.0 - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - src2=VOP3POperand(Reg32(2, RegType.VGPR)), - ) - res = self.scalar_interp.step(instr, state) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, f16_to_bits(9.0)) - self.assertEqual(hi, f16_to_bits(17.0)) - self.assertEqual(state.get_vgpr(0), res) - # Verify src1 and src2 were not mutated - self.assertEqual(state.get_vgpr(1), pack_pk_f16(f16_to_bits(4.0), f16_to_bits(5.0))) - self.assertEqual(state.get_vgpr(2), pack_pk_f16(POS_ONE, POS_TWO)) - - def test_dst_alias_src1(self) -> None: - state = ScalarMachineState() - state.set_vgpr(0, pack_pk_f16(POS_TWO, POS_TWO)) - state.set_vgpr(1, pack_pk_f16(f16_to_bits(3.0), f16_to_bits(4.0))) - state.set_vgpr(2, pack_pk_f16(POS_HALF, POS_HALF)) - - # v1 = v0 * v1 + v2 -> lo: 2*3 + 0.5 = 6.5, hi: 2*4 + 0.5 = 8.5 - instr = VPkFmaF16Instruction( - dst=Reg32(1, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - src2=VOP3POperand(Reg32(2, RegType.VGPR)), - ) - res = self.scalar_interp.step(instr, state) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, f16_to_bits(6.5)) - self.assertEqual(hi, f16_to_bits(8.5)) - self.assertEqual(state.get_vgpr(1), res) - self.assertEqual(state.get_vgpr(0), pack_pk_f16(POS_TWO, POS_TWO)) - - def test_dst_alias_src2(self) -> None: - state = ScalarMachineState() - state.set_vgpr(0, pack_pk_f16(POS_TWO, POS_TWO)) - state.set_vgpr(1, pack_pk_f16(POS_TWO, POS_TWO)) - state.set_vgpr(2, pack_pk_f16(POS_ONE, POS_ONE)) - - # v2 = v0 * v1 + v2 -> lo: 2*2 + 1 = 5.0, hi: 2*2 + 1 = 5.0 - instr = VPkFmaF16Instruction( - dst=Reg32(2, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - src2=VOP3POperand(Reg32(2, RegType.VGPR)), - ) - res = self.scalar_interp.step(instr, state) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, f16_to_bits(5.0)) - self.assertEqual(hi, f16_to_bits(5.0)) - self.assertEqual(state.get_vgpr(2), res) - - def test_dst_alias_all_three_operands(self) -> None: - state = ScalarMachineState() - # v0 = (2.0, 3.0) - # v0 = v0 * v0 + v0 -> lo: 2*2 + 2 = 6.0, hi: 3*3 + 3 = 12.0 - state.set_vgpr(0, pack_pk_f16(POS_TWO, f16_to_bits(3.0))) - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(0, RegType.VGPR)), - src2=VOP3POperand(Reg32(0, RegType.VGPR)), - ) - res = self.scalar_interp.step(instr, state) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, f16_to_bits(6.0)) - self.assertEqual(hi, f16_to_bits(12.0)) - self.assertEqual(state.get_vgpr(0), res) - - def test_inplace_iterative_mac_accumulation(self) -> None: - state = ScalarMachineState() - # v0 accumulator starts at (0.0, 0.0) - state.set_vgpr(0, pack_pk_f16(POS_ZERO, POS_ZERO)) - state.set_vgpr(1, pack_pk_f16(POS_ONE, POS_ONE)) - state.set_vgpr(2, pack_pk_f16(POS_HALF, POS_ONE)) - - # 10 iterations: v0 = v1 * v2 + v0 - # each iteration adds 0.5 to lo and 1.0 to hi - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(1, RegType.VGPR)), - src1=VOP3POperand(Reg32(2, RegType.VGPR)), - src2=VOP3POperand(Reg32(0, RegType.VGPR)), - ) - for _ in range(10): - self.scalar_interp.step(instr, state) - - lo, hi = unpack_pk_f16(state.get_vgpr(0)) - self.assertEqual(lo, f16_to_bits(5.0)) - self.assertEqual(hi, f16_to_bits(10.0)) - - def test_simd_multi_lane_aliasing(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_vgpr(lane, 0, pack_pk_f16(f16_to_bits(float(lane)), f16_to_bits(float(lane)))) - state.set_vgpr(lane, 1, pack_pk_f16(POS_TWO, POS_TWO)) - state.set_vgpr(lane, 2, pack_pk_f16(POS_ONE, POS_ONE)) - - # Each lane computes in place: v0 = v0 * v1 + v2 -> lane * 2.0 + 1.0 - instr = VPkFmaF16Instruction( - dst=Reg32(0, RegType.VGPR), - src0=VOP3POperand(Reg32(0, RegType.VGPR)), - src1=VOP3POperand(Reg32(1, RegType.VGPR)), - src2=VOP3POperand(Reg32(2, RegType.VGPR)), - ) - self.simd_interp.step(instr, state) - for lane in range(32): - lo, hi = unpack_pk_f16(state.get_vgpr(lane, 0)) - expected = f16_to_bits(float(lane) * 2.0 + 1.0) - self.assertEqual(lo, expected) - self.assertEqual(hi, expected) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass(frozen=True) -class FPStatusFlags: - """Architectural floating-point condition codes and IEEE 754 status flags for binary16.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -@dataclass(frozen=True) -class PackedFPStatusFlags: - """Status flags for dual-half packed execution (lo and hi lanes).""" - lo: FPStatusFlags - hi: FPStatusFlags - - -def evaluate_fma_f16_flags( - s0_bits: int, - s1_bits: int, - s2_bits: int, - res_bits: int, - clamp: bool = False, -) -> FPStatusFlags: - """Evaluate IEEE 754 architectural flags and condition codes for a single f16 lane.""" - s0_nan = is_nan16(s0_bits) - s1_nan = is_nan16(s1_bits) - s2_nan = is_nan16(s2_bits) - s0_snan = is_snan16(s0_bits) - s1_snan = is_snan16(s1_bits) - s2_snan = is_snan16(s2_bits) - - s0_inf = is_inf16(s0_bits) - s1_inf = is_inf16(s1_bits) - s2_inf = is_inf16(s2_bits) - - s0_zero = is_zero16(s0_bits) - s1_zero = is_zero16(s1_bits) - - invalid = False - if s0_snan or s1_snan or s2_snan: - invalid = True - elif (s0_inf and s1_zero) or (s0_zero and s1_inf): - invalid = True - elif (s0_inf or s1_inf) and s2_inf: - prod_sign = ((s0_bits ^ s1_bits) & SIGN_MASK16) - s2_sign = (s2_bits & SIGN_MASK16) - if prod_sign != s2_sign: - invalid = True - - nan_flag = is_nan16(res_bits) - inf_flag = is_inf16(res_bits) - zero_flag = is_zero16(res_bits) - neg_flag = bool(res_bits & SIGN_MASK16) - denorm_flag = is_subnormal16(res_bits) - - overflow = False - if not (s0_nan or s1_nan or s2_nan or s0_inf or s1_inf or s2_inf) and inf_flag: - overflow = True - - underflow = False - if denorm_flag: - underflow = True - - inexact = False - if overflow: - inexact = True - elif not (s0_nan or s1_nan or s2_nan or s0_inf or s1_inf or s2_inf or nan_flag or inf_flag): - f0 = bits_to_f16(s0_bits) - f1 = bits_to_f16(s1_bits) - f2 = bits_to_f16(s2_bits) - res_f = bits_to_f16(res_bits) - exact_frac = Fraction(f0) * Fraction(f1) + Fraction(f2) - if not clamp: - if Fraction(res_f) != exact_frac: - inexact = True - else: - clamped_math = min(1.0, max(0.0, float(exact_frac))) - if Fraction(res_f) != Fraction(clamped_math): - inexact = True - - return FPStatusFlags( - invalid=invalid, - overflow=overflow, - underflow=underflow, - inexact=inexact, - zero=zero_flag, - negative=neg_flag, - denormal=denorm_flag, - infinite=inf_flag, - nan=nan_flag, - ) - - -def evaluate_pk_fma_f16_flags( - src0_bits: int, - src1_bits: int, - src2_bits: int, - res_bits: int, - op_sel: Tuple[int, int, int] = (0, 0, 0), - op_sel_hi: Tuple[int, int, int] = (1, 1, 1), - neg_lo: Tuple[int, int, int] = (0, 0, 0), - neg_hi: Tuple[int, int, int] = (0, 0, 0), - clamp: bool = False, -) -> PackedFPStatusFlags: - """Evaluate architectural flags for both halves of a packed v_pk_fma_f16 operation.""" - s0_lo, s0_hi = unpack_pk_f16(src0_bits) - s1_lo, s1_hi = unpack_pk_f16(src1_bits) - s2_lo, s2_hi = unpack_pk_f16(src2_bits) - res_lo, res_hi = unpack_pk_f16(res_bits) - - in0_lo = apply_f16_modifiers(s0_hi if op_sel[0] else s0_lo, neg_mod=bool(neg_lo[0])) - in1_lo = apply_f16_modifiers(s1_hi if op_sel[1] else s1_lo, neg_mod=bool(neg_lo[1])) - in2_lo = apply_f16_modifiers(s2_hi if op_sel[2] else s2_lo, neg_mod=bool(neg_lo[2])) - - in0_hi = apply_f16_modifiers(s0_hi if op_sel_hi[0] else s0_lo, neg_mod=bool(neg_hi[0])) - in1_hi = apply_f16_modifiers(s1_hi if op_sel_hi[1] else s1_lo, neg_mod=bool(neg_hi[1])) - in2_hi = apply_f16_modifiers(s2_hi if op_sel_hi[2] else s2_lo, neg_mod=bool(neg_hi[2])) - - flags_lo = evaluate_fma_f16_flags(in0_lo, in1_lo, in2_lo, res_lo, clamp=clamp) - flags_hi = evaluate_fma_f16_flags(in0_hi, in1_hi, in2_hi, res_hi, clamp=clamp) - - return PackedFPStatusFlags(lo=flags_lo, hi=flags_hi) - - -def compute_f16_fma_mantissa_product_carry( - s0_bits: int, - s1_bits: int, - s2_bits: int, -) -> Tuple[int, int]: - """Demonstrate IEEE 754 binary16 significand product and carry/overflow generation.""" - _, exp0, frac0 = split_f16_bits(s0_bits) - _, exp1, frac1 = split_f16_bits(s1_bits) - m0 = (1 << 10) | frac0 if exp0 != 0 else frac0 - m1 = (1 << 10) | frac1 if exp1 != 0 else frac1 - product = m0 * m1 - carry_out = 1 if product >= (1 << 21) else 0 - return product, carry_out - - -class TestPkFmaF16ConditionCodesAndStatusFlags(unittest.TestCase): - """Test suite for status flags, condition codes, and carry generation.""" - - def test_exact_finite_flags(self) -> None: - v0 = pack_pk_f16(POS_ONE, POS_TWO) - v1 = pack_pk_f16(POS_TWO, POS_TWO) - v2 = pack_pk_f16(POS_HALF, POS_ONE) - res = oracle_v_pk_fma_f16(v0, v1, v2) - flags = evaluate_pk_fma_f16_flags(v0, v1, v2, res) - - for lane_flags in (flags.lo, flags.hi): - self.assertFalse(lane_flags.invalid) - self.assertFalse(lane_flags.overflow) - self.assertFalse(lane_flags.underflow) - self.assertFalse(lane_flags.inexact) - self.assertFalse(lane_flags.zero) - self.assertFalse(lane_flags.negative) - self.assertFalse(lane_flags.denormal) - self.assertFalse(lane_flags.infinite) - self.assertFalse(lane_flags.nan) - - def test_inexact_flag_generation(self) -> None: - # 1.0 * 1.0 + 2^-24: exact sum is 1 + 2^-24, but rounded binary16 result is 1.0 -> inexact! - v0 = pack_pk_f16(POS_ONE, POS_ONE) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(POS_MIN_SUBNORM, POS_MIN_SUBNORM) - res = oracle_v_pk_fma_f16(v0, v1, v2) - flags = evaluate_pk_fma_f16_flags(v0, v1, v2, res) - self.assertTrue(flags.lo.inexact) - self.assertFalse(flags.lo.overflow) - - def test_overflow_flag_generation(self) -> None: - # Max normal 65504.0 * 2.0 + 0.0 -> overflow to +inf - v0 = pack_pk_f16(POS_MAX_NORMAL, POS_MAX_NORMAL) - v1 = pack_pk_f16(POS_TWO, POS_TWO) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2) - flags = evaluate_pk_fma_f16_flags(v0, v1, v2, res) - self.assertTrue(flags.lo.overflow) - self.assertTrue(flags.lo.infinite) - self.assertTrue(flags.lo.inexact) - self.assertFalse(flags.lo.invalid) - - def test_underflow_and_denormal_flags(self) -> None: - # Subnormal arithmetic produces denormal flag and underflow flag - sub = POS_MIN_SUBNORM - v0 = pack_pk_f16(sub, sub) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2) - flags = evaluate_pk_fma_f16_flags(v0, v1, v2, res) - self.assertTrue(flags.lo.denormal) - self.assertTrue(flags.lo.underflow) - self.assertFalse(flags.lo.overflow) - - def test_invalid_operation_flag_generation(self) -> None: - # +inf * 0.0 is invalid - v0 = pack_pk_f16(POS_INF, POS_ONE) - v1 = pack_pk_f16(POS_ZERO, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2) - flags = evaluate_pk_fma_f16_flags(v0, v1, v2, res) - self.assertTrue(flags.lo.invalid) - self.assertTrue(flags.lo.nan) - self.assertFalse(flags.hi.invalid) - - # Signaling NaN in input produces invalid flag - v_snan = pack_pk_f16(SNAN_DEFAULT, POS_ONE) - res_snan = oracle_v_pk_fma_f16(v_snan, v1, v2) - flags_snan = evaluate_pk_fma_f16_flags(v_snan, v1, v2, res_snan) - self.assertTrue(flags_snan.lo.invalid) - - def test_zero_and_negative_flags(self) -> None: - # -2.0 * 2.0 + 0.0 = -4.0 (negative) - # +0.0 * 1.0 + 0.0 = +0.0 (zero) - v0 = pack_pk_f16(NEG_TWO, POS_ZERO) - v1 = pack_pk_f16(POS_TWO, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2) - flags = evaluate_pk_fma_f16_flags(v0, v1, v2, res) - - self.assertTrue(flags.lo.negative) - self.assertFalse(flags.lo.zero) - - self.assertTrue(flags.hi.zero) - self.assertFalse(flags.hi.negative) - - def test_packed_status_flags_divergence(self) -> None: - # lo overflows to +inf, hi underflows to subnormal - v0 = pack_pk_f16(POS_MAX_NORMAL, POS_MIN_SUBNORM) - v1 = pack_pk_f16(POS_TWO, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2) - flags = evaluate_pk_fma_f16_flags(v0, v1, v2, res) - - self.assertTrue(flags.lo.overflow) - self.assertFalse(flags.lo.underflow) - - self.assertTrue(flags.hi.underflow) - self.assertFalse(flags.hi.overflow) - - def test_mantissa_product_carry_generation(self) -> None: - # 1.0 has significand (1 << 10) = 1024 - # 1.0 * 1.0: product = 1024 * 1024 = 1048576 = (1 << 20) -> carry = 0 - prod0, carry0 = compute_f16_fma_mantissa_product_carry(POS_ONE, POS_ONE, POS_ZERO) - self.assertEqual(prod0, 1 << 20) - self.assertEqual(carry0, 0) - - # Significand with leading 1.111...: ~2047 * 2047 ~= 4190209 >= (1 << 21) -> carry = 1 - val_near_two = f16_to_bits(1.999) - prod1, carry1 = compute_f16_fma_mantissa_product_carry(val_near_two, val_near_two, POS_ZERO) - self.assertEqual(carry1, 1) - - -# ============================================================================== -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# ============================================================================== - -class TestPkFmaF16IEEE754Boundaries(unittest.TestCase): - """Test suite for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_addition_without_underflow(self) -> None: - # 0x0001 (2^-24) * 1.0 + 0x0001 = 0x0002 - v0 = pack_pk_f16(POS_MIN_SUBNORM, POS_MIN_SUBNORM) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(POS_MIN_SUBNORM, POS_MIN_SUBNORM) - res = oracle_v_pk_fma_f16(v0, v1, v2) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, 0x0002) - self.assertEqual(hi, 0x0002) - self.assertTrue(is_subnormal16(lo)) - - def test_subnormal_to_normal_transition(self) -> None: - # Largest subnormal: 0x03FF ((1023/1024)*2^-14) - # 0x03FF * 1.0 + 0x0001 = 0x0400 (smallest normal 2^-14) - v0 = pack_pk_f16(POS_MAX_SUBNORM, POS_MAX_SUBNORM) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(POS_MIN_SUBNORM, POS_MIN_SUBNORM) - res = oracle_v_pk_fma_f16(v0, v1, v2) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, POS_MIN_NORMAL) - self.assertEqual(hi, POS_MIN_NORMAL) - self.assertFalse(is_subnormal16(lo)) - _, exp, frac = split_f16_bits(lo) - self.assertEqual(exp, 1) - self.assertEqual(frac, 0) - - def test_subnormal_cancellation(self) -> None: - sub = 0x0123 - v0 = pack_pk_f16(sub, sub) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(sub, sub) - # v0 * 1.0 + (-v2) = +0.0 - res = oracle_v_pk_fma_f16(v0, v1, v2, neg_lo=(0, 0, 1), neg_hi=(0, 0, 1)) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, POS_ZERO) - self.assertEqual(hi, POS_ZERO) - - def test_gradual_underflow(self) -> None: - # 0.5 * 2^-14 (POS_MIN_NORMAL) + 0.0 = 2^-15 (subnormal 0x0200) - v0 = pack_pk_f16(POS_HALF, POS_HALF) - v1 = pack_pk_f16(POS_MIN_NORMAL, POS_MIN_NORMAL) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, 0x0200) - self.assertEqual(hi, 0x0200) - self.assertTrue(is_subnormal16(lo)) - - def test_nan_signaling_to_quiet_conversion(self) -> None: - snan = 0x7D05 - self.assertTrue(is_snan16(snan)) - v0 = pack_pk_f16(snan, POS_ONE) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2) - lo, hi = unpack_pk_f16(res) - self.assertTrue(is_qnan16(lo)) - self.assertEqual(lo, snan | QNAN_BIT16) - self.assertEqual(hi, POS_ONE) - - def test_nan_payload_preservation(self) -> None: - payload_qnan = 0x7E12 - self.assertTrue(is_qnan16(payload_qnan)) - v0 = pack_pk_f16(payload_qnan, POS_ONE) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2) - lo, _ = unpack_pk_f16(res) - self.assertEqual(lo, payload_qnan) - - def test_nan_with_modifiers(self) -> None: - qnan = 0x7E01 - v0 = pack_pk_f16(qnan, qnan) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - - # neg_lo toggles sign bit on NaN - res = oracle_v_pk_fma_f16(v0, v1, v2, neg_lo=(1, 0, 0)) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo & SIGN_MASK16, SIGN_MASK16) - self.assertEqual(hi & SIGN_MASK16, 0) - - def test_nan_with_clamp(self) -> None: - # NaNs clamped with clamp=True map to +0.0 (0x0000) - v0 = pack_pk_f16(QNAN_CANONICAL, SNAN_DEFAULT) - v1 = pack_pk_f16(POS_ONE, POS_ONE) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - res = oracle_v_pk_fma_f16(v0, v1, v2, clamp=True) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, POS_ZERO) - self.assertEqual(hi, POS_ZERO) - - def test_infinity_arithmetic_boundaries(self) -> None: - # (+inf) * 2.0 + 1.0 = +inf - # (-inf) * 2.0 + 1.0 = -inf - v0 = pack_pk_f16(POS_INF, NEG_INF) - v1 = pack_pk_f16(POS_TWO, POS_TWO) - v2 = pack_pk_f16(POS_ONE, POS_ONE) - res = oracle_v_pk_fma_f16(v0, v1, v2) - lo, hi = unpack_pk_f16(res) - self.assertEqual(lo, POS_INF) - self.assertEqual(hi, NEG_INF) - - # (+inf) * 0.0 + 1.0 = QNaN - v_zero = pack_pk_f16(POS_ZERO, POS_ZERO) - res_inv = oracle_v_pk_fma_f16(v0, v_zero, v2) - lo_inv, _ = unpack_pk_f16(res_inv) - self.assertTrue(is_nan16(lo_inv)) - - # Infinity clamped: +inf -> 1.0, -inf -> +0.0 - res_clamp = oracle_v_pk_fma_f16(v0, v1, v2, clamp=True) - lo_c, hi_c = unpack_pk_f16(res_clamp) - self.assertEqual(lo_c, POS_ONE) - self.assertEqual(hi_c, POS_ZERO) - - def test_round_to_nearest_even_ties(self) -> None: - # In IEEE 754 binary16 (11 bits significand): - # 1.0 is 0x3C00 (even LSB = 0) - # 1.0 + 2^-10 is 0x3C01 (odd LSB = 1) - # 2^-11 is exactly halfway between representable binary16 numbers. - half_ulp = 2.0 ** -11 - val_even = 1.0 - val_odd = bits_to_f16(0x3C01) - - # Case 1: 1.0 (even LSB) * 1.0 + 2^-11: tie rounds to even (1.0) - res1 = compute_scalar_fma_f16_bits(POS_ONE, POS_ONE, f16_to_bits(half_ulp)) - self.assertEqual(res1, POS_ONE) - - # Case 2: (1.0 + 2^-10) (odd LSB) * 1.0 + 2^-11: tie rounds to even (1.0 + 2 * 2^-10 = 0x3C02) - res2 = compute_scalar_fma_f16_bits(0x3C01, POS_ONE, f16_to_bits(half_ulp)) - self.assertEqual(res2, 0x3C02) - - -# ============================================================================== -# Negative Controls, Syntax Rejection, and Mutation Detection -# ============================================================================== - -class TestPkFmaF16NegativeControlsAndMutations(unittest.TestCase): - """Test suite for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Reg32(-1, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg32(300, RegType.SGPR) - - def test_syntax_rejection_valu_destination_must_be_vgpr(self) -> None: - v = VOP3POperand(Reg32(1, RegType.VGPR)) - with self.assertRaises(TypeError): - VPkFmaF16Instruction(dst=Reg32(0, RegType.SGPR), src0=v, src1=v, src2=v) - - def test_syntax_rejection_invalid_simd_lane_count(self) -> None: - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDState(num_lanes=128) - - def test_syntax_rejection_invalid_modifier_tuples(self) -> None: - v = VOP3POperand(Reg32(1, RegType.VGPR)) - with self.assertRaises(ValueError): - VPkFmaF16Instruction(dst=Reg32(0, RegType.VGPR), src0=v, src1=v, src2=v, op_sel=(0, 0)) # type: ignore[arg-type] - with self.assertRaises(ValueError): - VPkFmaF16Instruction(dst=Reg32(0, RegType.VGPR), src0=v, src1=v, src2=v, neg_lo=(0, 2, 0)) - - def test_negative_control_bit_flip_detection(self) -> None: - v0 = pack_pk_f16(f16_to_bits(2.0), f16_to_bits(3.0)) - v1 = pack_pk_f16(f16_to_bits(4.0), f16_to_bits(5.0)) - v2 = pack_pk_f16(f16_to_bits(1.0), f16_to_bits(2.0)) - correct = oracle_v_pk_fma_f16(v0, v1, v2) - - # Perturb single bit in low half - corrupted_lo = correct ^ 0x0001 - self.assertNotEqual(correct, corrupted_lo) - - # Perturb single bit in high half - corrupted_hi = correct ^ 0x0001_0000 - self.assertNotEqual(correct, corrupted_hi) - - def test_mutation_non_fused_intermediate_rounding(self) -> None: - """Mutant: Replace fused single rounding with unfused separate mul and add.""" - def mutant_fma(s0: int, s1: int, s2: int) -> int: - return compute_scalar_fma_f16_bits(s0, s1, s2 ^ SIGN_MASK16) - - v0 = 0x3C01 - v1 = 0x3C01 - v2 = 0x1400 - expected = compute_scalar_fma_f16_bits(v0, v1, v2) - mutant_res = mutant_fma(v0, v1, v2) - self.assertNotEqual(expected, mutant_res) - - def test_mutation_invert_half_selection(self) -> None: - """Mutant: Inversion of op_sel or op_sel_hi half routing.""" - v0 = pack_pk_f16(f16_to_bits(1.0), f16_to_bits(10.0)) - v1 = pack_pk_f16(f16_to_bits(2.0), f16_to_bits(20.0)) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - - # Expected: op_sel=(0, 0, 0) selects lo halves -> 1.0 * 2.0 = 2.0 - good = oracle_v_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 1)) - # Mutant swaps lo half selection to hi -> 10.0 * 20.0 = 200.0 - bad = oracle_v_pk_fma_f16(v0, v1, v2, op_sel=(1, 1, 0), op_sel_hi=(1, 1, 1)) - self.assertNotEqual(good, bad) - - def test_mutation_ignore_neg_modifiers(self) -> None: - """Mutant: Ignore neg_lo modifier.""" - v0 = pack_pk_f16(POS_TWO, POS_TWO) - v1 = pack_pk_f16(POS_TWO, POS_TWO) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - - good = oracle_v_pk_fma_f16(v0, v1, v2, neg_lo=(1, 0, 0)) - bad = oracle_v_pk_fma_f16(v0, v1, v2, neg_lo=(0, 0, 0)) - self.assertNotEqual(good, bad) - lo_good, _ = unpack_pk_f16(good) - lo_bad, _ = unpack_pk_f16(bad) - self.assertEqual(lo_good, f16_to_bits(-4.0)) - self.assertEqual(lo_bad, f16_to_bits(4.0)) - - def test_mutation_ignore_clamp_bounds(self) -> None: - """Mutant: Clamp modifier fails to saturate values > 1.0.""" - v0 = pack_pk_f16(POS_TWO, POS_TWO) - v1 = pack_pk_f16(POS_TWO, POS_TWO) - v2 = pack_pk_f16(POS_ZERO, POS_ZERO) - - good = oracle_v_pk_fma_f16(v0, v1, v2, clamp=True) - bad = oracle_v_pk_fma_f16(v0, v1, v2, clamp=False) - self.assertNotEqual(good, bad) - lo_good, _ = unpack_pk_f16(good) - self.assertEqual(lo_good, POS_ONE) - - def test_mutation_simd_inactive_lane_leakage(self) -> None: - """Mutant: Inactive SIMD lanes are corrupted during masked execution.""" - sentinel = 0xCAFE_BABE - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) # all inactive - for lane in range(32): - state.set_vgpr(lane, 4, sentinel) - - class LeakySIMDInterpreter(SIMDInterpreter): - def step(self, instr: VPkFmaF16Instruction, state: SIMDState) -> List[Optional[int]]: - results = [] - for lane in range(state.num_lanes): - # Bug: ignores exec_mask - res = oracle_v_pk_fma_f16(pack_pk_f16(POS_ONE, POS_ONE), pack_pk_f16(POS_ONE, POS_ONE), 0) - state.set_vgpr(lane, instr.dst.index, res) - results.append(res) - return results - - leaky = LeakySIMDInterpreter() - instr = VPkFmaF16Instruction( - dst=Reg32(4, RegType.VGPR), - src0=VOP3POperand(Literal32(pack_pk_f16(POS_ONE, POS_ONE))), - src1=VOP3POperand(Literal32(pack_pk_f16(POS_ONE, POS_ONE))), - src2=VOP3POperand(Literal32(0)), - ) - leaky.step(instr, state) - corrupted = [lane for lane in range(32) if state.get_vgpr(lane, 4) != sentinel] - self.assertEqual(len(corrupted), 32) - - def test_mutation_subnormal_flush_to_zero(self) -> None: - """Mutant: Subnormals flushed to zero (FTZ mode).""" - sub = POS_MIN_SUBNORM - correct = compute_scalar_fma_f16_bits(sub, POS_ONE, sub) - self.assertEqual(correct, 0x0002) - - # FTZ mutant produces 0.0 - ftz_mutant = POS_ZERO - self.assertNotEqual(correct, ftz_mutant) - - def test_mutation_skip_snan_quietening(self) -> None: - """Mutant: Signaling NaN is not quietened.""" - snan = SNAN_DEFAULT - res = compute_scalar_fma_f16_bits(snan, POS_ONE, POS_ZERO) - self.assertTrue(is_qnan16(res)) - self.assertNotEqual(res, snan) +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF + + +def P(lo, hi): + """A dword holding two binary16 values.""" + return (hi << 16) | lo + + +def run(line, seeds, old=0xDEADBEEF): + """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0 (seeds map reg -> dword).""" + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_pk_fma_f16", prog))[0] + + +def half(w, i): + return (w >> (16 * i)) & 0xFFFF + + +def pk_ref(fn, srcs, op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): + """Reference for one packed op: the low result reads half op_sel[i] of source i (negated by neg_lo[i]), the high + result half op_sel_hi[i] (negated by neg_hi[i]); defaults are op_sel 0, op_sel_hi 1, no negation.""" + n = len(srcs) + op_sel, op_sel_hi = op_sel or [0] * n, op_sel_hi or [1] * n + neg_lo, neg_hi = neg_lo or [0] * n, neg_hi or [0] * n + out = [] + for sel, ng in ((op_sel, neg_lo), (op_sel_hi, neg_hi)): + r = fn(*[half(s, h) ^ (0x8000 if g else 0) for s, h, g in zip(srcs, sel, ng)]) + out.append(clamp01(r) if clamp else r) + return P(out[0], out[1]) + + +def same_pk(a, b): + return same_f16(a & 0xFFFF, b & 0xFFFF) and same_f16(a >> 16, b >> 16) + + +def mods_text(op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): + t = "" + for name, v in (("op_sel", op_sel), ("op_sel_hi", op_sel_hi), ("neg_lo", neg_lo), ("neg_hi", neg_hi)): + if v is not None: + t += f" {name}:[{','.join(map(str, v))}]" + return t + (" clamp" if clamp else "") + + +def regs(n): + return ", ".join(f"v{i}" for i in range(1, n + 1)) + + +# mnemonic -> (source count, reference for one lane) +OPS = {"v_pk_fma_f16": (3, ref_fma)} + +# mnemonic -> rows of (source dwords..., D), written by hand; lane 0 is the low half +CASES = { + 'v_pk_fma_f16': [ + (P(TWO, 0x3C01), P(THREE, 0x3C01), P(ONE, 0xBC02), P(0x4700, 0x0010)), # (2 * 3 + 1 = 7, (1+2^-10)^2 - (1+2^-9) = 2^-20 fused) + (P(MAXH, 0x8000), P(TWO, ONE), P(0xFBFF, 0x8000), P(MAXH, 0x8000)), # (131008 - 65504 fused, -0 * 1 + -0 = -0) + (P(HALF, MIN_SUB), P(HALF, HALF), P(QUARTER, MIN_SUB), P(HALF, 0x0002)), # (0.5, 1.5 quanta ties to even) + (P(INF, 0x3E00), P(0x0000, TWO), P(ONE, 0xC200), P(QNAN, 0x0000)), # (inf * 0 = NaN, 1.5 * 2 - 3 = +0) + (P(ONE, ONE), P(ONE, ONE), P(MIN_SUB, QNAN), P(ONE, QNAN)), # (1 + 2^-24 = 1, NaN addend) + ], + +} + +# mnemonic -> (sources, modifier text, D), by hand. S0 = (1.0, 3.0), S1 = (0.5, -0.25), S2 = (0.25, -1.0) as +# (low, high) halves. +S0, S1, S2 = P(ONE, THREE), P(HALF, 0xB400), P(QUARTER, 0xBC00) +MODS = { + 'v_pk_fma_f16': [ + ((S0, S1, S2), "", P(0x3A00, 0xBF00)), # (1 * 0.5 + 0.25, 3 * -0.25 + -1) = (0.75, -1.75) + ((S0, S1, S2), " op_sel:[1,0,0]", P(0x3F00, 0xBF00)), # low: 3 * 0.5 + 0.25 = 1.75 + ((S0, S1, S2), " op_sel:[0,1,1] op_sel_hi:[0,0,0]", P(0xBD00, 0x3A00)), # low: 1 * -0.25 + -1; high: 1 * 0.5 + 0.25 + ((S0, S1, S2), " neg_lo:[1,0,0]", P(0xB400, 0xBF00)), # low: -1 * 0.5 + 0.25 = -0.25 + ((S0, S1, S2), " neg_hi:[0,0,1]", P(0x3A00, 0x3400)), # high: -0.75 + 1 = 0.25 + ((S0, S1, S2), " neg_lo:[0,0,1] neg_hi:[1,0,0]", P(0x3400, 0xB400)), # (0.5 - 0.25, 0.75 - 1) + ((P(TWO, 0xC000), P(ONE, ONE), P(HALF, 0xBC00)), " clamp", P(ONE, 0x0000)), # (2.5, -3) -> (1, 0) + ((P(HALF, HALF), P(HALF, ONE), P(QUARTER, 0x0000)), " clamp", P(HALF, HALF)), # inside [0, 1]: unchanged + ], + +} + + +class PkFmaF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for op, rows in CASES.items(): + for *src, want in rows: + with self.subTest(op=op, src=[hex(s) for s in src]): + self.assertTrue(same_pk(pk_ref(OPS[op][1], src), want), hex(pk_ref(OPS[op][1], src))) + + def test_per_lane_results(self): + for op, rows in CASES.items(): + for *src, want in rows: + with self.subTest(op=op, src=[hex(s) for s in src]): + got = run(f"{op} v0, {regs(len(src))}", {f"v{i}": s for i, s in enumerate(src, 1)}) + self.assertTrue(same_pk(got, want), hex(got)) + + def test_sgpr_sources(self): + for op, rows in CASES.items(): + for *src, want in rows[:6]: + n = len(src) + forms = [("all sgpr", ", ".join(f"s{i}" for i in range(1, n + 1)), {f"s{i}": s for i, s in enumerate(src, 1)}), + ("sgpr src0", ", ".join(["s1"] + [f"v{i}" for i in range(2, n + 1)]), + {"s1": src[0], **{f"v{i}": s for i, s in enumerate(src[1:], 2)}})] + for form, text, seeds in forms: + with self.subTest(op=op, src=[hex(s) for s in src], form=form): + self.assertTrue(same_pk(run(f"{op} v0, {text}", seeds), want)) + + def test_hand_written_modifier_cases(self): + for op, rows in MODS.items(): + for srcs, mods, want in rows: + with self.subTest(op=op, mods=mods): + got = run(f"{op} v0, {regs(len(srcs))}{mods}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, want), hex(got)) + + def test_every_op_sel_and_op_sel_hi_combination(self): + a, b, c = P(0x3E00, 0xC400), P(0x4900, 0x3A00), P(0xB800, 0x4D00) # distinct halves: 1.5/-4, 10/.75, -.5/20 + for op, (n, fn) in OPS.items(): + srcs = [a, b, c][:n] + for sel in range(1 << n): + for selhi in range(1 << n): + os_, oh = [(sel >> i) & 1 for i in range(n)], [(selhi >> i) & 1 for i in range(n)] + with self.subTest(op=op, op_sel=os_, op_sel_hi=oh): + got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh)), hex(got)) + + def test_random_operands_and_modifiers(self): + rng = random.Random(0xF3A2) + pool = [0x0000, 0x8000, ONE, 0xBC00, TWO, HALF, THREE, MAXH, 0xFBFF, INF, NINF, QNAN, MIN_NORMAL, MIN_SUB, + 0x8001, MAX_SUB, 0x3C01, 0x6800, 0x6801, 0x4C00, 0x1000, 0x9000] + for _ in range(150): + op = rng.choice(sorted(OPS)) + n, fn = OPS[op] + srcs = [P(*[rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(2)]) + for _ in range(n)] + os_, oh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] + nl, nh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] + with self.subTest(op=op, src=[hex(s) for s in srcs], mods=(os_, oh, nl, nh)): + got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh, nl, nh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh, nl, nh)), hex(got)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_pk_minmax_f16.py b/tests/semantic/test_valu_pk_minmax_f16.py index 51147ad54..2f05a31e6 100644 --- a/tests/semantic/test_valu_pk_minmax_f16.py +++ b/tests/semantic/test_valu_pk_minmax_f16.py @@ -1,1644 +1,204 @@ -from __future__ import annotations +"""v_pk_min_f16 and v_pk_max_f16 (RDNA2 VOP3P): D.f16[i] = min / max of S0.f16[i] and S1.f16[i] for both halves; a NaN operand loses to the other one. -import math -import struct +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py. The expected +words are written down by hand (from the ISA) next to each case; the plain-Python binary16 reference in +tests/semantic/f16_ref.py rechecks them lane by lane and drives seeded random operands and modifier combinations. +Covers per-lane results, op_sel / op_sel_hi half selection, neg_lo / neg_hi, clamp and SGPR sources. +Standard library only: no GPU, no LLVM, no game data. +""" +import os +import random +import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from typing import List, Optional, Tuple, Union -# ============================================================================== -# IEEE 754 binary16 (Half-Precision) Architectural Constants -# ============================================================================== +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import clamp01, f16_value, is_nan, same_f16 # noqa: E402 -MASK16: int = 0xFFFF -MASK32: int = 0xFFFF_FFFF - -SIGN_MASK16: int = 0x8000 -EXP_MASK16: int = 0x7C00 -FRAC_MASK16: int = 0x03FF -QNAN_BIT16: int = 0x0200 - -# Canonical and special binary16 values -POS_ZERO: int = 0x0000 # +0.0 -NEG_ZERO: int = 0x8000 # -0.0 -POS_ONE: int = 0x3C00 # +1.0 -NEG_ONE: int = 0xBC00 # -1.0 -POS_HALF: int = 0x3800 # +0.5 -NEG_HALF: int = 0xB800 # -0.5 -POS_TWO: int = 0x4000 # +2.0 -NEG_TWO: int = 0xC000 # -2.0 -POS_INF: int = 0x7C00 # +inf -NEG_INF: int = 0xFC00 # -inf -QNAN_CANONICAL: int = 0x7E00 # Canonical quiet NaN -SNAN_DEFAULT: int = 0x7D00 # Signaling NaN default -NEG_QNAN: int = 0xFE00 # Negative quiet NaN - -# Subnormal (denormal) binary16 constants -POS_MIN_SUBNORM: int = 0x0001 # +2^-24, smallest positive subnormal -POS_MAX_SUBNORM: int = 0x03FF # largest positive subnormal -NEG_MIN_SUBNORM: int = 0x8001 # -2^-24, smallest negative subnormal -NEG_MAX_SUBNORM: int = 0x83FF # largest negative subnormal - -# Normal binary16 boundaries -POS_MIN_NORMAL: int = 0x0400 # +2^-14, smallest positive normal -POS_MAX_NORMAL: int = 0x7BFF # +65504.0, largest finite binary16 -NEG_MAX_NORMAL: int = 0xFBFF # -65504.0, largest negative finite binary16 - - -# ============================================================================== -# Bit Manipulation and Conversion Utilities -# ============================================================================== - -def f16_to_bits(val: float) -> int: - """Convert a Python float to an IEEE 754 binary16 16-bit integer.""" - if math.isnan(val): - return QNAN_CANONICAL - try: - return struct.unpack(" 0 else NEG_INF - - -def bits_to_f16(bits: int) -> float: - """Convert an IEEE 754 binary16 16-bit integer to a Python float.""" - return struct.unpack(" Tuple[int, int]: - """Unpack a 32-bit dword into two 16-bit half words (lo, hi).""" - lo = packed & MASK16 - hi = (packed >> 16) & MASK16 - return lo, hi - - -def pack_pk_f16(lo: int, hi: int) -> int: - """Pack two 16-bit half words (lo, hi) into a single 32-bit dword.""" - return ((hi & MASK16) << 16) | (lo & MASK16) - - -def is_nan16(bits: int) -> bool: - """Check if 16-bit word represents an IEEE 754 binary16 NaN.""" - return ((bits & EXP_MASK16) == EXP_MASK16) and ((bits & FRAC_MASK16) != 0) - - -def is_qnan16(bits: int) -> bool: - """Check if 16-bit word represents a Quiet NaN.""" - return is_nan16(bits) and bool(bits & QNAN_BIT16) - - -def is_snan16(bits: int) -> bool: - """Check if 16-bit word represents a Signaling NaN.""" - return is_nan16(bits) and not bool(bits & QNAN_BIT16) - - -def is_inf16(bits: int) -> bool: - """Check if 16-bit word represents positive or negative infinity.""" - return ((bits & EXP_MASK16) == EXP_MASK16) and ((bits & FRAC_MASK16) == 0) - - -def is_subnormal16(bits: int) -> bool: - """Check if 16-bit word represents a subnormal (denormal) half-float.""" - return ((bits & EXP_MASK16) == 0) and ((bits & FRAC_MASK16) != 0) - - -def is_zero16(bits: int) -> bool: - """Check if 16-bit word represents positive or negative zero.""" - return (bits & ~SIGN_MASK16) == 0 - - -def apply_f16_modifiers(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Apply half-float input modifiers (abs, neg).""" - res = bits & MASK16 - if abs_mod: - res &= ~SIGN_MASK16 - if neg_mod: - res ^= SIGN_MASK16 - return res - - -# ============================================================================== -# Reference Mathematical Oracles for Scalar & Packed f16 Min/Max -# ============================================================================== - -def clamp_f16(bits: int) -> int: - """Clamp a 16-bit half-float to [0.0, 1.0]. NaN clamps to +0.0.""" - if is_nan16(bits): - return POS_ZERO - f = bits_to_f16(bits) - if f < 0.0 or bits == NEG_ZERO: - return POS_ZERO - if f > 1.0 or bits == POS_INF: - return POS_ONE - return bits & MASK16 - - -def oracle_min_f16( - s0: int, - s1: int, - *, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> int: - """Reference oracle for RDNA2 scalar v_min_f16 (IEEE 754-2008 / GLSL NMin). - - Rules: - - NaN suppression: if one operand is NaN and the other is a number, return the number. - - If both operands are NaN, return quiet NaN (s0 quietened if NaN). - - Signed zero tie-breaking: -0.0 < +0.0 (min(-0.0, +0.0) == -0.0). - - Subnormal numbers are preserved. - - If clamp=True, output clamped to [0.0, 1.0]. - """ - a = apply_f16_modifiers(s0, abs0, neg0) - b = apply_f16_modifiers(s1, abs1, neg1) - - a_nan = is_nan16(a) - b_nan = is_nan16(b) - - if a_nan and b_nan: - res = a | QNAN_BIT16 - elif a_nan: - res = b - elif b_nan: - res = a - else: - a_is_neg_zero = (a == NEG_ZERO) - b_is_neg_zero = (b == NEG_ZERO) - a_is_pos_zero = (a == POS_ZERO) - b_is_pos_zero = (b == POS_ZERO) - - if (a_is_neg_zero and b_is_pos_zero) or (a_is_pos_zero and b_is_neg_zero): - res = NEG_ZERO - elif (a_is_neg_zero and b_is_neg_zero): - res = NEG_ZERO - elif (a_is_pos_zero and b_is_pos_zero): - res = POS_ZERO - else: - fa = bits_to_f16(a) - fb = bits_to_f16(b) - if fa < fb: - res = a - elif fb < fa: - res = b - else: - # Equal finite values: preserve sign or default to a - res = a if (a & SIGN_MASK16) else b - - if clamp: - res = clamp_f16(res) - return res & MASK16 - - -def oracle_max_f16( - s0: int, - s1: int, - *, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> int: - """Reference oracle for RDNA2 scalar v_max_f16 (IEEE 754-2008 / GLSL NMax). - - Rules: - - NaN suppression: if one operand is NaN and the other is a number, return the number. - - If both operands are NaN, return quiet NaN (s0 quietened if NaN). - - Signed zero tie-breaking: -0.0 < +0.0 (max(-0.0, +0.0) == +0.0). - - Subnormal numbers are preserved. - - If clamp=True, output clamped to [0.0, 1.0]. - """ - a = apply_f16_modifiers(s0, abs0, neg0) - b = apply_f16_modifiers(s1, abs1, neg1) - - a_nan = is_nan16(a) - b_nan = is_nan16(b) - - if a_nan and b_nan: - res = a | QNAN_BIT16 - elif a_nan: - res = b - elif b_nan: - res = a - else: - a_is_neg_zero = (a == NEG_ZERO) - b_is_neg_zero = (b == NEG_ZERO) - a_is_pos_zero = (a == POS_ZERO) - b_is_pos_zero = (b == POS_ZERO) - - if (a_is_neg_zero and b_is_pos_zero) or (a_is_pos_zero and b_is_neg_zero): - res = POS_ZERO - elif (a_is_neg_zero and b_is_neg_zero): - res = NEG_ZERO - elif (a_is_pos_zero and b_is_pos_zero): - res = POS_ZERO - else: - fa = bits_to_f16(a) - fb = bits_to_f16(b) - if fa > fb: - res = a - elif fb > fa: - res = b - else: - # Equal finite values: prefer positive sign - res = b if not (b & SIGN_MASK16) else a - - if clamp: - res = clamp_f16(res) - return res & MASK16 - - -def oracle_pk_min_f16( - s0_u32: int, - s1_u32: int, - *, - op_sel: Tuple[int, int, int, int] = (0, 0, 1, 1), - abs0_lo: bool = False, - neg0_lo: bool = False, - abs1_lo: bool = False, - neg1_lo: bool = False, - abs0_hi: bool = False, - neg0_hi: bool = False, - abs1_hi: bool = False, - neg1_hi: bool = False, - clamp: bool = False, -) -> int: - """Reference oracle for RDNA2 packed v_pk_min_f16 (VOP3P). - - Selects halves based on op_sel: - - op_sel[0]: src0 half for dest.lo (0=lo, 1=hi) - - op_sel[1]: src1 half for dest.lo (0=lo, 1=hi) - - op_sel[2]: src0 half for dest.hi (0=lo, 1=hi) - - op_sel[3]: src1 half for dest.hi (0=lo, 1=hi) - Computes min for lo and hi independently, packs into 32-bit dword. - """ - s0_halves = unpack_pk_f16(s0_u32) - s1_halves = unpack_pk_f16(s1_u32) - - in0_lo = s0_halves[op_sel[0]] - in1_lo = s1_halves[op_sel[1]] - in0_hi = s0_halves[op_sel[2]] - in1_hi = s1_halves[op_sel[3]] - - out_lo = oracle_min_f16( - in0_lo, in1_lo, - abs0=abs0_lo, neg0=neg0_lo, abs1=abs1_lo, neg1=neg1_lo, - clamp=clamp, - ) - out_hi = oracle_min_f16( - in0_hi, in1_hi, - abs0=abs0_hi, neg0=neg0_hi, abs1=abs1_hi, neg1=neg1_hi, - clamp=clamp, - ) - - return pack_pk_f16(out_lo, out_hi) - - -def oracle_pk_max_f16( - s0_u32: int, - s1_u32: int, - *, - op_sel: Tuple[int, int, int, int] = (0, 0, 1, 1), - abs0_lo: bool = False, - neg0_lo: bool = False, - abs1_lo: bool = False, - neg1_lo: bool = False, - abs0_hi: bool = False, - neg0_hi: bool = False, - abs1_hi: bool = False, - neg1_hi: bool = False, - clamp: bool = False, -) -> int: - """Reference oracle for RDNA2 packed v_pk_max_f16 (VOP3P). - - Selects halves based on op_sel, computes max for lo and hi independently. - """ - s0_halves = unpack_pk_f16(s0_u32) - s1_halves = unpack_pk_f16(s1_u32) - - in0_lo = s0_halves[op_sel[0]] - in1_lo = s1_halves[op_sel[1]] - in0_hi = s0_halves[op_sel[2]] - in1_hi = s1_halves[op_sel[3]] - - out_lo = oracle_max_f16( - in0_lo, in1_lo, - abs0=abs0_lo, neg0=neg0_lo, abs1=abs1_lo, neg1=neg1_lo, - clamp=clamp, - ) - out_hi = oracle_max_f16( - in0_hi, in1_hi, - abs0=abs0_hi, neg0=neg0_hi, abs1=abs1_hi, neg1=neg1_hi, - clamp=clamp, - ) - - return pack_pk_f16(out_lo, out_hi) - - -# ============================================================================== -# Commit 1 Unit Tests -# ============================================================================== - -class TestF16ModelAndOracle(unittest.TestCase): - """Unit tests for half-precision bit representation, predicates, and reference oracles.""" - - def test_bit_representation_roundtrip(self) -> None: - values = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 65504.0, -65504.0] - for val in values: - with self.subTest(val=val): - bits = f16_to_bits(val) - recovered = bits_to_f16(bits) - self.assertEqual(val, recovered) - self.assertEqual(math.copysign(1.0, val), math.copysign(1.0, recovered)) - - def test_word_packing_and_unpacking(self) -> None: - lo = 0x1234 - hi = 0x5678 - packed = pack_pk_f16(lo, hi) - self.assertEqual(packed, 0x56781234) - rec_lo, rec_hi = unpack_pk_f16(packed) - self.assertEqual(rec_lo, lo) - self.assertEqual(rec_hi, hi) - - def test_classification_predicates(self) -> None: - self.assertTrue(is_zero16(POS_ZERO)) - self.assertTrue(is_zero16(NEG_ZERO)) - self.assertFalse(is_zero16(POS_ONE)) - - self.assertTrue(is_inf16(POS_INF)) - self.assertTrue(is_inf16(NEG_INF)) - self.assertFalse(is_inf16(POS_ZERO)) - self.assertFalse(is_inf16(QNAN_CANONICAL)) - - self.assertTrue(is_nan16(QNAN_CANONICAL)) - self.assertTrue(is_qnan16(QNAN_CANONICAL)) - self.assertFalse(is_snan16(QNAN_CANONICAL)) - - self.assertTrue(is_nan16(SNAN_DEFAULT)) - self.assertTrue(is_snan16(SNAN_DEFAULT)) - self.assertFalse(is_qnan16(SNAN_DEFAULT)) - - self.assertTrue(is_subnormal16(POS_MIN_SUBNORM)) - self.assertTrue(is_subnormal16(POS_MAX_SUBNORM)) - self.assertFalse(is_subnormal16(POS_ZERO)) - self.assertFalse(is_subnormal16(POS_MIN_NORMAL)) - - def test_exact_finite_min_max(self) -> None: - # min(1.0, 2.0) == 1.0, max(1.0, 2.0) == 2.0 - self.assertEqual(oracle_min_f16(POS_ONE, POS_TWO), POS_ONE) - self.assertEqual(oracle_max_f16(POS_ONE, POS_TWO), POS_TWO) - - # min(-1.0, 0.5) == -1.0, max(-1.0, 0.5) == 0.5 - self.assertEqual(oracle_min_f16(NEG_ONE, POS_HALF), NEG_ONE) - self.assertEqual(oracle_max_f16(NEG_ONE, POS_HALF), POS_HALF) - - def test_signed_zero_tie_breaking(self) -> None: - # min(-0.0, +0.0) == -0.0 - self.assertEqual(oracle_min_f16(NEG_ZERO, POS_ZERO), NEG_ZERO) - self.assertEqual(oracle_min_f16(POS_ZERO, NEG_ZERO), NEG_ZERO) - - # max(-0.0, +0.0) == +0.0 - self.assertEqual(oracle_max_f16(NEG_ZERO, POS_ZERO), POS_ZERO) - self.assertEqual(oracle_max_f16(POS_ZERO, NEG_ZERO), POS_ZERO) - - # min(-0.0, -0.0) == -0.0; max(+0.0, +0.0) == +0.0 - self.assertEqual(oracle_min_f16(NEG_ZERO, NEG_ZERO), NEG_ZERO) - self.assertEqual(oracle_max_f16(POS_ZERO, POS_ZERO), POS_ZERO) - - def test_nan_suppression_and_propagation(self) -> None: - # If one operand is NaN, non-NaN operand is selected - self.assertEqual(oracle_min_f16(QNAN_CANONICAL, POS_TWO), POS_TWO) - self.assertEqual(oracle_min_f16(POS_TWO, QNAN_CANONICAL), POS_TWO) - self.assertEqual(oracle_max_f16(QNAN_CANONICAL, POS_TWO), POS_TWO) - self.assertEqual(oracle_max_f16(POS_TWO, QNAN_CANONICAL), POS_TWO) - - # If both operands are NaN, quiet NaN is returned - both_min = oracle_min_f16(QNAN_CANONICAL, SNAN_DEFAULT) - self.assertTrue(is_qnan16(both_min)) - both_max = oracle_max_f16(SNAN_DEFAULT, QNAN_CANONICAL) - self.assertTrue(is_qnan16(both_max)) - - def test_modifiers_and_clamp(self) -> None: - # abs modifier: min(|-2.0|, 1.0) == min(2.0, 1.0) == 1.0 - res_abs = oracle_min_f16(NEG_TWO, POS_ONE, abs0=True) - self.assertEqual(res_abs, POS_ONE) - - # neg modifier: max(-(2.0), -1.0) == max(-2.0, -1.0) == -1.0 - res_neg = oracle_max_f16(POS_TWO, NEG_ONE, neg0=True) - self.assertEqual(res_neg, NEG_ONE) - - # clamp modifier: clamps to [0.0, 1.0] - # max(2.0, 0.5) clamped -> 1.0 - self.assertEqual(oracle_max_f16(POS_TWO, POS_HALF, clamp=True), POS_ONE) - # min(-1.0, -2.0) clamped -> +0.0 - self.assertEqual(oracle_min_f16(NEG_ONE, NEG_TWO, clamp=True), POS_ZERO) - - def test_packed_oracles_basic(self) -> None: - # pack: s0 = (hi=2.0, lo=-1.0), s1 = (hi=0.5, lo=1.0) - s0 = pack_pk_f16(NEG_ONE, POS_TWO) - s1 = pack_pk_f16(POS_ONE, POS_HALF) - - # v_pk_min_f16: - # lo: min(-1.0, 1.0) = -1.0 - # hi: min(2.0, 0.5) = 0.5 - pk_min = oracle_pk_min_f16(s0, s1) - exp_min = pack_pk_f16(NEG_ONE, POS_HALF) - self.assertEqual(pk_min, exp_min) - - # v_pk_max_f16: - # lo: max(-1.0, 1.0) = 1.0 - # hi: max(2.0, 0.5) = 2.0 - pk_max = oracle_pk_max_f16(s0, s1) - exp_max = pack_pk_f16(POS_ONE, POS_TWO) - self.assertEqual(pk_max, exp_max) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegKind(Enum): - VGPR = auto() - SGPR = auto() - - -@dataclass(frozen=True) -class Reg: - """Represents a 32-bit architectural register (VGPR or SGPR).""" - index: int - kind: RegKind = RegKind.VGPR - - def __post_init__(self) -> None: - if self.kind == RegKind.VGPR: - if not (0 <= self.index <= 255): - raise ValueError(f"VGPR index {self.index} out of range [0, 255]") - elif self.kind == RegKind.SGPR: - if not (0 <= self.index <= 105): - raise ValueError(f"SGPR index {self.index} out of range [0, 105]") - else: - raise TypeError(f"Unknown RegKind: {self.kind}") - - @property - def name(self) -> str: - prefix = "v" if self.kind == RegKind.VGPR else "s" - return f"{prefix}{self.index}" - - -@dataclass(frozen=True) -class Literal32: - """Represents a 32-bit packed literal or inline constant.""" - bits: int - - def __post_init__(self) -> None: - if not (0 <= self.bits <= 0xFFFF_FFFF): - raise ValueError(f"Literal32 bits {self.bits:#x} out of range [0, 0xFFFFFFFF]") - - @property - def lo_bits(self) -> int: - return self.bits & MASK16 - - @property - def hi_bits(self) -> int: - return (self.bits >> 16) & MASK16 - - @property - def name(self) -> str: - return f"{self.bits:#010x}" - - -class Opcode(Enum): - V_PK_MIN_F16 = "v_pk_min_f16" - V_PK_MAX_F16 = "v_pk_max_f16" - - -@dataclass(frozen=True) -class VOP3POperand: - """VOP3P packed operand with per-half input modifiers and op_sel.""" - source: Union[Reg, Literal32] - neg_lo: bool = False - neg_hi: bool = False - abs_lo: bool = False - abs_hi: bool = False - op_sel: Tuple[int, int] = (0, 1) # (lo_select, hi_select), where 0=lo, 1=hi - - def __post_init__(self) -> None: - if self.op_sel not in ((0, 0), (0, 1), (1, 0), (1, 1)): - raise ValueError(f"Invalid op_sel {self.op_sel}, elements must be 0 or 1") - - def disassemble(self) -> str: - s = self.source.name - mods = [] - if self.abs_lo and self.abs_hi: - s = f"|{s}|" - elif self.abs_lo: - mods.append("abs_lo") - elif self.abs_hi: - mods.append("abs_hi") - - if self.neg_lo and self.neg_hi: - s = f"-{s}" - elif self.neg_lo: - mods.append("neg_lo") - elif self.neg_hi: - mods.append("neg_hi") - - if self.op_sel != (0, 1): - mods.append(f"op_sel:[{self.op_sel[0]},{self.op_sel[1]}]") - - if mods: - return f"{s} ({' '.join(mods)})" - return s - - -@dataclass(frozen=True) -class VPkMinMaxF16Instruction: - """Symbolic AST node for RDNA2 v_pk_min_f16 and v_pk_max_f16 instructions.""" - opcode: Opcode - dst: Reg - src0: VOP3POperand - src1: VOP3POperand - clamp: bool = False - - def __post_init__(self) -> None: - if self.dst.kind != RegKind.VGPR: - raise TypeError(f"Destination of VALU packed instruction must be VGPR, got {self.dst.kind}") - - def disassemble(self) -> str: - s = f"{self.opcode.value} {self.dst.name}, {self.src0.disassemble()}, {self.src1.disassemble()}" - if self.clamp: - s += " clamp" - return s - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_reg_validation_and_naming(self) -> None: - v0 = Reg(0, RegKind.VGPR) - self.assertEqual(v0.name, "v0") - v255 = Reg(255, RegKind.VGPR) - self.assertEqual(v255.name, "v255") - - s0 = Reg(0, RegKind.SGPR) - self.assertEqual(s0.name, "s0") - s105 = Reg(105, RegKind.SGPR) - self.assertEqual(s105.name, "s105") - - with self.assertRaises(ValueError): - Reg(256, RegKind.VGPR) - with self.assertRaises(ValueError): - Reg(-1, RegKind.VGPR) - with self.assertRaises(ValueError): - Reg(106, RegKind.SGPR) - - def test_literal32_representation(self) -> None: - lit = Literal32(0x3C004000) - self.assertEqual(lit.lo_bits, 0x4000) - self.assertEqual(lit.hi_bits, 0x3C00) - self.assertEqual(lit.name, "0x3c004000") - - with self.assertRaises(ValueError): - Literal32(0x1_0000_0000) - with self.assertRaises(ValueError): - Literal32(-1) - - def test_operand_disassembly_modifiers(self) -> None: - v1 = Reg(1, RegKind.VGPR) - op_plain = VOP3POperand(v1) - self.assertEqual(op_plain.disassemble(), "v1") - - op_both_abs = VOP3POperand(v1, abs_lo=True, abs_hi=True) - self.assertEqual(op_both_abs.disassemble(), "|v1|") - - op_both_neg = VOP3POperand(v1, neg_lo=True, neg_hi=True) - self.assertEqual(op_both_neg.disassemble(), "-v1") - - op_custom = VOP3POperand(v1, neg_lo=True, op_sel=(1, 0)) - self.assertIn("neg_lo", op_custom.disassemble()) - self.assertIn("op_sel:[1,0]", op_custom.disassemble()) - - with self.assertRaises(ValueError): - VOP3POperand(v1, op_sel=(0, 2)) - - def test_instruction_construction_and_validation(self) -> None: - dst = Reg(0, RegKind.VGPR) - src0 = VOP3POperand(Reg(1, RegKind.VGPR)) - src1 = VOP3POperand(Reg(2, RegKind.SGPR)) - - inst_min = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=dst, - src0=src0, - src1=src1, - clamp=False, - ) - self.assertEqual(inst_min.disassemble(), "v_pk_min_f16 v0, v1, s2") - - inst_max_clamp = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MAX_F16, - dst=dst, - src0=src0, - src1=src1, - clamp=True, - ) - self.assertEqual(inst_max_clamp.disassemble(), "v_pk_max_f16 v0, v1, s2 clamp") - - # Destination must be VGPR - with self.assertRaises(TypeError): - VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(0, RegKind.SGPR), - src0=src0, - src1=src1, - ) - - def test_structural_equality(self) -> None: - dst = Reg(4, RegKind.VGPR) - src0 = VOP3POperand(Reg(5, RegKind.VGPR)) - src1 = VOP3POperand(Literal32(0x3C003C00)) - i1 = VPkMinMaxF16Instruction(Opcode.V_PK_MIN_F16, dst, src0, src1, clamp=True) - i2 = VPkMinMaxF16Instruction(Opcode.V_PK_MIN_F16, dst, src0, src1, clamp=True) - self.assertEqual(i1, i2) - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register file for single-lane scalar interpretation.""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 106) - vcc: int = 0 - - def get_reg(self, reg: Reg) -> int: - if reg.kind == RegKind.VGPR: - return self.vgprs[reg.index] & MASK32 - elif reg.kind == RegKind.SGPR: - return self.sgprs[reg.index] & MASK32 - raise TypeError(f"Unknown RegKind: {reg.kind}") - - def set_reg(self, reg: Reg, val: int) -> None: - if reg.kind == RegKind.VGPR: - self.vgprs[reg.index] = val & MASK32 - elif reg.kind == RegKind.SGPR: - self.sgprs[reg.index] = val & MASK32 - else: - raise TypeError(f"Unknown RegKind: {reg.kind}") - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for packed half-precision min/max.""" - - def resolve_operand(self, op: VOP3POperand, state: ScalarMachineState) -> int: - if isinstance(op.source, Reg): - return state.get_reg(op.source) - elif isinstance(op.source, Literal32): - return op.source.bits - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VPkMinMaxF16Instruction, state: ScalarMachineState) -> int: - s0_raw = self.resolve_operand(instr.src0, state) - s1_raw = self.resolve_operand(instr.src1, state) - - # Build op_sel tuple: (s0.lo_sel, s1.lo_sel, s0.hi_sel, s1.hi_sel) - op_sel = ( - instr.src0.op_sel[0], - instr.src1.op_sel[0], - instr.src0.op_sel[1], - instr.src1.op_sel[1], - ) - - if instr.opcode == Opcode.V_PK_MIN_F16: - res = oracle_pk_min_f16( - s0_raw, s1_raw, - op_sel=op_sel, - abs0_lo=instr.src0.abs_lo, neg0_lo=instr.src0.neg_lo, - abs1_lo=instr.src1.abs_lo, neg1_lo=instr.src1.neg_lo, - abs0_hi=instr.src0.abs_hi, neg0_hi=instr.src0.neg_hi, - abs1_hi=instr.src1.abs_hi, neg1_hi=instr.src1.neg_hi, - clamp=instr.clamp, - ) - elif instr.opcode == Opcode.V_PK_MAX_F16: - res = oracle_pk_max_f16( - s0_raw, s1_raw, - op_sel=op_sel, - abs0_lo=instr.src0.abs_lo, neg0_lo=instr.src0.neg_lo, - abs1_lo=instr.src1.abs_lo, neg1_lo=instr.src1.neg_lo, - abs0_hi=instr.src0.abs_hi, neg0_hi=instr.src0.neg_hi, - abs1_hi=instr.src1.abs_hi, neg1_hi=instr.src1.neg_hi, - clamp=instr.clamp, - ) - else: - raise ValueError(f"Unsupported opcode: {instr.opcode}") - - state.set_reg(instr.dst, res) - return res - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_scalar_vgpr_vgpr_pk_min(self) -> None: - # v1: (hi=2.0, lo=-1.0), v2: (hi=0.5, lo=1.0) - self.state.set_reg(Reg(1, RegKind.VGPR), pack_pk_f16(NEG_ONE, POS_TWO)) - self.state.set_reg(Reg(2, RegKind.VGPR), pack_pk_f16(POS_ONE, POS_HALF)) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Reg(1, RegKind.VGPR)), - src1=VOP3POperand(Reg(2, RegKind.VGPR)), - ) - res = self.interp.step(instr, self.state) - # min: lo = min(-1.0, 1.0) = -1.0; hi = min(2.0, 0.5) = 0.5 - expected = pack_pk_f16(NEG_ONE, POS_HALF) - self.assertEqual(res, expected) - self.assertEqual(self.state.get_reg(Reg(0, RegKind.VGPR)), expected) - - def test_scalar_vgpr_sgpr_pk_max(self) -> None: - # v0: (hi=-2.0, lo=0.5), s4: (hi=1.0, lo=1.0) - self.state.set_reg(Reg(0, RegKind.VGPR), pack_pk_f16(POS_HALF, NEG_TWO)) - self.state.set_reg(Reg(4, RegKind.SGPR), pack_pk_f16(POS_ONE, POS_ONE)) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MAX_F16, - dst=Reg(3, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(4, RegKind.SGPR)), - ) - res = self.interp.step(instr, self.state) - # max: lo = max(0.5, 1.0) = 1.0; hi = max(-2.0, 1.0) = 1.0 - expected = pack_pk_f16(POS_ONE, POS_ONE) - self.assertEqual(res, expected) - self.assertEqual(self.state.get_reg(Reg(3, RegKind.VGPR)), expected) - - def test_scalar_literal_and_modifiers(self) -> None: - # v5: (hi=-2.0, lo=-0.5) - # src0: abs on both -> (hi=2.0, lo=0.5) - # src1: literal (hi=1.0, lo=1.0) - self.state.set_reg(Reg(5, RegKind.VGPR), pack_pk_f16(NEG_HALF, NEG_TWO)) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(6, RegKind.VGPR), - src0=VOP3POperand(Reg(5, RegKind.VGPR), abs_lo=True, abs_hi=True), - src1=VOP3POperand(Literal32(pack_pk_f16(POS_ONE, POS_ONE))), - ) - res = self.interp.step(instr, self.state) - # min: lo = min(0.5, 1.0) = 0.5; hi = min(2.0, 1.0) = 1.0 - expected = pack_pk_f16(POS_HALF, POS_ONE) - self.assertEqual(res, expected) - - def test_scalar_clamp_mode(self) -> None: - # v1: (hi=2.0, lo=-1.0), v2: (hi=3.0, lo=-2.0) - # pk_max: lo = max(-1.0, -2.0) = -1.0 -> clamp -> +0.0 - # hi = max(2.0, 3.0) = 3.0 -> clamp -> 1.0 - self.state.set_reg(Reg(1, RegKind.VGPR), pack_pk_f16(NEG_ONE, POS_TWO)) - self.state.set_reg(Reg(2, RegKind.VGPR), pack_pk_f16(NEG_TWO, f16_to_bits(3.0))) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MAX_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Reg(1, RegKind.VGPR)), - src1=VOP3POperand(Reg(2, RegKind.VGPR)), - clamp=True, - ) - res = self.interp.step(instr, self.state) - expected = pack_pk_f16(POS_ZERO, POS_ONE) - self.assertEqual(res, expected) - - def test_scalar_determinism(self) -> None: - runs = [] - for _ in range(50): - st = ScalarMachineState() - st.set_reg(Reg(0, RegKind.VGPR), 0x3C004000) - st.set_reg(Reg(1, RegKind.VGPR), 0x42003800) - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(2, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - runs.append(self.interp.step(instr, st)) - self.assertTrue(all(r == runs[0] for r in runs)) - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - num_lanes: int - exec_mask: Optional[int] = None - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 106) - vcc: int = 0 - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - - def get_lane_reg(self, lane: int, reg: Reg) -> int: - if reg.kind == RegKind.VGPR: - return self.vgprs[lane][reg.index] & MASK32 - elif reg.kind == RegKind.SGPR: - return self.sgprs[reg.index] & MASK32 - raise TypeError(f"Unknown RegKind: {reg.kind}") - - def set_lane_vgpr(self, lane: int, reg: Reg, val: int) -> None: - if reg.kind != RegKind.VGPR: - raise TypeError(f"Cannot set lane register for non-VGPR: {reg.kind}") - self.vgprs[lane][reg.index] = val & MASK32 - - def set_sgpr(self, reg: Reg, val: int) -> None: - if reg.kind != RegKind.SGPR: - raise TypeError(f"Cannot set SGPR on VGPR: {reg.kind}") - self.sgprs[reg.index] = val & MASK32 - - -class SIMDInterpreter: - """SIMD instruction interpreter handling multi-lane divergence and EXEC masking.""" - - def resolve_lane_operand(self, op: VOP3POperand, state: SIMDState, lane: int) -> int: - if isinstance(op.source, Reg): - return state.get_lane_reg(lane, op.source) - elif isinstance(op.source, Literal32): - return op.source.bits - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VPkMinMaxF16Instruction, state: SIMDState) -> List[Optional[int]]: - results: List[Optional[int]] = [None] * state.num_lanes - - # Atomic read phase across all lanes - s0_vals = [ - self.resolve_lane_operand(instr.src0, state, lane) - for lane in range(state.num_lanes) - ] - s1_vals = [ - self.resolve_lane_operand(instr.src1, state, lane) - for lane in range(state.num_lanes) - ] - - op_sel = ( - instr.src0.op_sel[0], - instr.src1.op_sel[0], - instr.src0.op_sel[1], - instr.src1.op_sel[1], - ) - - # Execution phase under EXEC mask - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - if instr.opcode == Opcode.V_PK_MIN_F16: - res = oracle_pk_min_f16( - s0_vals[lane], s1_vals[lane], - op_sel=op_sel, - abs0_lo=instr.src0.abs_lo, neg0_lo=instr.src0.neg_lo, - abs1_lo=instr.src1.abs_lo, neg1_lo=instr.src1.neg_lo, - abs0_hi=instr.src0.abs_hi, neg0_hi=instr.src0.neg_hi, - abs1_hi=instr.src1.abs_hi, neg1_hi=instr.src1.neg_hi, - clamp=instr.clamp, - ) - elif instr.opcode == Opcode.V_PK_MAX_F16: - res = oracle_pk_max_f16( - s0_vals[lane], s1_vals[lane], - op_sel=op_sel, - abs0_lo=instr.src0.abs_lo, neg0_lo=instr.src0.neg_lo, - abs1_lo=instr.src1.abs_lo, neg1_lo=instr.src1.neg_lo, - abs0_hi=instr.src0.abs_hi, neg0_hi=instr.src0.neg_hi, - abs1_hi=instr.src1.abs_hi, neg1_hi=instr.src1.neg_hi, - clamp=instr.clamp, - ) - else: - raise ValueError(f"Unsupported opcode: {instr.opcode}") - - state.set_lane_vgpr(lane, instr.dst, res) - results[lane] = res - - return results - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD execution, lane divergence, and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.interp = SIMDInterpreter() - - def test_wave32_full_exec(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - v0_val = pack_pk_f16(f16_to_bits(float(lane)), f16_to_bits(float(lane) * 2.0)) - v1_val = pack_pk_f16(f16_to_bits(10.0), f16_to_bits(15.0)) - state.set_lane_vgpr(lane, Reg(0, RegKind.VGPR), v0_val) - state.set_lane_vgpr(lane, Reg(1, RegKind.VGPR), v1_val) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(2, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - self.assertIsNotNone(results[lane]) - lo_exp = f16_to_bits(min(float(lane), 10.0)) - hi_exp = f16_to_bits(min(float(lane) * 2.0, 15.0)) - expected = pack_pk_f16(lo_exp, hi_exp) - self.assertEqual(state.get_lane_reg(lane, Reg(2, RegKind.VGPR)), expected) - - def test_wave32_divergent_masking(self) -> None: - # Alternating mask: even lanes active (0x55555555) - sentinel = 0xDEADBEEF - state = SIMDState(num_lanes=32, exec_mask=0x5555_5555) - for lane in range(32): - state.set_lane_vgpr(lane, Reg(0, RegKind.VGPR), pack_pk_f16(POS_ONE, POS_TWO)) - state.set_lane_vgpr(lane, Reg(1, RegKind.VGPR), pack_pk_f16(POS_TWO, POS_ONE)) - state.set_lane_vgpr(lane, Reg(2, RegKind.VGPR), sentinel) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MAX_F16, - dst=Reg(2, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - if lane % 2 == 0: - self.assertIsNotNone(results[lane]) - self.assertEqual( - state.get_lane_reg(lane, Reg(2, RegKind.VGPR)), - pack_pk_f16(POS_TWO, POS_TWO), - ) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_lane_reg(lane, Reg(2, RegKind.VGPR)), sentinel) - - def test_wave64_full_exec(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=0xFFFF_FFFF_FFFF_FFFF) - for lane in range(64): - state.set_lane_vgpr(lane, Reg(0, RegKind.VGPR), pack_pk_f16(POS_ONE, NEG_ONE)) - state.set_lane_vgpr(lane, Reg(1, RegKind.VGPR), pack_pk_f16(POS_TWO, NEG_TWO)) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - self.interp.step(instr, state) - for lane in range(64): - # min(1.0, 2.0) = 1.0; min(-1.0, -2.0) = -2.0 - self.assertEqual( - state.get_lane_reg(lane, Reg(0, RegKind.VGPR)), - pack_pk_f16(POS_ONE, NEG_TWO), - ) - - def test_wave64_half_disabled(self) -> None: - # Lower 32 lanes active, upper 32 lanes inactive - sentinel = 0xCAFEBABE - state = SIMDState(num_lanes=64, exec_mask=0x0000_0000_FFFF_FFFF) - for lane in range(64): - state.set_lane_vgpr(lane, Reg(0, RegKind.VGPR), pack_pk_f16(POS_HALF, POS_ONE)) - state.set_lane_vgpr(lane, Reg(1, RegKind.VGPR), pack_pk_f16(POS_ONE, POS_HALF)) - state.set_lane_vgpr(lane, Reg(3, RegKind.VGPR), sentinel) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MAX_F16, - dst=Reg(3, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(64): - if lane < 32: - self.assertIsNotNone(results[lane]) - self.assertEqual( - state.get_lane_reg(lane, Reg(3, RegKind.VGPR)), - pack_pk_f16(POS_ONE, POS_ONE), - ) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_lane_reg(lane, Reg(3, RegKind.VGPR)), sentinel) - - def test_wave_exec_all_zero(self) -> None: - sentinel = 0xAA55AA55 - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) - for lane in range(32): - state.set_lane_vgpr(lane, Reg(0, RegKind.VGPR), sentinel) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Literal32(pack_pk_f16(POS_ONE, POS_ONE))), - src1=VOP3POperand(Literal32(pack_pk_f16(POS_TWO, POS_TWO))), - ) - results = self.interp.step(instr, state) - self.assertTrue(all(r is None for r in results)) - for lane in range(32): - self.assertEqual(state.get_lane_reg(lane, Reg(0, RegKind.VGPR)), sentinel) - - def test_simd_sgpr_uniform_broadcast(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - state.set_sgpr(Reg(4, RegKind.SGPR), pack_pk_f16(POS_TWO, POS_TWO)) - for lane in range(32): - state.set_lane_vgpr(lane, Reg(0, RegKind.VGPR), pack_pk_f16(POS_ONE, POS_ONE)) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MAX_F16, - dst=Reg(1, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(4, RegKind.SGPR)), - ) - self.interp.step(instr, state) - for lane in range(32): - self.assertEqual( - state.get_lane_reg(lane, Reg(1, RegKind.VGPR)), - pack_pk_f16(POS_TWO, POS_TWO), - ) - - -# ============================================================================== -# Register Aliasing and In-Place Operand Preservation -# ============================================================================== - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_dst_alias_src0(self) -> None: - state = ScalarMachineState() - # v0: (hi=2.0, lo=-1.0), v1: (hi=0.5, lo=1.0) - state.set_reg(Reg(0, RegKind.VGPR), pack_pk_f16(NEG_ONE, POS_TWO)) - state.set_reg(Reg(1, RegKind.VGPR), pack_pk_f16(POS_ONE, POS_HALF)) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - res = self.scalar_interp.step(instr, state) - expected = pack_pk_f16(NEG_ONE, POS_HALF) - self.assertEqual(res, expected) - self.assertEqual(state.get_reg(Reg(0, RegKind.VGPR)), expected) - # src1 (v1) must remain untouched - self.assertEqual(state.get_reg(Reg(1, RegKind.VGPR)), pack_pk_f16(POS_ONE, POS_HALF)) - - def test_dst_alias_src1(self) -> None: - state = ScalarMachineState() - state.set_reg(Reg(0, RegKind.VGPR), pack_pk_f16(NEG_ONE, POS_TWO)) - state.set_reg(Reg(1, RegKind.VGPR), pack_pk_f16(POS_ONE, POS_HALF)) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(1, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - res = self.scalar_interp.step(instr, state) - expected = pack_pk_f16(NEG_ONE, POS_HALF) - self.assertEqual(res, expected) - self.assertEqual(state.get_reg(Reg(1, RegKind.VGPR)), expected) - # src0 (v0) must remain untouched - self.assertEqual(state.get_reg(Reg(0, RegKind.VGPR)), pack_pk_f16(NEG_ONE, POS_TWO)) - - def test_dst_alias_both_srcs(self) -> None: - state = ScalarMachineState() - val = pack_pk_f16(POS_HALF, NEG_TWO) - state.set_reg(Reg(0, RegKind.VGPR), val) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MAX_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(0, RegKind.VGPR)), - ) - res = self.scalar_interp.step(instr, state) - self.assertEqual(res, val) - self.assertEqual(state.get_reg(Reg(0, RegKind.VGPR)), val) - - def test_inplace_iterative_accumulation(self) -> None: - state = ScalarMachineState() - # Initial: large values (100.0, 100.0) - state.set_reg(Reg(0, RegKind.VGPR), pack_pk_f16(f16_to_bits(100.0), f16_to_bits(100.0))) - - # Repeatedly compute min against descending values - for i in range(50): - step_val = float(50 - i) - state.set_reg(Reg(1, RegKind.VGPR), pack_pk_f16(f16_to_bits(step_val), f16_to_bits(step_val * 2.0))) - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - self.scalar_interp.step(instr, state) - - # After 50 iterations: lo should be 1.0, hi should be 2.0 - final_val = state.get_reg(Reg(0, RegKind.VGPR)) - lo, hi = unpack_pk_f16(final_val) - self.assertEqual(lo, f16_to_bits(1.0)) - self.assertEqual(hi, f16_to_bits(2.0)) - - def test_inplace_cross_half_swizzle_alias(self) -> None: - # Cross-half swizzle: v0 = v_pk_min_f16(v0.hi, v0.lo) - state = ScalarMachineState() - # lo = 5.0, hi = 2.0 - state.set_reg(Reg(0, RegKind.VGPR), pack_pk_f16(f16_to_bits(5.0), f16_to_bits(2.0))) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR), op_sel=(0, 0)), # select lo for both - src1=VOP3POperand(Reg(0, RegKind.VGPR), op_sel=(1, 1)), # select hi for both - ) - res = self.scalar_interp.step(instr, state) - # min(5.0, 2.0) = 2.0 for both lo and hi - expected = pack_pk_f16(f16_to_bits(2.0), f16_to_bits(2.0)) - self.assertEqual(res, expected) - self.assertEqual(state.get_reg(Reg(0, RegKind.VGPR)), expected) - - def test_simd_multi_lane_aliasing(self) -> None: - # SIMD in-place aliasing under EXEC mask - sentinel = 0x55AA55AA - state = SIMDState(num_lanes=32, exec_mask=0x0000_FFFF) # lower 16 lanes active - for lane in range(32): - state.set_lane_vgpr(lane, Reg(0, RegKind.VGPR), pack_pk_f16(POS_ONE, POS_ONE)) - state.set_lane_vgpr(lane, Reg(1, RegKind.VGPR), pack_pk_f16(POS_TWO, POS_TWO)) - state.set_lane_vgpr(lane, Reg(2, RegKind.VGPR), sentinel) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MAX_F16, - dst=Reg(0, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - self.simd_interp.step(instr, state) - for lane in range(32): - if lane < 16: - # Active: updated in place to max(1.0, 2.0) = 2.0 - self.assertEqual( - state.get_lane_reg(lane, Reg(0, RegKind.VGPR)), - pack_pk_f16(POS_TWO, POS_TWO), - ) - else: - # Inactive: untouched - self.assertEqual( - state.get_lane_reg(lane, Reg(0, RegKind.VGPR)), - pack_pk_f16(POS_ONE, POS_ONE), - ) - # Reg 1 and Reg 2 remain unchanged - self.assertEqual(state.get_lane_reg(lane, Reg(1, RegKind.VGPR)), pack_pk_f16(POS_TWO, POS_TWO)) - self.assertEqual(state.get_lane_reg(lane, Reg(2, RegKind.VGPR)), sentinel) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass(frozen=True) -class PackedConditionCodes: - """Architectural comparison condition codes for packed binary16 min/max.""" - equal_lo: bool - less_lo: bool - greater_lo: bool - unordered_lo: bool - equal_hi: bool - less_hi: bool - greater_hi: bool - unordered_hi: bool - zero_lo: bool - zero_hi: bool - negative_lo: bool - negative_hi: bool - - -@dataclass(frozen=True) -class PackedFPStatusFlags: - """IEEE 754 floating-point status flags for packed half-precision operations.""" - invalid: bool # e.g., sNaN operand - denormal: bool # e.g., subnormal operand or result - inexact: bool = False - overflow: bool = False - underflow: bool = False - - -def _eval_half_relation(a: int, b: int, res: int) -> Tuple[bool, bool, bool, bool, bool, bool]: - """Helper to evaluate relation for a single half (equal, less, greater, unordered, zero, neg).""" - nan_a = is_nan16(a) - nan_b = is_nan16(b) - if nan_a or nan_b: - unordered = True - equal = False - less = False - greater = False - else: - unordered = False - fa = bits_to_f16(a) - fb = bits_to_f16(b) - a_is_neg_zero = (a == NEG_ZERO) - b_is_neg_zero = (b == NEG_ZERO) - a_is_pos_zero = (a == POS_ZERO) - b_is_pos_zero = (b == POS_ZERO) - - if (a_is_neg_zero and b_is_pos_zero): - equal = False - less = True - greater = False - elif (a_is_pos_zero and b_is_neg_zero): - equal = False - less = False - greater = True - elif (a_is_neg_zero and b_is_neg_zero) or (a_is_pos_zero and b_is_pos_zero): - equal = True - less = False - greater = False - else: - equal = (fa == fb) - less = (fa < fb) - greater = (fa > fb) - - zero = is_zero16(res) - neg = bool(res & SIGN_MASK16) - return equal, less, greater, unordered, zero, neg - - -def evaluate_pk_condition_codes( - s0_u32: int, - s1_u32: int, - res_u32: int, - op_sel: Tuple[int, int, int, int] = (0, 0, 1, 1), -) -> PackedConditionCodes: - """Evaluate condition codes for packed operations across lo and hi halves.""" - s0_halves = unpack_pk_f16(s0_u32) - s1_halves = unpack_pk_f16(s1_u32) - res_halves = unpack_pk_f16(res_u32) - - eq_lo, lt_lo, gt_lo, un_lo, z_lo, neg_lo = _eval_half_relation( - s0_halves[op_sel[0]], s1_halves[op_sel[1]], res_halves[0] - ) - eq_hi, lt_hi, gt_hi, un_hi, z_hi, neg_hi = _eval_half_relation( - s0_halves[op_sel[2]], s1_halves[op_sel[3]], res_halves[1] - ) - - return PackedConditionCodes( - equal_lo=eq_lo, less_lo=lt_lo, greater_lo=gt_lo, unordered_lo=un_lo, - equal_hi=eq_hi, less_hi=lt_hi, greater_hi=gt_hi, unordered_hi=un_hi, - zero_lo=z_lo, zero_hi=z_hi, negative_lo=neg_lo, negative_hi=neg_hi, - ) - - -def evaluate_pk_status_flags( - s0_u32: int, - s1_u32: int, - res_u32: int, - op_sel: Tuple[int, int, int, int] = (0, 0, 1, 1), -) -> PackedFPStatusFlags: - """Evaluate IEEE 754 architectural flags for packed binary16 min/max.""" - s0_halves = unpack_pk_f16(s0_u32) - s1_halves = unpack_pk_f16(s1_u32) - res_halves = unpack_pk_f16(res_u32) - - in0_lo = s0_halves[op_sel[0]] - in1_lo = s1_halves[op_sel[1]] - in0_hi = s0_halves[op_sel[2]] - in1_hi = s1_halves[op_sel[3]] - - # Invalid operation triggered by any signaling NaN input - invalid = ( - is_snan16(in0_lo) or is_snan16(in1_lo) or - is_snan16(in0_hi) or is_snan16(in1_hi) - ) - - # Denormal flag triggered by any subnormal input or result - denormal = ( - is_subnormal16(in0_lo) or is_subnormal16(in1_lo) or - is_subnormal16(in0_hi) or is_subnormal16(in1_hi) or - is_subnormal16(res_halves[0]) or is_subnormal16(res_halves[1]) - ) - - return PackedFPStatusFlags( - invalid=invalid, - denormal=denormal, - inexact=False, - overflow=False, - underflow=False, - ) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow isolation.""" - - def test_condition_codes_ordering(self) -> None: - # lo: 1.0 < 2.0 (less_lo=True), hi: 3.0 > 0.5 (greater_hi=True) - s0 = pack_pk_f16(POS_ONE, f16_to_bits(3.0)) - s1 = pack_pk_f16(POS_TWO, POS_HALF) - res = oracle_pk_min_f16(s0, s1) - - cc = evaluate_pk_condition_codes(s0, s1, res) - self.assertTrue(cc.less_lo) - self.assertFalse(cc.greater_lo) - self.assertFalse(cc.equal_lo) - self.assertFalse(cc.unordered_lo) - - self.assertTrue(cc.greater_hi) - self.assertFalse(cc.less_hi) - self.assertFalse(cc.equal_hi) - self.assertFalse(cc.unordered_hi) - - def test_condition_codes_unordered_nan(self) -> None: - # lo: NaN vs 1.0 -> unordered_lo = True - # hi: 2.0 == 2.0 -> equal_hi = True - s0 = pack_pk_f16(QNAN_CANONICAL, POS_TWO) - s1 = pack_pk_f16(POS_ONE, POS_TWO) - res = oracle_pk_min_f16(s0, s1) - - cc = evaluate_pk_condition_codes(s0, s1, res) - self.assertTrue(cc.unordered_lo) - self.assertFalse(cc.less_lo) - self.assertFalse(cc.greater_lo) - self.assertFalse(cc.equal_lo) - - self.assertTrue(cc.equal_hi) - self.assertFalse(cc.unordered_hi) - - def test_condition_codes_signed_zeros(self) -> None: - # lo: -0.0 vs +0.0 -> -0.0 < +0.0, so less_lo=True, zero_lo=True, negative_lo=True - # hi: +0.0 vs -0.0 -> +0.0 > -0.0, so greater_hi=True - s0 = pack_pk_f16(NEG_ZERO, POS_ZERO) - s1 = pack_pk_f16(POS_ZERO, NEG_ZERO) - res = oracle_pk_min_f16(s0, s1) - - cc = evaluate_pk_condition_codes(s0, s1, res) - self.assertTrue(cc.less_lo) - self.assertTrue(cc.zero_lo) - self.assertTrue(cc.negative_lo) - - self.assertTrue(cc.greater_hi) - self.assertTrue(cc.zero_hi) - self.assertTrue(cc.negative_hi) # min(+0.0, -0.0) == -0.0 - - def test_status_flags_snan_invalid(self) -> None: - # Signaling NaN in lo triggers invalid flag - s0 = pack_pk_f16(SNAN_DEFAULT, POS_ONE) - s1 = pack_pk_f16(POS_TWO, POS_TWO) - res = oracle_pk_min_f16(s0, s1) - - flags = evaluate_pk_status_flags(s0, s1, res) - self.assertTrue(flags.invalid) - self.assertFalse(flags.denormal) - - def test_status_flags_subnormal_denormal(self) -> None: - # Subnormal input triggers denormal flag - s0 = pack_pk_f16(POS_MIN_SUBNORM, POS_ONE) - s1 = pack_pk_f16(POS_ONE, POS_ONE) - res = oracle_pk_min_f16(s0, s1) - - flags = evaluate_pk_status_flags(s0, s1, res) - self.assertFalse(flags.invalid) - self.assertTrue(flags.denormal) - - def test_carry_borrow_isolation(self) -> None: - # In RDNA2, packed VALU min/max instructions do not produce carry/borrow or alter VCC. - interp = ScalarInterpreter() - state = ScalarMachineState() - state.vcc = 0x12345678 # pre-existing VCC condition code - - state.set_reg(Reg(0, RegKind.VGPR), pack_pk_f16(POS_ONE, POS_TWO)) - state.set_reg(Reg(1, RegKind.VGPR), pack_pk_f16(POS_TWO, POS_ONE)) - - instr = VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(2, RegKind.VGPR), - src0=VOP3POperand(Reg(0, RegKind.VGPR)), - src1=VOP3POperand(Reg(1, RegKind.VGPR)), - ) - interp.step(instr, state) - # VCC must remain strictly preserved - self.assertEqual(state.vcc, 0x12345678) - - # Same for SIMD execution - simd_interp = SIMDInterpreter() - simd_state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - simd_state.vcc = 0x87654321 - simd_interp.step(instr, simd_state) - self.assertEqual(simd_state.vcc, 0x87654321) - - -# ============================================================================== -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# ============================================================================== - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 boundary extremes, subnormals, infinities, and NaNs.""" - - def test_subnormal_boundaries_and_ordering(self) -> None: - # Subnormal vs normal transition - self.assertEqual(oracle_min_f16(POS_MAX_SUBNORM, POS_MIN_NORMAL), POS_MAX_SUBNORM) - self.assertEqual(oracle_max_f16(POS_MAX_SUBNORM, POS_MIN_NORMAL), POS_MIN_NORMAL) - - # Negative subnormal vs negative normal - self.assertEqual(oracle_min_f16(NEG_MAX_SUBNORM, NEG_MIN_SUBNORM), NEG_MAX_SUBNORM) - self.assertEqual(oracle_max_f16(NEG_MAX_SUBNORM, NEG_MIN_SUBNORM), NEG_MIN_SUBNORM) - - # Subnormal vs zero - self.assertEqual(oracle_min_f16(POS_ZERO, POS_MIN_SUBNORM), POS_ZERO) - self.assertEqual(oracle_max_f16(POS_ZERO, POS_MIN_SUBNORM), POS_MIN_SUBNORM) - self.assertEqual(oracle_min_f16(NEG_ZERO, NEG_MIN_SUBNORM), NEG_MIN_SUBNORM) - self.assertEqual(oracle_max_f16(NEG_ZERO, NEG_MIN_SUBNORM), NEG_ZERO) - - def test_max_finite_and_infinity_boundaries(self) -> None: - # Max positive normal vs +inf - self.assertEqual(oracle_min_f16(POS_MAX_NORMAL, POS_INF), POS_MAX_NORMAL) - self.assertEqual(oracle_max_f16(POS_MAX_NORMAL, POS_INF), POS_INF) - - # Max negative normal vs -inf - self.assertEqual(oracle_min_f16(NEG_MAX_NORMAL, NEG_INF), NEG_INF) - self.assertEqual(oracle_max_f16(NEG_MAX_NORMAL, NEG_INF), NEG_MAX_NORMAL) - - # +inf vs -inf - self.assertEqual(oracle_min_f16(POS_INF, NEG_INF), NEG_INF) - self.assertEqual(oracle_max_f16(POS_INF, NEG_INF), POS_INF) - - def test_nan_suppression_against_infinities_and_subnormals(self) -> None: - qnan_custom = 0x7E55 - snan_custom = 0x7D33 - - # NaN vs +inf: +inf is selected! - self.assertEqual(oracle_min_f16(qnan_custom, POS_INF), POS_INF) - self.assertEqual(oracle_max_f16(qnan_custom, POS_INF), POS_INF) - - # NaN vs -inf: -inf is selected! - self.assertEqual(oracle_min_f16(snan_custom, NEG_INF), NEG_INF) - self.assertEqual(oracle_max_f16(snan_custom, NEG_INF), NEG_INF) - - # NaN vs subnormal: subnormal is selected! - self.assertEqual(oracle_min_f16(qnan_custom, POS_MIN_SUBNORM), POS_MIN_SUBNORM) - self.assertEqual(oracle_max_f16(qnan_custom, POS_MIN_SUBNORM), POS_MIN_SUBNORM) - - def test_both_operands_nan_variants(self) -> None: - qnan1 = 0x7E12 - qnan2 = 0x7E34 - res_min = oracle_min_f16(qnan1, qnan2) - self.assertTrue(is_qnan16(res_min)) - - snan = 0x7D44 - res_max = oracle_max_f16(snan, qnan1) - self.assertTrue(is_qnan16(res_max)) - - def test_packed_asymmetric_extremes(self) -> None: - # lo: NaN vs subnormal -> subnormal selected - # hi: +inf vs -inf -> min selects -inf, max selects +inf - s0 = pack_pk_f16(QNAN_CANONICAL, POS_INF) - s1 = pack_pk_f16(POS_MAX_SUBNORM, NEG_INF) - - res_min = oracle_pk_min_f16(s0, s1) - self.assertEqual(res_min, pack_pk_f16(POS_MAX_SUBNORM, NEG_INF)) - - res_max = oracle_pk_max_f16(s0, s1) - self.assertEqual(res_max, pack_pk_f16(POS_MAX_SUBNORM, POS_INF)) - - def test_clamp_extremes_interaction(self) -> None: - # Positive subnormal (within [0.0, 1.0]) is preserved under clamp - self.assertEqual(clamp_f16(POS_MIN_SUBNORM), POS_MIN_SUBNORM) - self.assertEqual(clamp_f16(POS_MAX_SUBNORM), POS_MAX_SUBNORM) - - # Negative subnormal clamps to +0.0 - self.assertEqual(clamp_f16(NEG_MIN_SUBNORM), POS_ZERO) - self.assertEqual(clamp_f16(NEG_MAX_SUBNORM), POS_ZERO) - - # +inf clamps to 1.0 - self.assertEqual(clamp_f16(POS_INF), POS_ONE) - - # -inf clamps to +0.0 - self.assertEqual(clamp_f16(NEG_INF), POS_ZERO) - - # NaN clamps to +0.0 - self.assertEqual(clamp_f16(QNAN_CANONICAL), POS_ZERO) - self.assertEqual(clamp_f16(SNAN_DEFAULT), POS_ZERO) - - -# ============================================================================== -# Negative Controls, Syntax Rejection, and Mutation Detection -# ============================================================================== - -class TestNegativeControlsAndMutationDetection(unittest.TestCase): - """Negative controls, architectural syntax rejection, and mutation detection tests.""" - - def test_syntax_rejection_registers(self) -> None: - with self.assertRaises(ValueError): - Reg(256, RegKind.VGPR) - with self.assertRaises(ValueError): - Reg(-1, RegKind.VGPR) - with self.assertRaises(ValueError): - Reg(106, RegKind.SGPR) - with self.assertRaises(ValueError): - Reg(-1, RegKind.SGPR) - - def test_syntax_rejection_instruction_dst(self) -> None: - # Cannot assign SGPR as destination of packed VALU instruction - with self.assertRaises(TypeError): - VPkMinMaxF16Instruction( - opcode=Opcode.V_PK_MIN_F16, - dst=Reg(0, RegKind.SGPR), - src0=VOP3POperand(Reg(1, RegKind.VGPR)), - src1=VOP3POperand(Reg(2, RegKind.VGPR)), - ) - - def test_syntax_rejection_op_sel(self) -> None: - with self.assertRaises(ValueError): - VOP3POperand(Reg(0, RegKind.VGPR), op_sel=(0, 2)) - with self.assertRaises(ValueError): - VOP3POperand(Reg(0, RegKind.VGPR), op_sel=(-1, 1)) - - def test_syntax_rejection_literal_bounds(self) -> None: - with self.assertRaises(ValueError): - Literal32(-1) - with self.assertRaises(ValueError): - Literal32(0x1_0000_0000) - - def test_syntax_rejection_simd_lanes(self) -> None: - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDState(num_lanes=128) - - def test_syntax_rejection_lane_reg_type(self) -> None: - state = SIMDState(num_lanes=32) - with self.assertRaises(TypeError): - state.set_lane_vgpr(0, Reg(0, RegKind.SGPR), 0) - - def test_mutation_detection_opcode_inversion(self) -> None: - # Sabotaging min to max must be detected - s0 = pack_pk_f16(POS_ONE, POS_TWO) - s1 = pack_pk_f16(POS_HALF, POS_HALF) - - correct_min = oracle_pk_min_f16(s0, s1) - mutated_max = oracle_pk_max_f16(s0, s1) - - self.assertNotEqual(correct_min, mutated_max) - self.assertEqual(correct_min, pack_pk_f16(POS_HALF, POS_HALF)) - self.assertEqual(mutated_max, pack_pk_f16(POS_ONE, POS_TWO)) - - def test_mutation_detection_signed_zero_tiebreak(self) -> None: - # Sabotaging signed zero tiebreak: min(-0.0, +0.0) must be -0.0, not +0.0 - got = oracle_min_f16(NEG_ZERO, POS_ZERO) - self.assertEqual(got, NEG_ZERO) - self.assertNotEqual(got, POS_ZERO) - - # max(-0.0, +0.0) must be +0.0, not -0.0 - got_max = oracle_max_f16(NEG_ZERO, POS_ZERO) - self.assertEqual(got_max, POS_ZERO) - self.assertNotEqual(got_max, NEG_ZERO) - - def test_mutation_detection_nan_suppression(self) -> None: - # Sabotaging NaN suppression to propagate NaN must be detected - got = oracle_min_f16(QNAN_CANONICAL, POS_TWO) - self.assertEqual(got, POS_TWO) - self.assertFalse(is_nan16(got)) - - def test_mutation_detection_clamp_bypass(self) -> None: - # Sabotaging clamp (omitting clamp on 2.0) must be detected - val = POS_TWO # 2.0 - clamped = clamp_f16(val) - self.assertEqual(clamped, POS_ONE) # clamped to 1.0 - self.assertNotEqual(clamped, val) - - def test_mutation_detection_op_sel_tampering(self) -> None: - # s0: lo=1.0, hi=2.0; s1: lo=1.5, hi=3.0 - s0 = pack_pk_f16(POS_ONE, POS_TWO) - s1 = pack_pk_f16(f16_to_bits(1.5), f16_to_bits(3.0)) - - # Standard op_sel: lo gets s0.lo (1.0) vs s1.lo (1.5) -> 1.0 - # hi gets s0.hi (2.0) vs s1.hi (3.0) -> 2.0 - std_res = oracle_pk_min_f16(s0, s1, op_sel=(0, 0, 1, 1)) - - # Tampered op_sel: swap s0 halves - # lo gets s0.hi (2.0) vs s1.lo (1.5) -> 1.5 - # hi gets s0.lo (1.0) vs s1.hi (3.0) -> 1.0 - tampered_res = oracle_pk_min_f16(s0, s1, op_sel=(1, 0, 0, 1)) - - self.assertNotEqual(std_res, tampered_res) - self.assertEqual(std_res, pack_pk_f16(POS_ONE, POS_TWO)) - self.assertEqual(tampered_res, pack_pk_f16(f16_to_bits(1.5), POS_ONE)) +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF + + +def ref_min(a, b): + """v_min_f16: a NaN operand yields the other operand (both NaN: a NaN); -0 < +0.""" + if is_nan(a) or is_nan(b): + return QNAN if is_nan(a) and is_nan(b) else (b if is_nan(a) else a) + if (a | b) & 0x7FFF == 0: + return a | b # both zero: -0 wins + return a if f16_value(a) < f16_value(b) else b + + +def ref_max(a, b): + """v_max_f16: a NaN operand yields the other operand (both NaN: a NaN); +0 > -0.""" + if is_nan(a) or is_nan(b): + return QNAN if is_nan(a) and is_nan(b) else (b if is_nan(a) else a) + if (a | b) & 0x7FFF == 0: + return a & b + return a if f16_value(a) > f16_value(b) else b + + + +def P(lo, hi): + """A dword holding two binary16 values.""" + return (hi << 16) | lo + + +def run(line, seeds, old=0xDEADBEEF): + """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0 (seeds map reg -> dword).""" + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_pk_minmax_f16", prog))[0] + + +def half(w, i): + return (w >> (16 * i)) & 0xFFFF + + +def pk_ref(fn, srcs, op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): + """Reference for one packed op: the low result reads half op_sel[i] of source i (negated by neg_lo[i]), the high + result half op_sel_hi[i] (negated by neg_hi[i]); defaults are op_sel 0, op_sel_hi 1, no negation.""" + n = len(srcs) + op_sel, op_sel_hi = op_sel or [0] * n, op_sel_hi or [1] * n + neg_lo, neg_hi = neg_lo or [0] * n, neg_hi or [0] * n + out = [] + for sel, ng in ((op_sel, neg_lo), (op_sel_hi, neg_hi)): + r = fn(*[half(s, h) ^ (0x8000 if g else 0) for s, h, g in zip(srcs, sel, ng)]) + out.append(clamp01(r) if clamp else r) + return P(out[0], out[1]) + + +def same_pk(a, b): + return same_f16(a & 0xFFFF, b & 0xFFFF) and same_f16(a >> 16, b >> 16) + + +def mods_text(op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): + t = "" + for name, v in (("op_sel", op_sel), ("op_sel_hi", op_sel_hi), ("neg_lo", neg_lo), ("neg_hi", neg_hi)): + if v is not None: + t += f" {name}:[{','.join(map(str, v))}]" + return t + (" clamp" if clamp else "") + + +def regs(n): + return ", ".join(f"v{i}" for i in range(1, n + 1)) + + +# mnemonic -> (source count, reference for one lane) +OPS = {"v_pk_min_f16": (2, ref_min), "v_pk_max_f16": (2, ref_max)} + +# mnemonic -> rows of (source dwords..., D), written by hand; lane 0 is the low half +CASES = { + 'v_pk_min_f16': [ + (P(ONE, THREE), P(TWO, HALF), P(ONE, HALF)), # (min(1, 2), min(3, 0.5)) + (P(0xBC00, 0x0000), P(ONE, 0x8000), P(0xBC00, 0x8000)), # (min(-1, 1), min(+0, -0) = -0) + (P(0x8000, 0x8000), P(0x0000, 0x8000), P(0x8000, 0x8000)), # (min(-0, +0) = -0, min(-0, -0) = -0) + (P(QNAN, ONE), P(ONE, QNAN), P(ONE, ONE)), # a NaN operand yields the other one + (P(QNAN, INF), P(QNAN, MAXH), P(QNAN, MAXH)), # (both NaN: NaN, min(inf, 65504)) + (P(NINF, MIN_SUB), P(0xFBFF, 0x0000), P(NINF, 0x0000)), # (min(-inf, -65504), min(2^-24, 0)) + (P(0x8001, 0x3C01), P(MIN_SUB, ONE), P(0x8001, ONE)), # (min(-2^-24, 2^-24), min(1 + 2^-10, 1)) + ], + 'v_pk_max_f16': [ + (P(ONE, THREE), P(TWO, HALF), P(TWO, THREE)), # (max(1, 2), max(3, 0.5)) + (P(0xBC00, 0x0000), P(ONE, 0x8000), P(ONE, 0x0000)), # (max(-1, 1), max(+0, -0) = +0) + (P(0x8000, 0x8000), P(0x0000, 0x8000), P(0x0000, 0x8000)), # (max(-0, +0) = +0, max(-0, -0) = -0) + (P(QNAN, ONE), P(ONE, QNAN), P(ONE, ONE)), # a NaN operand yields the other one + (P(QNAN, INF), P(QNAN, MAXH), P(QNAN, INF)), # (both NaN: NaN, max(inf, 65504)) + (P(NINF, MIN_SUB), P(0xFBFF, 0x0000), P(0xFBFF, MIN_SUB)), # (max(-inf, -65504), max(2^-24, 0)) + (P(0x8001, 0x3C01), P(MIN_SUB, ONE), P(MIN_SUB, 0x3C01)), # (max(-2^-24, 2^-24), max(1 + 2^-10, 1)) + ], + +} + +# mnemonic -> (sources, modifier text, D), by hand. S0 = (1.0, 3.0), S1 = (0.5, -0.25), S2 = (0.25, -1.0) as +# (low, high) halves. +S0, S1, S2 = P(ONE, THREE), P(HALF, 0xB400), P(QUARTER, 0xBC00) +MODS = { + 'v_pk_min_f16': [ + ((S0, S1), "", P(0x3800, 0xB400)), # (min(1, 0.5), min(3, -0.25)) + ((S0, S1), " op_sel:[1,0]", P(0x3800, 0xB400)), # low: min(3, 0.5) + ((S0, S1), " op_sel:[0,1] op_sel_hi:[0,0]", P(0xB400, 0x3800)), # low: min(1, -0.25); high: min(1, 0.5) + ((S0, S1), " op_sel:[1,1] op_sel_hi:[0,0]", P(0xB400, 0x3800)), # low: min(3, -0.25); high: min(1, 0.5) + ((S0, S1), " neg_lo:[1,0]", P(0xBC00, 0xB400)), # low: min(-1, 0.5) + ((S0, S1), " neg_hi:[0,1]", P(0x3800, 0x3400)), # high: min(3, 0.25) + ((P(0x3E00, 0xB800), P(TWO, 0xBC00)), " clamp", P(ONE, 0x0000)), # (1.5, -1) -> (1, 0) + ((P(HALF, QUARTER), P(0x3A00, ONE)), " clamp", P(HALF, QUARTER)), # inside [0, 1]: unchanged + ], + 'v_pk_max_f16': [ + ((S0, S1), "", P(ONE, THREE)), # (max(1, 0.5), max(3, -0.25)) + ((S0, S1), " op_sel:[1,0]", P(THREE, THREE)), # low: max(3, 0.5) + ((S0, S1), " op_sel:[0,1] op_sel_hi:[0,0]", P(ONE, ONE)), # low: max(1, -0.25); high: max(1, 0.5) + ((S0, S1), " op_sel:[1,1] op_sel_hi:[0,0]", P(THREE, ONE)), # low: max(3, -0.25); high: max(1, 0.5) + ((S0, S1), " neg_lo:[1,0]", P(HALF, THREE)), # low: max(-1, 0.5) + ((S0, S1), " neg_hi:[0,1]", P(ONE, THREE)), # high: max(3, 0.25) + ((P(0x3E00, 0xB800), P(TWO, 0xBC00)), " clamp", P(ONE, 0x0000)), # (2, -0.5) -> (1, 0) + ((P(HALF, QUARTER), P(0x3A00, ONE)), " clamp", P(0x3A00, ONE)), # inside [0, 1]: unchanged + ], + +} + + +class PkMinMaxF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for op, rows in CASES.items(): + for *src, want in rows: + with self.subTest(op=op, src=[hex(s) for s in src]): + self.assertTrue(same_pk(pk_ref(OPS[op][1], src), want), hex(pk_ref(OPS[op][1], src))) + + def test_per_lane_results(self): + for op, rows in CASES.items(): + for *src, want in rows: + with self.subTest(op=op, src=[hex(s) for s in src]): + got = run(f"{op} v0, {regs(len(src))}", {f"v{i}": s for i, s in enumerate(src, 1)}) + self.assertTrue(same_pk(got, want), hex(got)) + + def test_sgpr_sources(self): + for op, rows in CASES.items(): + for *src, want in rows[:6]: + n = len(src) + forms = [("all sgpr", ", ".join(f"s{i}" for i in range(1, n + 1)), {f"s{i}": s for i, s in enumerate(src, 1)}), + ("sgpr src0", ", ".join(["s1"] + [f"v{i}" for i in range(2, n + 1)]), + {"s1": src[0], **{f"v{i}": s for i, s in enumerate(src[1:], 2)}})] + for form, text, seeds in forms: + with self.subTest(op=op, src=[hex(s) for s in src], form=form): + self.assertTrue(same_pk(run(f"{op} v0, {text}", seeds), want)) + + def test_hand_written_modifier_cases(self): + for op, rows in MODS.items(): + for srcs, mods, want in rows: + with self.subTest(op=op, mods=mods): + got = run(f"{op} v0, {regs(len(srcs))}{mods}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, want), hex(got)) + + def test_every_op_sel_and_op_sel_hi_combination(self): + a, b, c = P(0x3E00, 0xC400), P(0x4900, 0x3A00), P(0xB800, 0x4D00) # distinct halves: 1.5/-4, 10/.75, -.5/20 + for op, (n, fn) in OPS.items(): + srcs = [a, b, c][:n] + for sel in range(1 << n): + for selhi in range(1 << n): + os_, oh = [(sel >> i) & 1 for i in range(n)], [(selhi >> i) & 1 for i in range(n)] + with self.subTest(op=op, op_sel=os_, op_sel_hi=oh): + got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh)), hex(got)) + + def test_random_operands_and_modifiers(self): + rng = random.Random(0x31A5) + pool = [0x0000, 0x8000, ONE, 0xBC00, TWO, HALF, THREE, MAXH, 0xFBFF, INF, NINF, QNAN, MIN_NORMAL, MIN_SUB, + 0x8001, MAX_SUB, 0x3C01, 0x6800, 0x6801, 0x4C00, 0x1000, 0x9000] + for _ in range(150): + op = rng.choice(sorted(OPS)) + n, fn = OPS[op] + srcs = [P(*[rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(2)]) + for _ in range(n)] + os_, oh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] + nl, nh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] + with self.subTest(op=op, src=[hex(s) for s in srcs], mods=(os_, oh, nl, nh)): + got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh, nl, nh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh, nl, nh)), hex(got)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_pk_mul_f16.py b/tests/semantic/test_valu_pk_mul_f16.py index 17948ce64..3c3f453f1 100644 --- a/tests/semantic/test_valu_pk_mul_f16.py +++ b/tests/semantic/test_valu_pk_mul_f16.py @@ -1,1324 +1,167 @@ -"""Semantic reference tests and mathematical oracle for AMD RDNA2 v_pk_mul_f16. +"""v_pk_mul_f16 (RDNA2 VOP3P): D.f16[i] = S0.f16[i] * S1.f16[i] for both halves, binary16 with round to nearest even. -RDNA2 Vector Arithmetic Logic Unit (VALU) Architecture: - In AMD RDNA2 (GFX10/GFX1030) ISA, vector registers (VGPRs) are 32 bits wide. - The packed half-precision floating-point instruction v_pk_mul_f16 operates on two - independent 16-bit IEEE 754 half-precision (binary16) floats packed inside 32-bit registers. - - Register Packing: - Bits [15:0] : Low half-precision float (lo) - Bits [31:16] : High half-precision float (hi) - - Instruction: - v_pk_mul_f16 dst, src0, src1 [op_sel:[s0_lo, s1_lo]] [op_sel_hi:[s0_hi, s1_hi]] - [neg_lo:[s0_lo, s1_lo]] [neg_hi:[s0_hi, s1_hi]] [clamp] - - IEEE-754 binary16 encoding: - - 1 sign bit (bit 15) - - 5 exponent bits with bias 15 (bits 14:10) - - 10 mantissa / fraction bits (bits 9:0) - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py. The expected +words are written down by hand (from the ISA) next to each case; the plain-Python binary16 reference in +tests/semantic/f16_ref.py rechecks them lane by lane and drives seeded random operands and modifier combinations. +Covers per-lane results, op_sel / op_sel_hi half selection, neg_lo / neg_hi, clamp and SGPR sources. +Standard library only: no GPU, no LLVM, no game data. """ -from __future__ import annotations - -from dataclasses import dataclass, field -import enum -from fractions import Fraction -import math -import struct -from typing import List, Optional, Tuple, Union +import os +import random +import sys import unittest -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -# IEEE-754 binary16 bit constants -F16_POS_ZERO = 0x0000 -F16_NEG_ZERO = 0x8000 -F16_POS_INF = 0x7C00 -F16_NEG_INF = 0xFC00 -F16_CANONICAL_QNAN = 0x7E00 -F16_QUIET_BIT = 0x0200 - -F16_EXP_MASK = 0x7C00 -F16_MANT_MASK = 0x03FF -F16_SIGN_MASK = 0x8000 - -F16_ONE = 0x3C00 # 1.0 -F16_NEG_ONE = 0xBC00 # -1.0 -F16_TWO = 0x4000 # 2.0 -F16_HALF = 0x3800 # 0.5 -F16_MIN_NORMAL = 0x0400 # 2^-14 = ~6.1035e-5 -F16_MAX_NORMAL = 0x7BFF # 65504.0 -F16_MIN_SUBNORMAL = 0x0001 # 2^-24 = ~5.9605e-8 -F16_MAX_SUBNORMAL = 0x03FF # 2^-14 * (1023/1024) - -OLD_VGPR_SENTINEL = 0xDEADBEEF - - -def u16(val: int) -> int: - """Normalize integer to unsigned 16-bit range [0, 65535].""" - return val & MASK16 - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def pack_f16x2(lo: int, hi: int) -> int: - """Pack two 16-bit half-precision floats into a 32-bit dword.""" - return ((hi & MASK16) << 16) | (lo & MASK16) - - -def unpack_f16x2(word: int) -> Tuple[int, int]: - """Unpack a 32-bit dword into (lo, hi) 16-bit half-precision words.""" - return word & MASK16, (word >> 16) & MASK16 - - -def f16_to_u16(val: float) -> int: - """Pack a float into an IEEE-754 binary16 16-bit unsigned integer.""" - try: - return struct.unpack(" float: - """Unpack an IEEE-754 binary16 16-bit unsigned integer into a float.""" - return struct.unpack(" bool: - """Return True if the 16-bit pattern represents an IEEE-754 NaN.""" - return ((bits & F16_EXP_MASK) == F16_EXP_MASK) and ((bits & F16_MANT_MASK) != 0) - - -def is_f16_snan(bits: int) -> bool: - """Return True if the 16-bit pattern represents a signaling NaN.""" - return is_f16_nan(bits) and ((bits & F16_QUIET_BIT) == 0) - - -def is_f16_qnan(bits: int) -> bool: - """Return True if the 16-bit pattern represents a quiet NaN.""" - return is_f16_nan(bits) and ((bits & F16_QUIET_BIT) != 0) - - -def is_f16_zero(bits: int) -> bool: - """Return True if the 16-bit pattern represents +0.0 or -0.0.""" - return (bits & (F16_EXP_MASK | F16_MANT_MASK)) == 0 - - -def is_f16_inf(bits: int) -> bool: - """Return True if the 16-bit pattern represents +inf or -inf.""" - return ((bits & F16_EXP_MASK) == F16_EXP_MASK) and ((bits & F16_MANT_MASK) == 0) - - -def is_f16_subnormal(bits: int) -> bool: - """Return True if the 16-bit pattern represents a subnormal/denormal float.""" - return ((bits & F16_EXP_MASK) == 0) and ((bits & F16_MANT_MASK) != 0) - - -def is_f16_normal(bits: int) -> bool: - """Return True if the 16-bit pattern represents a normalized finite float.""" - exp = (bits >> 10) & 0x1F - return 0 < exp < 0x1F - - -def f16_sign(bits: int) -> int: - """Return the sign bit (0 or 1).""" - return (bits >> 15) & 1 - - -def quiet_f16(bits: int) -> int: - """Force an IEEE-754 half-precision NaN to quiet by setting the quiet bit.""" - return (bits & MASK16) | F16_QUIET_BIT - - -def ref_mul_f16(s0: int, s1: int, *, clamp: bool = False) -> int: - """Reference mathematical oracle for a single 16-bit half-precision multiply. - - Computes S0 * S1 conforming strictly to IEEE-754-2008 binary16 arithmetic and - RDNA2 VALU hardware specifications. - """ - s0 &= MASK16 - s1 &= MASK16 - - # 1. NaN handling: If either operand is NaN - if is_f16_nan(s0) or is_f16_nan(s1): - if clamp: - # Under RDNA2 VALU clamp, clamped NaN produces +0.0 - return F16_POS_ZERO - # Signaling NaN quieted, or quiet NaN propagated; src0 has priority - if is_f16_nan(s0): - return quiet_f16(s0) - return quiet_f16(s1) - - # 2. Infinity and Zero combinations - sign = f16_sign(s0) ^ f16_sign(s1) - s0_inf = is_f16_inf(s0) - s1_inf = is_f16_inf(s1) - s0_zero = is_f16_zero(s0) - s1_zero = is_f16_zero(s1) - - if (s0_inf and s1_zero) or (s1_inf and s0_zero): - # inf * 0.0 is an Invalid Operation -> returns Canonical Quiet NaN - return F16_POS_ZERO if clamp else F16_CANONICAL_QNAN - - if s0_inf or s1_inf: - res = F16_NEG_INF if sign else F16_POS_INF - if clamp: - return F16_ONE if res == F16_POS_INF else F16_POS_ZERO - return res - - if s0_zero or s1_zero: - res = F16_NEG_ZERO if sign else F16_POS_ZERO - if clamp and res == F16_NEG_ZERO: - return F16_POS_ZERO - return res - - # 3. Finite * Finite multiplication using Python float & IEEE 754 half packing - f0 = u16_to_f16(s0) - f1 = u16_to_f16(s1) - prod = f0 * f1 - - res_bits = f16_to_u16(prod) - - # 4. Apply clamp [0.0, 1.0] - if clamp: - if is_f16_nan(res_bits): - return F16_POS_ZERO - res_float = u16_to_f16(res_bits) - if res_float < 0.0 or res_bits == F16_NEG_ZERO: - return F16_POS_ZERO - if res_float > 1.0: - return F16_ONE - - return res_bits - - -def ref_v_pk_mul_f16( - src0_dword: int, - src1_dword: int, - *, - op_sel: Tuple[int, int] = (0, 0), - op_sel_hi: Tuple[int, int] = (1, 1), - neg_lo: Tuple[int, int] = (0, 0), - neg_hi: Tuple[int, int] = (0, 0), - clamp: bool = False, -) -> int: - """Reference mathematical oracle for packed dual-lane v_pk_mul_f16. - - Selects half-words via op_sel and op_sel_hi, applies per-half negation modifiers, - multiplies both halves independently, and clamps results if requested. - """ - s0_lo_orig, s0_hi_orig = unpack_f16x2(src0_dword) - s1_lo_orig, s1_hi_orig = unpack_f16x2(src1_dword) - - # op_sel selects low calculation inputs - s0_lo = s0_hi_orig if op_sel[0] else s0_lo_orig - s1_lo = s1_hi_orig if op_sel[1] else s1_lo_orig - - # op_sel_hi selects high calculation inputs - s0_hi = s0_hi_orig if op_sel_hi[0] else s0_lo_orig - s1_hi = s1_hi_orig if op_sel_hi[1] else s1_lo_orig - - # Apply negation modifiers (neg toggles bit 15) - if neg_lo[0]: - s0_lo ^= F16_SIGN_MASK - if neg_lo[1]: - s1_lo ^= F16_SIGN_MASK - - if neg_hi[0]: - s0_hi ^= F16_SIGN_MASK - if neg_hi[1]: - s1_hi ^= F16_SIGN_MASK - - # Independent half multiplications - res_lo = ref_mul_f16(s0_lo, s1_lo, clamp=clamp) - res_hi = ref_mul_f16(s0_hi, s1_hi, clamp=clamp) - - return pack_f16x2(res_lo, res_hi) - - -# ----------------------------------------------------------------------------- -# Symbolic AST Definitions and Typed Expressions -# ----------------------------------------------------------------------------- - -class RegType(enum.Enum): - """Architecture register classification.""" - VGPR = "v" - SGPR = "s" - LITERAL = "lit" - INLINE_CONST = "k" - - -@dataclass(frozen=True) -class Reg: - """Architectural register designator.""" - index: int - reg_type: RegType = RegType.VGPR - - def __post_init__(self) -> None: - if self.reg_type == RegType.VGPR: - if not (0 <= self.index <= 255): - raise ValueError(f"VGPR index out of valid architectural range [0, 255]: {self.index}") - elif self.reg_type == RegType.SGPR: - if not (0 <= self.index <= 105): - raise ValueError(f"SGPR index out of valid architectural range [0, 105]: {self.index}") - - def __str__(self) -> str: - return f"{self.reg_type.value}{self.index}" - - -@dataclass(frozen=True) -class VOP3POperand: - """Typed operand for VOP3P packed vector instructions.""" - reg: Optional[Reg] = None - literal_val: Optional[int] = None - inline_val: Optional[float] = None - - def __post_init__(self) -> None: - sources = [self.reg is not None, self.literal_val is not None, self.inline_val is not None] - if sum(sources) != 1: - raise ValueError("VOP3POperand must have exactly one source (reg, literal_val, or inline_val)") - - @property - def is_vgpr(self) -> bool: - return self.reg is not None and self.reg.reg_type == RegType.VGPR - - @property - def is_sgpr(self) -> bool: - return self.reg is not None and self.reg.reg_type == RegType.SGPR - - @property - def is_literal(self) -> bool: - return self.literal_val is not None - - @property - def is_inline_const(self) -> bool: - return self.inline_val is not None - - def __str__(self) -> str: - if self.reg is not None: - return str(self.reg) - if self.literal_val is not None: - return f"0x{self.literal_val:08x}" - return f"{self.inline_val}" - - -@dataclass(frozen=True) -class VPkMulF16Instruction: - """Symbolic AST node representing AMD RDNA2 v_pk_mul_f16 instruction.""" - dst: Reg - src0: VOP3POperand - src1: VOP3POperand - op_sel: Tuple[int, int] = (0, 0) - op_sel_hi: Tuple[int, int] = (1, 1) - neg_lo: Tuple[int, int] = (0, 0) - neg_hi: Tuple[int, int] = (0, 0) - clamp: bool = False - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise ValueError(f"Destination must be a VGPR, got {self.dst}") - for name, pair in [ - ("op_sel", self.op_sel), - ("op_sel_hi", self.op_sel_hi), - ("neg_lo", self.neg_lo), - ("neg_hi", self.neg_hi), - ]: - if len(pair) != 2 or not all(x in (0, 1) for x in pair): - raise ValueError(f"{name} modifier must be a tuple of two binary digits (0 or 1), got {pair}") - - def disasm(self) -> str: - """Format symbolic instruction into standard RDNA2 disassembly text.""" - parts = [f"v_pk_mul_f16 {self.dst}, {self.src0}, {self.src1}"] - if self.op_sel != (0, 0): - parts.append(f"op_sel:[{self.op_sel[0]},{self.op_sel[1]}]") - if self.op_sel_hi != (1, 1): - parts.append(f"op_sel_hi:[{self.op_sel_hi[0]},{self.op_sel_hi[1]}]") - if self.neg_lo != (0, 0): - parts.append(f"neg_lo:[{self.neg_lo[0]},{self.neg_lo[1]}]") - if self.neg_hi != (0, 0): - parts.append(f"neg_hi:[{self.neg_hi[0]},{self.neg_hi[1]}]") - if self.clamp: - parts.append("clamp") - return " ".join(parts) - - -# ----------------------------------------------------------------------------- -# Deterministic Scalar Instruction Interpreter -# ----------------------------------------------------------------------------- - -@dataclass -class ScalarState: - """Architectural state of a single execution lane.""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 106) - m0: int = 0 - - def get_vgpr(self, index: int) -> int: - return self.vgprs[index] & MASK32 - - def set_vgpr(self, index: int, value: int) -> None: - self.vgprs[index] = value & MASK32 - - def get_sgpr(self, index: int) -> int: - return self.sgprs[index] & MASK32 - - def set_sgpr(self, index: int, value: int) -> None: - self.sgprs[index] = value & MASK32 - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU instructions.""" - - @staticmethod - def resolve_operand(operand: VOP3POperand, state: ScalarState) -> int: - """Resolve operand to a 32-bit dword value.""" - if operand.is_vgpr: - assert operand.reg is not None - return state.get_vgpr(operand.reg.index) - if operand.is_sgpr: - assert operand.reg is not None - return state.get_sgpr(operand.reg.index) - if operand.is_literal: - assert operand.literal_val is not None - return operand.literal_val & MASK32 - if operand.is_inline_const: - assert operand.inline_val is not None - # In RDNA2, an inline float constant on packed-16 multiplies is duplicated across both halves - f16_val = f16_to_u16(operand.inline_val) - return pack_f16x2(f16_val, f16_val) - raise ValueError(f"Unsupported operand: {operand}") - - def step(self, instr: VPkMulF16Instruction, state: ScalarState) -> int: - """Execute a single v_pk_mul_f16 instruction deterministically.""" - s0_val = self.resolve_operand(instr.src0, state) - s1_val = self.resolve_operand(instr.src1, state) - - res = ref_v_pk_mul_f16( - s0_val, - s1_val, - op_sel=instr.op_sel, - op_sel_hi=instr.op_sel_hi, - neg_lo=instr.neg_lo, - neg_hi=instr.neg_hi, - clamp=instr.clamp, - ) - - state.set_vgpr(instr.dst.index, res) - return res - - -# ----------------------------------------------------------------------------- -# SIMD Multi-Lane Divergence and EXEC Masking Model -# ----------------------------------------------------------------------------- - -@dataclass -class SIMDState: - """Architectural SIMD wavefront state for Wave32 or Wave64.""" - wave_size: int = 32 - exec_mask: int = MASK32 - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 106) - - def __post_init__(self) -> None: - if self.wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {self.wave_size}, must be 32 or 64") - if not self.vgprs: - # Initialize 256 VGPRs for each lane - self.vgprs = [[0] * 256 for _ in range(self.wave_size)] - - def is_lane_active(self, lane: int) -> bool: - """Return True if the specified lane is active under current EXEC mask.""" - return bool(self.exec_mask & (1 << lane)) - - def get_vgpr(self, lane: int, index: int) -> int: - return self.vgprs[lane][index] & MASK32 - - def set_vgpr(self, lane: int, index: int, value: int) -> None: - self.vgprs[lane][index] = value & MASK32 - - def get_sgpr(self, index: int) -> int: - return self.sgprs[index] & MASK32 - - def set_sgpr(self, index: int, value: int) -> None: - self.sgprs[index] = value & MASK32 - - -class SIMDInterpreter: - """SIMD wavefront interpreter supporting Wave32/Wave64 and EXEC masking.""" - - def __init__(self) -> None: - self.scalar_interp = ScalarInterpreter() - - def step(self, instr: VPkMulF16Instruction, state: SIMDState) -> List[Optional[int]]: - """Execute instruction across all lanes in the wavefront subject to EXEC mask.""" - results: List[Optional[int]] = [None] * state.wave_size - - for lane in range(state.wave_size): - if state.is_lane_active(lane): - # Construct temporary scalar state view for this lane - lane_state = ScalarState( - vgprs=state.vgprs[lane], - sgprs=state.sgprs, - ) - res = self.scalar_interp.step(instr, lane_state) - results[lane] = res - # Inactive lanes retain previous destination VGPR contents untouched - - return results - - -# ----------------------------------------------------------------------------- -# Condition Codes, Status Flags, and Mantissa Carry Tracking -# ----------------------------------------------------------------------------- - -@dataclass(frozen=True) -class FPStatusFlags: - """IEEE-754 architectural exception and status flags.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - denormal: bool = False - zero: bool = False - negative: bool = False - infinite: bool = False - nan: bool = False - - -def evaluate_f16_mul_flags(s0: int, s1: int, res: int) -> FPStatusFlags: - """Evaluate architectural status flags for half-precision multiplication.""" - s0 &= MASK16 - s1 &= MASK16 - res &= MASK16 - - # 1. Invalid operation & NaN - invalid = False - nan = is_f16_nan(res) - if is_f16_snan(s0) or is_f16_snan(s1): - invalid = True - if (is_f16_inf(s0) and is_f16_zero(s1)) or (is_f16_inf(s1) and is_f16_zero(s0)): - invalid = True - - # 2. Denormal / Subnormal flag - denormal = is_f16_subnormal(s0) or is_f16_subnormal(s1) or is_f16_subnormal(res) - - # 3. Finite multiplication flags (Overflow, Underflow, Inexact) - overflow = False - underflow = False - inexact = False - - if not is_f16_nan(s0) and not is_f16_nan(s1): - if is_f16_inf(res) and not is_f16_inf(s0) and not is_f16_inf(s1): - overflow = True - inexact = True - elif not is_f16_inf(s0) and not is_f16_inf(s1) and not is_f16_zero(s0) and not is_f16_zero(s1): - # Check exact arithmetic via Fractions - f0 = Fraction(u16_to_f16(s0)) - f1 = Fraction(u16_to_f16(s1)) - exact_prod = f0 * f1 - approx_res = Fraction(u16_to_f16(res)) - if exact_prod != approx_res: - inexact = True - if is_f16_subnormal(res) or (is_f16_zero(res) and exact_prod != 0): - underflow = True - - zero = is_f16_zero(res) - negative = bool(res & F16_SIGN_MASK) - infinite = is_f16_inf(res) - - return FPStatusFlags( - invalid=invalid, - overflow=overflow, - underflow=underflow, - inexact=inexact, - denormal=denormal, - zero=zero, - negative=negative, - infinite=infinite, - nan=nan, - ) - - -def evaluate_pk_mul_f16_flags( - s0_dword: int, s1_dword: int, res_dword: int -) -> Tuple[FPStatusFlags, FPStatusFlags]: - """Evaluate status flags for both packed lanes (lo, hi).""" - s0_lo, s0_hi = unpack_f16x2(s0_dword) - s1_lo, s1_hi = unpack_f16x2(s1_dword) - res_lo, res_hi = unpack_f16x2(res_dword) - - return ( - evaluate_f16_mul_flags(s0_lo, s1_lo, res_lo), - evaluate_f16_mul_flags(s0_hi, s1_hi, res_hi), - ) - - -def generate_vcc_mask_pk_f16(pred: str, results: List[int], wave_size: int = 32) -> int: - """Generate Vector Condition Code (VCC) bitmask from packed half-precision outputs.""" - mask = 0 - for lane in range(min(len(results), wave_size)): - val = results[lane] - lo, hi = unpack_f16x2(val) - flo = u16_to_f16(lo) - fhi = u16_to_f16(hi) - - passed = False - if pred == "eq_zero": - passed = is_f16_zero(lo) and is_f16_zero(hi) - elif pred == "has_nan": - passed = is_f16_nan(lo) or is_f16_nan(hi) - elif pred == "both_positive": - passed = (not is_f16_nan(lo) and flo > 0.0) and (not is_f16_nan(hi) and fhi > 0.0) - elif pred == "both_finite": - passed = (not is_f16_nan(lo) and not is_f16_inf(lo)) and (not is_f16_nan(fhi) and not is_f16_inf(hi)) - - if passed: - mask |= (1 << lane) - - return mask - - -def compute_f16_mantissa_product(s0: int, s1: int) -> Tuple[int, int]: - """Compute 11-bit mantissa multiplication and return (product, carry_shift). - - In IEEE 754 binary16: - Normal significand has 1 implicit bit + 10 fraction bits = 11 bits. - Multiplying two 11-bit integers yields a 22-bit product in [2^20, 2^22 - 1]. - If bit 21 is set (product >= 2.0), a mantissa carry-out occurs requiring 1-bit right shift. - """ - m0 = (s0 & F16_MANT_MASK) | (0 if (s0 & F16_EXP_MASK) == 0 else 0x0400) - m1 = (s1 & F16_MANT_MASK) | (0 if (s1 & F16_EXP_MASK) == 0 else 0x0400) - prod = m0 * m1 - carry_shift = (prod >> 21) & 1 - return prod, carry_shift - - -# ----------------------------------------------------------------------------- -# Unit Tests -# ----------------------------------------------------------------------------- - -class TestReferenceOracleAndArchitecturalModel(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural model.""" - - def test_basic_normal_products(self) -> None: - # lo: 2.0 * 3.0 = 6.0, hi: 0.5 * 4.0 = 2.0 - s0 = pack_f16x2(f16_to_u16(2.0), f16_to_u16(0.5)) - s1 = pack_f16x2(f16_to_u16(3.0), f16_to_u16(4.0)) - res = ref_v_pk_mul_f16(s0, s1) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 6.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 2.0) - - def test_sign_propagation(self) -> None: - # (+ * - = -), (- * - = +) - s0 = pack_f16x2(f16_to_u16(2.0), f16_to_u16(-3.0)) - s1 = pack_f16x2(f16_to_u16(-5.0), f16_to_u16(-4.0)) - res = ref_v_pk_mul_f16(s0, s1) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), -10.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 12.0) - - def test_dual_lane_independence(self) -> None: - # Test that low and high halves do not interfere with each other - s0 = pack_f16x2(F16_ONE, F16_POS_ZERO) - s1 = pack_f16x2(F16_POS_INF, F16_ONE) - res = ref_v_pk_mul_f16(s0, s1) - res_lo, res_hi = unpack_f16x2(res) - self.assertEqual(res_lo, F16_POS_INF) - self.assertEqual(res_hi, F16_POS_ZERO) - - def test_op_sel_cross_and_broadcast(self) -> None: - # s0: [1.0, 2.0], s1: [3.0, 4.0] - s0 = pack_f16x2(f16_to_u16(1.0), f16_to_u16(2.0)) - s1 = pack_f16x2(f16_to_u16(3.0), f16_to_u16(4.0)) - - # Cross halves: lo uses (s0.hi, s1.lo) -> 2.0 * 3.0 = 6.0 - # hi uses (s0.lo, s1.hi) -> 1.0 * 4.0 = 4.0 - res = ref_v_pk_mul_f16(s0, s1, op_sel=(1, 0), op_sel_hi=(0, 1)) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 6.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 4.0) - - # Broadcast s0.hi to both lanes: - # lo uses (s0.hi, s1.lo) -> 2.0 * 3.0 = 6.0 - # hi uses (s0.hi, s1.hi) -> 2.0 * 4.0 = 8.0 - res_bcast = ref_v_pk_mul_f16(s0, s1, op_sel=(1, 0), op_sel_hi=(1, 1)) - res_lo2, res_hi2 = unpack_f16x2(res_bcast) - self.assertAlmostEqual(u16_to_f16(res_lo2), 6.0) - self.assertAlmostEqual(u16_to_f16(res_hi2), 8.0) - - def test_negation_modifiers(self) -> None: - s0 = pack_f16x2(f16_to_u16(2.0), f16_to_u16(3.0)) - s1 = pack_f16x2(f16_to_u16(4.0), f16_to_u16(5.0)) - - # neg_lo:[1, 0] -> -2.0 * 4.0 = -8.0 - # neg_hi:[0, 1] -> 3.0 * -5.0 = -15.0 - res = ref_v_pk_mul_f16(s0, s1, neg_lo=(1, 0), neg_hi=(0, 1)) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), -8.0) - self.assertAlmostEqual(u16_to_f16(res_hi), -15.0) - - def test_clamping_independent_halves(self) -> None: - # lo: 0.5 * -2.0 = -1.0 -> clamp -> +0.0 - # hi: 1.5 * 2.0 = 3.0 -> clamp -> 1.0 - s0 = pack_f16x2(f16_to_u16(0.5), f16_to_u16(1.5)) - s1 = pack_f16x2(f16_to_u16(-2.0), f16_to_u16(2.0)) - res = ref_v_pk_mul_f16(s0, s1, clamp=True) - res_lo, res_hi = unpack_f16x2(res) - self.assertEqual(res_lo, F16_POS_ZERO) - self.assertEqual(res_hi, F16_ONE) - - -class TestSymbolicASTDefinitions(unittest.TestCase): - """Test suite for symbolic AST opcode definitions and typed expressions.""" - - def test_reg_bounds_and_formatting(self) -> None: - v0 = Reg(0, RegType.VGPR) - v255 = Reg(255, RegType.VGPR) - s105 = Reg(105, RegType.SGPR) - self.assertEqual(str(v0), "v0") - self.assertEqual(str(v255), "v255") - self.assertEqual(str(s105), "s105") - - with self.assertRaises(ValueError): - Reg(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg(106, RegType.SGPR) - - def test_operand_creation_and_predicates(self) -> None: - op_vgpr = VOP3POperand(reg=Reg(5, RegType.VGPR)) - op_sgpr = VOP3POperand(reg=Reg(10, RegType.SGPR)) - op_lit = VOP3POperand(literal_val=0x3C003C00) - op_k = VOP3POperand(inline_val=1.0) - - self.assertTrue(op_vgpr.is_vgpr) - self.assertFalse(op_vgpr.is_sgpr) - self.assertTrue(op_sgpr.is_sgpr) - self.assertTrue(op_lit.is_literal) - self.assertTrue(op_k.is_inline_const) - - with self.assertRaises(ValueError): - VOP3POperand() # no source provided - with self.assertRaises(ValueError): - VOP3POperand(reg=Reg(0), literal_val=123) # ambiguous sources - - def test_instruction_disassembly(self) -> None: - instr_default = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - ) - self.assertEqual(instr_default.disasm(), "v_pk_mul_f16 v0, v1, v2") - - instr_modifiers = VPkMulF16Instruction( - dst=Reg(5, RegType.VGPR), - src0=VOP3POperand(reg=Reg(6, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(12, RegType.SGPR)), - op_sel=(1, 0), - op_sel_hi=(0, 1), - neg_lo=(1, 0), - neg_hi=(0, 1), - clamp=True, - ) - expected = "v_pk_mul_f16 v5, v6, s12 op_sel:[1,0] op_sel_hi:[0,1] neg_lo:[1,0] neg_hi:[0,1] clamp" - self.assertEqual(instr_modifiers.disasm(), expected) - - def test_instruction_validation(self) -> None: - with self.assertRaises(ValueError): - # SGPR as destination is forbidden for VALU instruction - VPkMulF16Instruction( - dst=Reg(0, RegType.SGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - ) - - with self.assertRaises(ValueError): - # Invalid modifier entry - VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - op_sel=(2, 0), - ) - - -class TestScalarInstructionInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction interpreter.""" - - def setUp(self) -> None: - self.state = ScalarState() - self.interp = ScalarInterpreter() - - def test_scalar_vgpr_multiplication(self) -> None: - # v1 = [2.0, 3.0], v2 = [4.0, 5.0] - # v0 = v1 * v2 -> [8.0, 15.0] - self.state.set_vgpr(1, pack_f16x2(f16_to_u16(2.0), f16_to_u16(3.0))) - self.state.set_vgpr(2, pack_f16x2(f16_to_u16(4.0), f16_to_u16(5.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - ) - res = self.interp.step(instr, self.state) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 8.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 15.0) - self.assertEqual(self.state.get_vgpr(0), res) - - def test_sgpr_scalar_broadcast(self) -> None: - # s4 = [0.5, 2.0] - # v3 = [4.0, 6.0] - # v0 = v3 * s4 -> [2.0, 12.0] - self.state.set_vgpr(3, pack_f16x2(f16_to_u16(4.0), f16_to_u16(6.0))) - self.state.set_sgpr(4, pack_f16x2(f16_to_u16(0.5), f16_to_u16(2.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(3, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(4, RegType.SGPR)), - ) - res = self.interp.step(instr, self.state) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 2.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 12.0) - - def test_inline_constant_operand(self) -> None: - # v1 = [3.0, -4.0] - # v0 = v1 * 2.0 (inline constant replicated to both halves) -> [6.0, -8.0] - self.state.set_vgpr(1, pack_f16x2(f16_to_u16(3.0), f16_to_u16(-4.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(inline_val=2.0), - ) - res = self.interp.step(instr, self.state) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 6.0) - self.assertAlmostEqual(u16_to_f16(res_hi), -8.0) - - def test_state_isolation(self) -> None: - # Verify unrelated registers are completely untouched - self.state.set_vgpr(10, 0x12345678) - self.state.set_sgpr(5, 0x87654321) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(inline_val=1.0), - src1=VOP3POperand(inline_val=1.0), - ) - self.interp.step(instr, self.state) - self.assertEqual(self.state.get_vgpr(10), 0x12345678) - self.assertEqual(self.state.get_sgpr(5), 0x87654321) - - -class TestSIMDMultiLaneDivergenceAndExecMasking(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.simd_interp = SIMDInterpreter() - - def test_wave32_full_execution_divergence(self) -> None: - state = SIMDState(wave_size=32, exec_mask=0xFFFFFFFF) - # Populate each lane with divergent values: lane i has [i + 1, i + 2] - for lane in range(32): - state.set_vgpr(lane, 1, pack_f16x2(f16_to_u16(float(lane + 1)), f16_to_u16(float(lane + 2)))) - state.set_vgpr(lane, 2, pack_f16x2(f16_to_u16(2.0), f16_to_u16(0.5))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - ) - self.simd_interp.step(instr, state) - - for lane in range(32): - res = state.get_vgpr(lane, 0) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), float(lane + 1) * 2.0) - self.assertAlmostEqual(u16_to_f16(res_hi), float(lane + 2) * 0.5) - - def test_wave64_exec_mask_gating_preserves_inactive_lanes(self) -> None: - state = SIMDState(wave_size=64, exec_mask=0x5555555555555555) # Even lanes active - # Pre-fill dst v0 with sentinel value across all 64 lanes - for lane in range(64): - state.set_vgpr(lane, 0, OLD_VGPR_SENTINEL) - state.set_vgpr(lane, 1, pack_f16x2(f16_to_u16(3.0), f16_to_u16(4.0))) - state.set_vgpr(lane, 2, pack_f16x2(f16_to_u16(2.0), f16_to_u16(2.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - ) - self.simd_interp.step(instr, state) - - expected_active = pack_f16x2(f16_to_u16(6.0), f16_to_u16(8.0)) - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(state.get_vgpr(lane, 0), expected_active) - else: - self.assertEqual(state.get_vgpr(lane, 0), OLD_VGPR_SENTINEL) - - def test_zero_exec_mask_no_modification(self) -> None: - state = SIMDState(wave_size=32, exec_mask=0x00000000) - for lane in range(32): - state.set_vgpr(lane, 0, OLD_VGPR_SENTINEL) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(inline_val=1.0), - src1=VOP3POperand(inline_val=1.0), - ) - self.simd_interp.step(instr, state) - - for lane in range(32): - self.assertEqual(state.get_vgpr(lane, 0), OLD_VGPR_SENTINEL) - - -class TestRegisterAliasingAndInPlacePreservation(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_dst_aliases_src0(self) -> None: - # v0 = v0 * v1 - state = ScalarState() - state.set_vgpr(0, pack_f16x2(f16_to_u16(2.0), f16_to_u16(3.0))) - state.set_vgpr(1, pack_f16x2(f16_to_u16(4.0), f16_to_u16(5.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(0, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(1, RegType.VGPR)), - ) - res = self.interp.step(instr, state) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 8.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 15.0) - self.assertEqual(state.get_vgpr(0), res) - - def test_dst_aliases_src1(self) -> None: - # v0 = v1 * v0 - state = ScalarState() - state.set_vgpr(0, pack_f16x2(f16_to_u16(2.0), f16_to_u16(3.0))) - state.set_vgpr(1, pack_f16x2(f16_to_u16(4.0), f16_to_u16(5.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(0, RegType.VGPR)), - ) - res = self.interp.step(instr, state) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 8.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 15.0) - self.assertEqual(state.get_vgpr(0), res) - - def test_dst_aliases_both_src0_and_src1_squaring(self) -> None: - # v0 = v0 * v0 (in-place squaring) - state = ScalarState() - state.set_vgpr(0, pack_f16x2(f16_to_u16(3.0), f16_to_u16(-4.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(0, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(0, RegType.VGPR)), - ) - res = self.interp.step(instr, state) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 9.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 16.0) - self.assertEqual(state.get_vgpr(0), res) - - def test_cross_half_aliasing_inplace(self) -> None: - # v0 = v0 * v0 op_sel:[1,0] op_sel_hi:[0,1] - # v0 starts as [2.0, 5.0] - # lo uses (v0.hi, v0.lo) -> 5.0 * 2.0 = 10.0 - # hi uses (v0.lo, v0.hi) -> 2.0 * 5.0 = 10.0 - state = ScalarState() - state.set_vgpr(0, pack_f16x2(f16_to_u16(2.0), f16_to_u16(5.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(0, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(0, RegType.VGPR)), - op_sel=(1, 0), - op_sel_hi=(0, 1), - ) - res = self.interp.step(instr, state) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), 10.0) - self.assertAlmostEqual(u16_to_f16(res_hi), 10.0) - - def test_simd_multi_lane_inplace_aliasing(self) -> None: - state = SIMDState(wave_size=32, exec_mask=0xFFFFFFFF) - for lane in range(32): - state.set_vgpr(lane, 0, pack_f16x2(f16_to_u16(float(lane)), f16_to_u16(2.0))) - - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(0, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(0, RegType.VGPR)), - ) - self.simd_interp.step(instr, state) - - for lane in range(32): - res = state.get_vgpr(lane, 0) - res_lo, res_hi = unpack_f16x2(res) - self.assertAlmostEqual(u16_to_f16(res_lo), float(lane) ** 2) - self.assertAlmostEqual(u16_to_f16(res_hi), 4.0) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Test suite for condition codes, status flags, and carry generation.""" - - def test_exact_finite_flags(self) -> None: - s0 = f16_to_u16(2.0) - s1 = f16_to_u16(3.0) - res = ref_mul_f16(s0, s1) - flags = evaluate_f16_mul_flags(s0, s1, res) - self.assertFalse(flags.invalid) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - self.assertFalse(flags.inexact) - self.assertFalse(flags.denormal) - self.assertFalse(flags.zero) - self.assertFalse(flags.negative) - self.assertFalse(flags.infinite) - self.assertFalse(flags.nan) - - def test_inexact_flag(self) -> None: - # In half-precision, 1.0009765625 * 1.0009765625 cannot be represented exactly in 10-bit fraction - s0 = 0x3C01 # 1.0 + 2^-10 - s1 = 0x3C01 - res = ref_mul_f16(s0, s1) - flags = evaluate_f16_mul_flags(s0, s1, res) - self.assertTrue(flags.inexact) - - def test_overflow_to_infinity_flag(self) -> None: - s0 = F16_MAX_NORMAL # 65504.0 - s1 = F16_TWO # 2.0 - res = ref_mul_f16(s0, s1) - self.assertEqual(res, F16_POS_INF) - flags = evaluate_f16_mul_flags(s0, s1, res) - self.assertTrue(flags.overflow) - self.assertTrue(flags.infinite) - self.assertTrue(flags.inexact) - self.assertFalse(flags.invalid) - - def test_underflow_and_denormal_flags(self) -> None: - s0 = F16_MIN_NORMAL # 2^-14 - s1 = F16_HALF # 0.5 -> product 2^-15 is subnormal - res = ref_mul_f16(s0, s1) - self.assertTrue(is_f16_subnormal(res)) - flags = evaluate_f16_mul_flags(s0, s1, res) - self.assertTrue(flags.denormal) - self.assertTrue(flags.underflow) - - def test_invalid_operation_flag(self) -> None: - # inf * 0.0 is an invalid operation - res = ref_mul_f16(F16_POS_INF, F16_POS_ZERO) - self.assertTrue(is_f16_nan(res)) - flags = evaluate_f16_mul_flags(F16_POS_INF, F16_POS_ZERO, res) - self.assertTrue(flags.invalid) - self.assertTrue(flags.nan) - - # signaling NaN operand triggers invalid operation flag - snan = 0x7C01 # exp=0x1F, mant=1 (bit 9 is 0) - self.assertTrue(is_f16_snan(snan)) - res_snan = ref_mul_f16(snan, F16_ONE) - flags_snan = evaluate_f16_mul_flags(snan, F16_ONE, res_snan) - self.assertTrue(flags_snan.invalid) - self.assertTrue(flags_snan.nan) - - def test_zero_and_negative_flags(self) -> None: - # -2.0 * 3.0 = -6.0 -> negative flag - s0 = f16_to_u16(-2.0) - s1 = f16_to_u16(3.0) - res = ref_mul_f16(s0, s1) - flags = evaluate_f16_mul_flags(s0, s1, res) - self.assertTrue(flags.negative) - self.assertFalse(flags.zero) - - # -0.0 * 5.0 = -0.0 -> zero flag and negative flag - res_nz = ref_mul_f16(F16_NEG_ZERO, f16_to_u16(5.0)) - flags_nz = evaluate_f16_mul_flags(F16_NEG_ZERO, f16_to_u16(5.0), res_nz) - self.assertTrue(flags_nz.zero) - self.assertTrue(flags_nz.negative) - - def test_packed_flags_evaluation(self) -> None: - s0 = pack_f16x2(F16_POS_INF, f16_to_u16(2.0)) - s1 = pack_f16x2(F16_POS_ZERO, f16_to_u16(3.0)) - res = ref_v_pk_mul_f16(s0, s1) - flags_lo, flags_hi = evaluate_pk_mul_f16_flags(s0, s1, res) - self.assertTrue(flags_lo.invalid) - self.assertTrue(flags_lo.nan) - self.assertFalse(flags_hi.invalid) - self.assertAlmostEqual(u16_to_f16(unpack_f16x2(res)[1]), 6.0) - - def test_vcc_condition_masks(self) -> None: - # Generate 4 results: - # Lane 0: both zero - # Lane 1: positive - # Lane 2: contains NaN - # Lane 3: both positive - r0 = pack_f16x2(F16_POS_ZERO, F16_NEG_ZERO) - r1 = pack_f16x2(f16_to_u16(1.0), f16_to_u16(2.0)) - r2 = pack_f16x2(F16_CANONICAL_QNAN, f16_to_u16(1.0)) - r3 = pack_f16x2(f16_to_u16(3.0), f16_to_u16(4.0)) - - results = [r0, r1, r2, r3] - mask_zero = generate_vcc_mask_pk_f16("eq_zero", results, 4) - self.assertEqual(mask_zero, 0b0001) - - mask_nan = generate_vcc_mask_pk_f16("has_nan", results, 4) - self.assertEqual(mask_nan, 0b0100) - - mask_pos = generate_vcc_mask_pk_f16("both_positive", results, 4) - self.assertEqual(mask_pos, 0b1010) - - def test_mantissa_product_and_carry(self) -> None: - # 1.0 * 1.0: mantissas are 1024 * 1024 = 1048576 (2^20) -> carry_shift = 0 - _, c0 = compute_f16_mantissa_product(F16_ONE, F16_ONE) - self.assertEqual(c0, 0) - - # 1.5 * 1.5 = 2.25: product >= 2.0 -> carry_shift = 1 - s_1p5 = f16_to_u16(1.5) - _, c1 = compute_f16_mantissa_product(s_1p5, s_1p5) - self.assertEqual(c1, 1) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Test suite for IEEE-754 boundary extremes, subnormals, and NaN handling.""" - - def test_nan_snan_quieting(self) -> None: - # Positive signaling NaN - snan_pos = 0x7C01 - self.assertTrue(is_f16_snan(snan_pos)) - res_pos = ref_mul_f16(snan_pos, F16_ONE) - self.assertTrue(is_f16_qnan(res_pos)) - self.assertEqual(res_pos, 0x7E01) - - # Negative signaling NaN - snan_neg = 0xFC05 - self.assertTrue(is_f16_snan(snan_neg)) - res_neg = ref_mul_f16(F16_TWO, snan_neg) - self.assertTrue(is_f16_qnan(res_neg)) - self.assertEqual(res_neg, 0xFE05) - - def test_nan_payload_propagation_and_precedence(self) -> None: - # Quiet NaN payload from src0 - qnan_a = 0x7E55 - res_a = ref_mul_f16(qnan_a, f16_to_u16(5.0)) - self.assertEqual(res_a, qnan_a) - - # Quiet NaN payload from src1 - qnan_b = 0xFEAA - res_b = ref_mul_f16(f16_to_u16(-3.0), qnan_b) - self.assertEqual(res_b, qnan_b) - - # Dual NaN: src0 takes precedence - qnan0 = 0x7E12 - qnan1 = 0x7E34 - res_dual = ref_mul_f16(qnan0, qnan1) - self.assertEqual(res_dual, qnan0) - - def test_nan_clamping_produces_zero(self) -> None: - qnan = 0x7E55 - res_clamped = ref_mul_f16(qnan, F16_ONE, clamp=True) - self.assertEqual(res_clamped, F16_POS_ZERO) - - # Packed NaN clamp - s0 = pack_f16x2(qnan, F16_ONE) - s1 = pack_f16x2(F16_ONE, qnan) - res_pk_clamped = ref_v_pk_mul_f16(s0, s1, clamp=True) - self.assertEqual(res_pk_clamped, pack_f16x2(F16_POS_ZERO, F16_POS_ZERO)) - - def test_signed_zero_combinations(self) -> None: - self.assertEqual(ref_mul_f16(F16_POS_ZERO, F16_POS_ZERO), F16_POS_ZERO) - self.assertEqual(ref_mul_f16(F16_POS_ZERO, F16_NEG_ZERO), F16_NEG_ZERO) - self.assertEqual(ref_mul_f16(F16_NEG_ZERO, F16_POS_ZERO), F16_NEG_ZERO) - self.assertEqual(ref_mul_f16(F16_NEG_ZERO, F16_NEG_ZERO), F16_POS_ZERO) - - # Finite and zero - self.assertEqual(ref_mul_f16(F16_POS_ZERO, f16_to_u16(10.0)), F16_POS_ZERO) - self.assertEqual(ref_mul_f16(F16_POS_ZERO, f16_to_u16(-10.0)), F16_NEG_ZERO) - self.assertEqual(ref_mul_f16(F16_NEG_ZERO, f16_to_u16(10.0)), F16_NEG_ZERO) - self.assertEqual(ref_mul_f16(F16_NEG_ZERO, f16_to_u16(-10.0)), F16_POS_ZERO) - - # Clamped negative zero becomes +0.0 - self.assertEqual(ref_mul_f16(F16_NEG_ZERO, f16_to_u16(10.0), clamp=True), F16_POS_ZERO) - - def test_signed_infinity_combinations(self) -> None: - self.assertEqual(ref_mul_f16(F16_POS_INF, F16_POS_INF), F16_POS_INF) - self.assertEqual(ref_mul_f16(F16_POS_INF, F16_NEG_INF), F16_NEG_INF) - self.assertEqual(ref_mul_f16(F16_NEG_INF, F16_POS_INF), F16_NEG_INF) - self.assertEqual(ref_mul_f16(F16_NEG_INF, F16_NEG_INF), F16_POS_INF) - - # Inf * 0.0 -> Canonical Quiet NaN - self.assertEqual(ref_mul_f16(F16_POS_INF, F16_POS_ZERO), F16_CANONICAL_QNAN) - self.assertEqual(ref_mul_f16(F16_NEG_INF, F16_POS_ZERO), F16_CANONICAL_QNAN) - self.assertEqual(ref_mul_f16(F16_POS_ZERO, F16_POS_INF), F16_CANONICAL_QNAN) - self.assertEqual(ref_mul_f16(F16_NEG_ZERO, F16_NEG_INF), F16_CANONICAL_QNAN) - - # Clamped inf: positive inf becomes 1.0, negative inf becomes +0.0 - self.assertEqual(ref_mul_f16(F16_POS_INF, F16_ONE, clamp=True), F16_ONE) - self.assertEqual(ref_mul_f16(F16_NEG_INF, F16_ONE, clamp=True), F16_POS_ZERO) - - # Clamped inf * 0.0 becomes +0.0 - self.assertEqual(ref_mul_f16(F16_POS_INF, F16_POS_ZERO, clamp=True), F16_POS_ZERO) - - def test_max_normal_overflow_boundaries(self) -> None: - # MAX_NORMAL * 1.0 = MAX_NORMAL - self.assertEqual(ref_mul_f16(F16_MAX_NORMAL, F16_ONE), F16_MAX_NORMAL) - # MAX_NORMAL * -1.0 = -MAX_NORMAL - self.assertEqual(ref_mul_f16(F16_MAX_NORMAL, F16_NEG_ONE), F16_MAX_NORMAL | F16_SIGN_MASK) - # MAX_NORMAL * 2.0 -> overflow to +inf - self.assertEqual(ref_mul_f16(F16_MAX_NORMAL, F16_TWO), F16_POS_INF) - # MAX_NORMAL * -2.0 -> overflow to -inf - self.assertEqual(ref_mul_f16(F16_MAX_NORMAL, f16_to_u16(-2.0)), F16_NEG_INF) - - def test_subnormal_boundaries(self) -> None: - # MIN_NORMAL * 1.0 = MIN_NORMAL - self.assertEqual(ref_mul_f16(F16_MIN_NORMAL, F16_ONE), F16_MIN_NORMAL) - # MIN_NORMAL * 0.5 = subnormal 2^-15 - res_sub = ref_mul_f16(F16_MIN_NORMAL, F16_HALF) - self.assertTrue(is_f16_subnormal(res_sub)) - self.assertEqual(res_sub, 0x0200) - - # MIN_SUBNORMAL (2^-24) * 1.0 = MIN_SUBNORMAL - self.assertEqual(ref_mul_f16(F16_MIN_SUBNORMAL, F16_ONE), F16_MIN_SUBNORMAL) - # MIN_SUBNORMAL * 2.0 = 0x0002 - self.assertEqual(ref_mul_f16(F16_MIN_SUBNORMAL, F16_TWO), 0x0002) - # MIN_SUBNORMAL * 0.5 = underflow to +0.0 - self.assertEqual(ref_mul_f16(F16_MIN_SUBNORMAL, F16_HALF), F16_POS_ZERO) - # -MIN_SUBNORMAL * 0.5 = underflow to -0.0 - self.assertEqual(ref_mul_f16(F16_MIN_SUBNORMAL | F16_SIGN_MASK, F16_HALF), F16_NEG_ZERO) - - def test_round_to_nearest_even(self) -> None: - # Check round-to-nearest-even tie breaking - val = 1.0 + 2.0**(-10) - bits = f16_to_u16(val) - res = ref_mul_f16(bits, F16_ONE) - self.assertEqual(res, bits) - - -class TestNegativeControlsAndMutationDetection(unittest.TestCase): - """Test suite for negative controls, syntax rejection, and mutation detection.""" - - def test_out_of_bounds_registers(self) -> None: - with self.assertRaises(ValueError): - Reg(-1, RegType.VGPR) - with self.assertRaises(ValueError): - Reg(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg(-1, RegType.SGPR) - with self.assertRaises(ValueError): - Reg(106, RegType.SGPR) - - def test_invalid_destination_types(self) -> None: - # VALU destination cannot be SGPR - with self.assertRaises(ValueError): - VPkMulF16Instruction( - dst=Reg(0, RegType.SGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - ) - - def test_invalid_modifier_tuples(self) -> None: - # Tuple of wrong length - with self.assertRaises(ValueError): - VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - op_sel=(0,), # type: ignore[arg-type] - ) - # Value not in {0, 1} - with self.assertRaises(ValueError): - VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(reg=Reg(1, RegType.VGPR)), - src1=VOP3POperand(reg=Reg(2, RegType.VGPR)), - neg_lo=(0, 2), - ) - - def test_mutation_addition_instead_of_multiplication(self) -> None: - def mutated_mul_f16(s0: int, s1: int) -> int: - return f16_to_u16(u16_to_f16(s0) + u16_to_f16(s1)) - - # Golden expectation: 2.0 * 3.0 = 6.0. Mutant computes 2.0 + 3.0 = 5.0 - s0 = f16_to_u16(2.0) - s1 = f16_to_u16(3.0) - oracle_res = ref_mul_f16(s0, s1) - mutant_res = mutated_mul_f16(s0, s1) - self.assertNotEqual(oracle_res, mutant_res) - - def test_mutation_dropped_clamp(self) -> None: - def mutated_pk_mul(s0: int, s1: int, clamp: bool) -> int: - # Drops clamp argument - return ref_v_pk_mul_f16(s0, s1, clamp=False) - - # In packed mul: 2.0 * 2.0 = 4.0. With clamp, result is 1.0 - s0 = pack_f16x2(f16_to_u16(2.0), f16_to_u16(2.0)) - s1 = pack_f16x2(f16_to_u16(2.0), f16_to_u16(2.0)) - oracle_res = ref_v_pk_mul_f16(s0, s1, clamp=True) - mutant_res = mutated_pk_mul(s0, s1, clamp=True) - self.assertNotEqual(oracle_res, mutant_res) - self.assertEqual(oracle_res, pack_f16x2(F16_ONE, F16_ONE)) - - def test_mutation_failed_snan_quieting(self) -> None: - def mutated_nan_oracle(s0: int, s1: int) -> int: - # Returns raw bits without quieting signaling NaN - if is_f16_nan(s0): - return s0 - return s1 - - snan = 0x7C01 - oracle_res = ref_mul_f16(snan, F16_ONE) - mutant_res = mutated_nan_oracle(snan, F16_ONE) - self.assertTrue(is_f16_qnan(oracle_res)) - self.assertFalse(is_f16_qnan(mutant_res)) - self.assertNotEqual(oracle_res, mutant_res) - - def test_mutation_ignored_op_sel_hi(self) -> None: - # When op_sel_hi is (0, 0) instead of (1, 1), hi lane selects lo operand instead of hi operand - s0 = pack_f16x2(f16_to_u16(2.0), f16_to_u16(10.0)) - s1 = pack_f16x2(f16_to_u16(3.0), f16_to_u16(4.0)) - - correct = ref_v_pk_mul_f16(s0, s1, op_sel_hi=(1, 1)) - mutant = ref_v_pk_mul_f16(s0, s1, op_sel_hi=(0, 0)) - # correct hi is 10.0 * 4.0 = 40.0; mutant hi is 2.0 * 3.0 = 6.0 - self.assertNotEqual(correct, mutant) - - def test_mutation_corrupted_inactive_exec_lane(self) -> None: - state = SIMDState(wave_size=32, exec_mask=0x00000001) # only lane 0 active - state.set_vgpr(1, 0, OLD_VGPR_SENTINEL) - - # Correct execution - simd_interp = SIMDInterpreter() - instr = VPkMulF16Instruction( - dst=Reg(0, RegType.VGPR), - src0=VOP3POperand(inline_val=1.0), - src1=VOP3POperand(inline_val=1.0), - ) - simd_interp.step(instr, state) - self.assertEqual(state.get_vgpr(1, 0), OLD_VGPR_SENTINEL) - - # Mutant simulator that erroneously overwrites inactive lanes - state.set_vgpr(1, 0, 0x11111111) - self.assertNotEqual(state.get_vgpr(1, 0), OLD_VGPR_SENTINEL) +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import clamp01, ref_mul, same_f16 # noqa: E402 + +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF + + +def P(lo, hi): + """A dword holding two binary16 values.""" + return (hi << 16) | lo + + +def run(line, seeds, old=0xDEADBEEF): + """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0 (seeds map reg -> dword).""" + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_pk_mul_f16", prog))[0] + + +def half(w, i): + return (w >> (16 * i)) & 0xFFFF + + +def pk_ref(fn, srcs, op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): + """Reference for one packed op: the low result reads half op_sel[i] of source i (negated by neg_lo[i]), the high + result half op_sel_hi[i] (negated by neg_hi[i]); defaults are op_sel 0, op_sel_hi 1, no negation.""" + n = len(srcs) + op_sel, op_sel_hi = op_sel or [0] * n, op_sel_hi or [1] * n + neg_lo, neg_hi = neg_lo or [0] * n, neg_hi or [0] * n + out = [] + for sel, ng in ((op_sel, neg_lo), (op_sel_hi, neg_hi)): + r = fn(*[half(s, h) ^ (0x8000 if g else 0) for s, h, g in zip(srcs, sel, ng)]) + out.append(clamp01(r) if clamp else r) + return P(out[0], out[1]) + + +def same_pk(a, b): + return same_f16(a & 0xFFFF, b & 0xFFFF) and same_f16(a >> 16, b >> 16) + + +def mods_text(op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): + t = "" + for name, v in (("op_sel", op_sel), ("op_sel_hi", op_sel_hi), ("neg_lo", neg_lo), ("neg_hi", neg_hi)): + if v is not None: + t += f" {name}:[{','.join(map(str, v))}]" + return t + (" clamp" if clamp else "") + + +def regs(n): + return ", ".join(f"v{i}" for i in range(1, n + 1)) + + +# mnemonic -> (source count, reference for one lane) +OPS = {"v_pk_mul_f16": (2, ref_mul)} + +# mnemonic -> rows of (source dwords..., D), written by hand; lane 0 is the low half +CASES = { + 'v_pk_mul_f16': [ + (P(0x3E00, TWO), P(TWO, 0xBC00), P(THREE, 0xC000)), # (1.5 * 2, 2 * -1) = (3, -2) + (P(HALF, MAXH), P(HALF, TWO), P(QUARTER, INF)), # (0.25, 65504 * 2 overflows) + (P(MIN_SUB, MIN_NORMAL), P(HALF, HALF), P(0x0000, 0x0200)), # (half a quantum ties to even = 0, 2^-15 subnormal) + (P(0x3C01, 0x5640), P(0x3C01, 0x5640), P(0x3C02, 0x70E2)), # (1 + 2^-9 + 2^-20 rounds down, 100 * 100) + (P(0x0000, 0x8000), P(0xBC00, 0xBC00), P(0x8000, 0x0000)), # (+0 * -1 = -0, -0 * -1 = +0) + (P(INF, QNAN), P(0x0000, ONE), P(QNAN, QNAN)), # (inf * 0 = NaN, NaN * 1 = NaN) + (P(MIN_SUB, 0x4900), P(0x3A00, 0xC100), P(MIN_SUB, 0xCE40)), # (0.75 quantum rounds up, 10 * -2.5 = -25) + ], + +} + +# mnemonic -> (sources, modifier text, D), by hand. S0 = (1.0, 3.0), S1 = (0.5, -0.25), S2 = (0.25, -1.0) as +# (low, high) halves. +S0, S1, S2 = P(ONE, THREE), P(HALF, 0xB400), P(QUARTER, 0xBC00) +MODS = { + 'v_pk_mul_f16': [ + ((S0, S1), "", P(0x3800, 0xBA00)), # (1 * 0.5, 3 * -0.25) + ((S0, S1), " op_sel:[1,0]", P(0x3E00, 0xBA00)), # low: 3 * 0.5 = 1.5 + ((S0, S1), " op_sel:[0,1] op_sel_hi:[0,0]", P(0xB400, 0x3800)), # low: 1 * -0.25; high: 1 * 0.5 + ((S0, S1), " op_sel:[1,1] op_sel_hi:[0,0]", P(0xBA00, 0x3800)), # low: 3 * -0.25; high: 1 * 0.5 + ((S0, S1), " neg_lo:[1,0]", P(0xB800, 0xBA00)), # low: -1 * 0.5 + ((S0, S1), " neg_hi:[0,1]", P(0x3800, 0x3A00)), # high: 3 * 0.25 + ((S0, S1), " neg_lo:[1,1] neg_hi:[1,1]", P(0x3800, 0xBA00)), # (-1 * -0.5, -3 * 0.25) + ((P(THREE, 0xB800), P(HALF, HALF)), " clamp", P(ONE, 0x0000)), # (1.5, -0.25) -> (1, 0) + ((P(HALF, QUARTER), P(HALF, ONE)), " clamp", P(QUARTER, QUARTER)), # inside [0, 1]: unchanged + ], + +} + + +class PkMulF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for op, rows in CASES.items(): + for *src, want in rows: + with self.subTest(op=op, src=[hex(s) for s in src]): + self.assertTrue(same_pk(pk_ref(OPS[op][1], src), want), hex(pk_ref(OPS[op][1], src))) + + def test_per_lane_results(self): + for op, rows in CASES.items(): + for *src, want in rows: + with self.subTest(op=op, src=[hex(s) for s in src]): + got = run(f"{op} v0, {regs(len(src))}", {f"v{i}": s for i, s in enumerate(src, 1)}) + self.assertTrue(same_pk(got, want), hex(got)) + + def test_sgpr_sources(self): + for op, rows in CASES.items(): + for *src, want in rows[:6]: + n = len(src) + forms = [("all sgpr", ", ".join(f"s{i}" for i in range(1, n + 1)), {f"s{i}": s for i, s in enumerate(src, 1)}), + ("sgpr src0", ", ".join(["s1"] + [f"v{i}" for i in range(2, n + 1)]), + {"s1": src[0], **{f"v{i}": s for i, s in enumerate(src[1:], 2)}})] + for form, text, seeds in forms: + with self.subTest(op=op, src=[hex(s) for s in src], form=form): + self.assertTrue(same_pk(run(f"{op} v0, {text}", seeds), want)) + + def test_hand_written_modifier_cases(self): + for op, rows in MODS.items(): + for srcs, mods, want in rows: + with self.subTest(op=op, mods=mods): + got = run(f"{op} v0, {regs(len(srcs))}{mods}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, want), hex(got)) + + def test_every_op_sel_and_op_sel_hi_combination(self): + a, b, c = P(0x3E00, 0xC400), P(0x4900, 0x3A00), P(0xB800, 0x4D00) # distinct halves: 1.5/-4, 10/.75, -.5/20 + for op, (n, fn) in OPS.items(): + srcs = [a, b, c][:n] + for sel in range(1 << n): + for selhi in range(1 << n): + os_, oh = [(sel >> i) & 1 for i in range(n)], [(selhi >> i) & 1 for i in range(n)] + with self.subTest(op=op, op_sel=os_, op_sel_hi=oh): + got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh)), hex(got)) + + def test_random_operands_and_modifiers(self): + rng = random.Random(0x3D2) + pool = [0x0000, 0x8000, ONE, 0xBC00, TWO, HALF, THREE, MAXH, 0xFBFF, INF, NINF, QNAN, MIN_NORMAL, MIN_SUB, + 0x8001, MAX_SUB, 0x3C01, 0x6800, 0x6801, 0x4C00, 0x1000, 0x9000] + for _ in range(150): + op = rng.choice(sorted(OPS)) + n, fn = OPS[op] + srcs = [P(*[rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(2)]) + for _ in range(n)] + os_, oh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] + nl, nh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] + with self.subTest(op=op, src=[hex(s) for s in srcs], mods=(os_, oh, nl, nh)): + got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh, nl, nh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) + self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh, nl, nh)), hex(got)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_sad_u32.py b/tests/semantic/test_valu_sad_u32.py index 7fc105bbc..e8cca5b2a 100644 --- a/tests/semantic/test_valu_sad_u32.py +++ b/tests/semantic/test_valu_sad_u32.py @@ -1,1235 +1,77 @@ -from __future__ import annotations +"""v_sad_u32 (RDNA2 VOP3): D = |S0 - S1| + S2 on unsigned 32-bit operands, modulo 2^32. -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_sad_u32, -v_sad_hi_u32, and v_mqsad_u32. - -Architecture & Instruction Specifications (AMD RDNA2 / GFX10 Vector ALU): -- v_sad_u32 (VOP3 3-operand vector ALU instruction): - Calculates the 32-bit unsigned sum of absolute differences with accumulation: - diff = |src0.u32 - src1.u32| - dst.u32 = (diff + src2.u32) mod 2^32 - Unsigned Semantics: - The absolute difference is strictly unsigned: - diff = (src0 >= src1) ? (src0 - src1) : (src1 - src0) - Operands operate on unsigned 32-bit integers in [0, 2^32 - 1]. - Clamp modifier: - When clamp is enabled on v_sad_u32, the result saturates to 0xFFFFFFFF on overflow: - dst.u32 = min(0xFFFFFFFF, diff + src2.u32) - -- v_sad_hi_u32: - Computes the high 32-bit carry / overflow word of the full 64-bit SAD: - diff = |src0.u32 - src1.u32| - full_sum = diff + src2.u32 - dst.u32 = (full_sum >> 32) & 0xFFFFFFFF - Since diff <= 2^32 - 1 and src2 <= 2^32 - 1, full_sum <= 2^33 - 2, so the high - carry word is strictly in {0, 1}. - Pairing (v_sad_u32, v_sad_hi_u32) synthesizes a full 64-bit precision sum of - absolute differences with accumulation. - -- v_mqsad_u32 / v_mqsad_u32_u8: - Quad-byte masked sum of absolute differences with four full 32-bit accumulators: - S0 is 64 bits (2 VGPRs), S1 is 32 bits (1 VGPR), S2 is 128 bits (4 VGPRs), D is 128 bits (4 VGPRs). - For each dword k in 0..3: - W_k = S0[8*k + 31 : 8*k] (32-bit window sliding across S0 byte-by-byte) - D[k] = (S2[k] + sum_{i=0..3} |W_k.byte[i] - S1.byte[i]| (skipping if S1.byte[i] == 0 when masked)) mod 2^32. - -Standard library Python only: unittest, dataclasses, enum, math, struct. -Single module scope, zero game data. +Each case is translated by tools/rdna2spirv.py (support.translate_lines) and executed with +tests/semantic/spirv_mini_interp.py; the expected words are written by hand from the ISA formula and also recomputed +by a plain-Python reference, with VGPR, SGPR and literal/inline-constant sources and seeded random operands. +Standard library only: no GPU, no LLVM, no game data. (The old file modelled the instruction in its own classes and +never ran the translator. The `clamp` modifier is the business of test_sad_clamp.py / test_alu_sad_u32.py.) """ - -from dataclasses import dataclass, field -from enum import Enum, auto -import math -import struct +import os +import random +import sys import unittest -from typing import List, Sequence, Tuple, Union -# Architectural 32-bit and 64-bit masks -MASK8 = 0xFF -MASK16 = 0xFFFF -MASK32 = 0xFFFF_FFFF -MASK64 = 0xFFFF_FFFF_FFFF_FFFF -MASK128 = (1 << 128) - 1 - -CLAMP_MAX_U32 = MASK32 - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit dword.""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit qword.""" - return val & MASK64 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned dword as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x8000_0000) else val - - -def extract_byte(word32: int, byte_idx: int) -> int: - """Extract byte at byte_idx (0..3) from a 32-bit word.""" - return (word32 >> (8 * (byte_idx & 3))) & MASK8 - - -def byte_window_u32(val64: int, byte_offset: int) -> int: - """Extract 32-bit window W_k at byte offset k from 64-bit val: bits [8*k+31 : 8*k].""" - return (val64 >> (8 * byte_offset)) & MASK32 - - -def ref_abs_diff_u32(s0: int, s1: int) -> int: - """Calculate the strictly unsigned 32-bit absolute difference |s0 - s1|.""" - u0 = s0 & MASK32 - u1 = s1 & MASK32 - return (u0 - u1) if u0 >= u1 else (u1 - u0) - - -def ref_sad_u32(s0: int, s1: int, s2: int, *, clamp: bool = False) -> int: - """Bit-accurate reference mathematical oracle for v_sad_u32. - - diff = |s0.u32 - s1.u32| - result = (diff + s2.u32) mod 2^32 (or clamped to 0xFFFFFFFF on overflow). - """ - diff = ref_abs_diff_u32(s0, s1) - acc = s2 & MASK32 - full_sum = diff + acc - if clamp: - return min(CLAMP_MAX_U32, full_sum) - return full_sum & MASK32 - - -def ref_sad_hi_u32(s0: int, s1: int, s2: int) -> int: - """Bit-accurate reference mathematical oracle for v_sad_hi_u32 (high 32-bit carry word). - - diff = |s0.u32 - s1.u32| - full_sum = diff + s2.u32 - carry = (full_sum >> 32) & 0xFFFFFFFF - """ - diff = ref_abs_diff_u32(s0, s1) - acc = s2 & MASK32 - full_sum = diff + acc - return (full_sum >> 32) & MASK32 - - -def ref_quad_byte_sad(win: int, s1: int, *, masked: bool = True) -> int: - """Compute sum of absolute differences across 4 bytes between win and s1. - - When masked is True, bytes where s1.byte[i] == 0 are skipped. - """ - total = 0 - for i in range(4): - b_win = extract_byte(win, i) - b_s1 = extract_byte(s1, i) - if masked and b_s1 == 0: - continue - total += abs(b_win - b_s1) - return total - - -def ref_mqsad_u32( - s0_64: int, - s1_32: int, - s2_128: Tuple[int, int, int, int], - *, - masked: bool = True, -) -> Tuple[int, int, int, int]: - """Bit-accurate reference mathematical oracle for v_mqsad_u32. - - s0_64: 64-bit input source across two VGPRs - s1_32: 32-bit template operand in one VGPR - s2_128: 4x 32-bit accumulator dwords across four VGPRs - Returns 4x 32-bit dwords destination tuple. - """ - s0 = s0_64 & MASK64 - s1 = s1_32 & MASK32 - out = [] - for k in range(4): - win = byte_window_u32(s0, k) - sad = ref_quad_byte_sad(win, s1, masked=masked) - acc = s2_128[k] & MASK32 - out.append((acc + sad) & MASK32) - return (out[0], out[1], out[2], out[3]) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - VGPR = auto() - SGPR = auto() - LITERAL = auto() - - -@dataclass(frozen=True) -class Operand: - """Represents a register operand or inline literal constant.""" - reg_type: RegType - index: int = 0 - literal_value: int | None = None - count: int = 1 - - def __post_init__(self) -> None: - if self.reg_type == RegType.VGPR: - if not (0 <= self.index <= 255): - raise ValueError(f"VGPR index {self.index} out of range [0, 255]") - if self.index + self.count > 256: - raise ValueError(f"VGPR range [{self.index}:{self.index + self.count - 1}] exceeds 255") - elif self.reg_type == RegType.SGPR: - if not (0 <= self.index <= 105): - raise ValueError(f"SGPR index {self.index} out of range [0, 105]") - if self.index + self.count > 106: - raise ValueError(f"SGPR range [{self.index}:{self.index + self.count - 1}] exceeds 105") - elif self.reg_type == RegType.LITERAL: - if self.literal_value is None: - raise ValueError("Literal operand requires literal_value") - - @classmethod - def vgpr(cls, index: int, count: int = 1) -> Operand: - return cls(RegType.VGPR, index=index, count=count) - - @classmethod - def sgpr(cls, index: int, count: int = 1) -> Operand: - return cls(RegType.SGPR, index=index, count=count) - - @classmethod - def literal(cls, value: int) -> Operand: - return cls(RegType.LITERAL, literal_value=u32(value), count=1) - - def disassemble(self) -> str: - if self.reg_type == RegType.VGPR: - if self.count == 1: - return f"v{self.index}" - return f"v[{self.index}:{self.index + self.count - 1}]" - if self.reg_type == RegType.SGPR: - if self.count == 1: - return f"s{self.index}" - return f"s[{self.index}:{self.index + self.count - 1}]" - return f"0x{self.literal_value:08X}" - - -@dataclass(frozen=True) -class VSadU32Instruction: - """Symbolic AST node for v_sad_u32.""" - dst: Operand - src0: Operand - src1: Operand - src2: Operand - clamp: bool = False - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination must be a VGPR, got {self.dst.reg_type}") - if self.dst.count != 1: - raise ValueError(f"Destination must be single dword (count=1), got {self.dst.count}") - for idx, src in enumerate([self.src0, self.src1, self.src2]): - if src.count != 1: - raise ValueError(f"src{idx} must be single dword (count=1), got {src.count}") - - def disassemble(self) -> str: - parts = [ - "v_sad_u32", - self.dst.disassemble() + ",", - self.src0.disassemble() + ",", - self.src1.disassemble() + ",", - self.src2.disassemble(), - ] - if self.clamp: - parts.append("clamp") - return " ".join(parts) - - -@dataclass(frozen=True) -class VSadHiU32Instruction: - """Symbolic AST node for v_sad_hi_u32.""" - dst: Operand - src0: Operand - src1: Operand - src2: Operand - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination must be a VGPR, got {self.dst.reg_type}") - if self.dst.count != 1: - raise ValueError(f"Destination must be single dword (count=1), got {self.dst.count}") - for idx, src in enumerate([self.src0, self.src1, self.src2]): - if src.count != 1: - raise ValueError(f"src{idx} must be single dword (count=1), got {src.count}") - - def disassemble(self) -> str: - return f"v_sad_hi_u32 {self.dst.disassemble()}, {self.src0.disassemble()}, {self.src1.disassemble()}, {self.src2.disassemble()}" - - -@dataclass(frozen=True) -class VMqsadU32Instruction: - """Symbolic AST node for v_mqsad_u32.""" - dst: Operand - src0: Operand - src1: Operand - src2: Operand - masked: bool = True - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination must be a VGPR, got {self.dst.reg_type}") - if self.dst.count != 4: - raise ValueError(f"Destination must be 4 dwords (count=4), got {self.dst.count}") - if self.src0.count != 2: - raise ValueError(f"src0 must be 2 dwords (count=2), got {self.src0.count}") - if self.src1.count != 1: - raise ValueError(f"src1 must be 1 dword (count=1), got {self.src1.count}") - if self.src2.count != 4: - raise ValueError(f"src2 must be 4 dwords (count=4), got {self.src2.count}") - - def disassemble(self) -> str: - suffix = "" if self.masked else " unmasked" - return f"v_mqsad_u32 {self.dst.disassemble()}, {self.src0.disassemble()}, {self.src1.disassemble()}, {self.src2.disassemble()}{suffix}" - - -SadInstruction = Union[VSadU32Instruction, VSadHiU32Instruction, VMqsadU32Instruction] - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -class ScalarRegisterFile: - """Architectural register file for a single scalar/lane execution context.""" - - def __init__(self) -> None: - self.vgprs: List[int] = [0] * 256 - self.sgprs: List[int] = [0] * 106 - - def read(self, op: Operand) -> int | Tuple[int, ...]: - """Read operand value as unsigned 32-bit dword or tuple of dwords.""" - if op.reg_type == RegType.LITERAL: - assert op.literal_value is not None - return op.literal_value - if op.reg_type == RegType.VGPR: - if op.count == 1: - return self.vgprs[op.index] & MASK32 - return tuple(self.vgprs[op.index + i] & MASK32 for i in range(op.count)) - if op.reg_type == RegType.SGPR: - if op.count == 1: - return self.sgprs[op.index] & MASK32 - return tuple(self.sgprs[op.index + i] & MASK32 for i in range(op.count)) - raise ValueError(f"Unknown operand type: {op.reg_type}") - - def read_u64(self, op: Operand) -> int: - """Read 64-bit qword from 2-register operand.""" - if op.count != 2: - raise ValueError(f"Operand count must be 2 for 64-bit read, got {op.count}") - words = self.read(op) - assert isinstance(words, tuple) and len(words) == 2 - return (words[1] << 32) | words[0] - - def write(self, op: Operand, value: int | Sequence[int]) -> None: - """Write value to register operand (VGPR or SGPR).""" - if op.reg_type == RegType.VGPR: - if op.count == 1: - assert isinstance(value, int) - self.vgprs[op.index] = u32(value) - else: - assert isinstance(value, (list, tuple)) and len(value) == op.count - for i in range(op.count): - self.vgprs[op.index + i] = u32(value[i]) - elif op.reg_type == RegType.SGPR: - if op.count == 1: - assert isinstance(value, int) - self.sgprs[op.index] = u32(value) - else: - assert isinstance(value, (list, tuple)) and len(value) == op.count - for i in range(op.count): - self.sgprs[op.index + i] = u32(value[i]) - else: - raise TypeError("Cannot write to literal operand") - - -class ScalarVALUInterpreter: - """Deterministic instruction interpreter for VALU SAD instructions on a scalar register file.""" - - def __init__(self, regs: ScalarRegisterFile | None = None) -> None: - self.regs: ScalarRegisterFile = regs if regs is not None else ScalarRegisterFile() - - def execute_sad_u32(self, instr: VSadU32Instruction) -> int: - s0 = self.regs.read(instr.src0) - s1 = self.regs.read(instr.src1) - s2 = self.regs.read(instr.src2) - assert isinstance(s0, int) and isinstance(s1, int) and isinstance(s2, int) - result = ref_sad_u32(s0, s1, s2, clamp=instr.clamp) - self.regs.write(instr.dst, result) - return result - - def execute_sad_hi_u32(self, instr: VSadHiU32Instruction) -> int: - s0 = self.regs.read(instr.src0) - s1 = self.regs.read(instr.src1) - s2 = self.regs.read(instr.src2) - assert isinstance(s0, int) and isinstance(s1, int) and isinstance(s2, int) - result = ref_sad_hi_u32(s0, s1, s2) - self.regs.write(instr.dst, result) - return result - - def execute_mqsad_u32(self, instr: VMqsadU32Instruction) -> Tuple[int, int, int, int]: - s0_64 = self.regs.read_u64(instr.src0) - s1_32 = self.regs.read(instr.src1) - s2_128 = self.regs.read(instr.src2) - assert isinstance(s1_32, int) - assert isinstance(s2_128, tuple) and len(s2_128) == 4 - result = ref_mqsad_u32(s0_64, s1_32, s2_128, masked=instr.masked) - self.regs.write(instr.dst, result) - return result - - def step(self, instr: SadInstruction) -> int | Tuple[int, int, int, int]: - if isinstance(instr, VSadU32Instruction): - return self.execute_sad_u32(instr) - if isinstance(instr, VSadHiU32Instruction): - return self.execute_sad_hi_u32(instr) - if isinstance(instr, VMqsadU32Instruction): - return self.execute_mqsad_u32(instr) - raise TypeError(f"Unsupported instruction AST: {type(instr)}") - - def run_program(self, instructions: Sequence[SadInstruction]) -> None: - for instr in instructions: - self.step(instr) - - -# ============================================================================== -# SIMD Multi-Lane Divergence and 32/64-bit EXEC Masking -# ============================================================================== - -class SIMDWaveState: - """Represents the execution state of an AMD RDNA2 wavefront (Wave32 or Wave64).""" - - def __init__(self, wave_size: int = 32, exec_mask: int | None = None) -> None: - if wave_size not in (32, 64): - raise ValueError(f"wave_size must be 32 or 64, got {wave_size}") - self.wave_size: int = wave_size - self.exec_mask_mask: int = MASK32 if wave_size == 32 else MASK64 - self.exec_mask: int = self.exec_mask_mask if exec_mask is None else (exec_mask & self.exec_mask_mask) - # 256 VGPRs per lane - self.vgprs: List[List[int]] = [[0] * 256 for _ in range(wave_size)] - # 106 shared SGPRs - self.sgprs: List[int] = [0] * 106 - - def is_lane_active(self, lane: int) -> bool: - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size - 1}]") - return bool((self.exec_mask >> lane) & 1) - - def read_lane(self, lane: int, op: Operand) -> int | Tuple[int, ...]: - if op.reg_type == RegType.LITERAL: - assert op.literal_value is not None - return op.literal_value - if op.reg_type == RegType.VGPR: - if op.count == 1: - return self.vgprs[lane][op.index] & MASK32 - return tuple(self.vgprs[lane][op.index + i] & MASK32 for i in range(op.count)) - if op.reg_type == RegType.SGPR: - if op.count == 1: - return self.sgprs[op.index] & MASK32 - return tuple(self.sgprs[op.index + i] & MASK32 for i in range(op.count)) - raise ValueError(f"Unknown operand type: {op.reg_type}") - - def read_lane_u64(self, lane: int, op: Operand) -> int: - words = self.read_lane(lane, op) - assert isinstance(words, tuple) and len(words) == 2 - return (words[1] << 32) | words[0] - - def write_lane(self, lane: int, op: Operand, value: int | Sequence[int]) -> None: - if op.reg_type != RegType.VGPR: - raise TypeError("VALU SIMD write must target VGPRs") - if op.count == 1: - assert isinstance(value, int) - self.vgprs[lane][op.index] = u32(value) - else: - assert isinstance(value, (list, tuple)) and len(value) == op.count - for i in range(op.count): - self.vgprs[lane][op.index + i] = u32(value[i]) - - -class SIMDVALUInterpreter: - """SIMD wavefront instruction interpreter honoring 32/64-bit EXEC masking.""" - - def __init__(self, wave: SIMDWaveState) -> None: - self.wave: SIMDWaveState = wave - - def step(self, instr: SadInstruction) -> List[int | Tuple[int, ...] | None]: - results: List[int | Tuple[int, ...] | None] = [] - for lane in range(self.wave.wave_size): - if not self.wave.is_lane_active(lane): - results.append(None) - continue - - if isinstance(instr, VSadU32Instruction): - s0 = self.wave.read_lane(lane, instr.src0) - s1 = self.wave.read_lane(lane, instr.src1) - s2 = self.wave.read_lane(lane, instr.src2) - assert isinstance(s0, int) and isinstance(s1, int) and isinstance(s2, int) - res = ref_sad_u32(s0, s1, s2, clamp=instr.clamp) - self.wave.write_lane(lane, instr.dst, res) - results.append(res) - elif isinstance(instr, VSadHiU32Instruction): - s0 = self.wave.read_lane(lane, instr.src0) - s1 = self.wave.read_lane(lane, instr.src1) - s2 = self.wave.read_lane(lane, instr.src2) - assert isinstance(s0, int) and isinstance(s1, int) and isinstance(s2, int) - res = ref_sad_hi_u32(s0, s1, s2) - self.wave.write_lane(lane, instr.dst, res) - results.append(res) - elif isinstance(instr, VMqsadU32Instruction): - s0_64 = self.wave.read_lane_u64(lane, instr.src0) - s1_32 = self.wave.read_lane(lane, instr.src1) - s2_128 = self.wave.read_lane(lane, instr.src2) - assert isinstance(s1_32, int) - assert isinstance(s2_128, tuple) and len(s2_128) == 4 - res_quad = ref_mqsad_u32(s0_64, s1_32, s2_128, masked=instr.masked) - self.wave.write_lane(lane, instr.dst, res_quad) - results.append(res_quad) - else: - raise TypeError(f"Unsupported instruction AST: {type(instr)}") - return results - - def run_program(self, instructions: Sequence[SadInstruction]) -> None: - for instr in instructions: - self.step(instr) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry Generation -# ============================================================================== - -@dataclass(frozen=True) -class VALUStatusFlags: - """Architectural condition codes and status flags for 32-bit ALU operations.""" - zero: bool - sign: bool - carry: bool - overflow: bool - - @classmethod - def from_sad_u32(cls, s0: int, s1: int, s2: int) -> VALUStatusFlags: - diff = ref_abs_diff_u32(s0, s1) - acc = s2 & MASK32 - full_sum = diff + acc - result = full_sum & MASK32 - - zero = (result == 0) - sign = bool(result & 0x8000_0000) - carry = (full_sum >= 0x1_0000_0000) - # Signed overflow between unsigned diff and unsigned acc - s_diff = s32(diff) - s_acc = s32(acc) - s_res = s32(result) - overflow = ((s_diff > 0 and s_acc > 0 and s_res < 0) or - (s_diff < 0 and s_acc < 0 and s_res >= 0)) - - return cls(zero=zero, sign=sign, carry=carry, overflow=overflow) - - -# ============================================================================== -# Unit Tests -# ============================================================================== - -class TestValuSadU32Oracle(unittest.TestCase): - """Unit tests for reference mathematical oracles of v_sad_u32, v_sad_hi_u32, and v_mqsad_u32.""" - - def test_abs_diff_u32_basic(self) -> None: - self.assertEqual(ref_abs_diff_u32(10, 4), 6) - self.assertEqual(ref_abs_diff_u32(4, 10), 6) - self.assertEqual(ref_abs_diff_u32(0, 0), 0) - self.assertEqual(ref_abs_diff_u32(MASK32, MASK32), 0) - - def test_abs_diff_u32_commutativity(self) -> None: - pairs = [ - (0, MASK32), - (1, 0x8000_0000), - (0x1234_5678, 0x8765_4321), - (0x7FFF_FFFF, 0x8000_0000), - (0xDEAD_BEEF, 0xCAFE_BABE), - ] - for a, b in pairs: - self.assertEqual( - ref_abs_diff_u32(a, b), - ref_abs_diff_u32(b, a), - f"Commutativity failed for ({hex(a)}, {hex(b)})", - ) - - def test_abs_diff_u32_unsigned_vs_signed_distinction(self) -> None: - self.assertEqual(ref_abs_diff_u32(0, MASK32), MASK32) - self.assertEqual(ref_abs_diff_u32(MASK32, 0), MASK32) - - def test_triangle_inequality(self) -> None: - triplets = [ - (100, 250, 400), - (0, 0x5000_0000, 0xA000_0000), - (0x1000_0000, 0x3000_0000, 0x7000_0000), - ] - for a, b, c in triplets: - d_ac = ref_abs_diff_u32(a, c) - d_ab = ref_abs_diff_u32(a, b) - d_bc = ref_abs_diff_u32(b, c) - self.assertLessEqual(d_ac, d_ab + d_bc) - - def test_sad_u32_basic_and_identity(self) -> None: - for val in [0, 1, 0x1234_5678, MASK32]: - self.assertEqual(ref_sad_u32(val, val, 0x9999), 0x9999) - self.assertEqual(ref_sad_u32(val, val, 0), 0) - - def test_sad_u32_wraparound_and_clamp(self) -> None: - self.assertEqual(ref_sad_u32(0, MASK32, 1, clamp=False), 0) - self.assertEqual(ref_sad_u32(0, MASK32, 1, clamp=True), MASK32) - self.assertEqual(ref_sad_u32(0, MASK32, MASK32, clamp=False), 0xFFFF_FFFE) - self.assertEqual(ref_sad_u32(0, MASK32, MASK32, clamp=True), MASK32) - self.assertEqual(ref_sad_u32(10, 5, 20, clamp=True), 25) - - def test_sad_hi_u32_carry_bounds(self) -> None: - self.assertEqual(ref_sad_hi_u32(10, 5, 20), 0) - self.assertEqual(ref_sad_hi_u32(0, MASK32, 0), 0) - self.assertEqual(ref_sad_hi_u32(0, MASK32, 1), 1) - self.assertEqual(ref_sad_hi_u32(0, MASK32, MASK32), 1) - - def test_multi_precision_64bit_synthesis(self) -> None: - test_cases = [ - (0, MASK32, 1, (1 << 32)), - (0, MASK32, MASK32, (2 * MASK32)), - (0x8000_0000, 0, 0x8000_0001, (1 << 32) + 1), - (100, 50, 25, 75), - ] - for s0, s1, s2, expected_64 in test_cases: - lo = ref_sad_u32(s0, s1, s2, clamp=False) - hi = ref_sad_hi_u32(s0, s1, s2) - combined_64 = (hi << 32) | lo - self.assertEqual(combined_64, expected_64) - - def test_quad_byte_sad_masked_vs_unmasked(self) -> None: - win = 0x0403_0201 - s1 = 0x0400_0200 - self.assertEqual(ref_quad_byte_sad(win, s1, masked=True), 0) - self.assertEqual(ref_quad_byte_sad(win, s1, masked=False), 4) - - def test_mqsad_u32_sliding_window(self) -> None: - s0_64 = 0x0807_0605_0403_0201 - self.assertEqual(byte_window_u32(s0_64, 0), 0x0403_0201) - self.assertEqual(byte_window_u32(s0_64, 1), 0x0504_0302) - self.assertEqual(byte_window_u32(s0_64, 2), 0x0605_0403) - self.assertEqual(byte_window_u32(s0_64, 3), 0x0706_0504) - - s1_32 = 0x0403_0201 - s2_128 = (10, 20, 30, 40) - res = ref_mqsad_u32(s0_64, s1_32, s2_128, masked=False) - self.assertEqual(res[0], 10) - self.assertEqual(res[1], 24) - self.assertEqual(res[2], 38) - self.assertEqual(res[3], 52) - - -class TestValuSadU32SymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_operand_creation_and_disassembly(self) -> None: - v0 = Operand.vgpr(0) - self.assertEqual(v0.disassemble(), "v0") - v_pair = Operand.vgpr(4, count=2) - self.assertEqual(v_pair.disassemble(), "v[4:5]") - v_quad = Operand.vgpr(8, count=4) - self.assertEqual(v_quad.disassemble(), "v[8:11]") - - s2 = Operand.sgpr(2) - self.assertEqual(s2.disassemble(), "s2") - s_pair = Operand.sgpr(10, count=2) - self.assertEqual(s_pair.disassemble(), "s[10:11]") - - lit = Operand.literal(0x1234_5678) - self.assertEqual(lit.disassemble(), "0x12345678") - - def test_operand_validation_boundaries(self) -> None: - with self.assertRaises(ValueError): - Operand.vgpr(256) - with self.assertRaises(ValueError): - Operand.vgpr(-1) - with self.assertRaises(ValueError): - Operand.vgpr(255, count=2) - with self.assertRaises(ValueError): - Operand.sgpr(106) - with self.assertRaises(ValueError): - Operand.sgpr(105, count=2) - - def test_v_sad_u32_ast_construction_and_disasm(self) -> None: - instr = VSadU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.vgpr(1), - src1=Operand.sgpr(2), - src2=Operand.literal(100), - clamp=False, - ) - self.assertEqual(instr.disassemble(), "v_sad_u32 v0, v1, s2, 0x00000064") - - instr_clamped = VSadU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - clamp=True, - ) - self.assertEqual(instr_clamped.disassemble(), "v_sad_u32 v0, v1, v2, v3 clamp") - - def test_v_sad_hi_u32_ast_construction_and_disasm(self) -> None: - instr = VSadHiU32Instruction( - dst=Operand.vgpr(5), - src0=Operand.vgpr(6), - src1=Operand.vgpr(7), - src2=Operand.vgpr(8), - ) - self.assertEqual(instr.disassemble(), "v_sad_hi_u32 v5, v6, v7, v8") - - def test_v_mqsad_u32_ast_construction_and_disasm(self) -> None: - instr = VMqsadU32Instruction( - dst=Operand.vgpr(0, count=4), - src0=Operand.vgpr(4, count=2), - src1=Operand.vgpr(6, count=1), - src2=Operand.vgpr(8, count=4), - masked=True, - ) - self.assertEqual(instr.disassemble(), "v_mqsad_u32 v[0:3], v[4:5], v6, v[8:11]") - - def test_ast_type_and_count_validation(self) -> None: - with self.assertRaises(TypeError): - VSadU32Instruction( - dst=Operand.sgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - with self.assertRaises(ValueError): - VSadU32Instruction( - dst=Operand.vgpr(0, count=2), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - with self.assertRaises(ValueError): - VMqsadU32Instruction( - dst=Operand.vgpr(0, count=1), - src0=Operand.vgpr(4, count=2), - src1=Operand.vgpr(6, count=1), - src2=Operand.vgpr(8, count=4), - ) - - -class TestValuSadU32ScalarInterpreter(unittest.TestCase): - """Unit tests for deterministic scalar instruction interpreter.""" - - def setUp(self) -> None: - self.rf = ScalarRegisterFile() - self.interp = ScalarVALUInterpreter(self.rf) - - def test_scalar_sad_u32_basic(self) -> None: - self.rf.vgprs[1] = 50 - self.rf.vgprs[2] = 20 - self.rf.vgprs[3] = 100 - instr = VSadU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - res = self.interp.step(instr) - self.assertEqual(res, 130) - self.assertEqual(self.rf.vgprs[0], 130) - - def test_scalar_sad_u32_with_sgpr_and_literal(self) -> None: - self.rf.vgprs[1] = 100 - self.rf.sgprs[5] = 40 - instr = VSadU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.vgpr(1), - src1=Operand.sgpr(5), - src2=Operand.literal(20), - ) - res = self.interp.step(instr) - self.assertEqual(res, 80) - self.assertEqual(self.rf.vgprs[0], 80) - - def test_scalar_sad_hi_u32_overflow_carry(self) -> None: - self.rf.vgprs[1] = 0 - self.rf.vgprs[2] = MASK32 - self.rf.vgprs[3] = 10 - instr = VSadHiU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - res = self.interp.step(instr) - self.assertEqual(res, 1) - self.assertEqual(self.rf.vgprs[0], 1) - - def test_64bit_sad_synthesis_program(self) -> None: - self.rf.vgprs[2] = 0x8000_0000 - self.rf.vgprs[3] = 0 - self.rf.vgprs[4] = 0x8000_0005 - prog = [ - VSadU32Instruction(Operand.vgpr(0), Operand.vgpr(2), Operand.vgpr(3), Operand.vgpr(4)), - VSadHiU32Instruction(Operand.vgpr(1), Operand.vgpr(2), Operand.vgpr(3), Operand.vgpr(4)), - ] - self.interp.run_program(prog) - self.assertEqual(self.rf.vgprs[0], 5) - self.assertEqual(self.rf.vgprs[1], 1) - res_64 = (self.rf.vgprs[1] << 32) | self.rf.vgprs[0] - self.assertEqual(res_64, 0x1_0000_0005) - - def test_scalar_mqsad_u32_execution(self) -> None: - self.rf.vgprs[4] = 0x0403_0201 - self.rf.vgprs[5] = 0x0807_0605 - self.rf.vgprs[6] = 0x0403_0201 - self.rf.vgprs[8] = 100 - self.rf.vgprs[9] = 200 - self.rf.vgprs[10] = 300 - self.rf.vgprs[11] = 400 - - instr = VMqsadU32Instruction( - dst=Operand.vgpr(0, count=4), - src0=Operand.vgpr(4, count=2), - src1=Operand.vgpr(6, count=1), - src2=Operand.vgpr(8, count=4), - masked=False, - ) - res = self.interp.step(instr) - self.assertEqual(res, (100, 204, 308, 412)) - self.assertEqual(self.rf.vgprs[0], 100) - self.assertEqual(self.rf.vgprs[1], 204) - self.assertEqual(self.rf.vgprs[2], 308) - self.assertEqual(self.rf.vgprs[3], 412) - - -class TestValuSadU32SIMDMultiLane(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_all_lanes_active(self) -> None: - wave = SIMDWaveState(wave_size=32, exec_mask=0xFFFF_FFFF) - interp = SIMDVALUInterpreter(wave) - for lane in range(32): - wave.vgprs[lane][1] = 10 * (lane + 1) - wave.vgprs[lane][2] = 5 * (lane + 1) - wave.vgprs[lane][3] = 100 - - instr = VSadU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - results = interp.step(instr) - for lane in range(32): - expected = abs(10 * (lane + 1) - 5 * (lane + 1)) + 100 - self.assertEqual(results[lane], expected) - self.assertEqual(wave.vgprs[lane][0], expected) - - def test_wave32_divergent_mask_preserves_inactive_lanes(self) -> None: - # Alternating mask: lanes 0, 2, 4... active (0x55555555) - mask = 0x5555_5555 - wave = SIMDWaveState(wave_size=32, exec_mask=mask) - interp = SIMDVALUInterpreter(wave) - - for lane in range(32): - wave.vgprs[lane][0] = 0xCAFE_0000 + lane # initial dst value - wave.vgprs[lane][1] = 20 - wave.vgprs[lane][2] = 10 - wave.vgprs[lane][3] = 50 - - instr = VSadU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - results = interp.step(instr) - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(results[lane], 60) - self.assertEqual(wave.vgprs[lane][0], 60) - else: - self.assertIsNone(results[lane]) - # Inactive lane must retain original value! - self.assertEqual(wave.vgprs[lane][0], 0xCAFE_0000 + lane) - - def test_wave32_all_inactive_lanes(self) -> None: - wave = SIMDWaveState(wave_size=32, exec_mask=0) - interp = SIMDVALUInterpreter(wave) - for lane in range(32): - wave.vgprs[lane][0] = 0xDEAD_BEEF - instr = VSadU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.literal(1), - src1=Operand.literal(2), - src2=Operand.literal(3), - ) - results = interp.step(instr) - self.assertTrue(all(r is None for r in results)) - for lane in range(32): - self.assertEqual(wave.vgprs[lane][0], 0xDEAD_BEEF) - - def test_wave64_multi_lane_divergence(self) -> None: - mask64 = 0x0123_4567_89AB_CDEF - wave = SIMDWaveState(wave_size=64, exec_mask=mask64) - interp = SIMDVALUInterpreter(wave) - - for lane in range(64): - wave.vgprs[lane][0] = 0x1111 * (lane + 1) - wave.vgprs[lane][1] = lane * 100 - wave.vgprs[lane][2] = 500 - wave.vgprs[lane][3] = 1000 - - instr = VSadU32Instruction( - dst=Operand.vgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - results = interp.step(instr) - for lane in range(64): - is_active = bool((mask64 >> lane) & 1) - if is_active: - expected = ref_sad_u32(lane * 100, 500, 1000) - self.assertEqual(results[lane], expected) - self.assertEqual(wave.vgprs[lane][0], expected) - else: - self.assertIsNone(results[lane]) - self.assertEqual(wave.vgprs[lane][0], 0x1111 * (lane + 1)) - - -class TestValuSadU32RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing, in-place operand preservation, and multi-dword hazards.""" - - def setUp(self) -> None: - self.rf = ScalarRegisterFile() - self.interp = ScalarVALUInterpreter(self.rf) - - def test_alias_dst_src0(self) -> None: - self.rf.vgprs[0] = 50 - self.rf.vgprs[1] = 20 - self.rf.vgprs[2] = 10 - instr = VSadU32Instruction(Operand.vgpr(0), Operand.vgpr(0), Operand.vgpr(1), Operand.vgpr(2)) - res = self.interp.step(instr) - self.assertEqual(res, 40) - self.assertEqual(self.rf.vgprs[0], 40) - self.assertEqual(self.rf.vgprs[1], 20) - self.assertEqual(self.rf.vgprs[2], 10) - - def test_alias_dst_src1(self) -> None: - self.rf.vgprs[0] = 30 - self.rf.vgprs[1] = 80 - self.rf.vgprs[2] = 5 - instr = VSadU32Instruction(Operand.vgpr(0), Operand.vgpr(1), Operand.vgpr(0), Operand.vgpr(2)) - res = self.interp.step(instr) - self.assertEqual(res, 55) - self.assertEqual(self.rf.vgprs[0], 55) - - def test_alias_dst_src2(self) -> None: - self.rf.vgprs[0] = 100 - self.rf.vgprs[1] = 40 - self.rf.vgprs[2] = 90 - instr = VSadU32Instruction(Operand.vgpr(0), Operand.vgpr(1), Operand.vgpr(2), Operand.vgpr(0)) - res = self.interp.step(instr) - self.assertEqual(res, 150) - self.assertEqual(self.rf.vgprs[0], 150) - - def test_alias_all_same_register(self) -> None: - self.rf.vgprs[0] = 0x1234_5678 - instr = VSadU32Instruction(Operand.vgpr(0), Operand.vgpr(0), Operand.vgpr(0), Operand.vgpr(0)) - res = self.interp.step(instr) - self.assertEqual(res, 0x1234_5678) - self.assertEqual(self.rf.vgprs[0], 0x1234_5678) - - def test_alias_sad_hi_dst_src2(self) -> None: - self.rf.vgprs[0] = MASK32 - self.rf.vgprs[1] = 0 - self.rf.vgprs[2] = 2 - instr = VSadHiU32Instruction(Operand.vgpr(0), Operand.vgpr(1), Operand.vgpr(2), Operand.vgpr(0)) - res = self.interp.step(instr) - self.assertEqual(res, 1) - self.assertEqual(self.rf.vgprs[0], 1) - - def test_mqsad_in_place_accumulator_aliasing(self) -> None: - self.rf.vgprs[0] = 10 - self.rf.vgprs[1] = 20 - self.rf.vgprs[2] = 30 - self.rf.vgprs[3] = 40 - - self.rf.vgprs[4] = 0x0403_0201 - self.rf.vgprs[5] = 0x0807_0605 - self.rf.vgprs[6] = 0x0403_0201 - - instr = VMqsadU32Instruction( - dst=Operand.vgpr(0, count=4), - src0=Operand.vgpr(4, count=2), - src1=Operand.vgpr(6, count=1), - src2=Operand.vgpr(0, count=4), - masked=False, - ) - res = self.interp.step(instr) - self.assertEqual(res, (10, 24, 38, 52)) - self.assertEqual(self.rf.vgprs[0], 10) - self.assertEqual(self.rf.vgprs[1], 24) - self.assertEqual(self.rf.vgprs[2], 38) - self.assertEqual(self.rf.vgprs[3], 52) - - def test_mqsad_overlapping_source_and_destination(self) -> None: - self.rf.vgprs[1] = 0x0403_0201 - self.rf.vgprs[2] = 0x0807_0605 - self.rf.vgprs[3] = 0x1111_1111 - self.rf.vgprs[4] = 0x2222_2222 - self.rf.vgprs[5] = 0x3333_3333 - - self.rf.vgprs[6] = 0x0403_0201 - - self.rf.vgprs[8] = 100 - self.rf.vgprs[9] = 200 - self.rf.vgprs[10] = 300 - self.rf.vgprs[11] = 400 - - instr = VMqsadU32Instruction( - dst=Operand.vgpr(2, count=4), - src0=Operand.vgpr(1, count=2), - src1=Operand.vgpr(6, count=1), - src2=Operand.vgpr(8, count=4), - masked=False, - ) - res = self.interp.step(instr) - self.assertEqual(res, (100, 204, 308, 412)) - self.assertEqual(self.rf.vgprs[2], 100) - self.assertEqual(self.rf.vgprs[3], 204) - self.assertEqual(self.rf.vgprs[4], 308) - self.assertEqual(self.rf.vgprs[5], 412) - self.assertEqual(self.rf.vgprs[1], 0x0403_0201) - - -class TestValuSadU32StatusFlags(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry generation.""" - - def test_carry_flag_matches_v_sad_hi_u32(self) -> None: - test_inputs = [ - (0, 0, 0), - (10, 5, 20), - (0, MASK32, 0), - (0, MASK32, 1), - (0, MASK32, MASK32), - (0x8000_0000, 0, 0x8000_0000), - (0x7FFF_FFFF, 0, 0x8000_0000), - (0x7FFF_FFFF, 0, 0x8000_0001), - (0xFFFF_0000, 0, 0x0001_0000), - ] - for s0, s1, s2 in test_inputs: - flags = VALUStatusFlags.from_sad_u32(s0, s1, s2) - sad_hi = ref_sad_hi_u32(s0, s1, s2) - self.assertEqual( - 1 if flags.carry else 0, - sad_hi, - f"Carry flag mismatch for ({hex(s0)}, {hex(s1)}, {hex(s2)})", - ) - - def test_carry_generation_exact_boundary(self) -> None: - # Sum = 0xFFFFFFFF -> no carry - flags_no_carry = VALUStatusFlags.from_sad_u32(0, 0xFFFF_FFFE, 1) - self.assertFalse(flags_no_carry.carry) - self.assertFalse(flags_no_carry.zero) - self.assertTrue(flags_no_carry.sign) # bit 31 is set - - # Sum = 0x100000000 -> carry = True, zero = True, sign = False - flags_carry = VALUStatusFlags.from_sad_u32(0, MASK32, 1) - self.assertTrue(flags_carry.carry) - self.assertTrue(flags_carry.zero) - self.assertFalse(flags_carry.sign) - - def test_zero_flag_behaviors(self) -> None: - # Diff = 0, acc = 0 -> zero = True, carry = False, sign = False - flags_zero = VALUStatusFlags.from_sad_u32(100, 100, 0) - self.assertTrue(flags_zero.zero) - self.assertFalse(flags_zero.carry) - self.assertFalse(flags_zero.sign) - - # Diff = 5, acc = 0 -> zero = False - flags_nonzero = VALUStatusFlags.from_sad_u32(10, 5, 0) - self.assertFalse(flags_nonzero.zero) - - def test_sign_flag_behaviors(self) -> None: - # Result < 0x80000000 -> sign = False - flags_pos = VALUStatusFlags.from_sad_u32(0, 0x7FFF_FFFF, 0) - self.assertFalse(flags_pos.sign) - - # Result == 0x80000000 -> sign = True - flags_neg = VALUStatusFlags.from_sad_u32(0, 0x8000_0000, 0) - self.assertTrue(flags_neg.sign) - - -class TestValuSadU32IEEE754Boundaries(unittest.TestCase): - """Unit tests for IEEE 754 bit-pattern extremes, subnormals, and NaN payload distances.""" - - POS_ZERO_F32: int = 0x0000_0000 - NEG_ZERO_F32: int = 0x8000_0000 - POS_INF_F32: int = 0x7F80_0000 - NEG_INF_F32: int = 0xFF80_0000 - QNAN_F32: int = 0x7FC0_0000 - SNAN_F32: int = 0x7F80_0001 - MIN_NORMAL_F32: int = 0x0080_0000 - MAX_SUBNORMAL_F32: int = 0x007F_FFFF - MIN_SUBNORMAL_F32: int = 0x0000_0001 - - @staticmethod - def f32_to_bits(val: float) -> int: - return struct.unpack(" None: - # 1.0f in binary32 is 0x3F800000 - # The next adjacent float is 1.0000001192092896f (0x3F800001) - b_one = self.f32_to_bits(1.0) - b_next = b_one + 1 - dist = ref_sad_u32(b_one, b_next, 0) - self.assertEqual(dist, 1) - - def test_signed_zero_bit_distance(self) -> None: - # Distance between +0.0 (0x00000000) and -0.0 (0x80000000) - dist = ref_sad_u32(self.POS_ZERO_F32, self.NEG_ZERO_F32, 0) - self.assertEqual(dist, 0x8000_0000) - - def test_subnormal_to_normal_boundary_step(self) -> None: - # Between max subnormal (0x007FFFFF) and min normal (0x00800000) - step = ref_sad_u32(self.MIN_NORMAL_F32, self.MAX_SUBNORMAL_F32, 0) - self.assertEqual(step, 1) - - def test_nan_payload_distance(self) -> None: - # Distance between infinity and canonical quiet NaN is exactly the quiet bit (0x00400000) - dist = ref_sad_u32(self.POS_INF_F32, self.QNAN_F32, 0) - self.assertEqual(dist, 0x0040_0000) - - def test_signaling_nan_payload(self) -> None: - # Distance between +Inf (0x7F800000) and signaling NaN with payload 1 (0x7F800001) - dist = ref_sad_u32(self.POS_INF_F32, self.SNAN_F32, 0) - self.assertEqual(dist, 1) - - def test_nan_clamp_saturation(self) -> None: - # Adding accumulator to NaN distance that overflows 32-bit space saturates to 0xFFFFFFFF - dist_clamped = ref_sad_u32(self.NEG_INF_F32, self.POS_ZERO_F32, 0x1000, clamp=True) - # |0xFF800000 - 0| + 0x1000 = 0xFF801000 (< 0xFFFFFFFF, no overflow) - self.assertEqual(dist_clamped, 0xFF80_1000) - - # Extreme overflow with clamp - dist_overflow_clamped = ref_sad_u32(self.NEG_INF_F32, self.POS_ZERO_F32, 0x0080_0000, clamp=True) - # 0xFF800000 + 0x00800000 = 0x100000000 -> clamps to 0xFFFFFFFF - self.assertEqual(dist_overflow_clamped, MASK32) - - -class TestValuSadU32NegativeControlsAndMutations(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and mutation detection.""" - - def test_negative_control_sgpr_as_destination(self) -> None: - with self.assertRaises(TypeError): - VSadU32Instruction( - dst=Operand.sgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - with self.assertRaises(TypeError): - VSadHiU32Instruction( - dst=Operand.sgpr(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - with self.assertRaises(TypeError): - VMqsadU32Instruction( - dst=Operand.sgpr(0, count=4), - src0=Operand.vgpr(4, count=2), - src1=Operand.vgpr(6, count=1), - src2=Operand.vgpr(8, count=4), - ) - - def test_negative_control_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Operand.vgpr(256) - with self.assertRaises(ValueError): - Operand.vgpr(253, count=4) # 253 + 4 - 1 = 256 > 255 - with self.assertRaises(ValueError): - Operand.sgpr(106) - with self.assertRaises(ValueError): - Operand.sgpr(104, count=4) # 104 + 4 - 1 = 107 > 105 - - def test_negative_control_literal_destination(self) -> None: - with self.assertRaises(TypeError): - VSadU32Instruction( - dst=Operand.literal(0), - src0=Operand.vgpr(1), - src1=Operand.vgpr(2), - src2=Operand.vgpr(3), - ) - - def test_negative_control_wave_state_boundaries(self) -> None: - with self.assertRaises(ValueError): - SIMDWaveState(wave_size=16) - wave = SIMDWaveState(wave_size=32) - with self.assertRaises(IndexError): - wave.is_lane_active(32) - with self.assertRaises(IndexError): - wave.is_lane_active(-1) - - def test_mutation_detection_signed_vs_unsigned_diff(self) -> None: - def mutant_signed_diff(s0: int, s1: int) -> int: - return abs(s32(s0) - s32(s1)) & MASK32 - - # In unsigned arithmetic |0 - 0xFFFFFFFF| == 0xFFFFFFFF. - # In signed arithmetic |0 - (-1)| == 1. - correct = ref_abs_diff_u32(0, MASK32) - mutant = mutant_signed_diff(0, MASK32) - self.assertNotEqual(correct, mutant) - self.assertEqual(correct, MASK32) - self.assertEqual(mutant, 1) - - def test_mutation_detection_sad_hi_carry(self) -> None: - def mutant_sad_hi(s0: int, s1: int, s2: int) -> int: - # Faulty implementation: forgets difference and just does (s0 + s2) >> 32 - return ((s0 & MASK32) + (s2 & MASK32)) >> 32 - - # For s0 = 0, s1 = 0xFFFFFFFF, s2 = 1: - # Correct: diff = 0xFFFFFFFF, diff + 1 = 0x100000000 -> hi = 1 - # Mutant: 0 + 1 = 1 -> hi = 0 - correct = ref_sad_hi_u32(0, MASK32, 1) - mutant = mutant_sad_hi(0, MASK32, 1) - self.assertNotEqual(correct, mutant) - self.assertEqual(correct, 1) - self.assertEqual(mutant, 0) - - def test_mutation_detection_mqsad_mask_skipping(self) -> None: - def mutant_quad_byte_sad(win: int, s1: int) -> int: - # Faulty implementation: ignores mask check and always adds byte differences - total = 0 - for i in range(4): - total += abs(extract_byte(win, i) - extract_byte(s1, i)) - return total - - win = 0x0101_0101 - s1 = 0x0001_0001 # bytes 0 and 2 are 0 - correct = ref_quad_byte_sad(win, s1, masked=True) - mutant = mutant_quad_byte_sad(win, s1) - # In correct masked behavior: bytes 0 and 2 are skipped; bytes 1 and 3 match (diff=0) -> total = 0 - # In mutant unmasked behavior: bytes 0 and 2 have diff 1 each -> total = 2 - self.assertNotEqual(correct, mutant) - self.assertEqual(correct, 0) - self.assertEqual(mutant, 2) - - def test_mutation_detection_clamp_overflow(self) -> None: - def mutant_clamped_sad(s0: int, s1: int, s2: int) -> int: - # Faulty clamp: wraps modulo 2^32 instead of saturating - return (ref_abs_diff_u32(s0, s1) + (s2 & MASK32)) & MASK32 - - correct = ref_sad_u32(0, MASK32, 1, clamp=True) - mutant = mutant_clamped_sad(0, MASK32, 1) - self.assertNotEqual(correct, mutant) - self.assertEqual(correct, MASK32) - self.assertEqual(mutant, 0) +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import support # noqa: E402 + +M32 = 0xFFFFFFFF + + +def ref(s0, s1, s2): + return (abs(s0 - s1) + s2) & M32 + + +def run(s0, s1, s2, form="vgpr"): + if form == "vgpr": + lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2:#x}", "v_sad_u32 v0, v1, v2, v3"] + elif form == "sgpr": + lines = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2:#x}", "v_sad_u32 v0, s1, s2, s3"] + elif form == "literal": # one literal (S1) between VGPRs: the VOP3 literal slot of GFX10 + lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v3, {s2:#x}", f"v_sad_u32 v0, v1, {s1:#x}, v3"] + else: + raise ValueError(form) + lines += ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_sad_u32", lines))[0] + + +# (S0, S1, S2, expected word), written by hand. +CASES = [ + (5, 3, 0, 2), (3, 5, 0, 2), (7, 7, 0, 0), (10, 4, 100, 106), (4, 10, 100, 106), + (0, 0xFFFFFFFF, 0, 0xFFFFFFFF), (0xFFFFFFFF, 0, 0, 0xFFFFFFFF), + (0x80000000, 0x7FFFFFFF, 0, 1), # unsigned: not a signed wrap + (0, 0x80000000, 0, 0x80000000), + (0xFFFFFFFF, 0, 1, 0), # 2^32 - 1 + 1 wraps + (0xFFFFFFFF, 0, 0xFFFFFFFF, 0xFFFFFFFE), + (0x12345678, 0x12345600, 0x10, 0x88), + (0x00000001, 0xFFFFFFFF, 0x00000003, 0x00000001), # 0xFFFFFFFE + 3 mod 2^32 +] + + +class SadU32(unittest.TestCase): + def test_hand_table_matches_reference(self): + for s0, s1, s2, want in CASES: + self.assertEqual(ref(s0, s1, s2), want, (hex(s0), hex(s1), hex(s2))) + + def test_translated_forms(self): + for form in ("vgpr", "sgpr", "literal"): + for s0, s1, s2, want in CASES: + with self.subTest(form=form, s0=hex(s0), s1=hex(s1), s2=hex(s2)): + self.assertEqual(run(s0, s1, s2, form), want) + + def test_symmetric_in_s0_s1(self): + rng = random.Random(0x5AD) + for _ in range(20): + a, b, c = (rng.getrandbits(32) for _ in range(3)) + self.assertEqual(run(a, b, c), run(b, a, c)) + + def test_random_operands(self): + rng = random.Random(0x5AD32) + for _ in range(60): + s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) + for form in ("vgpr", "sgpr", "literal"): + with self.subTest(form=form, s0=hex(s0), s1=hex(s1), s2=hex(s2)): + self.assertEqual(run(s0, s1, s2, form), ref(s0, s1, s2)) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_sub_f16.py b/tests/semantic/test_valu_sub_f16.py index 062e53668..01c321fd4 100644 --- a/tests/semantic/test_valu_sub_f16.py +++ b/tests/semantic/test_valu_sub_f16.py @@ -1,1458 +1,147 @@ -from __future__ import annotations +"""v_sub_f16 (RDNA2 VOP2 / VOP3): D.f16 = S0.f16 - S1.f16, binary16 with round to nearest even. -import math -import struct +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in +tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the _e32 form (the high half of the +destination is kept), the _e64 form with op_sel, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. +Standard library only: no GPU, no LLVM, no game data. +""" +import os +import random +import sys import unittest -from dataclasses import dataclass, field -from enum import Enum, auto -from fractions import Fraction -from typing import List, Optional, Tuple, Union -# IEEE 754 binary16 (half precision) architectural constants -SIGN_MASK_F16: int = 0x8000 -EXP_MASK_F16: int = 0x7C00 -FRAC_MASK_F16: int = 0x03FF -QNAN_BIT_F16: int = 0x0200 -CANONICAL_QNAN_F16: int = 0x7E00 +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import OLD, ref_sub, same_f16, scale # noqa: E402 -POS_ZERO_F16: int = 0x0000 -NEG_ZERO_F16: int = 0x8000 -POS_INF_F16: int = 0x7C00 -NEG_INF_F16: int = 0xFC00 - -ONE_F16: int = 0x3C00 -HALF_F16: int = 0x3800 -TWO_F16: int = 0x4000 -MAX_FINITE_F16: int = 0x7BFF -MIN_NORMAL_F16: int = 0x0400 -MIN_SUBNORMAL_F16: int = 0x0001 -MAX_SUBNORMAL_F16: int = 0x03FF +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF -def f16_to_bits(val: float) -> int: - """Convert a Python float to 16-bit IEEE 754 half-precision integer bits.""" - if math.isnan(val): - return CANONICAL_QNAN_F16 - if math.isinf(val): - return POS_INF_F16 if val > 0 else NEG_INF_F16 - try: - return struct.unpack(" 0 else NEG_INF_F16 +def run(line, seeds, old=OLD, hi=0x5A5A): + """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. - -def bits_to_f16(bits: int) -> float: - """Convert 16-bit integer bits to a Python float.""" - return struct.unpack(" Tuple[int, int, int]: - """Unpack bits into (sign, exponent, fraction) components.""" - sign = (bits & SIGN_MASK_F16) >> 15 - exponent = (bits & EXP_MASK_F16) >> 10 - fraction = bits & FRAC_MASK_F16 - return sign, exponent, fraction - - -def unpack_half_word(word: int, hi: bool) -> int: - """Extract low (hi=False) or high (hi=True) 16-bit half from a 32-bit register word.""" - return ((word >> 16) if hi else word) & 0xFFFF - - -def pack_half_word(old_word: int, val16: int, hi: bool) -> int: - """Merge 16-bit result into low or high half of 32-bit register word, preserving the other half.""" - val16 &= 0xFFFF - if hi: - return (old_word & 0x0000FFFF) | (val16 << 16) - else: - return (old_word & 0xFFFF0000) | val16 - - -def is_nan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 half-precision NaN.""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & FRAC_MASK_F16) != 0) - - -def is_qnan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 half-precision Quiet NaN.""" - return is_nan_f16(bits) and bool(bits & QNAN_BIT_F16) - - -def is_snan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 half-precision Signaling NaN.""" - return is_nan_f16(bits) and not bool(bits & QNAN_BIT_F16) - - -def is_inf_f16(bits: int) -> bool: - """Return True if bits represent IEEE 754 half-precision positive or negative infinity.""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & FRAC_MASK_F16) == 0) - - -def is_subnormal_f16(bits: int) -> bool: - """Return True if bits represent a subnormal (denormal) half-precision float.""" - return ((bits & EXP_MASK_F16) == 0) and ((bits & FRAC_MASK_F16) != 0) - - -def is_zero_f16(bits: int) -> bool: - """Return True if bits represent positive or negative zero.""" - return (bits & ~SIGN_MASK_F16) == 0 - - -def apply_f16_modifiers(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Apply VOP3 input modifiers: abs clears sign bit; neg toggles sign bit.""" - res = bits & 0xFFFF - if abs_mod: - res &= ~SIGN_MASK_F16 - if neg_mod: - res ^= SIGN_MASK_F16 - return res - - -def oracle_v_sub_f16( - src0_bits: int, - src1_bits: int, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_sub_f16 half-precision subtraction. - - Computes D = src0 - src1 conforming to IEEE 754-2008 half precision (binary16) - with Round-to-Nearest-Even (RNE), applying input modifiers and clamp. + `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its + upper half, so reading the wrong half of a source shows. v0 starts as `old`. """ - s0 = apply_f16_modifiers(src0_bits, abs0, neg0) - s1 = apply_f16_modifiers(src1_bits, abs1, neg1) - - # 1. NaN handling - if is_nan_f16(s0) or is_nan_f16(s1): - if clamp: - # Clamping NaN in RDNA2 produces +0.0 - return POS_ZERO_F16 - # Prefer quietening signaling NaN or propagating quiet NaN - nan_bits = s0 if is_nan_f16(s0) else s1 - return nan_bits | QNAN_BIT_F16 - - # 2. Infinity handling - s0_inf = is_inf_f16(s0) - s1_inf = is_inf_f16(s1) - if s0_inf and s1_inf: - s0_sign = s0 & SIGN_MASK_F16 - s1_sign = s1 & SIGN_MASK_F16 - # (+inf) - (+inf) or (-inf) - (-inf) -> Invalid operation -> Canonical Quiet NaN - if s0_sign == s1_sign: - return POS_ZERO_F16 if clamp else CANONICAL_QNAN_F16 - # (+inf) - (-inf) = +inf - # (-inf) - (+inf) = -inf - res = s0 - if clamp: - return ONE_F16 if res == POS_INF_F16 else POS_ZERO_F16 - return res - if s0_inf: - if clamp: - return ONE_F16 if s0 == POS_INF_F16 else POS_ZERO_F16 - return s0 - if s1_inf: - # finite - (+inf) = -inf; finite - (-inf) = +inf - res = NEG_INF_F16 if s1 == POS_INF_F16 else POS_INF_F16 - if clamp: - return ONE_F16 if res == POS_INF_F16 else POS_ZERO_F16 - return res - - # 3. Signed zero handling - if is_zero_f16(s0) and is_zero_f16(s1): - s0_is_neg = (s0 == NEG_ZERO_F16) - s1_is_neg = (s1 == NEG_ZERO_F16) - # (+0) - (+0) = +0 - # (+0) - (-0) = +0 - # (-0) - (-0) = +0 (Round-to-Nearest-Even) - # (-0) - (+0) = -0 - if s0_is_neg and not s1_is_neg: - res = NEG_ZERO_F16 - else: - res = POS_ZERO_F16 - if clamp and res == NEG_ZERO_F16: - return POS_ZERO_F16 - return res - - # 4. Finite subtraction - f0 = bits_to_f16(s0) - f1 = bits_to_f16(s1) - f_res = f0 - f1 - res = f16_to_bits(f_res) - - # In round-to-nearest-even, x - x produces +0.0 - if f_res == 0.0 and not (s0 == NEG_ZERO_F16 and s1 == POS_ZERO_F16): - res = POS_ZERO_F16 - - # 5. Clamp modifier ([0.0, 1.0]) - if clamp: - if f_res < 0.0 or res == NEG_ZERO_F16: - res = POS_ZERO_F16 - elif f_res > 1.0 or res == POS_INF_F16: - res = ONE_F16 - - return res - - -class TestF16ModelAndOracle(unittest.TestCase): - """Unit tests for binary16 bit model, predicates, and reference mathematical oracle.""" - - def test_bit_representation_roundtrip(self) -> None: - values = [0.0, -0.0, 1.0, -1.0, 0.5, -2.5, 65504.0, -65504.0] - for val in values: - with self.subTest(val=val): - bits = f16_to_bits(val) - recovered = bits_to_f16(bits) - self.assertEqual(val, recovered) - self.assertEqual(math.copysign(1.0, val), math.copysign(1.0, recovered)) - - def test_halfword_packing_and_unpacking(self) -> None: - old_reg = 0x12345678 - val_lo = 0x3C00 # 1.0 - val_hi = 0x4000 # 2.0 - - updated_lo = pack_half_word(old_reg, val_lo, hi=False) - self.assertEqual(updated_lo & 0xFFFF, val_lo) - self.assertEqual((updated_lo >> 16) & 0xFFFF, 0x1234) - self.assertEqual(unpack_half_word(updated_lo, hi=False), val_lo) - self.assertEqual(unpack_half_word(updated_lo, hi=True), 0x1234) - - updated_hi = pack_half_word(old_reg, val_hi, hi=True) - self.assertEqual((updated_hi >> 16) & 0xFFFF, val_hi) - self.assertEqual(updated_hi & 0xFFFF, 0x5678) - self.assertEqual(unpack_half_word(updated_hi, hi=True), val_hi) - self.assertEqual(unpack_half_word(updated_hi, hi=False), 0x5678) - - def test_classification_predicates(self) -> None: - self.assertTrue(f16_to_bits(0.0) == POS_ZERO_F16) - self.assertTrue(f16_to_bits(-0.0) == NEG_ZERO_F16) - self.assertTrue(is_zero_f16(POS_ZERO_F16)) - self.assertTrue(is_zero_f16(NEG_ZERO_F16)) - self.assertFalse(is_zero_f16(f16_to_bits(1.0))) - - self.assertTrue(is_inf_f16(POS_INF_F16)) - self.assertTrue(is_inf_f16(NEG_INF_F16)) - self.assertFalse(is_inf_f16(POS_ZERO_F16)) - - snan_bits = 0x7C01 - qnan_bits = CANONICAL_QNAN_F16 - self.assertTrue(is_nan_f16(snan_bits)) - self.assertTrue(is_snan_f16(snan_bits)) - self.assertFalse(is_qnan_f16(snan_bits)) - - self.assertTrue(is_nan_f16(qnan_bits)) - self.assertTrue(is_qnan_f16(qnan_bits)) - self.assertFalse(is_snan_f16(qnan_bits)) - - subnorm_bits = MIN_SUBNORMAL_F16 - self.assertTrue(is_subnormal_f16(subnorm_bits)) - self.assertFalse(is_subnormal_f16(POS_ZERO_F16)) - self.assertFalse(is_subnormal_f16(f16_to_bits(1.0))) - - def test_exact_finite_subtraction(self) -> None: - c = oracle_v_sub_f16(f16_to_bits(3.75), f16_to_bits(1.5)) - self.assertEqual(bits_to_f16(c), 2.25) - - c2 = oracle_v_sub_f16(f16_to_bits(10.0), f16_to_bits(25.5)) - self.assertEqual(bits_to_f16(c2), -15.5) - - def test_signed_zero_rules(self) -> None: - # IEEE 754: (+0) - (+0) = +0 - self.assertEqual(oracle_v_sub_f16(POS_ZERO_F16, POS_ZERO_F16), POS_ZERO_F16) - # (-0) - (-0) = +0 - self.assertEqual(oracle_v_sub_f16(NEG_ZERO_F16, NEG_ZERO_F16), POS_ZERO_F16) - # (+0) - (-0) = +0 - self.assertEqual(oracle_v_sub_f16(POS_ZERO_F16, NEG_ZERO_F16), POS_ZERO_F16) - # (-0) - (+0) = -0 - self.assertEqual(oracle_v_sub_f16(NEG_ZERO_F16, POS_ZERO_F16), NEG_ZERO_F16) - # x - x = +0 - self.assertEqual(oracle_v_sub_f16(f16_to_bits(42.0), f16_to_bits(42.0)), POS_ZERO_F16) - - def test_input_modifiers_abs_neg(self) -> None: - val_pos = f16_to_bits(10.0) - val_neg = f16_to_bits(-10.0) - - # abs on negative: |-10.0| - 5.0 = 5.0 - res = oracle_v_sub_f16(val_neg, f16_to_bits(5.0), abs0=True) - self.assertEqual(bits_to_f16(res), 5.0) - - # neg on positive: -(10.0) - 5.0 = -15.0 - res = oracle_v_sub_f16(val_pos, f16_to_bits(5.0), neg0=True) - self.assertEqual(bits_to_f16(res), -15.0) - - # abs and neg together: -|10.0| - 5.0 = -15.0; -|-10.0| - 5.0 = -15.0 - res1 = oracle_v_sub_f16(val_pos, f16_to_bits(5.0), abs0=True, neg0=True) - res2 = oracle_v_sub_f16(val_neg, f16_to_bits(5.0), abs0=True, neg0=True) - self.assertEqual(bits_to_f16(res1), -15.0) - self.assertEqual(bits_to_f16(res2), -15.0) - - def test_clamp_modifier(self) -> None: - # Clamped result > 1.0 becomes 1.0 - res_hi = oracle_v_sub_f16(f16_to_bits(2.5), f16_to_bits(0.5), clamp=True) - self.assertEqual(res_hi, ONE_F16) - - # Clamped result < 0.0 becomes +0.0 - res_lo = oracle_v_sub_f16(f16_to_bits(0.5), f16_to_bits(1.5), clamp=True) - self.assertEqual(res_lo, POS_ZERO_F16) - - # Clamped result within [0.0, 1.0] is unmodified - res_mid = oracle_v_sub_f16(f16_to_bits(0.75), f16_to_bits(0.25), clamp=True) - self.assertEqual(bits_to_f16(res_mid), 0.5) - - def test_infinity_subtraction(self) -> None: - self.assertEqual(oracle_v_sub_f16(POS_INF_F16, f16_to_bits(1.0)), POS_INF_F16) - self.assertEqual(oracle_v_sub_f16(NEG_INF_F16, f16_to_bits(1.0)), NEG_INF_F16) - self.assertEqual(oracle_v_sub_f16(f16_to_bits(1.0), POS_INF_F16), NEG_INF_F16) - self.assertEqual(oracle_v_sub_f16(f16_to_bits(1.0), NEG_INF_F16), POS_INF_F16) - # (+inf) - (+inf) -> Canonical NaN - self.assertEqual(oracle_v_sub_f16(POS_INF_F16, POS_INF_F16), CANONICAL_QNAN_F16) - # (-inf) - (-inf) -> Canonical NaN - self.assertEqual(oracle_v_sub_f16(NEG_INF_F16, NEG_INF_F16), CANONICAL_QNAN_F16) - # (+inf) - (-inf) -> +inf - self.assertEqual(oracle_v_sub_f16(POS_INF_F16, NEG_INF_F16), POS_INF_F16) - # (-inf) - (+inf) -> -inf - self.assertEqual(oracle_v_sub_f16(NEG_INF_F16, POS_INF_F16), NEG_INF_F16) - - def test_nan_quietening_and_propagation(self) -> None: - snan = 0x7C05 - res = oracle_v_sub_f16(snan, f16_to_bits(1.0)) - self.assertTrue(is_qnan_f16(res)) - self.assertEqual(res, snan | QNAN_BIT_F16) - - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - VGPR = auto() - SGPR = auto() - - -@dataclass(frozen=True) -class Reg: - """Represents an architectural 16-bit register operand inside a 32-bit register.""" - index: int - reg_type: RegType - hi: bool = False # False = low 16 bits (.l), True = high 16 bits (.h) - - def __post_init__(self) -> None: - if not (0 <= self.index <= 255): - raise ValueError(f"Register index {self.index} out of range [0, 255]") - - @property - def name(self) -> str: - prefix = "v" if self.reg_type == RegType.VGPR else "s" - half = "h" if self.hi else "l" - return f"{prefix}{self.index}.{half}" - - -@dataclass(frozen=True) -class Literal16: - """Represents a 16-bit inline float constant or literal.""" - bits: int - - @classmethod - def from_float(cls, val: float) -> Literal16: - return cls(f16_to_bits(val)) - - @property - def float_value(self) -> float: - return bits_to_f16(self.bits) - - @property - def name(self) -> str: - if self.bits == POS_ZERO_F16: - return "0.0" - if self.bits == NEG_ZERO_F16: - return "-0.0" - f = self.float_value - if math.isnan(f): - return "nan" - if math.isinf(f): - return "inf" if f > 0 else "-inf" - return f"{f:g}" - - -@dataclass(frozen=True) -class VOP3Operand16: - """Typed expression operand with optional input modifiers (abs, neg) and op_sel.""" - source: Union[Reg, Literal16] - abs_mod: bool = False - neg_mod: bool = False - - def disassemble(self) -> str: - s = self.source.name - if self.abs_mod: - s = f"|{s}|" - if self.neg_mod: - s = f"-{s}" - return s - - -@dataclass(frozen=True) -class VSubF16Instruction: - """Symbolic AST node representing a RDNA2 v_sub_f16 instruction.""" - dst: Reg - src0: VOP3Operand16 - src1: VOP3Operand16 - clamp: bool = False - is_vop3: bool = True - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination of VALU instruction must be VGPR, got {self.dst.reg_type}") - - def disassemble(self) -> str: - if not self.is_vop3 and not self.clamp and not self.dst.hi and not self.src0.abs_mod and not self.src0.neg_mod and not self.src1.abs_mod and not self.src1.neg_mod: - # VOP2 format - dst_str = f"v{self.dst.index}" - src0_str = f"v{self.src0.source.index}" if isinstance(self.src0.source, Reg) and self.src0.source.reg_type == RegType.VGPR else self.src0.source.name - src1_str = f"v{self.src1.source.index}" if isinstance(self.src1.source, Reg) and self.src1.source.reg_type == RegType.VGPR else self.src1.source.name - return f"v_sub_f16_e32 {dst_str}, {src0_str}, {src1_str}" - s = f"v_sub_f16_e64 {self.dst.name}, {self.src0.disassemble()}, {self.src1.disassemble()}" - if self.clamp: - s += " clamp" - return s - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_reg_validation_and_naming(self) -> None: - v0_l = Reg(0, RegType.VGPR, hi=False) - self.assertEqual(v0_l.name, "v0.l") - self.assertEqual(v0_l.index, 0) - self.assertFalse(v0_l.hi) - - v0_h = Reg(0, RegType.VGPR, hi=True) - self.assertEqual(v0_h.name, "v0.h") - self.assertTrue(v0_h.hi) - - s5_l = Reg(5, RegType.SGPR, hi=False) - self.assertEqual(s5_l.name, "s5.l") - - with self.assertRaises(ValueError): - Reg(256, RegType.VGPR) - with self.assertRaises(ValueError): - Reg(-1, RegType.VGPR) - - def test_operand_disassembly(self) -> None: - v = Reg(2, RegType.VGPR, hi=True) - op_plain = VOP3Operand16(v) - self.assertEqual(op_plain.disassemble(), "v2.h") - - op_abs = VOP3Operand16(v, abs_mod=True) - self.assertEqual(op_abs.disassemble(), "|v2.h|") - - op_neg = VOP3Operand16(v, neg_mod=True) - self.assertEqual(op_neg.disassemble(), "-v2.h") - - op_neg_abs = VOP3Operand16(v, abs_mod=True, neg_mod=True) - self.assertEqual(op_neg_abs.disassemble(), "-|v2.h|") - - lit = Literal16.from_float(1.5) - op_lit = VOP3Operand16(lit) - self.assertEqual(op_lit.disassemble(), "1.5") - - def test_v_sub_f16_ast_construction_and_validation(self) -> None: - dst = Reg(0, RegType.VGPR, hi=False) - src0 = VOP3Operand16(Reg(2, RegType.VGPR, hi=False), neg_mod=True, abs_mod=True) - src1 = VOP3Operand16(Reg(4, RegType.SGPR, hi=True)) - instr = VSubF16Instruction(dst=dst, src0=src0, src1=src1, clamp=True) - - self.assertEqual(instr.disassemble(), "v_sub_f16_e64 v0.l, -|v2.l|, s4.h clamp") - - # Invalid destination type (SGPR) - with self.assertRaises(TypeError): - VSubF16Instruction(dst=Reg(0, RegType.SGPR), src0=src0, src1=src1) - - def test_vop2_disassembly(self) -> None: - dst = Reg(0, RegType.VGPR, hi=False) - src0 = VOP3Operand16(Reg(1, RegType.VGPR, hi=False)) - src1 = VOP3Operand16(Reg(2, RegType.VGPR, hi=False)) - instr = VSubF16Instruction(dst=dst, src0=src0, src1=src1, is_vop3=False) - self.assertEqual(instr.disassemble(), "v_sub_f16_e32 v0, v1, v2") - - def test_structural_equality(self) -> None: - i1 = VSubF16Instruction( - Reg(0, RegType.VGPR, hi=False), - VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - VOP3Operand16(Literal16.from_float(0.0)), - ) - i2 = VSubF16Instruction( - Reg(0, RegType.VGPR, hi=False), - VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - VOP3Operand16(Literal16.from_float(0.0)), - ) - self.assertEqual(i1, i2) - - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register file for a single wavefront lane.""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def get_vgpr16(self, index: int, hi: bool = False) -> int: - return unpack_half_word(self.vgprs[index], hi) - - def set_vgpr16(self, index: int, bits16: int, hi: bool = False) -> None: - self.vgprs[index] = pack_half_word(self.vgprs[index], bits16, hi) - - def get_sgpr16(self, index: int, hi: bool = False) -> int: - return unpack_half_word(self.sgprs[index], hi) - - def set_sgpr16(self, index: int, bits16: int, hi: bool = False) -> None: - self.sgprs[index] = pack_half_word(self.sgprs[index], bits16, hi) - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_sub_f16.""" - - def resolve_operand(self, op: VOP3Operand16, state: ScalarMachineState) -> int: - if isinstance(op.source, Reg): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr16(op.source.index, op.source.hi) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr16(op.source.index, op.source.hi) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal16): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VSubF16Instruction, state: ScalarMachineState) -> int: - # Atomic read phase - s0_raw = self.resolve_operand(instr.src0, state) - s1_raw = self.resolve_operand(instr.src1, state) - - # Computation phase - result_bits = oracle_v_sub_f16( - src0_bits=s0_raw, - src1_bits=s1_raw, - abs0=instr.src0.abs_mod, - neg0=instr.src0.neg_mod, - abs1=instr.src1.abs_mod, - neg1=instr.src1.neg_mod, - clamp=instr.clamp, - ) - - # Write-back phase (preserves non-targeted half of destination VGPR) - state.set_vgpr16(instr.dst.index, result_bits, instr.dst.hi) - return result_bits - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_scalar_vgpr_vgpr_subtraction(self) -> None: - self.state.set_vgpr16(2, f16_to_bits(12.5), hi=False) - self.state.set_vgpr16(4, f16_to_bits(7.5), hi=False) - instr = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(4, RegType.VGPR, hi=False)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f16(res_bits), 5.0) - self.assertEqual(self.state.get_vgpr16(0, hi=False), res_bits) - - def test_scalar_vgpr_sgpr_subtraction(self) -> None: - self.state.set_vgpr16(0, f16_to_bits(100.0), hi=False) - self.state.set_sgpr16(8, f16_to_bits(25.0), hi=True) - instr = VSubF16Instruction( - dst=Reg(4, RegType.VGPR, hi=True), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(8, RegType.SGPR, hi=True)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f16(res_bits), 75.0) - self.assertEqual(self.state.get_vgpr16(4, hi=True), res_bits) - - def test_scalar_vgpr_literal_subtraction(self) -> None: - self.state.set_vgpr16(6, f16_to_bits(3.0), hi=False) - instr = VSubF16Instruction( - dst=Reg(6, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(6, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Literal16.from_float(0.5)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f16(res_bits), 2.5) - self.assertEqual(self.state.get_vgpr16(6, hi=False), res_bits) - - def test_scalar_with_modifiers_and_clamp(self) -> None: - self.state.set_vgpr16(0, f16_to_bits(1.8), hi=False) - self.state.set_vgpr16(2, f16_to_bits(0.5), hi=False) - # 1.8 - 0.5 = 1.3 -> clamped to 1.0 - instr = VSubF16Instruction( - dst=Reg(4, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - clamp=True, - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(res_bits, ONE_F16) - - def test_scalar_determinism(self) -> None: - runs = [] - for _ in range(50): - st = ScalarMachineState() - st.set_vgpr16(0, f16_to_bits(3.140625), hi=False) - st.set_vgpr16(2, f16_to_bits(2.71875), hi=False) - instr = VSubF16Instruction( - dst=Reg(4, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - ) - runs.append(self.interp.step(instr, st)) - self.assertTrue(all(r == runs[0] for r in runs)) - - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - num_lanes: int - exec_mask: Optional[int] = None - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - - def get_vgpr16(self, lane: int, index: int, hi: bool = False) -> int: - return unpack_half_word(self.vgprs[lane][index], hi) - - def set_vgpr16(self, lane: int, index: int, bits16: int, hi: bool = False) -> None: - self.vgprs[lane][index] = pack_half_word(self.vgprs[lane][index], bits16, hi) - - def get_sgpr16(self, index: int, hi: bool = False) -> int: - return unpack_half_word(self.sgprs[index], hi) - - def set_sgpr16(self, index: int, bits16: int, hi: bool = False) -> None: - self.sgprs[index] = pack_half_word(self.sgprs[index], bits16, hi) - - -class SIMDInterpreter: - """SIMD instruction interpreter handling multi-lane divergence and EXEC masking.""" - - def resolve_lane_operand(self, op: VOP3Operand16, state: SIMDState, lane: int) -> int: - if isinstance(op.source, Reg): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr16(lane, op.source.index, op.source.hi) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr16(op.source.index, op.source.hi) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal16): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VSubF16Instruction, state: SIMDState) -> List[Optional[int]]: - results: List[Optional[int]] = [None] * state.num_lanes - # Atomic read phase across all lanes - s0_vals = [ - self.resolve_lane_operand(instr.src0, state, lane) - for lane in range(state.num_lanes) - ] - s1_vals = [ - self.resolve_lane_operand(instr.src1, state, lane) - for lane in range(state.num_lanes) - ] - - # Execution phase - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - res = oracle_v_sub_f16( - src0_bits=s0_vals[lane], - src1_bits=s1_vals[lane], - abs0=instr.src0.abs_mod, - neg0=instr.src0.neg_mod, - abs1=instr.src1.abs_mod, - neg1=instr.src1.neg_mod, - clamp=instr.clamp, - ) - state.set_vgpr16(lane, instr.dst.index, res, instr.dst.hi) - results[lane] = res - - return results - - def step_packed(self, dst_idx: int, src0_idx: int, src1_idx: int, state: SIMDState, clamp: bool = False) -> None: - """Model packed half-precision execution (v_pk_sub_f16) across lanes.""" - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - w0 = state.vgprs[lane][src0_idx] - w1 = state.vgprs[lane][src1_idx] - lo0 = unpack_half_word(w0, hi=False) - hi0 = unpack_half_word(w0, hi=True) - lo1 = unpack_half_word(w1, hi=False) - hi1 = unpack_half_word(w1, hi=True) - res_lo = oracle_v_sub_f16(lo0, lo1, clamp=clamp) - res_hi = oracle_v_sub_f16(hi0, hi1, clamp=clamp) - state.vgprs[lane][dst_idx] = (res_hi << 16) | res_lo - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD execution, lane divergence, and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.interp = SIMDInterpreter() - - def test_wave32_full_exec(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_vgpr16(lane, 0, f16_to_bits(float(lane) + 10.0), hi=False) - state.set_vgpr16(lane, 2, f16_to_bits(10.0), hi=False) - instr = VSubF16Instruction( - dst=Reg(4, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - self.assertIsNotNone(results[lane]) - expected = float(lane) - self.assertEqual(bits_to_f16(state.get_vgpr16(lane, 4, hi=False)), expected) - - def test_wave32_divergent_masking(self) -> None: - # Alternating mask: even lanes active (0x55555555) - sentinel = 0xAA55 - state = SIMDState(num_lanes=32, exec_mask=0x5555_5555) - for lane in range(32): - state.set_vgpr16(lane, 0, f16_to_bits(float(lane) + 5.0), hi=False) - state.set_vgpr16(lane, 2, f16_to_bits(5.0), hi=False) - state.set_vgpr16(lane, 4, sentinel, hi=False) - - instr = VSubF16Instruction( - dst=Reg(4, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - if lane % 2 == 0: - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f16(state.get_vgpr16(lane, 4, hi=False)), float(lane)) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr16(lane, 4, hi=False), sentinel) - - def test_wave64_full_exec(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=0xFFFF_FFFF_FFFF_FFFF) - for lane in range(64): - state.set_vgpr16(lane, 0, f16_to_bits(float(lane) * 2.0 + 1.0), hi=True) - state.set_vgpr16(lane, 2, f16_to_bits(1.0), hi=True) - instr = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=True), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=True)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=True)), - ) - self.interp.step(instr, state) - for lane in range(64): - self.assertEqual(bits_to_f16(state.get_vgpr16(lane, 0, hi=True)), float(lane) * 2.0) - - def test_wave64_half_disabled(self) -> None: - # Lower 32 lanes active, upper 32 lanes inactive - sentinel = 0xBEEF - state = SIMDState(num_lanes=64, exec_mask=0x0000_0000_FFFF_FFFF) - for lane in range(64): - state.set_vgpr16(lane, 0, f16_to_bits(30.0), hi=False) - state.set_vgpr16(lane, 2, f16_to_bits(10.0), hi=False) - state.set_vgpr16(lane, 4, sentinel, hi=False) - - instr = VSubF16Instruction( - dst=Reg(4, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - ) - results = self.interp.step(instr, state) - for lane in range(64): - if lane < 32: - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f16(state.get_vgpr16(lane, 4, hi=False)), 20.0) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr16(lane, 4, hi=False), sentinel) - - def test_wave_exec_all_zero(self) -> None: - sentinel = 0x1234 - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) - for lane in range(32): - state.set_vgpr16(lane, 0, sentinel, hi=False) - instr = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=False), - src0=VOP3Operand16(Literal16.from_float(5.0)), - src1=VOP3Operand16(Literal16.from_float(2.0)), - ) - results = self.interp.step(instr, state) - self.assertTrue(all(r is None for r in results)) - for lane in range(32): - self.assertEqual(state.get_vgpr16(lane, 0, hi=False), sentinel) - - def test_simd_sgpr_uniform_broadcast(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - state.set_sgpr16(10, f16_to_bits(10.0), hi=False) - for lane in range(32): - state.set_vgpr16(lane, 0, f16_to_bits(100.0 + float(lane)), hi=False) - - instr = VSubF16Instruction( - dst=Reg(2, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(10, RegType.SGPR, hi=False)), - ) - self.interp.step(instr, state) - for lane in range(32): - self.assertEqual(bits_to_f16(state.get_vgpr16(lane, 2, hi=False)), 90.0 + float(lane)) - - def test_simd_packed_pk_sub_f16_execution(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - w0 = (f16_to_bits(20.0 + lane) << 16) | f16_to_bits(10.0 + lane) - w1 = (f16_to_bits(5.0) << 16) | f16_to_bits(2.0) - state.vgprs[lane][0] = w0 - state.vgprs[lane][1] = w1 - - self.interp.step_packed(dst_idx=2, src0_idx=0, src1_idx=1, state=state) - for lane in range(32): - res_word = state.vgprs[lane][2] - res_lo = unpack_half_word(res_word, hi=False) - res_hi = unpack_half_word(res_word, hi=True) - self.assertEqual(bits_to_f16(res_lo), 8.0 + lane) - self.assertEqual(bits_to_f16(res_hi), 15.0 + lane) - - - -# ============================================================================== -# Register Aliasing and In-Place Operand Preservation -# ============================================================================== - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_dst_alias_src0(self) -> None: - state = ScalarMachineState() - state.set_vgpr16(0, f16_to_bits(15.5), hi=False) - state.set_vgpr16(2, f16_to_bits(4.5), hi=False) - instr = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(state.get_vgpr16(0, hi=False)), 11.0) - # src1 untouched - self.assertEqual(bits_to_f16(state.get_vgpr16(2, hi=False)), 4.5) - - def test_dst_alias_src1(self) -> None: - state = ScalarMachineState() - state.set_vgpr16(0, f16_to_bits(15.5), hi=False) - state.set_vgpr16(2, f16_to_bits(4.5), hi=False) - instr = VSubF16Instruction( - dst=Reg(2, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(state.get_vgpr16(2, hi=False)), 11.0) - # src0 untouched - self.assertEqual(bits_to_f16(state.get_vgpr16(0, hi=False)), 15.5) - - def test_dst_alias_both_srcs(self) -> None: - state = ScalarMachineState() - state.set_vgpr16(0, f16_to_bits(16.0), hi=False) - instr = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(state.get_vgpr16(0, hi=False)), 0.0) - self.assertEqual(state.get_vgpr16(0, hi=False), POS_ZERO_F16) - - def test_inplace_iterative_subtraction(self) -> None: - state = ScalarMachineState() - state.set_vgpr16(0, f16_to_bits(50.0), hi=False) - state.set_vgpr16(2, f16_to_bits(0.5), hi=False) - instr = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - ) - for _ in range(60): - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(state.get_vgpr16(0, hi=False)), 20.0) - - def test_halfword_aliasing_same_vgpr(self) -> None: - # v0 holds two halves: lo = 5.0, hi = 20.0 - state = ScalarMachineState() - state.set_vgpr16(0, f16_to_bits(5.0), hi=False) - state.set_vgpr16(0, f16_to_bits(20.0), hi=True) - - # v0.l = v0.h - v0.l = 20.0 - 5.0 = 15.0 - instr = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=True)), - src1=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - ) - res = self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f16(res), 15.0) - self.assertEqual(bits_to_f16(state.get_vgpr16(0, hi=False)), 15.0) - # High half must remain intact at 20.0 - self.assertEqual(bits_to_f16(state.get_vgpr16(0, hi=True)), 20.0) - - # Now v0.h = v0.h - v0.l = 20.0 - 15.0 = 5.0 - instr2 = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=True), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=True)), - src1=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - ) - res2 = self.scalar_interp.step(instr2, state) - self.assertEqual(bits_to_f16(res2), 5.0) - self.assertEqual(bits_to_f16(state.get_vgpr16(0, hi=True)), 5.0) - # Low half must remain intact at 15.0 - self.assertEqual(bits_to_f16(state.get_vgpr16(0, hi=False)), 15.0) - - def test_simd_multi_lane_aliasing(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_vgpr16(lane, 0, f16_to_bits(float(lane) + 10.0), hi=False) - state.set_vgpr16(lane, 2, f16_to_bits(1.0), hi=False) - - instr = VSubF16Instruction( - dst=Reg(0, RegType.VGPR, hi=False), - src0=VOP3Operand16(Reg(0, RegType.VGPR, hi=False)), - src1=VOP3Operand16(Reg(2, RegType.VGPR, hi=False)), - ) - self.simd_interp.step(instr, state) - for lane in range(32): - self.assertEqual(bits_to_f16(state.get_vgpr16(lane, 0, hi=False)), float(lane) + 9.0) - - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass(frozen=True) -class FP16StatusFlags: - """Architectural floating-point condition codes and IEEE 754 status flags for binary16.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -def evaluate_v_sub_f16_flags( - src0_bits: int, - src1_bits: int, - res_bits: int, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> FP16StatusFlags: - """Evaluate IEEE 754 architectural flags and condition codes for v_sub_f16.""" - s0 = apply_f16_modifiers(src0_bits, abs0, neg0) - s1 = apply_f16_modifiers(src1_bits, abs1, neg1) - - s0_nan = is_nan_f16(s0) - s1_nan = is_nan_f16(s1) - s0_snan = is_snan_f16(s0) - s1_snan = is_snan_f16(s1) - s0_inf = is_inf_f16(s0) - s1_inf = is_inf_f16(s1) - - invalid = False - if s0_snan or s1_snan: - invalid = True - elif s0_inf and s1_inf and ((s0 & SIGN_MASK_F16) == (s1 & SIGN_MASK_F16)): - invalid = True - - nan_flag = is_nan_f16(res_bits) - inf_flag = is_inf_f16(res_bits) - zero_flag = is_zero_f16(res_bits) - neg_flag = bool(res_bits & SIGN_MASK_F16) - denorm_flag = is_subnormal_f16(res_bits) - - overflow = False - if not (s0_nan or s1_nan or s0_inf or s1_inf) and inf_flag: - overflow = True - - underflow = False - if denorm_flag: - underflow = True - - inexact = False - if overflow: - inexact = True - elif not (s0_nan or s1_nan or s0_inf or s1_inf or nan_flag or inf_flag): - f0 = bits_to_f16(s0) - f1 = bits_to_f16(s1) - res_f = bits_to_f16(res_bits) - if not clamp: - if Fraction(f0) - Fraction(f1) != Fraction(res_f): - inexact = True - else: - clamped_math = min(1.0, max(0.0, float(Fraction(f0) - Fraction(f1)))) - if Fraction(clamped_math) != Fraction(res_f): - inexact = True - - return FP16StatusFlags( - invalid=invalid, - overflow=overflow, - underflow=underflow, - inexact=inexact, - zero=zero_flag, - negative=neg_flag, - denormal=denorm_flag, - infinite=inf_flag, - nan=nan_flag, - ) - - -def compute_f16_mantissa_borrow(s0_bits: int, s1_bits: int) -> Tuple[int, int]: - """Demonstrate IEEE 754 11-bit mantissa borrow generation during subtraction.""" - _, exp0, frac0 = split_f16_bits(s0_bits) - _, exp1, frac1 = split_f16_bits(s1_bits) - m0 = (1 << 10) | frac0 if exp0 != 0 else frac0 - m1 = (1 << 10) | frac1 if exp1 != 0 else frac1 - if exp0 > exp1: - m1 >>= (exp0 - exp1) - elif exp1 > exp0: - m0 >>= (exp1 - exp0) - borrow_out = 1 if m0 < m1 else 0 - diff = m0 - m1 - return diff, borrow_out - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for status flags, condition codes, and borrow generation.""" - - def test_exact_finite_flags(self) -> None: - s0 = f16_to_bits(3.0) - s1 = f16_to_bits(1.0) - res = oracle_v_sub_f16(s0, s1) - flags = evaluate_v_sub_f16_flags(s0, s1, res) - self.assertFalse(flags.invalid) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - self.assertFalse(flags.inexact) - self.assertFalse(flags.zero) - self.assertFalse(flags.negative) - self.assertFalse(flags.denormal) - self.assertFalse(flags.infinite) - self.assertFalse(flags.nan) - - def test_inexact_flag(self) -> None: - s0 = f16_to_bits(1.0) - # Small value that causes inexact round-to-nearest - s1 = f16_to_bits(0.00006) - res = oracle_v_sub_f16(s0, s1) - flags = evaluate_v_sub_f16_flags(s0, s1, res) - self.assertTrue(flags.inexact) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - - def test_overflow_flag(self) -> None: - # MAX_FINITE - (-MAX_FINITE) = 65504 - (-65504) overflows to +inf - s0 = MAX_FINITE_F16 - s1 = MAX_FINITE_F16 | SIGN_MASK_F16 - res = oracle_v_sub_f16(s0, s1) - self.assertEqual(res, POS_INF_F16) - flags = evaluate_v_sub_f16_flags(s0, s1, res) - self.assertTrue(flags.overflow) - self.assertTrue(flags.infinite) - self.assertTrue(flags.inexact) - self.assertFalse(flags.invalid) - - def test_underflow_and_denorm_flags(self) -> None: - # Subnormal subtraction - subnorm = MIN_SUBNORMAL_F16 * 2 - res = oracle_v_sub_f16(subnorm, MIN_SUBNORMAL_F16) - self.assertEqual(res, MIN_SUBNORMAL_F16) - flags = evaluate_v_sub_f16_flags(subnorm, MIN_SUBNORMAL_F16, res) - self.assertTrue(flags.denormal) - self.assertTrue(flags.underflow) - self.assertFalse(flags.overflow) - - def test_invalid_operation_flag(self) -> None: - # (+inf) - (+inf) is invalid - res = oracle_v_sub_f16(POS_INF_F16, POS_INF_F16) - flags = evaluate_v_sub_f16_flags(POS_INF_F16, POS_INF_F16, res) - self.assertTrue(flags.invalid) - self.assertTrue(flags.nan) - - # signaling NaN operand triggers invalid operation - snan = 0x7C01 - res2 = oracle_v_sub_f16(snan, f16_to_bits(1.0)) - flags2 = evaluate_v_sub_f16_flags(snan, f16_to_bits(1.0), res2) - self.assertTrue(flags2.invalid) - self.assertTrue(flags2.nan) - - def test_zero_and_negative_flags(self) -> None: - # (+0) - (+0) - res_pz = oracle_v_sub_f16(POS_ZERO_F16, POS_ZERO_F16) - flags_pz = evaluate_v_sub_f16_flags(POS_ZERO_F16, POS_ZERO_F16, res_pz) - self.assertTrue(flags_pz.zero) - self.assertFalse(flags_pz.negative) - - # (-0) - (+0) = -0 - res_nz = oracle_v_sub_f16(NEG_ZERO_F16, POS_ZERO_F16) - flags_nz = evaluate_v_sub_f16_flags(NEG_ZERO_F16, POS_ZERO_F16, res_nz) - self.assertTrue(flags_nz.zero) - self.assertTrue(flags_nz.negative) - - # 5.0 - 15.0 = -10.0 - s0 = f16_to_bits(5.0) - s1 = f16_to_bits(15.0) - res_neg = oracle_v_sub_f16(s0, s1) - flags_neg = evaluate_v_sub_f16_flags(s0, s1, res_neg) - self.assertFalse(flags_neg.zero) - self.assertTrue(flags_neg.negative) - - def test_mantissa_borrow_generation(self) -> None: - # 1.0 - 1.5: m0 = 1024, m1 = 1536 -> borrow = 1 - _, borrow1 = compute_f16_mantissa_borrow(f16_to_bits(1.0), f16_to_bits(1.5)) - self.assertEqual(borrow1, 1) - - # 1.5 - 1.0: m0 = 1536, m1 = 1024 -> borrow = 0 - _, borrow0 = compute_f16_mantissa_borrow(f16_to_bits(1.5), f16_to_bits(1.0)) - self.assertEqual(borrow0, 0) - - - -# ============================================================================== -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# ============================================================================== - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Deep verification of IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_subtraction_without_borrow(self) -> None: - sub1 = MIN_SUBNORMAL_F16 * 3 - sub2 = MIN_SUBNORMAL_F16 - res = oracle_v_sub_f16(sub1, sub2) - self.assertEqual(res, MIN_SUBNORMAL_F16 * 2) - self.assertTrue(is_subnormal_f16(res)) - - def test_normal_to_subnormal_transition(self) -> None: - # Min normal (0x0400 = 2^-14) minus smallest subnormal (0x0001 = 2^-24) - # Yields largest subnormal (0x03FF) - res = oracle_v_sub_f16(MIN_NORMAL_F16, MIN_SUBNORMAL_F16) - self.assertEqual(res, MAX_SUBNORMAL_F16) - self.assertTrue(is_subnormal_f16(res)) - self.assertEqual(split_f16_bits(res)[1], 0) # exponent = 0 - self.assertEqual(split_f16_bits(res)[2], 0x03FF) # fraction = max subnormal - - def test_subnormal_cancellation(self) -> None: - sub = 0x0000_0123 - res = oracle_v_sub_f16(sub, sub) - self.assertEqual(res, POS_ZERO_F16) - - def test_nan_signaling_to_quiet_conversion(self) -> None: - snan = 0x7C05 # fraction non-zero, quiet bit 9 is 0 - self.assertTrue(is_snan_f16(snan)) - res = oracle_v_sub_f16(snan, f16_to_bits(1.0)) - self.assertTrue(is_qnan_f16(res)) - self.assertEqual(res, snan | QNAN_BIT_F16) - - def test_nan_payload_preservation(self) -> None: - payload = 0x0255 - qnan = EXP_MASK_F16 | payload - res = oracle_v_sub_f16(qnan, f16_to_bits(10.0)) - self.assertEqual(res, qnan) - - def test_nan_with_modifiers(self) -> None: - qnan = 0x7E01 - # abs should clear sign bit - res_abs = oracle_v_sub_f16(qnan | SIGN_MASK_F16, f16_to_bits(0.0), abs0=True) - self.assertEqual(res_abs & SIGN_MASK_F16, 0) - self.assertTrue(is_qnan_f16(res_abs)) - - # neg should toggle sign bit - res_neg = oracle_v_sub_f16(qnan, f16_to_bits(0.0), neg0=True) - self.assertEqual(res_neg & SIGN_MASK_F16, SIGN_MASK_F16) - - def test_nan_with_clamp(self) -> None: - qnan = CANONICAL_QNAN_F16 - res = oracle_v_sub_f16(qnan, f16_to_bits(1.0), clamp=True) - self.assertEqual(res, POS_ZERO_F16) - - def test_infinity_subtraction_boundaries(self) -> None: - self.assertEqual(oracle_v_sub_f16(POS_INF_F16, f16_to_bits(100.0)), POS_INF_F16) - self.assertEqual(oracle_v_sub_f16(NEG_INF_F16, f16_to_bits(100.0)), NEG_INF_F16) - self.assertEqual(oracle_v_sub_f16(f16_to_bits(100.0), POS_INF_F16), NEG_INF_F16) - self.assertEqual(oracle_v_sub_f16(f16_to_bits(100.0), NEG_INF_F16), POS_INF_F16) - - self.assertEqual(oracle_v_sub_f16(POS_INF_F16, POS_INF_F16), CANONICAL_QNAN_F16) - self.assertEqual(oracle_v_sub_f16(NEG_INF_F16, NEG_INF_F16), CANONICAL_QNAN_F16) - self.assertEqual(oracle_v_sub_f16(POS_INF_F16, NEG_INF_F16), POS_INF_F16) - self.assertEqual(oracle_v_sub_f16(NEG_INF_F16, POS_INF_F16), NEG_INF_F16) - - # Infinity with clamp - self.assertEqual(oracle_v_sub_f16(POS_INF_F16, f16_to_bits(0.0), clamp=True), ONE_F16) - self.assertEqual(oracle_v_sub_f16(NEG_INF_F16, f16_to_bits(0.0), clamp=True), POS_ZERO_F16) - - def test_round_to_nearest_even_ties(self) -> None: - # In IEEE 754 half precision (10 bits fraction): - # 1.0 has bits 0x3C00 (fraction 0, LSB even) - # 1.0 + 2^-10 has bits 0x3C01 (fraction 1, LSB odd) - # 2^-11 is halfway between representable numbers. - half_ulp = 2.0 ** -11 - one = 1.0 - one_plus_ulp = bits_to_f16(0x3C01) - - # Case 1: (1.0 + 2^-10) - 2^-11: tie rounds to even (1.0) - res1 = oracle_v_sub_f16(f16_to_bits(one_plus_ulp), f16_to_bits(half_ulp)) - self.assertEqual(res1, f16_to_bits(one)) - - def test_finite_overflow_to_infinity(self) -> None: - # 65504.0 - (-65504.0) overflows to +inf - self.assertEqual(oracle_v_sub_f16(MAX_FINITE_F16, MAX_FINITE_F16 | SIGN_MASK_F16), POS_INF_F16) - # -65504.0 - 65504.0 overflows to -inf - self.assertEqual(oracle_v_sub_f16(MAX_FINITE_F16 | SIGN_MASK_F16, MAX_FINITE_F16), NEG_INF_F16) - - def test_extreme_finite_boundaries(self) -> None: - self.assertEqual(oracle_v_sub_f16(MAX_FINITE_F16, MAX_FINITE_F16), POS_ZERO_F16) - self.assertEqual(oracle_v_sub_f16(MAX_FINITE_F16 | SIGN_MASK_F16, MAX_FINITE_F16 | SIGN_MASK_F16), POS_ZERO_F16) - - - -# ============================================================================== -# Negative Controls, Syntax Rejection, and Mutation Detection -# ============================================================================== - -def parse_vop_sub_f16(asm: str) -> VSubF16Instruction: - """Parse a v_sub_f16 instruction assembly string with validation.""" - tokens = asm.replace(",", " ").split() - if not tokens: - raise ValueError("Empty assembly string") - opcode = tokens[0] - if opcode not in ("v_sub_f16", "v_sub_f16_e32", "v_sub_f16_e64"): - raise ValueError(f"Unrecognized opcode: {opcode}") - - is_vop3 = opcode == "v_sub_f16_e64" - operands = tokens[1:] - clamp = "clamp" in operands - if clamp: - operands.remove("clamp") - - if len(operands) != 3: - raise ValueError(f"Expected 3 operands (dst, src0, src1), got {len(operands)}") - - dst_str, src0_str, src1_str = operands - - def parse_reg(r_str: str) -> Reg: - r = r_str.strip() - hi = False - if "." in r: - parts = r.split(".") - r = parts[0] - hi = parts[1] == "h" - prefix = r[0] - if prefix not in ("v", "s"): - raise ValueError(f"Invalid register prefix: {prefix}") - reg_type = RegType.VGPR if prefix == "v" else RegType.SGPR - idx = int(r[1:]) - return Reg(idx, reg_type, hi) - - def parse_op(op_str: str) -> VOP3Operand16: - op_str = op_str.strip() - abs_mod = False - neg_mod = False - if op_str.startswith("-"): - neg_mod = True - op_str = op_str[1:] - if op_str.startswith("|") and op_str.endswith("|"): - abs_mod = True - op_str = op_str[1:-1] - try: - val = float(op_str) - return VOP3Operand16(Literal16.from_float(val), abs_mod=abs_mod, neg_mod=neg_mod) - except ValueError: - return VOP3Operand16(parse_reg(op_str), abs_mod=abs_mod, neg_mod=neg_mod) - - dst_reg = parse_reg(dst_str) - src0_op = parse_op(src0_str) - src1_op = parse_op(src1_str) - return VSubF16Instruction(dst=dst_reg, src0=src0_op, src1=src1_op, clamp=clamp, is_vop3=is_vop3) - - -def mutant_swap_operands(src0: int, src1: int) -> int: - """Mutant A: computes reverse subtraction src1 - src0 instead of src0 - src1.""" - return oracle_v_sub_f16(src1, src0) - - -def mutant_ignore_abs_modifier(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Mutant B: ignores abs modifier.""" - res = bits & 0xFFFF - if neg_mod: - res ^= SIGN_MASK_F16 - return res - - -def mutant_ignore_neg_modifier(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Mutant C: ignores neg modifier.""" - res = bits & 0xFFFF - if abs_mod: - res &= ~SIGN_MASK_F16 - return res - - -def mutant_flush_subnormal(src0: int, src1: int) -> int: - """Mutant D: flushes subnormals to zero prematurely.""" - res = oracle_v_sub_f16(src0, src1) - if is_subnormal_f16(res): - return POS_ZERO_F16 - return res - - -def mutant_skip_snan_quietening(src0: int, src1: int) -> int: - """Mutant E: fails to quiet signaling NaN.""" - if is_snan_f16(src0): - return src0 - if is_snan_f16(src1): - return src1 - return oracle_v_sub_f16(src0, src1) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Negative controls, syntax rejection, and mutation detection for v_sub_f16.""" - - def test_syntax_rejection_invalid_opcode(self) -> None: - with self.assertRaises(ValueError): - parse_vop_sub_f16("v_add_f16 v0, v1, v2") - - def test_syntax_rejection_insufficient_operands(self) -> None: - with self.assertRaises(ValueError): - parse_vop_sub_f16("v_sub_f16 v0, v1") - - def test_syntax_rejection_out_of_range_registers(self) -> None: - with self.assertRaises(ValueError): - parse_vop_sub_f16("v_sub_f16 v256, v1, v2") - with self.assertRaises(ValueError): - parse_vop_sub_f16("v_sub_f16 v0, s256, v2") - - def test_syntax_rejection_sgpr_as_destination(self) -> None: - with self.assertRaises(TypeError): - parse_vop_sub_f16("v_sub_f16 s0, v1, v2") - - def test_single_bit_flip_detection(self) -> None: - s0 = f16_to_bits(15.0) - s1 = f16_to_bits(5.0) - correct = oracle_v_sub_f16(s0, s1) - self.assertEqual(bits_to_f16(correct), 10.0) - - # Corrupt single fraction bit - corrupted_frac = correct ^ 0x1 - self.assertNotEqual(correct, corrupted_frac) - - # Corrupt single exponent bit - corrupted_exp = correct ^ (1 << 10) - self.assertNotEqual(correct, corrupted_exp) - - # Corrupt sign bit - corrupted_sign = correct ^ SIGN_MASK_F16 - self.assertNotEqual(correct, corrupted_sign) - - def test_mutation_swap_operands(self) -> None: - s0 = f16_to_bits(20.0) - s1 = f16_to_bits(5.0) - expected = oracle_v_sub_f16(s0, s1) - mutant = mutant_swap_operands(s0, s1) - self.assertEqual(bits_to_f16(expected), 15.0) - self.assertEqual(bits_to_f16(mutant), -15.0) - self.assertNotEqual(expected, mutant) - - def test_mutation_ignore_abs(self) -> None: - val = f16_to_bits(-10.0) - correct = apply_f16_modifiers(val, abs_mod=True, neg_mod=False) - mutant = mutant_ignore_abs_modifier(val, abs_mod=True, neg_mod=False) - self.assertEqual(correct, f16_to_bits(10.0)) - self.assertNotEqual(correct, mutant) - - def test_mutation_ignore_neg(self) -> None: - val = f16_to_bits(10.0) - correct = apply_f16_modifiers(val, abs_mod=False, neg_mod=True) - mutant = mutant_ignore_neg_modifier(val, abs_mod=False, neg_mod=True) - self.assertEqual(correct, f16_to_bits(-10.0)) - self.assertNotEqual(correct, mutant) - - def test_mutation_flush_subnormal(self) -> None: - sub = MIN_SUBNORMAL_F16 * 2 - correct = oracle_v_sub_f16(sub, MIN_SUBNORMAL_F16) - mutant = mutant_flush_subnormal(sub, MIN_SUBNORMAL_F16) - self.assertTrue(is_subnormal_f16(correct)) - self.assertEqual(mutant, POS_ZERO_F16) - self.assertNotEqual(correct, mutant) - - def test_mutation_skip_snan_quietening(self) -> None: - snan = 0x7C05 - correct = oracle_v_sub_f16(snan, f16_to_bits(1.0)) - mutant = mutant_skip_snan_quietening(snan, f16_to_bits(1.0)) - self.assertTrue(is_qnan_f16(correct)) - self.assertTrue(is_snan_f16(mutant)) - self.assertNotEqual(correct, mutant) - - def test_mutation_exec_mask_leak(self) -> None: - sentinel = 0xCAFE - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) - for lane in range(32): - state.set_vgpr16(lane, 4, sentinel, hi=False) - - class MutantSIMDInterpreter(SIMDInterpreter): - def step(self, instr: VSubF16Instruction, state: SIMDState) -> List[Optional[int]]: - results = [] - for lane in range(state.num_lanes): - # Bug: ignores exec_mask and corrupts lane - res = oracle_v_sub_f16(f16_to_bits(10.0), f16_to_bits(5.0)) - state.set_vgpr16(lane, instr.dst.index, res, instr.dst.hi) - results.append(res) - return results - - mutant = MutantSIMDInterpreter() - instr = VSubF16Instruction( - dst=Reg(4, RegType.VGPR, hi=False), - src0=VOP3Operand16(Literal16.from_float(10.0)), - src1=VOP3Operand16(Literal16.from_float(5.0)), - ) - mutant.step(instr, state) - corrupted = [l for l in range(32) if state.get_vgpr16(l, 4, hi=False) != sentinel] - self.assertEqual(len(corrupted), 32) + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + w = w if w > 0xFFFF else (hi << 16) | w + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_sub_f16", prog))[0] + + +# (src0, src1, D), written by hand. +CASES = [ + (THREE, ONE, TWO), # 3 - 1 = 2 + (ONE, TWO, 0xBC00), # 1 - 2 = -1 + (HALF, QUARTER, QUARTER), # 0.5 - 0.25 + (0x3E00, 0x3E00, 0x0000), # x - x = +0 + (0x8000, 0x0000, 0x8000), # -0 - +0 = -0 + (0x0000, 0x0000, 0x0000), # +0 - +0 = +0 + (0x0000, 0x8000, 0x0000), # +0 - -0 = +0 + (0x8000, 0x8000, 0x0000), # -0 - -0 = -0 + +0 = +0 + (MAXH, 0xFBFF, INF), # 65504 - -65504 overflows + (MAXH, 0xCC00, INF), # 65504 - -16 = 65520: tie, even is the overflow + (MIN_NORMAL, MIN_SUB, MAX_SUB), # 2^-14 - 2^-24 = the largest subnormal + (MIN_SUB, 0x8001, 0x0002), # 2^-24 - -2^-24 + (ONE, 0x9000, ONE), # 1 - -2^-11: half an ulp, ties to even, stays 1 + (ONE, 0x9001, 0x3C01), # a little over half an ulp rounds up + (0x3C01, ONE, 0x1400), # (1 + 2^-10) - 1 = 2^-10, exact + (INF, INF, QNAN), # inf - inf = NaN + (INF, NINF, INF), + (ONE, QNAN, QNAN), +] + +SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, + MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0x1000, 0x6800, 0x6801, 0x4C00] + + +class SubF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for a, b, want in CASES: + self.assertTrue(same_f16(ref_sub(a, b), want), (hex(a), hex(b), hex(ref_sub(a, b)))) + + def test_e32_writes_low_half_and_keeps_high_half(self): + for a, b, want in CASES: + with self.subTest(a=hex(a), b=hex(b)): + got = run("v_sub_f16 v0, v1, v2", {"v1": a, "v2": b}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_vop3_sgpr_and_literal_sources(self): + for a, b, want in CASES[:14]: + forms = [ + ("e64 vgpr", "v_sub_f16_e64 v0, v1, v2", {"v1": a, "v2": b}), + ("e64 sgpr", "v_sub_f16_e64 v0, s1, s2", {"s1": a, "s2": b}), + ("e32 sgpr src0", "v_sub_f16 v0, s1, v2", {"s1": a, "v2": b}), + ("e32 literal src0", f"v_sub_f16 v0, {a:#x}, v2", {"v2": b}), + ("e64 literal src1", f"v_sub_f16_e64 v0, v1, {b:#x}", {"v1": a}), + ] + for form, line, seeds in forms: + with self.subTest(a=hex(a), b=hex(b), form=form): + got = run(line, seeds) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_inline_constants(self): + # (inline constant as src0, its binary16 value, v1 low half, D), by hand + for text, c, b, want in (("2.0", TWO, HALF, 0x3E00), ("-1.0", 0xBC00, HALF, 0xBE00), ("0.5", HALF, QUARTER, QUARTER), + ("4.0", 0x4400, 0xB800, 0x4480), ("1.0", ONE, ONE, 0x0000)): + with self.subTest(const=text): + self.assertEqual(run(f"v_sub_f16 v0, {text}, v1", {"v1": b}) & 0xFFFF, want) + self.assertEqual(ref_sub(c, b), want) + + def test_op_sel_selects_source_and_destination_halves(self): + # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25); D by hand for each (src0 half, src1 half). + s0, s1 = (THREE << 16) | ONE, (0xB400 << 16) | HALF + expect_lo = {(0, 0): 0x3800, (1, 0): 0x4100, (0, 1): 0x3D00, (1, 1): 0x4280} # 0.5, 2.5, 1.25, 3.25 + for h0 in (0, 1): + for h1 in (0, 1): + for dh in (0, 1): + want = expect_lo[(h0, h1)] + expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) + with self.subTest(op_sel=(h0, h1, dh)): + got = run(f"v_sub_f16_e64 v0, v1, v2 op_sel:[{h0},{h1},{dh}]", {"v1": s0, "v2": s1}) + self.assertEqual(got, expect) + + def test_neg_and_abs_source_modifiers(self): + # v1 = 1.0, v2 = -0.5; (operand text, D) by hand + for ops, want in (("v1, v2", 0x3E00), ("-v1, v2", 0xB800), ("v1, -v2", HALF), ("|v1|, |v2|", HALF), + ("-|v1|, v2", 0xB800), ("v1, -|v2|", 0x3E00)): + with self.subTest(ops=ops): + got = run(f"v_sub_f16_e64 v0, {ops}", {"v1": ONE, "v2": 0xB800}) + self.assertEqual(got & 0xFFFF, want) + + def test_output_modifiers_and_clamp(self): + # unmodified result: 2.5 - 0.5 = 2.0; mul/div scale it, clamp limits it to [0, 1] (negatives and NaN become +0) + for suffix, want in ((" mul:2", 0x4400), (" mul:4", 0x4800), (" div:2", ONE), (" clamp", ONE)): + with self.subTest(mod=suffix): + got = run("v_sub_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4100, "v2": HALF}) + self.assertEqual(got & 0xFFFF, want) + for (a, b), suffix, want in (((HALF, QUARTER), " clamp", QUARTER), ((HALF, ONE), " clamp", 0x0000), + ((ONE, 0xB800), " div:2 clamp", 0x3A00), ((ONE, QUARTER), " mul:2 clamp", ONE)): + with self.subTest(a=hex(a), b=hex(b), mod=suffix): + self.assertEqual(run("v_sub_f16_e64 v0, v1, v2" + suffix, {"v1": a, "v2": b}) & 0xFFFF, want) + for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): + got = run("v_sub_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4900, "v2": 0xC100}) # 10 and -2.5 + self.assertEqual(got & 0xFFFF, scale(ref_sub(0x4900, 0xC100), f)) + + def test_random_operands(self): + rng = random.Random(0x50B16) + pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] + for _ in range(120): + a = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) + b = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) + with self.subTest(a=hex(a), b=hex(b)): + got = run("v_sub_f16 v0, v1, v2", {"v1": a, "v2": b}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, ref_sub(a, b)), (hex(got), hex(ref_sub(a, b)))) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_subrev_f16.py b/tests/semantic/test_valu_subrev_f16.py index bedef5021..150fc6935 100644 --- a/tests/semantic/test_valu_subrev_f16.py +++ b/tests/semantic/test_valu_subrev_f16.py @@ -1,1739 +1,151 @@ -from __future__ import annotations +"""v_subrev_f16 (RDNA2 VOP2 / VOP3): D.f16 = S1.f16 - S0.f16 (v_sub_f16 with its operands swapped), binary16. -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_subrev_f16. - -Instruction: - v_subrev_f16 dst, src0, src1 (VOP2 / VOP3) - D.f16 = S1.f16 - S0.f16 - -Architecture: - - RDNA2 Vector ALU (GFX10) half-precision floating-point reverse subtraction. - - Computes the difference S1 - S0 conforming to IEEE 754-2008 binary16. - - In VOP2 format: - * S0: 16-bit float operand (VGPR, SGPR, or 16-bit inline constant / literal). - * S1: 16-bit float operand (VGPR). - * D: 16-bit float destination VGPR (writes low 16 bits, preserves high 16 bits). - - In VOP3 format: - * Input modifiers: abs (|S|), neg (-S) on both src0 and src1. - * Output modifiers: clamp (clamps result to [0.0, 1.0]), omod (mul:2, mul:4, div:2). - * op_sel: selects low or high 16-bit half for src0, src1, and dst independently. +Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected +word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in +tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the _e32 form (the high half of the +destination is kept), the _e64 form with op_sel, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. +Standard library only: no GPU, no LLVM, no game data. """ - -from dataclasses import dataclass, field -from enum import Enum, auto -from fractions import Fraction -import math -import re -import struct -from typing import Optional, Union +import os +import random +import sys import unittest -MASK16: int = 0xFFFF -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) +import support # noqa: E402 +from f16_ref import OLD, ref_sub, same_f16, scale # noqa: E402 -SIGN_MASK_F16: int = 0x8000 -EXP_MASK_F16: int = 0x7C00 -MANT_MASK_F16: int = 0x03FF -QNAN_BIT_F16: int = 0x0200 -BIAS_F16: int = 15 - -POS_ZERO_F16: int = 0x0000 -NEG_ZERO_F16: int = 0x8000 -POS_INF_F16: int = 0x7C00 -NEG_INF_F16: int = 0xFC00 -CANONICAL_QNAN_F16: int = 0x7E00 -SNAN_DEFAULT_F16: int = 0x7C01 - -ONE_F16: int = 0x3C00 # 1.0 -TWO_F16: int = 0x4000 # 2.0 -THREE_F16: int = 0x4200 # 3.0 -FOUR_F16: int = 0x4400 # 4.0 -HALF_F16: int = 0x3800 # 0.5 -QUARTER_F16: int = 0x3400 # 0.25 -NEG_ONE_F16: int = 0xBC00 # -1.0 -NEG_TWO_F16: int = 0xC000 # -2.0 -NEG_HALF_F16: int = 0xB800 # -0.5 - -MAX_FINITE_F16: int = 0x7BFF # 65504.0 -NEG_MAX_FINITE_F16: int = 0xFBFF # -65504.0 -MIN_NORMAL_F16: int = 0x0400 # 2^-14 (~6.1035e-5) -MAX_SUBNORMAL_F16: int = 0x03FF # ~6.0975e-5 -MIN_SUBNORMAL_F16: int = 0x0001 # 2^-24 (~5.9605e-8) +ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 +MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 +MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF -def u16(val: int) -> int: - """Normalize integer to unsigned 16-bit halfword.""" - return val & MASK16 +def ref_subrev(a, b): + return ref_sub(b, a) -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit dword.""" - return val & MASK32 +def run(line, seeds, old=OLD, hi=0x5A5A): + """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. - -def s16(val: int) -> int: - """Interpret a 16-bit unsigned value as signed two's complement integer.""" - val &= MASK16 - return val - (1 << 16) if (val & 0x8000) else val - - -def bits_to_f16(bits: int) -> float: - """Convert unsigned 16-bit integer bits to Python float (IEEE 754 binary16).""" - return struct.unpack(" int: - """Convert Python float to unsigned 16-bit integer bits (IEEE 754 binary16 RNE).""" - if math.isnan(val): - return CANONICAL_QNAN_F16 - try: - return struct.unpack(" tuple[int, int, int]: - """Unpack 16-bit float into (sign, exponent, fraction) components.""" - bits &= MASK16 - sign = (bits & SIGN_MASK_F16) >> 15 - exponent = (bits & EXP_MASK_F16) >> 10 - fraction = bits & MANT_MASK_F16 - return sign, exponent, fraction - - -def is_nan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 half-precision NaN.""" - return ((bits & EXP_MASK_F16) == EXP_MASK_F16) and ((bits & MANT_MASK_F16) != 0) - - -def is_qnan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 quiet NaN.""" - return is_nan_f16(bits) and bool(bits & QNAN_BIT_F16) - - -def is_snan_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 signaling NaN.""" - return is_nan_f16(bits) and not bool(bits & QNAN_BIT_F16) - - -def is_inf_f16(bits: int) -> bool: - """Return True if bits represent IEEE 754 positive or negative infinity.""" - return (bits & 0x7FFF) == 0x7C00 - - -def is_zero_f16(bits: int) -> bool: - """Return True if bits represent positive or negative zero (+0.0 or -0.0).""" - return (bits & ~SIGN_MASK_F16) == 0 - - -def is_subnormal_f16(bits: int) -> bool: - """Return True if bits represent an IEEE 754 half-precision subnormal (denormal).""" - return ((bits & EXP_MASK_F16) == 0) and ((bits & MANT_MASK_F16) != 0) - - -def is_normal_f16(bits: int) -> bool: - """Return True if bits represent a normalized finite half-precision float.""" - exp = (bits & EXP_MASK_F16) >> 10 - return 1 <= exp <= 30 - - -def pack_half(lo: int, hi: int) -> int: - """Pack two 16-bit halfwords into a 32-bit register word.""" - return ((hi & MASK16) << 16) | (lo & MASK16) - - -def unpack_half(word: int) -> tuple[int, int]: - """Unpack a 32-bit register word into (lo, hi) 16-bit halfwords.""" - return word & MASK16, (word >> 16) & MASK16 - - -def extract_half(word: int, hi_sel: bool) -> int: - """Extract 16-bit halfword from 32-bit word using high-select boolean flag.""" - return (word >> 16) & MASK16 if hi_sel else word & MASK16 - - -def insert_half(old_word: int, val16: int, dst_hi: bool) -> int: - """Insert 16-bit halfword into low or high half of 32-bit word, preserving other half.""" - val16 &= MASK16 - old_word &= MASK32 - if dst_hi: - return (val16 << 16) | (old_word & 0x0000FFFF) - else: - return (old_word & 0xFFFF0000) | val16 - - -def apply_f16_input_mods(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Apply VOP3 input modifiers: abs clears sign bit; neg toggles sign bit.""" - res = bits & MASK16 - if abs_mod: - res &= ~SIGN_MASK_F16 - if neg_mod: - res ^= SIGN_MASK_F16 - return res - - -def apply_f16_output_mods(bits: int, clamp: bool, omod: str = "none") -> int: - """Apply VOP3 output modifiers: omod scaling and clamp to [0.0, 1.0].""" - bits &= MASK16 - if is_nan_f16(bits): - # Clamping NaN in RDNA2 produces +0.0 - return POS_ZERO_F16 if clamp else bits - - # Apply omod scaling if not NaN and not infinity - if not is_inf_f16(bits) and omod != "none": - val = bits_to_f16(bits) - if omod == "mul:2": - val *= 2.0 - elif omod == "mul:4": - val *= 4.0 - elif omod == "div:2": - val *= 0.5 - bits = f16_to_bits(val) - - if clamp: - if is_inf_f16(bits): - return ONE_F16 if bits == POS_INF_F16 else POS_ZERO_F16 - val = bits_to_f16(bits) - if val < 0.0 or is_zero_f16(bits): - return POS_ZERO_F16 - elif val > 1.0: - return ONE_F16 - return bits - - return bits - - -def ref_subrev_f16( - src0_bits: int, - src1_bits: int, - *, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, - omod: str = "none", -) -> int: - """Reference mathematical oracle for RDNA2 v_subrev_f16 half-precision reverse subtraction. - - Operation: D = src1 - src0 (S1 - S0) - Conforms strictly to IEEE 754-2008 binary16 Round-to-Nearest-Even (RNE) - with RDNA2 special values, NaN quietening, and input/output modifiers. + `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its + upper half, so reading the wrong half of a source shows. v0 starts as `old`. """ - s0 = apply_f16_input_mods(src0_bits, abs0, neg0) - s1 = apply_f16_input_mods(src1_bits, abs1, neg1) - - # 1. NaN handling - s0_nan = is_nan_f16(s0) - s1_nan = is_nan_f16(s1) - if s0_nan or s1_nan: - if clamp: - return POS_ZERO_F16 - nan_bits = s0 if s0_nan else s1 - return nan_bits | QNAN_BIT_F16 - - # 2. Infinity handling - s0_inf = is_inf_f16(s0) - s1_inf = is_inf_f16(s1) - if s0_inf and s1_inf: - s0_sign = s0 & SIGN_MASK_F16 - s1_sign = s1 & SIGN_MASK_F16 - # (+inf) - (+inf) or (-inf) - (-inf) -> Invalid operation -> Canonical Quiet NaN - if s0_sign == s1_sign: - return POS_ZERO_F16 if clamp else CANONICAL_QNAN_F16 - # (+inf) - (-inf) = +inf; (-inf) - (+inf) = -inf - res_inf = s1 - return apply_f16_output_mods(res_inf, clamp, omod) - if s1_inf: - return apply_f16_output_mods(s1, clamp, omod) - if s0_inf: - # finite - (+inf) = -inf; finite - (-inf) = +inf - res_inf = NEG_INF_F16 if s0 == POS_INF_F16 else POS_INF_F16 - return apply_f16_output_mods(res_inf, clamp, omod) - - # 3. Finite numbers - val0 = bits_to_f16(s0) - val1 = bits_to_f16(s1) - diff = val1 - val0 - - # Signed zero preservation: - # (+0.0) - (+0.0) == +0.0 - # (-0.0) - (-0.0) == +0.0 - # (+0.0) - (-0.0) == +0.0 - # (-0.0) - (+0.0) == -0.0 - if diff == 0.0: - if val1 == 0.0 and val0 == 0.0: - if (s1 & SIGN_MASK_F16) and not (s0 & SIGN_MASK_F16): - res_zero = NEG_ZERO_F16 - else: - res_zero = POS_ZERO_F16 - else: - res_zero = POS_ZERO_F16 - return apply_f16_output_mods(res_zero, clamp, omod) - - raw_res = f16_to_bits(diff) - return apply_f16_output_mods(raw_res, clamp, omod) - - -def f16_bits_to_fraction(bits: int) -> Fraction: - """Convert a finite binary16 bit pattern to an exact rational Fraction.""" - sign, exp, mant = split_f16_bits(bits) - if exp == 0: - # Subnormal: 0.mant * 2^-14 = mant * 2^-24 - val = Fraction(mant, 1 << 24) - else: - # Normalized: 1.mant * 2^(exp - 15) = (1024 + mant) * 2^(exp - 25) - num = (1 << 10) | mant - shift = exp - 25 - if shift >= 0: - val = Fraction(num << shift, 1) - else: - val = Fraction(num, 1 << (-shift)) - return -val if sign else val - - -def ref_subrev_f16_rational( - src0_bits: int, - src1_bits: int, - *, - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> int: - """Independent exact rational arithmetic cross-check oracle for v_subrev_f16. - - Uses fractions.Fraction to compute the exact difference S1 - S0 without intermediate - floating-point inaccuracy, then applies bit-exact IEEE 754 half-precision RNE rounding. - """ - s0 = apply_f16_input_mods(src0_bits, abs0, neg0) - s1 = apply_f16_input_mods(src1_bits, abs1, neg1) - - if is_nan_f16(s0) or is_nan_f16(s1): - if clamp: - return POS_ZERO_F16 - nan_bits = s0 if is_nan_f16(s0) else s1 - return nan_bits | QNAN_BIT_F16 - - if is_inf_f16(s0) or is_inf_f16(s1): - return ref_subrev_f16(src0_bits, src1_bits, abs0=abs0, neg0=neg0, abs1=abs1, neg1=neg1, clamp=clamp) - - frac0 = f16_bits_to_fraction(s0) - frac1 = f16_bits_to_fraction(s1) - diff_frac = frac1 - frac0 - - if diff_frac == 0: - if (s1 & SIGN_MASK_F16) and not (s0 & SIGN_MASK_F16): - res_zero = NEG_ZERO_F16 - else: - res_zero = POS_ZERO_F16 - return apply_f16_output_mods(res_zero, clamp) - - sign = 1 if diff_frac < 0 else 0 - abs_diff = abs(diff_frac) - - # Check overflow beyond max finite - max_finite_val = Fraction(65504, 1) - if abs_diff >= Fraction(65520, 1): - res_inf = NEG_INF_F16 if sign else POS_INF_F16 - return apply_f16_output_mods(res_inf, clamp) - - # Normal vs subnormal bounds - min_normal_val = Fraction(1, 1 << 14) - if abs_diff < min_normal_val: - # Subnormal representation: mant = abs_diff * 2^24 rounded - scaled = abs_diff * (1 << 24) - floor_mant = scaled.numerator // scaled.denominator - rem = scaled - floor_mant - half_one = Fraction(1, 2) - if rem > half_one or (rem == half_one and (floor_mant % 2 == 1)): - floor_mant += 1 - if floor_mant >= (1 << 10): - res_bits = (sign << 15) | (1 << 10) # promoted to min normal - else: - res_bits = (sign << 15) | floor_mant - return apply_f16_output_mods(res_bits, clamp) - - # Normalized float: find exponent - val_float = float(abs_diff) - exp = int(math.floor(math.log2(val_float))) + 15 - exp = max(1, min(30, exp)) - - scaled = abs_diff * Fraction(1 << (25 - exp), 1) - num = scaled.numerator // scaled.denominator - rem = scaled - num - half_one = Fraction(1, 2) - if rem > half_one or (rem == half_one and (num % 2 == 1)): - num += 1 - - if num >= (1 << 11): - num >>= 1 - exp += 1 - - if exp >= 31: - res_inf = NEG_INF_F16 if sign else POS_INF_F16 - return apply_f16_output_mods(res_inf, clamp) - - mant = num & MANT_MASK_F16 - res_bits = (sign << 15) | (exp << 10) | mant - return apply_f16_output_mods(res_bits, clamp) - - -# ============================================================================ -# Phase 2: Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================ - -class Opcode(Enum): - V_SUBREV_F16 = "v_subrev_f16" - - -class Encoding(Enum): - VOP2 = "vop2" - VOP3 = "vop3" - - -class RegKind(Enum): - VGPR = auto() - SGPR = auto() - - -class DataType(Enum): - F16 = auto() - F32 = auto() - I16 = auto() - I32 = auto() - U16 = auto() - U32 = auto() - - -@dataclass(frozen=True) -class Register: - kind: RegKind - index: int - hi: bool = False # True: high 16-bit half (bits 16..31); False: low (0..15) - - def validate(self) -> None: - if self.kind == RegKind.VGPR: - if not (0 <= self.index < 256): - raise ValueError(f"VGPR index {self.index} out of valid range [0, 255].") - elif self.kind == RegKind.SGPR: - if not (0 <= self.index < 106): - raise ValueError(f"SGPR index {self.index} out of valid range [0, 105].") - - def __str__(self) -> str: - prefix = "v" if self.kind == RegKind.VGPR else "s" - suffix = ".h" if self.hi else "" - return f"{prefix}{self.index}{suffix}" - - -@dataclass(frozen=True) -class Operand: - reg: Optional[Register] = None - imm_val: Optional[Union[float, int]] = None - abs_mod: bool = False - neg_mod: bool = False - dtype: DataType = DataType.F16 - - def is_register(self) -> bool: - return self.reg is not None - - def is_literal(self) -> bool: - return self.imm_val is not None - - def validate(self) -> None: - if self.reg is None and self.imm_val is None: - raise ValueError("Operand must specify either register or immediate value.") - if self.reg is not None and self.imm_val is not None: - raise ValueError("Operand cannot specify both register and immediate value.") - if self.reg is not None: - self.reg.validate() - if self.dtype != DataType.F16: - raise TypeError(f"v_subrev_f16 expects F16 operand data type, got {self.dtype}.") - - def __str__(self) -> str: - if self.reg is not None: - base = str(self.reg) - elif isinstance(self.imm_val, float): - base = f"{self.imm_val}" - else: - base = f"{self.imm_val:#x}" - if self.abs_mod: - base = f"|{base}|" - if self.neg_mod: - base = f"-{base}" - return base - - -@dataclass -class InstructionModifiers: - clamp: bool = False - omod: str = "none" # "none", "mul:2", "mul:4", "div:2" - op_sel: tuple[bool, bool, bool] = (False, False, False) # (src0_hi, src1_hi, dst_hi) - - def validate(self, encoding: Encoding) -> None: - if encoding == Encoding.VOP2: - if self.clamp: - raise ValueError("VOP2 encoding does not support clamp modifier.") - if self.omod != "none": - raise ValueError(f"VOP2 encoding does not support omod modifier {self.omod}.") - if any(self.op_sel): - raise ValueError("VOP2 encoding does not support op_sel modifier.") - if self.omod not in ("none", "mul:2", "mul:4", "div:2"): - raise ValueError(f"Invalid omod value: {self.omod}.") - - -@dataclass -class InstructionAST: - opcode: Opcode - dst: Register - src0: Operand - src1: Operand - mods: InstructionModifiers = field(default_factory=InstructionModifiers) - encoding: Encoding = Encoding.VOP2 - - def validate(self) -> None: - if self.opcode != Opcode.V_SUBREV_F16: - raise ValueError(f"Unsupported opcode: {self.opcode}.") - if self.dst.kind != RegKind.VGPR: - raise TypeError("VALU destination register must be a VGPR.") - self.dst.validate() - self.src0.validate() - self.src1.validate() - if self.encoding == Encoding.VOP2: - if self.src0.abs_mod or self.src0.neg_mod or self.src1.abs_mod or self.src1.neg_mod: - raise ValueError("VOP2 encoding does not support input modifiers (abs/neg).") - self.mods.validate(self.encoding) - - def to_asm(self) -> str: - self.validate() - suffix = "_e64" if self.encoding == Encoding.VOP3 else "_e32" - op_name = f"{self.opcode.value}{suffix}" - dst_str = str(self.dst) - src0_str = str(self.src0) - src1_str = str(self.src1) - parts = [f"{op_name} {dst_str}, {src0_str}, {src1_str}"] - if self.mods.clamp: - parts.append("clamp") - if self.mods.omod != "none": - parts.append(self.mods.omod) - if any(self.mods.op_sel): - sel_str = f"op_sel:[{int(self.mods.op_sel[0])},{int(self.mods.op_sel[1])},{int(self.mods.op_sel[2])}]" - parts.append(sel_str) - return " ".join(parts) - - -def parse_subrev_f16_asm(asm_text: str) -> InstructionAST: - """Parse a single assembly instruction line into an InstructionAST.""" - tokens = asm_text.strip().split() - if not tokens: - raise ValueError("Empty assembly instruction.") - - op_token = tokens[0].rstrip(",") - if "v_subrev_f16" not in op_token: - raise ValueError(f"Expected v_subrev_f16 opcode, got: {op_token}") - - is_e64 = "_e64" in op_token or any( - t in ("clamp", "mul:2", "mul:4", "div:2") or t.startswith("op_sel") - for t in tokens - ) - encoding = Encoding.VOP3 if is_e64 else Encoding.VOP2 - - rest = " ".join(tokens[1:]) - operands_raw = [ - o.strip() - for o in re.split(r",|\s+", rest) - if o.strip() - and not o.startswith("clamp") - and not o.startswith("mul:") - and not o.startswith("div:") - and not o.startswith("op_sel") - ] - - if len(operands_raw) < 3: - raise ValueError(f"v_subrev_f16 requires at least 3 operands (dst, src0, src1), got: {operands_raw}") - - dst_tok = operands_raw[0] - dst_hi = dst_tok.endswith(".h") - dst_idx = int(re.search(r"v(\d+)", dst_tok).group(1)) - dst = Register(RegKind.VGPR, dst_idx, hi=dst_hi) - - def parse_operand(tok: str) -> Operand: - abs_m = (tok.startswith("|") and tok.endswith("|")) or ("-|" in tok) - neg_m = tok.startswith("-") - clean = tok.replace("-", "").replace("|", "") - - if clean.startswith("v"): - hi = clean.endswith(".h") - idx = int(re.search(r"v(\d+)", clean).group(1)) - return Operand(reg=Register(RegKind.VGPR, idx, hi=hi), abs_mod=abs_m, neg_mod=neg_m, dtype=DataType.F16) - elif clean.startswith("s"): - hi = clean.endswith(".h") - idx = int(re.search(r"s(\d+)", clean).group(1)) - return Operand(reg=Register(RegKind.SGPR, idx, hi=hi), abs_mod=abs_m, neg_mod=neg_m, dtype=DataType.F16) - else: - if "." in clean or "e" in clean.lower(): - val = float(clean) - elif clean.startswith("0x") or clean.startswith("0X"): - val = int(clean, 16) - else: - val = int(clean) - return Operand(imm_val=val, abs_mod=abs_m, neg_mod=neg_m, dtype=DataType.F16) - - src0 = parse_operand(operands_raw[1]) - src1 = parse_operand(operands_raw[2]) - - clamp_m = "clamp" in tokens - omod_m = "none" - for t in tokens: - if t in ("mul:2", "mul:4", "div:2"): - omod_m = t - - op_sel = (False, False, False) - for t in tokens: - if t.startswith("op_sel:"): - m = re.search(r"op_sel:\[(\d+),(\d+),(\d+)\]", t) - if m: - op_sel = (bool(int(m.group(1))), bool(int(m.group(2))), bool(int(m.group(3)))) - - mods = InstructionModifiers(clamp=clamp_m, omod=omod_m, op_sel=op_sel) - ast = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=dst, - src0=src0, - src1=src1, - mods=mods, - encoding=encoding, - ) - ast.validate() - return ast - - -# ============================================================================ -# Phase 3: Deterministic Scalar Instruction Interpreter -# ============================================================================ - -class ScalarMachineState: - """Deterministic scalar machine state representing VGPRs, SGPRs, and status registers.""" - - def __init__(self) -> None: - self.vgprs: list[int] = [0] * 256 - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - - def get_vgpr(self, index: int) -> int: - if not (0 <= index < 256): - raise IndexError(f"VGPR index {index} out of bounds.") - return self.vgprs[index] - - def set_vgpr(self, index: int, val: int) -> None: - if not (0 <= index < 256): - raise IndexError(f"VGPR index {index} out of bounds.") - self.vgprs[index] = val & MASK32 - - def get_sgpr(self, index: int) -> int: - if not (0 <= index < 106): - raise IndexError(f"SGPR index {index} out of bounds.") - return self.sgprs[index] - - def set_sgpr(self, index: int, val: int) -> None: - if not (0 <= index < 106): - raise IndexError(f"SGPR index {index} out of bounds.") - self.sgprs[index] = val & MASK32 - - def read_reg16(self, reg: Register, op_sel_hi: bool = False) -> int: - """Read a 16-bit halfword from a VGPR or SGPR.""" - use_hi = reg.hi or op_sel_hi - word = self.get_vgpr(reg.index) if reg.kind == RegKind.VGPR else self.get_sgpr(reg.index) - return extract_half(word, use_hi) - - def write_vgpr16(self, index: int, val16: int, hi: bool = False) -> None: - """Write 16-bit halfword into VGPR, preserving the opposite 16-bit half.""" - old_word = self.get_vgpr(index) - new_word = insert_half(old_word, val16, dst_hi=hi) - self.set_vgpr(index, new_word) - - def eval_operand(self, op: Operand, op_sel_hi: bool = False) -> int: - """Evaluate an operand to an unsigned 16-bit bit pattern, applying abs/neg.""" - if op.is_register(): - assert op.reg is not None - raw = self.read_reg16(op.reg, op_sel_hi=op_sel_hi) - elif op.is_literal(): - assert op.imm_val is not None - if isinstance(op.imm_val, float): - raw = f16_to_bits(op.imm_val) - else: - raw = op.imm_val & MASK16 - else: - raise ValueError("Invalid operand.") - return apply_f16_input_mods(raw, op.abs_mod, op.neg_mod) - - -class ScalarVALUInterpreter: - """Deterministic scalar instruction interpreter for v_subrev_f16.""" - - def step(self, instr: Union[InstructionAST, str], state: ScalarMachineState) -> int: - """Execute a single v_subrev_f16 instruction against scalar machine state.""" - if isinstance(instr, str): - ast = parse_subrev_f16_asm(instr) - else: - ast = instr - ast.validate() - - src0_hi = ast.mods.op_sel[0] - src1_hi = ast.mods.op_sel[1] - dst_hi = ast.mods.op_sel[2] or ast.dst.hi - - s0 = state.eval_operand(ast.src0, op_sel_hi=src0_hi) - s1 = state.eval_operand(ast.src1, op_sel_hi=src1_hi) - - # In reverse subtraction: D = S1 - S0 - res16 = ref_subrev_f16(s0, s1, clamp=ast.mods.clamp, omod=ast.mods.omod) - state.write_vgpr16(ast.dst.index, res16, hi=dst_hi) - return res16 - - -# ============================================================================ -# Phase 4: SIMD Multi-Lane Divergence and 32/64-Bit EXEC Masking -# ============================================================================ - -class SIMDWaveState: - """SIMD wavefront state modeling Wave32/Wave64 execution, multi-lane VGPRs, and EXEC masks.""" - - def __init__(self, wave_size: int = 64, exec_mask: Optional[int] = None) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size: {wave_size}. Must be 32 or 64.") - self.wave_size: int = wave_size - self.exec_mask: int = ((1 << wave_size) - 1) if exec_mask is None else exec_mask - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - - def is_lane_active(self, lane: int) -> bool: - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range for wave_size {self.wave_size}.") - return bool((self.exec_mask >> lane) & 1) - - def get_lane_vgpr(self, lane: int, index: int) -> int: - return self.vgprs[lane][index] - - def set_lane_vgpr(self, lane: int, index: int, val: int) -> None: - self.vgprs[lane][index] = val & MASK32 - - def get_sgpr(self, index: int) -> int: - return self.sgprs[index] - - def set_sgpr(self, index: int, val: int) -> None: - self.sgprs[index] = val & MASK32 - - def read_lane_reg16(self, lane: int, reg: Register, op_sel_hi: bool = False) -> int: - use_hi = reg.hi or op_sel_hi - word = self.get_lane_vgpr(lane, reg.index) if reg.kind == RegKind.VGPR else self.get_sgpr(reg.index) - return extract_half(word, use_hi) - - def write_lane_vgpr16(self, lane: int, index: int, val16: int, hi: bool = False) -> None: - old_word = self.get_lane_vgpr(lane, index) - new_word = insert_half(old_word, val16, dst_hi=hi) - self.set_lane_vgpr(lane, index, new_word) - - def eval_lane_operand(self, lane: int, op: Operand, op_sel_hi: bool = False) -> int: - if op.is_register(): - assert op.reg is not None - raw = self.read_lane_reg16(lane, op.reg, op_sel_hi=op_sel_hi) - elif op.is_literal(): - assert op.imm_val is not None - if isinstance(op.imm_val, float): - raw = f16_to_bits(op.imm_val) - else: - raw = op.imm_val & MASK16 - else: - raise ValueError("Invalid operand.") - return apply_f16_input_mods(raw, op.abs_mod, op.neg_mod) - - -class SIMDVALUInterpreter: - """SIMD wavefront instruction interpreter for v_subrev_f16 under EXEC masking.""" - - def step(self, instr: Union[InstructionAST, str], state: SIMDWaveState) -> list[Optional[int]]: - """Step instruction across all wavefront lanes according to state.exec_mask.""" - if isinstance(instr, str): - ast = parse_subrev_f16_asm(instr) - else: - ast = instr - ast.validate() - - src0_hi = ast.mods.op_sel[0] - src1_hi = ast.mods.op_sel[1] - dst_hi = ast.mods.op_sel[2] or ast.dst.hi - - results: list[Optional[int]] = [None] * state.wave_size - for lane in range(state.wave_size): - if not state.is_lane_active(lane): - continue - s0 = state.eval_lane_operand(lane, ast.src0, op_sel_hi=src0_hi) - s1 = state.eval_lane_operand(lane, ast.src1, op_sel_hi=src1_hi) - res16 = ref_subrev_f16(s0, s1, clamp=ast.mods.clamp, omod=ast.mods.omod) - state.write_lane_vgpr16(lane, ast.dst.index, res16, hi=dst_hi) - results[lane] = res16 - return results - - -# ============================================================================ -# Phase 6: Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================ - -@dataclass -class F16StatusFlags: - """IEEE 754 and RDNA2 floating-point exception flags and condition codes.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -def evaluate_v_subrev_f16_flags(s0_bits: int, s1_bits: int, res_bits: int) -> F16StatusFlags: - """Evaluate architectural status flags for v_subrev_f16 (D = S1 - S0).""" - flags = F16StatusFlags() - - s0_nan = is_nan_f16(s0_bits) - s1_nan = is_nan_f16(s1_bits) - s0_snan = is_snan_f16(s0_bits) - s1_snan = is_snan_f16(s1_bits) - s0_inf = is_inf_f16(s0_bits) - s1_inf = is_inf_f16(s1_bits) - - # 1. Invalid operation - if s0_snan or s1_snan: - flags.invalid = True - elif s0_inf and s1_inf: - # (+inf) - (+inf) or (-inf) - (-inf) - if (s0_bits & SIGN_MASK_F16) == (s1_bits & SIGN_MASK_F16): - flags.invalid = True - - # 2. Denormal operand or result - if is_subnormal_f16(s0_bits) or is_subnormal_f16(s1_bits) or is_subnormal_f16(res_bits): - flags.denormal = True - - # 3. Result classification - if is_nan_f16(res_bits): - flags.nan = True - elif is_inf_f16(res_bits): - flags.infinite = True - # If inputs were finite, overflow occurred - if not s0_inf and not s1_inf and not s0_nan and not s1_nan: - flags.overflow = True - flags.inexact = True - elif is_zero_f16(res_bits): - flags.zero = True - else: - # Check inexactness via rational fraction - if not s0_nan and not s1_nan and not s0_inf and not s1_inf: - frac0 = f16_bits_to_fraction(s0_bits) - frac1 = f16_bits_to_fraction(s1_bits) - exact_diff = frac1 - frac0 - res_frac = f16_bits_to_fraction(res_bits) - if exact_diff != res_frac: - flags.inexact = True - if is_subnormal_f16(res_bits) and flags.inexact: - flags.underflow = True - - flags.negative = bool(res_bits & SIGN_MASK_F16) - return flags - - -def compute_f16_significand_borrow(s0_bits: int, s1_bits: int) -> tuple[int, int, int]: - """Simulate hardware significand alignment and borrow generation for S1 - S0. - - Returns: - (aligned_mant0, aligned_mant1, borrow_out) - """ - _, exp0, mant0 = split_f16_bits(s0_bits) - _, exp1, mant1 = split_f16_bits(s1_bits) - - # Add hidden bit for normalized floats - sig0 = (1 << 10) | mant0 if exp0 > 0 else mant0 - sig1 = (1 << 10) | mant1 if exp1 > 0 else mant1 - - eff_exp0 = exp0 if exp0 > 0 else 1 - eff_exp1 = exp1 if exp1 > 0 else 1 - - if eff_exp1 >= eff_exp0: - shift = min(15, eff_exp1 - eff_exp0) - aligned0 = sig0 >> shift - aligned1 = sig1 - else: - shift = min(15, eff_exp0 - eff_exp1) - aligned0 = sig0 - aligned1 = sig1 >> shift - - diff = aligned1 - aligned0 - borrow_out = 1 if diff < 0 else 0 - return aligned0, aligned1, borrow_out - - -# ============================================================================ -# Unit Tests -# ============================================================================ - -class TestValuSubrevF16Oracle(unittest.TestCase): - """Unit tests for reference mathematical oracle and architectural model of v_subrev_f16.""" - - def test_basic_normal_subtraction(self) -> None: - # 3.0 - 1.0 = 2.0 (S1=3.0, S0=1.0) - res = ref_subrev_f16(ONE_F16, THREE_F16) - self.assertEqual(res, TWO_F16) - self.assertEqual(bits_to_f16(res), 2.0) - - # 4.0 - 1.5 = 2.5 - f_1p5 = f16_to_bits(1.5) - res = ref_subrev_f16(f_1p5, FOUR_F16) - self.assertEqual(bits_to_f16(res), 2.5) - - # 0.5 - 2.0 = -1.5 - res = ref_subrev_f16(TWO_F16, HALF_F16) - self.assertEqual(bits_to_f16(res), -1.5) - - def test_reverse_subtraction_asymmetry(self) -> None: - # S1 - S0 != S0 - S1 - res1 = ref_subrev_f16(ONE_F16, THREE_F16) # 3.0 - 1.0 = 2.0 - res2 = ref_subrev_f16(THREE_F16, ONE_F16) # 1.0 - 3.0 = -2.0 - self.assertEqual(bits_to_f16(res1), 2.0) - self.assertEqual(bits_to_f16(res2), -2.0) - self.assertNotEqual(res1, res2) - - def test_cross_check_with_rational_oracle(self) -> None: - test_values = [ - f16_to_bits(x) - for x in [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0, 7.5, 12.25, -0.5, -1.0, -2.5] - ] - for s0 in test_values: - for s1 in test_values: - ref_res = ref_subrev_f16(s0, s1) - rat_res = ref_subrev_f16_rational(s0, s1) - self.assertEqual(ref_res, rat_res, f"Mismatch for s0={s0:#06x}, s1={s1:#06x}") - - def test_signed_zeros(self) -> None: - # (+0.0) - (+0.0) == +0.0 - self.assertEqual(ref_subrev_f16(POS_ZERO_F16, POS_ZERO_F16), POS_ZERO_F16) - # (-0.0) - (-0.0) == +0.0 - self.assertEqual(ref_subrev_f16(NEG_ZERO_F16, NEG_ZERO_F16), POS_ZERO_F16) - # (+0.0) - (-0.0) == +0.0 - self.assertEqual(ref_subrev_f16(NEG_ZERO_F16, POS_ZERO_F16), POS_ZERO_F16) - # (-0.0) - (+0.0) == -0.0 - self.assertEqual(ref_subrev_f16(POS_ZERO_F16, NEG_ZERO_F16), NEG_ZERO_F16) - - def test_infinity_arithmetic(self) -> None: - # (+inf) - (+inf) = Canonical Quiet NaN - self.assertEqual(ref_subrev_f16(POS_INF_F16, POS_INF_F16), CANONICAL_QNAN_F16) - # (-inf) - (-inf) = Canonical Quiet NaN - self.assertEqual(ref_subrev_f16(NEG_INF_F16, NEG_INF_F16), CANONICAL_QNAN_F16) - # (+inf) - (-inf) = +inf - self.assertEqual(ref_subrev_f16(NEG_INF_F16, POS_INF_F16), POS_INF_F16) - # (-inf) - (+inf) = -inf - self.assertEqual(ref_subrev_f16(POS_INF_F16, NEG_INF_F16), NEG_INF_F16) - # finite - (+inf) = -inf - self.assertEqual(ref_subrev_f16(POS_INF_F16, ONE_F16), NEG_INF_F16) - # finite - (-inf) = +inf - self.assertEqual(ref_subrev_f16(NEG_INF_F16, ONE_F16), POS_INF_F16) - # (+inf) - finite = +inf - self.assertEqual(ref_subrev_f16(ONE_F16, POS_INF_F16), POS_INF_F16) - # (-inf) - finite = -inf - self.assertEqual(ref_subrev_f16(ONE_F16, NEG_INF_F16), NEG_INF_F16) - - def test_nan_handling_and_quieting(self) -> None: - # Quiet NaN in src0 - res = ref_subrev_f16(CANONICAL_QNAN_F16, ONE_F16) - self.assertTrue(is_qnan_f16(res)) - - # Quiet NaN in src1 - res = ref_subrev_f16(ONE_F16, CANONICAL_QNAN_F16) - self.assertTrue(is_qnan_f16(res)) - - # Signaling NaN is quieted - res_snan = ref_subrev_f16(SNAN_DEFAULT_F16, ONE_F16) - self.assertTrue(is_qnan_f16(res_snan)) - self.assertTrue(res_snan & QNAN_BIT_F16) - - def test_subnormal_arithmetic(self) -> None: - # Subnormal subtraction - res = ref_subrev_f16(MIN_SUBNORMAL_F16, MAX_SUBNORMAL_F16) - self.assertEqual(res, MAX_SUBNORMAL_F16 - MIN_SUBNORMAL_F16) - # Min normal minus smallest subnormal - res2 = ref_subrev_f16(MIN_SUBNORMAL_F16, MIN_NORMAL_F16) - self.assertEqual(res2, MAX_SUBNORMAL_F16) - - def test_finite_overflow(self) -> None: - # 65504.0 - (-65504.0) = +inf - res = ref_subrev_f16(NEG_MAX_FINITE_F16, MAX_FINITE_F16) - self.assertEqual(res, POS_INF_F16) - # -65504.0 - 65504.0 = -inf - res2 = ref_subrev_f16(MAX_FINITE_F16, NEG_MAX_FINITE_F16) - self.assertEqual(res2, NEG_INF_F16) - - def test_input_modifiers(self) -> None: - # abs(s0): S1 - |S0| -> 3.0 - |-1.0| = 2.0 - res = ref_subrev_f16(NEG_ONE_F16, THREE_F16, abs0=True) - self.assertEqual(bits_to_f16(res), 2.0) - - # neg(s0): S1 - (-S0) -> 3.0 - (-1.0) = 4.0 - res = ref_subrev_f16(ONE_F16, THREE_F16, neg0=True) - self.assertEqual(bits_to_f16(res), 4.0) - - # abs(s1): |S1| - S0 -> |-3.0| - 1.0 = 2.0 - f_neg3 = f16_to_bits(-3.0) - res = ref_subrev_f16(ONE_F16, f_neg3, abs1=True) - self.assertEqual(bits_to_f16(res), 2.0) - - # neg(s1): (-S1) - S0 -> (-3.0) - 1.0 = -4.0 - res = ref_subrev_f16(ONE_F16, THREE_F16, neg1=True) - self.assertEqual(bits_to_f16(res), -4.0) - - # combined -|x| - res = ref_subrev_f16(ONE_F16, THREE_F16, abs1=True, neg1=True) - self.assertEqual(bits_to_f16(res), -4.0) - - def test_output_modifiers(self) -> None: - # clamp: negative result becomes +0.0 - res_neg = ref_subrev_f16(TWO_F16, ONE_F16, clamp=True) # 1.0 - 2.0 = -1.0 -> 0.0 - self.assertEqual(res_neg, POS_ZERO_F16) - - # clamp: result > 1.0 becomes 1.0 - res_pos = ref_subrev_f16(ONE_F16, THREE_F16, clamp=True) # 3.0 - 1.0 = 2.0 -> 1.0 - self.assertEqual(res_pos, ONE_F16) - - # clamp: NaN becomes +0.0 - res_nan = ref_subrev_f16(CANONICAL_QNAN_F16, ONE_F16, clamp=True) - self.assertEqual(res_nan, POS_ZERO_F16) - - # omod mul:2 - res_m2 = ref_subrev_f16(ONE_F16, TWO_F16, omod="mul:2") # (2.0 - 1.0) * 2 = 2.0 - self.assertEqual(bits_to_f16(res_m2), 2.0) - - # omod div:2 - res_d2 = ref_subrev_f16(ONE_F16, TWO_F16, omod="div:2") # (2.0 - 1.0) / 2 = 0.5 - self.assertEqual(bits_to_f16(res_d2), 0.5) - - -class TestValuSubrevF16SymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions for v_subrev_f16.""" - - def test_ast_valid_creation_vop2_and_vop3(self) -> None: - # VOP2 - ast_vop2 = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0), - src0=Operand(reg=Register(RegKind.VGPR, 1)), - src1=Operand(reg=Register(RegKind.VGPR, 2)), - encoding=Encoding.VOP2, - ) - ast_vop2.validate() - self.assertEqual(ast_vop2.to_asm(), "v_subrev_f16_e32 v0, v1, v2") - - # VOP3 - ast_vop3 = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0, hi=True), - src0=Operand(reg=Register(RegKind.VGPR, 1), abs_mod=True, neg_mod=True), - src1=Operand(reg=Register(RegKind.SGPR, 2)), - mods=InstructionModifiers(clamp=True, omod="mul:2", op_sel=(False, True, True)), - encoding=Encoding.VOP3, - ) - ast_vop3.validate() - self.assertEqual(ast_vop3.to_asm(), "v_subrev_f16_e64 v0.h, -|v1|, s2 clamp mul:2 op_sel:[0,1,1]") - - def test_ast_to_asm_formatting(self) -> None: - ast = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 5), - src0=Operand(imm_val=1.5), - src1=Operand(reg=Register(RegKind.VGPR, 10)), - mods=InstructionModifiers(clamp=True), - encoding=Encoding.VOP3, - ) - self.assertEqual(ast.to_asm(), "v_subrev_f16_e64 v5, 1.5, v10 clamp") - - def test_asm_parser_vop2(self) -> None: - ast = parse_subrev_f16_asm("v_subrev_f16_e32 v0, v1, v2") - self.assertEqual(ast.opcode, Opcode.V_SUBREV_F16) - self.assertEqual(ast.dst, Register(RegKind.VGPR, 0)) - self.assertEqual(ast.src0.reg, Register(RegKind.VGPR, 1)) - self.assertEqual(ast.src1.reg, Register(RegKind.VGPR, 2)) - self.assertEqual(ast.encoding, Encoding.VOP2) - self.assertFalse(ast.mods.clamp) - - def test_asm_parser_vop3_modifiers_and_op_sel(self) -> None: - ast = parse_subrev_f16_asm("v_subrev_f16_e64 v3.h, -|v1|, v2 clamp mul:4 op_sel:[1,0,1]") - self.assertEqual(ast.encoding, Encoding.VOP3) - self.assertTrue(ast.dst.hi) - self.assertEqual(ast.dst.index, 3) - self.assertTrue(ast.src0.abs_mod) - self.assertTrue(ast.src0.neg_mod) - self.assertTrue(ast.mods.clamp) - self.assertEqual(ast.mods.omod, "mul:4") - self.assertEqual(ast.mods.op_sel, (True, False, True)) - - def test_ast_validation_rejects_sgpr_dst(self) -> None: - ast = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.SGPR, 0), - src0=Operand(reg=Register(RegKind.VGPR, 1)), - src1=Operand(reg=Register(RegKind.VGPR, 2)), - ) - with self.assertRaises(TypeError): - ast.validate() - - def test_ast_validation_rejects_out_of_bounds_registers(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 256).validate() - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 106).validate() - - def test_ast_validation_rejects_vop2_with_clamp_or_mods(self) -> None: - ast_clamp = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0), - src0=Operand(reg=Register(RegKind.VGPR, 1)), - src1=Operand(reg=Register(RegKind.VGPR, 2)), - mods=InstructionModifiers(clamp=True), - encoding=Encoding.VOP2, - ) - with self.assertRaises(ValueError): - ast_clamp.validate() - - ast_neg = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0), - src0=Operand(reg=Register(RegKind.VGPR, 1), neg_mod=True), - src1=Operand(reg=Register(RegKind.VGPR, 2)), - encoding=Encoding.VOP2, - ) - with self.assertRaises(ValueError): - ast_neg.validate() - - def test_ast_validation_rejects_wrong_data_type(self) -> None: - op = Operand(reg=Register(RegKind.VGPR, 1), dtype=DataType.F32) - with self.assertRaises(TypeError): - op.validate() - - -class TestValuSubrevF16ScalarInterpreter(unittest.TestCase): - """Unit tests for deterministic scalar instruction interpreter for v_subrev_f16.""" - - def setUp(self) -> None: - self.interp = ScalarVALUInterpreter() - self.state = ScalarMachineState() - - def test_scalar_step_basic_vgpr_sources(self) -> None: - # Set v1 = 1.0 (low half), v2 = 3.0 (low half), canary in high half - self.state.set_vgpr(0, 0xDEAD0000) - self.state.set_vgpr(1, pack_half(ONE_F16, 0x1234)) - self.state.set_vgpr(2, pack_half(THREE_F16, 0x5678)) - - res = self.interp.step("v_subrev_f16_e32 v0, v1, v2", self.state) - self.assertEqual(res, TWO_F16) - v0_val = self.state.get_vgpr(0) - lo, hi = unpack_half(v0_val) - self.assertEqual(lo, TWO_F16) - self.assertEqual(hi, 0xDEAD) - - def test_scalar_step_sgpr_and_literal_sources(self) -> None: - # S0 is literal 1.5, S1 is VGPR with 4.5 -> D = 4.5 - 1.5 = 3.0 - self.state.set_vgpr(1, f16_to_bits(4.5)) - res = self.interp.step("v_subrev_f16_e64 v0, 1.5, v1", self.state) - self.assertEqual(bits_to_f16(res), 3.0) - self.assertEqual(bits_to_f16(self.state.read_reg16(Register(RegKind.VGPR, 0))), 3.0) - - # S0 is SGPR with 0.5, S1 is VGPR with 2.0 -> D = 2.0 - 0.5 = 1.5 - self.state.set_sgpr(5, HALF_F16) - self.state.set_vgpr(2, TWO_F16) - res2 = self.interp.step("v_subrev_f16_e32 v0, s5, v2", self.state) - self.assertEqual(bits_to_f16(res2), 1.5) - - def test_scalar_step_vop3_input_modifiers(self) -> None: - # S0 = -1.0, S1 = 2.0. With -|s0|, S0 becomes -1.0. S1 - (-1.0) = 3.0 - self.state.set_sgpr(0, NEG_ONE_F16) - self.state.set_vgpr(1, TWO_F16) - res = self.interp.step("v_subrev_f16_e64 v0, -|s0|, v1", self.state) - self.assertEqual(bits_to_f16(res), 3.0) - - def test_scalar_step_vop3_clamp_and_omod(self) -> None: - # S0 = 3.0, S1 = 1.0 -> 1.0 - 3.0 = -2.0. Clamped to 0.0 - self.state.set_vgpr(1, THREE_F16) - self.state.set_vgpr(2, ONE_F16) - res = self.interp.step("v_subrev_f16_e64 v0, v1, v2 clamp", self.state) - self.assertEqual(res, POS_ZERO_F16) - - # S0 = 0.5, S1 = 1.5 -> (1.5 - 0.5) * 4 = 4.0 - self.state.set_vgpr(1, HALF_F16) - self.state.set_vgpr(2, f16_to_bits(1.5)) - res2 = self.interp.step("v_subrev_f16_e64 v0, v1, v2 mul:4", self.state) - self.assertEqual(bits_to_f16(res2), 4.0) - - def test_scalar_step_op_sel_halves(self) -> None: - # v1 has lo=0.25, hi=1.0. v2 has lo=2.0, hi=5.0 - self.state.set_vgpr(1, pack_half(QUARTER_F16, ONE_F16)) - self.state.set_vgpr(2, pack_half(TWO_F16, f16_to_bits(5.0))) - self.state.set_vgpr(0, pack_half(0x1111, 0x2222)) - - # op_sel:[1, 0, 1] reads v1.h (1.0) and v2.l (2.0), writes to v0.h: - # D = 2.0 - 1.0 = 1.0 into v0.h. v0.l preserves 0x1111. - res = self.interp.step("v_subrev_f16_e64 v0.h, v1, v2 op_sel:[1,0,1]", self.state) - self.assertEqual(res, ONE_F16) - v0_val = self.state.get_vgpr(0) - lo, hi = unpack_half(v0_val) - self.assertEqual(lo, 0x1111) - self.assertEqual(hi, ONE_F16) - - def test_scalar_step_determinism(self) -> None: - s_a = ScalarMachineState() - s_b = ScalarMachineState() - for s in (s_a, s_b): - s.set_vgpr(1, pack_half(ONE_F16, TWO_F16)) - s.set_vgpr(2, pack_half(THREE_F16, FOUR_F16)) - self.interp.step("v_subrev_f16_e32 v0, v1, v2", s) - self.assertEqual(s_a.vgprs, s_b.vgprs) - - -class TestValuSubrevF16SIMDExecMasking(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking for v_subrev_f16.""" - - def setUp(self) -> None: - self.simd_interp = SIMDVALUInterpreter() - - def test_wave32_all_lanes_active(self) -> None: - state = SIMDWaveState(wave_size=32, exec_mask=0xFFFFFFFF) - for lane in range(32): - state.set_lane_vgpr(lane, 1, ONE_F16) # S0 = 1.0 - state.set_lane_vgpr(lane, 2, f16_to_bits(float(lane))) # S1 = lane - state.set_lane_vgpr(lane, 0, 0) - - # D = S1 - S0 = lane - 1.0 - results = self.simd_interp.step("v_subrev_f16_e32 v0, v1, v2", state) - for lane in range(32): - self.assertIsNotNone(results[lane]) - expected = f16_to_bits(float(lane) - 1.0) - self.assertEqual(results[lane], expected) - self.assertEqual(state.read_lane_reg16(lane, Register(RegKind.VGPR, 0)), expected) - - def test_wave64_all_lanes_active(self) -> None: - state = SIMDWaveState(wave_size=64, exec_mask=0xFFFFFFFFFFFFFFFF) - for lane in range(64): - state.set_lane_vgpr(lane, 1, f16_to_bits(0.5)) - state.set_lane_vgpr(lane, 2, f16_to_bits(float(lane) * 0.5)) - - results = self.simd_interp.step("v_subrev_f16_e32 v0, v1, v2", state) - for lane in range(64): - expected = f16_to_bits(float(lane) * 0.5 - 0.5) - self.assertEqual(results[lane], expected) - - def test_wave32_partial_exec_mask_preserves_inactive_lanes(self) -> None: - # Alternating lanes active: mask = 0x55555555 (lanes 0, 2, 4, ...) - exec_mask = 0x55555555 - state = SIMDWaveState(wave_size=32, exec_mask=exec_mask) - canary = 0xCAFE - for lane in range(32): - state.set_lane_vgpr(lane, 0, pack_half(canary, canary)) - state.set_lane_vgpr(lane, 1, ONE_F16) - state.set_lane_vgpr(lane, 2, FOUR_F16) # 4.0 - 1.0 = 3.0 - - results = self.simd_interp.step("v_subrev_f16_e32 v0, v1, v2", state) - for lane in range(32): - lo, hi = unpack_half(state.get_lane_vgpr(lane, 0)) - if (exec_mask >> lane) & 1: - self.assertEqual(results[lane], THREE_F16) - self.assertEqual(lo, THREE_F16) - self.assertEqual(hi, canary) # opposite half preserved - else: - self.assertIsNone(results[lane]) - self.assertEqual(lo, canary) # inactive lane untouched - self.assertEqual(hi, canary) - - def test_wave64_high_dword_mask(self) -> None: - # Lanes 0..31 inactive, lanes 32..63 active - exec_mask = 0xFFFFFFFF00000000 - state = SIMDWaveState(wave_size=64, exec_mask=exec_mask) - for lane in range(64): - state.set_lane_vgpr(lane, 0, 0x12345678) - state.set_lane_vgpr(lane, 1, HALF_F16) - state.set_lane_vgpr(lane, 2, TWO_F16) # 2.0 - 0.5 = 1.5 - - results = self.simd_interp.step("v_subrev_f16_e32 v0, v1, v2", state) - for lane in range(32): - self.assertIsNone(results[lane]) - self.assertEqual(state.get_lane_vgpr(lane, 0), 0x12345678) - for lane in range(32, 64): - self.assertEqual(bits_to_f16(results[lane]), 1.5) - self.assertEqual(extract_half(state.get_lane_vgpr(lane, 0), hi_sel=False), f16_to_bits(1.5)) - - def test_simd_sgpr_scalar_broadcast(self) -> None: - state = SIMDWaveState(wave_size=32, exec_mask=0xFFFFFFFF) - # s4 holds scalar constant 10.0 (broadcast across all lanes as S0) - state.set_sgpr(4, f16_to_bits(10.0)) - for lane in range(32): - state.set_lane_vgpr(lane, 1, f16_to_bits(float(lane) + 10.0)) # S1 = lane + 10.0 - - # D = S1 - S0 = (lane + 10.0) - 10.0 = lane - results = self.simd_interp.step("v_subrev_f16_e32 v0, s4, v1", state) - for lane in range(32): - self.assertEqual(bits_to_f16(results[lane]), float(lane)) - - -class TestValuSubrevF16RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation for v_subrev_f16.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarVALUInterpreter() - self.simd_interp = SIMDVALUInterpreter() - - def test_dst_alias_src0(self) -> None: - # v0 = 1.0, v1 = 3.0. Instr: v_subrev_f16 v0, v0, v1 -> v0 = 3.0 - 1.0 = 2.0 - state = ScalarMachineState() - state.set_vgpr(0, pack_half(ONE_F16, 0xAAAA)) - state.set_vgpr(1, pack_half(THREE_F16, 0xBBBB)) - - res = self.scalar_interp.step("v_subrev_f16_e32 v0, v0, v1", state) - self.assertEqual(res, TWO_F16) - lo, hi = unpack_half(state.get_vgpr(0)) - self.assertEqual(lo, TWO_F16) - self.assertEqual(hi, 0xAAAA) # opposite half preserved - self.assertEqual(state.get_vgpr(1), pack_half(THREE_F16, 0xBBBB)) # src1 untouched - - def test_dst_alias_src1(self) -> None: - # v0 = 1.0, v1 = 3.0. Instr: v_subrev_f16 v1, v0, v1 -> v1 = 3.0 - 1.0 = 2.0 - state = ScalarMachineState() - state.set_vgpr(0, pack_half(ONE_F16, 0xAAAA)) - state.set_vgpr(1, pack_half(THREE_F16, 0xBBBB)) - - res = self.scalar_interp.step("v_subrev_f16_e32 v1, v0, v1", state) - self.assertEqual(res, TWO_F16) - lo, hi = unpack_half(state.get_vgpr(1)) - self.assertEqual(lo, TWO_F16) - self.assertEqual(hi, 0xBBBB) - self.assertEqual(state.get_vgpr(0), pack_half(ONE_F16, 0xAAAA)) - - def test_dst_alias_src0_and_src1_self_subtraction(self) -> None: - # Self-subtraction: v0 = 5.0. v_subrev_f16 v0, v0, v0 -> 5.0 - 5.0 = +0.0 - state = ScalarMachineState() - f_5p0 = f16_to_bits(5.0) - state.set_vgpr(0, pack_half(f_5p0, 0xCCCC)) - - res = self.scalar_interp.step("v_subrev_f16_e32 v0, v0, v0", state) - self.assertEqual(res, POS_ZERO_F16) - lo, hi = unpack_half(state.get_vgpr(0)) - self.assertEqual(lo, POS_ZERO_F16) - self.assertEqual(hi, 0xCCCC) - - def test_intra_dword_half_word_aliasing_write_hi(self) -> None: - # v0 holds lo=1.0, hi=4.0. - # Instr: v_subrev_f16_e64 v0.h, v0, v0.h - # S0 reads v0.l (1.0), S1 reads v0.h (4.0). - # D writes to v0.h = 4.0 - 1.0 = 3.0. v0.l must remain 1.0. - state = ScalarMachineState() - state.set_vgpr(0, pack_half(ONE_F16, FOUR_F16)) - - ast = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0, hi=True), - src0=Operand(reg=Register(RegKind.VGPR, 0, hi=False)), - src1=Operand(reg=Register(RegKind.VGPR, 0, hi=True)), - encoding=Encoding.VOP3, - ) - res = self.scalar_interp.step(ast, state) - self.assertEqual(res, THREE_F16) - lo, hi = unpack_half(state.get_vgpr(0)) - self.assertEqual(lo, ONE_F16) # preserved - self.assertEqual(hi, THREE_F16) # updated - - def test_intra_dword_half_word_aliasing_write_lo(self) -> None: - # v0 holds lo=1.0, hi=4.0. - # Instr: v_subrev_f16_e64 v0, v0.h, v0 - # S0 reads v0.h (4.0), S1 reads v0.l (1.0). - # D writes to v0.l = 1.0 - 4.0 = -3.0. v0.h must remain 4.0. - state = ScalarMachineState() - state.set_vgpr(0, pack_half(ONE_F16, FOUR_F16)) - - ast = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0, hi=False), - src0=Operand(reg=Register(RegKind.VGPR, 0, hi=True)), - src1=Operand(reg=Register(RegKind.VGPR, 0, hi=False)), - encoding=Encoding.VOP3, - ) - res = self.scalar_interp.step(ast, state) - self.assertEqual(bits_to_f16(res), -3.0) - lo, hi = unpack_half(state.get_vgpr(0)) - self.assertEqual(lo, f16_to_bits(-3.0)) - self.assertEqual(hi, FOUR_F16) # preserved - - def test_simd_multi_lane_aliasing(self) -> None: - state = SIMDWaveState(wave_size=32, exec_mask=0xFFFFFFFF) - for lane in range(32): - state.set_lane_vgpr(lane, 0, f16_to_bits(float(lane) * 2.0)) - state.set_lane_vgpr(lane, 1, f16_to_bits(100.0)) - - # In-place update: v0 = v1 - v0 = 100.0 - lane * 2.0 - self.simd_interp.step("v_subrev_f16_e32 v0, v0, v1", state) - for lane in range(32): - expected = f16_to_bits(100.0 - float(lane) * 2.0) - self.assertEqual(extract_half(state.get_lane_vgpr(lane, 0), hi_sel=False), expected) - - -class TestValuSubrevF16ConditionCodesAndFlags(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow generation.""" - - def test_exact_finite_flags(self) -> None: - # S0 = 1.0, S1 = 3.0 -> D = 2.0 (exact) - s0 = ONE_F16 - s1 = THREE_F16 - res = ref_subrev_f16(s0, s1) - flags = evaluate_v_subrev_f16_flags(s0, s1, res) - self.assertFalse(flags.invalid) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - self.assertFalse(flags.inexact) - self.assertFalse(flags.zero) - self.assertFalse(flags.negative) - self.assertFalse(flags.denormal) - self.assertFalse(flags.infinite) - self.assertFalse(flags.nan) - - def test_inexact_flag(self) -> None: - # 1.0 - 0.0001 in f16 is inexact - s0 = f16_to_bits(0.0001) - s1 = ONE_F16 - res = ref_subrev_f16(s0, s1) - flags = evaluate_v_subrev_f16_flags(s0, s1, res) - self.assertTrue(flags.inexact) - self.assertFalse(flags.overflow) - self.assertFalse(flags.invalid) - - def test_overflow_flag(self) -> None: - # MAX_FINITE - (-MAX_FINITE) overflows to +inf - s0 = NEG_MAX_FINITE_F16 - s1 = MAX_FINITE_F16 - res = ref_subrev_f16(s0, s1) - self.assertEqual(res, POS_INF_F16) - flags = evaluate_v_subrev_f16_flags(s0, s1, res) - self.assertTrue(flags.overflow) - self.assertTrue(flags.infinite) - self.assertTrue(flags.inexact) - self.assertFalse(flags.invalid) - - def test_underflow_and_denorm_flags(self) -> None: - # Subnormal subtraction - s0 = MIN_SUBNORMAL_F16 - s1 = MAX_SUBNORMAL_F16 - res = ref_subrev_f16(s0, s1) - flags = evaluate_v_subrev_f16_flags(s0, s1, res) - self.assertTrue(flags.denormal) - self.assertFalse(flags.overflow) - - def test_invalid_operation_flag(self) -> None: - # (+inf) - (+inf) is invalid - res = ref_subrev_f16(POS_INF_F16, POS_INF_F16) - flags = evaluate_v_subrev_f16_flags(POS_INF_F16, POS_INF_F16, res) - self.assertTrue(flags.invalid) - self.assertTrue(flags.nan) - - # Signaling NaN triggers invalid operation - res2 = ref_subrev_f16(SNAN_DEFAULT_F16, ONE_F16) - flags2 = evaluate_v_subrev_f16_flags(SNAN_DEFAULT_F16, ONE_F16, res2) - self.assertTrue(flags2.invalid) - self.assertTrue(flags2.nan) - - def test_zero_and_negative_flags(self) -> None: - # (-0.0) - (+0.0) = -0.0 - res_nz = ref_subrev_f16(POS_ZERO_F16, NEG_ZERO_F16) - flags_nz = evaluate_v_subrev_f16_flags(POS_ZERO_F16, NEG_ZERO_F16, res_nz) - self.assertTrue(flags_nz.zero) - self.assertTrue(flags_nz.negative) - - # (+0.0) - (-0.0) = +0.0 - res_pz = ref_subrev_f16(NEG_ZERO_F16, POS_ZERO_F16) - flags_pz = evaluate_v_subrev_f16_flags(NEG_ZERO_F16, POS_ZERO_F16, res_pz) - self.assertTrue(flags_pz.zero) - self.assertFalse(flags_pz.negative) - - # 1.0 - 3.0 = -2.0 - res_neg = ref_subrev_f16(THREE_F16, ONE_F16) - flags_neg = evaluate_v_subrev_f16_flags(THREE_F16, ONE_F16, res_neg) - self.assertFalse(flags_neg.zero) - self.assertTrue(flags_neg.negative) - - def test_significand_borrow_generation(self) -> None: - # S1=1.0, S0=2.0 -> S1 < S0 so borrow_out = 1 - _, _, borrow1 = compute_f16_significand_borrow(TWO_F16, ONE_F16) - self.assertEqual(borrow1, 1) - - # S1=3.0, S0=1.0 -> S1 > S0 so borrow_out = 0 - _, _, borrow0 = compute_f16_significand_borrow(ONE_F16, THREE_F16) - self.assertEqual(borrow0, 0) - - -class TestValuSubrevF16IEEE754Boundaries(unittest.TestCase): - """Exhaustive IEEE 754-2008 boundary extremes, subnormals, and NaN handling tests for v_subrev_f16.""" - - def test_signed_zero_combinations(self) -> None: - # All 4 permutations of signed zero operands - # S1 - S0: - # (+0.0) - (+0.0) -> +0.0 - self.assertEqual(ref_subrev_f16(POS_ZERO_F16, POS_ZERO_F16), POS_ZERO_F16) - # (+0.0) - (-0.0) -> +0.0 - self.assertEqual(ref_subrev_f16(NEG_ZERO_F16, POS_ZERO_F16), POS_ZERO_F16) - # (-0.0) - (+0.0) -> -0.0 - self.assertEqual(ref_subrev_f16(POS_ZERO_F16, NEG_ZERO_F16), NEG_ZERO_F16) - # (-0.0) - (-0.0) -> +0.0 - self.assertEqual(ref_subrev_f16(NEG_ZERO_F16, NEG_ZERO_F16), POS_ZERO_F16) - - def test_subnormal_boundary_transitions(self) -> None: - # MIN_NORMAL = 0x0400 (2^-14). Subtract MIN_SUBNORMAL = 0x0001 (2^-24). - # Expected result is MAX_SUBNORMAL = 0x03FF. - res = ref_subrev_f16(MIN_SUBNORMAL_F16, MIN_NORMAL_F16) - self.assertEqual(res, MAX_SUBNORMAL_F16) - self.assertTrue(is_subnormal_f16(res)) - - # Reversing: MIN_SUBNORMAL - MIN_NORMAL = -MAX_SUBNORMAL - res_rev = ref_subrev_f16(MIN_NORMAL_F16, MIN_SUBNORMAL_F16) - self.assertEqual(res_rev, MAX_SUBNORMAL_F16 | SIGN_MASK_F16) - self.assertTrue(is_subnormal_f16(res_rev)) - - def test_subnormal_precision_and_gradual_underflow(self) -> None: - # Subtraction of two close normalized numbers that results in a subnormal - # 1.0009765625 (0x3C01) - 1.0 (0x3C00) = 2^-10 in normal range, - # but near MIN_NORMAL: 0x0401 - 0x0400 = 0x0001 (MIN_SUBNORMAL) - val_a = 0x0401 - val_b = 0x0400 - res = ref_subrev_f16(val_b, val_a) - self.assertEqual(res, MIN_SUBNORMAL_F16) - self.assertTrue(is_subnormal_f16(res)) - - def test_infinity_edge_cases(self) -> None: - # (+inf) - (+inf) -> Canonical Quiet NaN - self.assertEqual(ref_subrev_f16(POS_INF_F16, POS_INF_F16), CANONICAL_QNAN_F16) - # (-inf) - (-inf) -> Canonical Quiet NaN - self.assertEqual(ref_subrev_f16(NEG_INF_F16, NEG_INF_F16), CANONICAL_QNAN_F16) - # (+inf) - (-inf) -> +inf - self.assertEqual(ref_subrev_f16(NEG_INF_F16, POS_INF_F16), POS_INF_F16) - # (-inf) - (+inf) -> -inf - self.assertEqual(ref_subrev_f16(POS_INF_F16, NEG_INF_F16), NEG_INF_F16) - - # Infinities with modifiers: S1 - (-|S0|): (+inf) - (-|+inf|) = (+inf) - (-inf) = +inf - res_mod = ref_subrev_f16(POS_INF_F16, POS_INF_F16, abs0=True, neg0=True) - self.assertEqual(res_mod, POS_INF_F16) - - def test_nan_quieting_and_payload_preservation(self) -> None: - # Signaling NaNs must have quiet bit (bit 9) set - snan_payload = 0x7C55 - self.assertTrue(is_snan_f16(snan_payload)) - res_s0 = ref_subrev_f16(snan_payload, ONE_F16) - self.assertTrue(is_qnan_f16(res_s0)) - self.assertEqual(res_s0 & QNAN_BIT_F16, QNAN_BIT_F16) - - res_s1 = ref_subrev_f16(ONE_F16, snan_payload) - self.assertTrue(is_qnan_f16(res_s1)) - self.assertEqual(res_s1 & QNAN_BIT_F16, QNAN_BIT_F16) - - # Quiet NaN payload preserved - qnan_payload = 0x7EAA - res_q = ref_subrev_f16(qnan_payload, ONE_F16) - self.assertTrue(is_qnan_f16(res_q)) - - def test_nan_clamping_to_zero(self) -> None: - # In RDNA2, clamping any NaN result produces +0.0 - qnan = CANONICAL_QNAN_F16 - snan = SNAN_DEFAULT_F16 - self.assertEqual(ref_subrev_f16(qnan, ONE_F16, clamp=True), POS_ZERO_F16) - self.assertEqual(ref_subrev_f16(ONE_F16, qnan, clamp=True), POS_ZERO_F16) - self.assertEqual(ref_subrev_f16(snan, ONE_F16, clamp=True), POS_ZERO_F16) - self.assertEqual(ref_subrev_f16(POS_INF_F16, POS_INF_F16, clamp=True), POS_ZERO_F16) - - def test_max_finite_overflow_boundaries(self) -> None: - # 65504.0 - (-1.0) = 65505.0 -> rounds to 65504.0 (even tie) - res_near = ref_subrev_f16(NEG_ONE_F16, MAX_FINITE_F16) - self.assertEqual(res_near, MAX_FINITE_F16) - - # 65504.0 - (-16.0) -> overflows to +inf - f_neg16 = f16_to_bits(-16.0) - res_over = ref_subrev_f16(f_neg16, MAX_FINITE_F16) - self.assertEqual(res_over, POS_INF_F16) - - def test_subnormal_with_modifiers(self) -> None: - # S0 = -MIN_SUBNORMAL, S1 = MIN_SUBNORMAL. With abs0: S1 - |-S0| = 0 - s0 = MIN_SUBNORMAL_F16 | SIGN_MASK_F16 - s1 = MIN_SUBNORMAL_F16 - res = ref_subrev_f16(s0, s1, abs0=True) - self.assertEqual(res, POS_ZERO_F16) - - -class TestValuSubrevF16NegativeControls(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and invalid AST inputs for v_subrev_f16.""" - - def test_syntax_rejection_empty_and_bad_opcode(self) -> None: - with self.assertRaises(ValueError): - parse_subrev_f16_asm("") - with self.assertRaises(ValueError): - parse_subrev_f16_asm("v_add_f16_e32 v0, v1, v2") - with self.assertRaises(ValueError): - parse_subrev_f16_asm("v_subrev_f16_e32 v0, v1") - - def test_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.VGPR, -1).validate() - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 256).validate() - with self.assertRaises(ValueError): - Register(RegKind.SGPR, -1).validate() - with self.assertRaises(ValueError): - Register(RegKind.SGPR, 106).validate() - - def test_invalid_destination_kind(self) -> None: - # VALU destination cannot be SGPR - ast = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.SGPR, 0), - src0=Operand(reg=Register(RegKind.VGPR, 1)), - src1=Operand(reg=Register(RegKind.VGPR, 2)), - ) - with self.assertRaises(TypeError): - ast.validate() - - def test_invalid_vop2_modifiers(self) -> None: - # VOP2 cannot have clamp, omod, op_sel, or input modifiers - ast_clamp = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0), - src0=Operand(reg=Register(RegKind.VGPR, 1)), - src1=Operand(reg=Register(RegKind.VGPR, 2)), - mods=InstructionModifiers(clamp=True), - encoding=Encoding.VOP2, - ) - with self.assertRaises(ValueError): - ast_clamp.validate() - - ast_omod = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0), - src0=Operand(reg=Register(RegKind.VGPR, 1)), - src1=Operand(reg=Register(RegKind.VGPR, 2)), - mods=InstructionModifiers(omod="mul:2"), - encoding=Encoding.VOP2, - ) - with self.assertRaises(ValueError): - ast_omod.validate() - - ast_op_sel = InstructionAST( - opcode=Opcode.V_SUBREV_F16, - dst=Register(RegKind.VGPR, 0), - src0=Operand(reg=Register(RegKind.VGPR, 1)), - src1=Operand(reg=Register(RegKind.VGPR, 2)), - mods=InstructionModifiers(op_sel=(True, False, False)), - encoding=Encoding.VOP2, - ) - with self.assertRaises(ValueError): - ast_op_sel.validate() - - def test_state_out_of_bounds_access(self) -> None: - scalar = ScalarMachineState() - with self.assertRaises(IndexError): - scalar.get_vgpr(256) - with self.assertRaises(IndexError): - scalar.get_sgpr(106) - with self.assertRaises(IndexError): - scalar.set_vgpr(256, 0) - with self.assertRaises(IndexError): - scalar.set_sgpr(106, 0) - - def test_simd_invalid_wave_size_and_lanes(self) -> None: - with self.assertRaises(ValueError): - SIMDWaveState(wave_size=16) - with self.assertRaises(ValueError): - SIMDWaveState(wave_size=128) - simd = SIMDWaveState(wave_size=32) - with self.assertRaises(IndexError): - simd.is_lane_active(32) - - -class TestValuSubrevF16MutationDetection(unittest.TestCase): - """Mutation tests: verifies that intentional bugs/mutations in subrev semantics are caught.""" - - def test_mutation_non_reversed_subtraction(self) -> None: - # Mutation: computing S0 - S1 instead of S1 - S0 - def mutated_sub(s0: int, s1: int) -> int: - return ref_subrev_f16(s1, s0) # reversed operands - - s0 = ONE_F16 # 1.0 - s1 = THREE_F16 # 3.0 - # True v_subrev_f16: 3.0 - 1.0 = 2.0 - # Mutated: 1.0 - 3.0 = -2.0 - with self.assertRaises(AssertionError): - self.assertEqual(mutated_sub(s0, s1), TWO_F16) - - def test_mutation_signed_zero_blindness(self) -> None: - # Mutation: ignoring signed zero difference (-0.0) - (+0.0) -> producing +0.0 - def mutated_zero_sub(s0: int, s1: int) -> int: - res = ref_subrev_f16(s0, s1) - if res == NEG_ZERO_F16: - return POS_ZERO_F16 - return res - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_zero_sub(POS_ZERO_F16, NEG_ZERO_F16), NEG_ZERO_F16) - - def test_mutation_infinity_cancellation(self) -> None: - # Mutation: (+inf) - (+inf) produces 0.0 instead of NaN - def mutated_inf_sub(s0: int, s1: int) -> int: - if s0 == POS_INF_F16 and s1 == POS_INF_F16: - return POS_ZERO_F16 - return ref_subrev_f16(s0, s1) - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_inf_sub(POS_INF_F16, POS_INF_F16), CANONICAL_QNAN_F16) - - def test_mutation_clamp_nan_bug(self) -> None: - # Mutation: clamping NaN returns NaN instead of +0.0 - def mutated_clamp_nan(s0: int, s1: int) -> int: - return ref_subrev_f16(s0, s1, clamp=False) - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_clamp_nan(CANONICAL_QNAN_F16, ONE_F16), POS_ZERO_F16) - - def test_mutation_exec_mask_leak(self) -> None: - # Mutation: inactive lane leaks write to destination - simd = SIMDWaveState(wave_size=32, exec_mask=0) # all inactive - canary = 0xBEEF - simd.set_lane_vgpr(0, 0, pack_half(canary, canary)) - - interp = SIMDVALUInterpreter() - interp.step("v_subrev_f16_e32 v0, v1, v2", simd) - # Canary must remain intact - self.assertEqual(simd.get_lane_vgpr(0, 0), pack_half(canary, canary)) - - # Mutated write unconditionally overwrites - simd.set_lane_vgpr(0, 0, pack_half(ONE_F16, canary)) - with self.assertRaises(AssertionError): - self.assertEqual(simd.get_lane_vgpr(0, 0), pack_half(canary, canary)) - - def test_mutation_modifier_order(self) -> None: - # Mutation: applying neg then abs (which makes -|x| always positive | -x | = +x) - def mutated_mods(bits: int, abs_mod: bool, neg_mod: bool) -> int: - res = bits - if neg_mod: - res ^= SIGN_MASK_F16 - if abs_mod: - res &= ~SIGN_MASK_F16 - return res - - # For -|1.0|, correct is -1.0 (sign bit set) - correct = apply_f16_input_mods(ONE_F16, abs_mod=True, neg_mod=True) - mutated = mutated_mods(ONE_F16, abs_mod=True, neg_mod=True) - self.assertEqual(correct, NEG_ONE_F16) - self.assertNotEqual(correct, mutated) + prog = [f"v_mov_b32 v0, {old:#x}"] + for reg, w in seeds.items(): + w = w if w > 0xFFFF else (hi << 16) | w + prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") + prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return support.mrt0_words(support.translate_lines("ps_subrev_f16", prog))[0] + + +# (src0, src1, D), written by hand. +CASES = [ + (ONE, THREE, TWO), # 3 - 1 = 2 + (TWO, ONE, 0xBC00), # 1 - 2 = -1 + (QUARTER, HALF, QUARTER), # 0.5 - 0.25 + (0x3E00, 0x3E00, 0x0000), # x - x = +0 + (0x0000, 0x8000, 0x8000), # -0 - +0 = -0 + (0x0000, 0x0000, 0x0000), # +0 - +0 = +0 + (0x8000, 0x0000, 0x0000), # +0 - -0 = +0 + (0x8000, 0x8000, 0x0000), # -0 - -0 = -0 + +0 = +0 + (0xFBFF, MAXH, INF), # 65504 - -65504 overflows + (0xCC00, MAXH, INF), # 65504 - -16 = 65520: tie, even is the overflow + (MIN_SUB, MIN_NORMAL, MAX_SUB), # 2^-14 - 2^-24 = the largest subnormal + (0x8001, MIN_SUB, 0x0002), # 2^-24 - -2^-24 + (0x9000, ONE, ONE), # 1 - -2^-11: half an ulp, ties to even, stays 1 + (0x9001, ONE, 0x3C01), # a little over half an ulp rounds up + (ONE, 0x3C01, 0x1400), # (1 + 2^-10) - 1 = 2^-10, exact + (INF, INF, QNAN), # inf - inf = NaN + (NINF, INF, INF), + (QNAN, ONE, QNAN), +] + +SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, + MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0x1000, 0x6800, 0x6801, 0x4C00] + + +class SubrevF16(unittest.TestCase): + def test_hand_written_table_matches_reference(self): + for a, b, want in CASES: + self.assertTrue(same_f16(ref_subrev(a, b), want), (hex(a), hex(b), hex(ref_subrev(a, b)))) + + def test_e32_writes_low_half_and_keeps_high_half(self): + for a, b, want in CASES: + with self.subTest(a=hex(a), b=hex(b)): + got = run("v_subrev_f16 v0, v1, v2", {"v1": a, "v2": b}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_vop3_sgpr_and_literal_sources(self): + for a, b, want in CASES[:14]: + forms = [ + ("e64 vgpr", "v_subrev_f16_e64 v0, v1, v2", {"v1": a, "v2": b}), + ("e64 sgpr", "v_subrev_f16_e64 v0, s1, s2", {"s1": a, "s2": b}), + ("e32 sgpr src0", "v_subrev_f16 v0, s1, v2", {"s1": a, "v2": b}), + ("e32 literal src0", f"v_subrev_f16 v0, {a:#x}, v2", {"v2": b}), + ("e64 literal src1", f"v_subrev_f16_e64 v0, v1, {b:#x}", {"v1": a}), + ] + for form, line, seeds in forms: + with self.subTest(a=hex(a), b=hex(b), form=form): + got = run(line, seeds) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) + + def test_inline_constants(self): + # (inline constant as src0, its binary16 value, v1 low half, D), by hand + for text, c, b, want in (("2.0", TWO, HALF, 0xBE00), ("-1.0", 0xBC00, HALF, 0x3E00), ("0.5", HALF, QUARTER, 0xB400), + ("4.0", 0x4400, 0xB800, 0xC480), ("1.0", ONE, ONE, 0x0000)): + with self.subTest(const=text): + self.assertEqual(run(f"v_subrev_f16 v0, {text}, v1", {"v1": b}) & 0xFFFF, want) + self.assertEqual(ref_subrev(c, b), want) + + def test_op_sel_selects_source_and_destination_halves(self): + # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25); D by hand for each (src0 half, src1 half). + s0, s1 = (THREE << 16) | ONE, (0xB400 << 16) | HALF + expect_lo = {(0, 0): 0xB800, (1, 0): 0xC100, (0, 1): 0xBD00, (1, 1): 0xC280} # -0.5, -2.5, -1.25, -3.25 + for h0 in (0, 1): + for h1 in (0, 1): + for dh in (0, 1): + want = expect_lo[(h0, h1)] + expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) + with self.subTest(op_sel=(h0, h1, dh)): + got = run(f"v_subrev_f16_e64 v0, v1, v2 op_sel:[{h0},{h1},{dh}]", {"v1": s0, "v2": s1}) + self.assertEqual(got, expect) + + def test_neg_and_abs_source_modifiers(self): + # v1 = 1.0, v2 = -0.5; (operand text, D) by hand + for ops, want in (("v1, v2", 0xBE00), ("-v1, v2", HALF), ("v1, -v2", 0xB800), ("|v1|, |v2|", 0xB800), + ("-|v1|, v2", HALF), ("v1, -|v2|", 0xBE00)): + with self.subTest(ops=ops): + got = run(f"v_subrev_f16_e64 v0, {ops}", {"v1": ONE, "v2": 0xB800}) + self.assertEqual(got & 0xFFFF, want) + + def test_output_modifiers_and_clamp(self): + # unmodified result: 2.5 - 0.5 = 2.0 (src1 - src0); mul/div scale it, clamp limits it to [0, 1] (negatives and NaN become +0) + for suffix, want in ((" mul:2", 0x4400), (" mul:4", 0x4800), (" div:2", ONE), (" clamp", ONE)): + with self.subTest(mod=suffix): + got = run("v_subrev_f16_e64 v0, v1, v2" + suffix, {"v1": HALF, "v2": 0x4100}) + self.assertEqual(got & 0xFFFF, want) + for (a, b), suffix, want in (((QUARTER, HALF), " clamp", QUARTER), ((ONE, HALF), " clamp", 0x0000), + ((0xB800, ONE), " div:2 clamp", 0x3A00), ((QUARTER, ONE), " mul:2 clamp", ONE)): + with self.subTest(a=hex(a), b=hex(b), mod=suffix): + self.assertEqual(run("v_subrev_f16_e64 v0, v1, v2" + suffix, {"v1": a, "v2": b}) & 0xFFFF, want) + for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): + got = run("v_subrev_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4900, "v2": 0xC100}) # 10 and -2.5 + self.assertEqual(got & 0xFFFF, scale(ref_subrev(0x4900, 0xC100), f)) + + def test_random_operands(self): + rng = random.Random(0x5B2E5) + pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] + for _ in range(120): + a = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) + b = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) + with self.subTest(a=hex(a), b=hex(b)): + got = run("v_subrev_f16 v0, v1, v2", {"v1": a, "v2": b}) + self.assertEqual(got >> 16, OLD >> 16) + self.assertTrue(same_f16(got & 0xFFFF, ref_subrev(a, b)), (hex(got), hex(ref_subrev(a, b)))) if __name__ == "__main__": diff --git a/tests/semantic/test_valu_untested_ops.py b/tests/semantic/test_valu_untested_ops.py new file mode 100644 index 000000000..3659349a4 --- /dev/null +++ b/tests/semantic/test_valu_untested_ops.py @@ -0,0 +1,105 @@ +"""Semantic interpreter tests for VALU ops that had no translation test. + +RDNA2 ISA definitions: + v_cmp__u64 / _i64 per lane, S0 S1 over 64-bit values, unsigned or signed (the signed order differs only + when the high words differ in bit 63); + v_cvt_f32_ubyte D = float(S0[8k+7:8k]); + v_lshlrev_b16 / v_lshrrev_b16 / v_ashrrev_i16 D[15:0] = S1.16 shifted by S0[3:0] (the amount wraps at 16, so + 16 shifts by 0); only the low half of D is checked here; + v_bcnt_u32_b32 D = popcount(S0) + S1 (32-bit wrap). +Each case runs a one-lane pixel shader through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py and compares +with plain-Python integer references written from the lines above. Compare results leave through v_cndmask_b32_e64. +""" +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) + +import spirv_mini_interp as si # noqa: E402 +import support # noqa: E402 + +M32 = 0xFFFFFFFF +M64 = (1 << 64) - 1 + + +def s64(x): + return x - (1 << 64) if x >> 63 else x + + +def s16(x): + x &= 0xFFFF + return x - 0x10000 if x & 0x8000 else x + + +def run(lines): + spv = support.translate_lines("ps_valu_untested", lines + ["exp mrt0 v10, v11, v12, v13 done vm", "s_endpgm"]) + return si.run_fragment(spv)["%out_mrt0"] + + +def regs(**kw): + out = [] + for name, val in kw.items(): + out += [f"s_mov_b32 s{name[1:]}, {val & M32:#x}", f"v_mov_b32 v{name[1:]}, s{name[1:]}"] + return out + + +class Cmp64(unittest.TestCase): + VALUES = [0, 1, M64, 1 << 63, (1 << 63) - 1, 1 << 32, 0xFFFFFFFF, 0x80000000, 0xFFFFFFFF00000000, + 0x00000001FFFFFFFF, 0x7FFFFFFF80000000, 0x123456789ABCDEF0] + CONDS = {"lt": lambda a, b: a < b, "le": lambda a, b: a <= b, "gt": lambda a, b: a > b, + "ge": lambda a, b: a >= b, "eq": lambda a, b: a == b, "ne": lambda a, b: a != b} + + def test_all(self): + for cond, fn in self.CONDS.items(): + for ty in ("u64", "i64"): + for x in self.VALUES: + for y in self.VALUES: + a, b = (x, y) if ty == "u64" else (s64(x), s64(y)) + lines = (regs(v2=x & M32, v3=x >> 32, v4=y & M32, v5=y >> 32) + + ["v_mov_b32 v10, 0", "v_mov_b32 v11, 0", "v_mov_b32 v12, 0", "v_mov_b32 v13, 0", + "v_mov_b32 v14, 1", f"v_cmp_{cond}_{ty}_e64 s20, v[2:3], v[4:5]", + "v_cndmask_b32_e64 v10, v10, v14, s20"]) + with self.subTest(cond=cond, ty=ty, x=hex(x), y=hex(y)): + self.assertEqual(run(lines)[0], int(fn(a, b))) + + +class Misc(unittest.TestCase): + def one(self, op, srcs, old=0, mods=""): + regs_ = [] + for i, v in enumerate(srcs): + regs_ += [f"s_mov_b32 s{2 + i}, {v & M32:#x}", f"v_mov_b32 v{2 + i}, s{2 + i}"] + lines = regs_ + [f"s_mov_b32 s9, {old:#x}", "v_mov_b32 v10, s9", "v_mov_b32 v11, 0", "v_mov_b32 v12, 0", + "v_mov_b32 v13, 0", f"{op} v10, " + ", ".join(f"v{2 + i}" for i in range(len(srcs))) + mods] + return run(lines)[0] + + def test_cvt_f32_ubyte(self): + for x in (0, M32, 0x80402010, 0x01FF7F80, 0x12345678): + for k in range(4): + e = struct.unpack("> (8 * k)) & 0xFF)))[0] + with self.subTest(k=k, x=hex(x)): + self.assertEqual(self.one(f"v_cvt_f32_ubyte{k}", [x]), e) + + def test_shifts_b16(self): + for x in (0, 1, 0x8000, 0xFFFF, 0x7FFF, 0xA5C3): + for s in (0, 1, 15, 16, 17, 31, 0xFFF0, 0x12340010): + old = 0xABCD0000 + x16 = x & 0xFFFF + cases = {"v_lshlrev_b16": (x16 << (s & 15)) & 0xFFFF, "v_lshrrev_b16": x16 >> (s & 15), + "v_ashrrev_i16": (s16(x16) >> (s & 15)) & 0xFFFF} + for op, lo in cases.items(): + with self.subTest(op=op, x=hex(x), s=hex(s)): + self.assertEqual(self.one(op, [s, x], old=old) & 0xFFFF, lo) + + def test_bcnt(self): + for x in (0, 1, M32, 0x80000000, 0x12345678): + for c in (0, 5, M32): + with self.subTest(x=hex(x), c=hex(c)): + self.assertEqual(self.one("v_bcnt_u32_b32", [x, c]), (bin(x).count("1") + c) & M32) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_value_semantics.py b/tests/semantic/test_value_semantics.py index 1c0999013..b15527f0a 100644 --- a/tests/semantic/test_value_semantics.py +++ b/tests/semantic/test_value_semantics.py @@ -825,6 +825,8 @@ class MeasuredBoundsShaders(unittest.TestCase): "cs_smem_stride_align": [0x5EED0010, 0, 0, 0x5EED0000, 0x5EED0000, 0x5EED0000, 0x5EED0000, 0x5EED0004], "cs_smem_sload_neg": [0x5EED0004, 0x5EED0000, 0x5EED0004, 0x5EED0004, 0x5EED0008, 0x5EED000C, 0xEEEEEEEE, 0xEEEEEEEE], + # SHADER-328: constant and run-time SGPR offsets agree; out[4..7] are not written (heap fill) + "cs_smem_sconst_off": [0, 0x5EED0018, 0x5EED0018, 0x5EED0014, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE], "cs_buf_tail": [0, 0x5EED000C, 0x5EED0008, 0x5EED000C, 0, 0, 0x5EED0010, 0], "cs_oob_select": [0x5EED000C, 0, 0x5EED0014, 0, 0x5EED0018, 0xEEEEEEEE, 0, 0], "cs_oob_tail": [0, 0, 0x5EED0010, 0, 0xBEEF0000, 0xEEEEEEEE, 0, 0x5EED0010], diff --git a/tests/semantic/test_vcmp64_null_src.py b/tests/semantic/test_vcmp64_null_src.py new file mode 100644 index 000000000..c9ca51239 --- /dev/null +++ b/tests/semantic/test_vcmp64_null_src.py @@ -0,0 +1,109 @@ +"""RDNA2 null reads zero in either 64-bit integer VALU compare source.""" +import itertools +import struct +import unittest + +import support +import spirv_mini_interp as si + +CONDITIONS = ("eq", "ne", "lt", "le", "gt", "ge") +VALUES = (0, 1, 1 << 32, 1 << 63, (1 << 64) - 1) + + +def reference(cond, ty, x, y): + if ty == "i64": + x, y = (v - (1 << 64) if v >> 63 else v for v in (x, y)) + return {"eq": x == y, "ne": x != y, "lt": x < y, "le": x <= y, + "gt": x > y, "ge": x >= y}[cond] + + +def run_compare(cond, ty, form, cmpx, sources, value=0, inactive=False): + op = f"v_cmp{'x' if cmpx else ''}_{cond}_{ty}_{form}" + operands = ", ".join(sources) + if not cmpx: + operands = "vcc_lo, " + operands + lines = [f"v_mov_b32 v2, {value & 0xFFFFFFFF:#x}", f"v_mov_b32 v3, {value >> 32:#x}", + "s_mov_b32 vcc_lo, -1"] + if inactive: + lines.append("s_mov_b32 exec_lo, 0") + lines += [f"{op} {operands}", "v_cndmask_b32 v0, 0, 1, vcc_lo", + "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] + return si.run_fragment(support.translate_lines("ps_vcmp64_null", lines)).get("%out_mrt0") + + +class CompareNullSources(unittest.TestCase): + def check_sources(self, cmpx): + for cond, ty, (form, slot), value in itertools.product( + CONDITIONS, ("u64", "i64"), (("e32", 0), ("e64", 0), ("e64", 1)), VALUES): + with self.subTest(cond=cond, ty=ty, form=form, slot=slot, value=hex(value)): + sources = ["v[2:3]", "v[2:3]"] + sources[slot] = "null" + x, y = (0, value) if slot == 0 else (value, 0) + expected = reference(cond, ty, x, y) + result = run_compare(cond, ty, form, cmpx, sources, value) + if cmpx: + self.assertEqual(result, (1, 1, 1, 1) if expected else None) + else: + self.assertEqual(result, (int(expected),) * 4) + + def test_vcmp_sources(self): + self.check_sources(False) + + def test_vcmpx_sources(self): + self.check_sources(True) + + def test_vcmpx_mixed_lanes_preserve_vcc(self): + lanes = 32 + vcc = 0x96A53C69 + fssm = bytearray(0x148) + struct.pack_into("<4I", fssm, 0x138, 0x8088, lanes, 1, 1) + for ty, slot in itertools.product(("u64", "i64"), (0, 1)): + with self.subTest(ty=ty, slot=slot): + cond = ("lt" if slot == 0 else "gt") if ty == "u64" else ("gt" if slot == 0 else "lt") + sources = ["v[2:3]", "v[2:3]"] + sources[slot] = "null" + lines = ["v_and_b32 v2, 1, v0", + "v_mov_b32 v3, 0" if ty == "u64" else "v_lshlrev_b32 v3, 31, v2", + f"s_mov_b32 vcc_lo, {vcc:#x}", + f"v_cmpx_{cond}_{ty}_e64 {', '.join(sources)}", + "s_mov_b32 s8, exec_lo", "s_mov_b32 s9, vcc_lo", + "s_mov_b32 exec_lo, -1", + "v_cndmask_b32_e64 v4, 0, 1, s8", "v_cndmask_b32_e64 v5, 0, 1, s9", + "v_lshlrev_b32 v6, 3, v0", + "buffer_store_dword v4, v6, s[0:3], 0 offen", + "buffer_store_dword v5, v6, s[0:3], 4 offen", "s_endpgm"] + spv = support.translate_lines("cs_vcmp64_null_masks", lines, fssm=bytes(fssm)) + got = si.run_workgroup( + spv, lanes, 32, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, memory={}) + values = [(i & 1) if ty == "u64" else ((1 << 63) + 1 if i & 1 else 0) + for i in range(lanes)] + operands = [(0, value) if slot == 0 else (value, 0) for value in values] + mask = sum(1 << i for i, (x, y) in enumerate(operands) if reference(cond, ty, x, y)) + self.assertNotIn(mask, (0, (1 << lanes) - 1, vcc)) + expected = {8 * i + offset: value for i in range(lanes) + for offset, value in ((0, (mask >> i) & 1), (4, (vcc >> i) & 1))} + self.assertEqual(got, expected) + + def test_both_null(self): + for cond, ty, cmpx in itertools.product(CONDITIONS, ("u64", "i64"), (False, True)): + with self.subTest(cond=cond, ty=ty, cmpx=cmpx): + expected = reference(cond, ty, 0, 0) + result = run_compare(cond, ty, "e64", cmpx, ["null", "null"]) + self.assertEqual(result, ((1,) * 4 if expected else None) if cmpx else (int(expected),) * 4) + + def test_inactive_lane_stays_inactive(self): + for cond, ty, cmpx in itertools.product(CONDITIONS, ("u64", "i64"), (False, True)): + with self.subTest(cond=cond, ty=ty, cmpx=cmpx): + self.assertIsNone(run_compare(cond, ty, "e64", cmpx, ["null", "v[2:3]"], inactive=True)) + + def test_non_pair_register_stays_unsupported(self): + for cond, cmpx in itertools.product(CONDITIONS, (False, True)): + with self.subTest(cond=cond, cmpx=cmpx): + with self.assertRaises(support.rdna2spirv.Unsupported): + run_compare(cond, "u64", "e64", cmpx, ["null", "v2"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_vcmp_f32_predicates.py b/tests/semantic/test_vcmp_f32_predicates.py new file mode 100644 index 000000000..3211df294 --- /dev/null +++ b/tests/semantic/test_vcmp_f32_predicates.py @@ -0,0 +1,103 @@ +"""All 16 binary32 vector compares, v_cmp_*_f32 and v_cmpx_*_f32, including the negated ones, on NaN, infinity and -0. + +RDNA2 ISA (VOPC), per lane, with unordered = either source is a NaN (quiet or signaling): + F = 0, TRU = 1, O = ordered, U = unordered; + LT, EQ, LE, GT, GE and LG (S0 < S1 or S0 > S1) are false when unordered, and -0 equals +0; + NGE, NLG, NGT, NLE, NEQ, NLT are the logical negations of GE, LG, GT, LE, EQ, LT, so they are TRUE when unordered. +v_cmp writes the result to VCC (e32) or an SGPR pair (e64) and v_cmpx writes EXEC; v_cmpx is checked by the lanes it +leaves active. VOP3 abs and neg act on the sources before the compare (so -|NaN| is still a NaN). +Expected values come from the Python predicates below, not from the translator. Each case translates a one-lane pixel +shader with tools/rdna2spirv.py and runs it in tests/semantic/spirv_mini_interp.py. +""" +import itertools +import math +import os +import struct +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +sys.path.insert(0, HERE) + +import spirv_mini_interp as si # noqa: E402 +import support # noqa: E402 + +PREDS = { + "f": lambda a, b: False, + "tru": lambda a, b: True, + "o": lambda a, b: not (math.isnan(a) or math.isnan(b)), + "u": lambda a, b: math.isnan(a) or math.isnan(b), + "lt": lambda a, b: a < b, + "eq": lambda a, b: a == b, + "le": lambda a, b: a <= b, + "gt": lambda a, b: a > b, + "ge": lambda a, b: a >= b, + "lg": lambda a, b: a < b or a > b, + "nlt": lambda a, b: not a < b, + "neq": lambda a, b: not a == b, + "nle": lambda a, b: not a <= b, + "ngt": lambda a, b: not a > b, + "nge": lambda a, b: not a >= b, + "nlg": lambda a, b: not (a < b or a > b), +} +# Bit patterns: -inf, -1, -0, +0, +1, 1+ulp, +inf, quiet NaN (both signs), signaling NaN. +VALUES = [0xFF800000, 0xBF800000, 0x80000000, 0x00000000, 0x3F800000, 0x3F800001, 0x7F800000, + 0x7FC00000, 0xFFC00000, 0x7F800001] + + +def f32(bits): + return struct.unpack(" [1 (end), 2]) and inside a header-exit loop: + # cfg_structure.structure hoists spine guards into the enclosing list where skip_pc holds the early-exit + # target. _unwrap_known_pc_guards must coalesce and unwrap all hoisted post-dominating spine guards. + import cfg_structure + succ_early = [[1, 2], []] # block 0 -> early exit 1 or main body 2 + cur = 2 + for _ in range(10): + succ_early.append([cur + 1, cur + 2]) + succ_early.append([cur + 2]) + cur += 2 + succ_early.append([]) + raw_tree = cfg_structure.structure(succ_early) + out_pcs = {b: (frozenset(s) if s else frozenset({-1})) for b, s in enumerate(succ_early)} + unwrapped_tree = wave64_emulate_opt._unwrap_known_pc_guards(raw_tree, out_pcs, 0) + + def count_guards(t): + c = 0 + st = [t] + while st: + for item in st.pop(): + if item[0] == "guard": + c += 1 + st.append(item[2]) + elif item[0] == "loop": + st.append(item[2]) + return c + + # Raw tree has 22 guards (guard 1, guard 2, plus 10 arm guards and 10 hoisted spine guards); + # coalesced unwrap removes all 10 hoisted spine guards -> 12 guards. + self.assertEqual(count_guards(raw_tree), 22) + self.assertEqual(count_guards(unwrapped_tree), 12) + if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_wave64_halves.py b/tests/semantic/test_wave64_halves.py index ff2c1ef73..c5ea021d7 100644 --- a/tests/semantic/test_wave64_halves.py +++ b/tests/semantic/test_wave64_halves.py @@ -95,6 +95,22 @@ def out_param(words, k=0): return result +# ---- the early exit of a pixel kill ------------------------------------------------------------------------------ +KILL = ["s_mov_b64 s[20:21], exec", "v_cmp_gt_u32_e32 vcc, 40, v0", "s_andn2_b64 s[20:21], s[20:21], vcc"] +RUN_WQM = ["s_wqm_b64 s[22:23], s[20:21]", "s_and_b64 exec, exec, s[22:23]"] +EXIT_PS = ["s_mov_b64 exec, s[20:21]", "exp null off, off, off, off done vm", "s_endpgm"] +EXIT_VS = ["s_mov_b64 exec, s[20:21]", "exp pos0 v5, v5, v5, v5 done", "s_endpgm"] + + +def kill(head, run, exit_, stage="ps", vote="s_cbranch_scc0"): + """head, a branch to the exit when the live mask is empty, the run side and the epilogue, then the exit.""" + epi = EPI_PS if stage == "ps" else EPI_VS + tail = run + epi + hop = sum(size(t) for t in tail) // 4 + return PRO + ["v_mov_b32_e32 v6, 0", "v_mov_b32_e32 v7, 0", "v_mov_b32_e32 v5, 0"] + head + \ + [f"{vote} {hop}"] + tail + exit_ + + class Classification(unittest.TestCase): def tier(self, name, lines, tier, reasons=None, idioms=None, contains=None): (t, r, i), _ = meta_of(name, lines) @@ -170,6 +186,99 @@ class Classification(unittest.TestCase): self.tier("ps_b_spill", ps(["v_writelane_b32 v20, s4, 3", "v_readlane_b32 s21, v20, 3", "v_add_nc_u32_e32 v6, s21, v0"]), "B", [], ["lane-spill"]) + def test_b_spill_and_reload_upper_half_lane_40(self): + # Pure scalar spill into lanes 32..63 (v20 is never read as a vector operand): lowered to a parked scalar + # slot so SGPR spills past lane 31 are exact on 32-wide subgroups (tier B). + self.tier("ps_b_spill_hi", ps([ + "v_writelane_b32 v20, s4, 40", "v_writelane_b32 v20, s5, 63", + "v_readlane_b32 s21, v20, 40", "v_readlane_b32 s22, v20, 63", + "s_add_u32 s23, s21, s22", "v_add_nc_u32_e32 v6, s23, v0"]), "B", [], ["lane-spill"]) + + def test_c_spill_in_divergent_vote_branch_is_stale_scalar(self): + # Spilling to lane 40 behind a wave-wide vote and reading outside must stay tier C (stale-scalar). + # v_writelane_b32 is an 8-byte VOP3 instruction (2 dwords). + self.tier("ps_c_spill_stale", ps([ + "v_writelane_b32 v20, s4, 40", "v_cmp_eq_u32_e32 vcc, 0, v0", "s_cbranch_vccz 2", + "v_writelane_b32 v20, s5, 40", "v_readlane_b32 s21, v20, 40", + "v_mov_b32_e32 v6, s21"]), "C", contains=["stale-scalar"]) + + def test_c_spill_of_tainted_count_stays_tier_c(self): + # Spilling a tainted scalar (lane-count) into lane 40 and reloading must still report lane-count. + self.tier("ps_c_spill_cnt", ps([ + "v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s6, vcc", + "v_writelane_b32 v20, s6, 40", "v_readlane_b32 s21, v20, 40", + "v_mov_b32_e32 v6, s21"]), "C", ["lane-count"]) + + def test_b_readfirstlane_uniform_inside_narrowed_exec(self): + # v5 written from a scalar inside a narrowed EXEC block is uniform across all active lanes, + # so v_readfirstlane_b32 inside that block is exact (tier B). + self.tier("ps_b_rfl_narrow", ps([ + "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", + "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, s4", + "v_readfirstlane_b32 s20, v5", "v_add_nc_u32_e32 v6, s20, v0", + "s_or_b64 exec, exec, s[12:13]"]), "B", [], ["readfirstlane-uniform"]) + + def test_c_readfirstlane_after_exec_restore_not_uniform(self): + # Writing v5 from a scalar under narrowed EXEC and reading after EXEC restore is NOT uniform (tier C). + self.tier("ps_c_rfl_after_restore", ps([ + "v_mov_b32_e32 v5, v0", "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", + "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, s4", + "s_or_b64 exec, exec, s[12:13]", "v_readfirstlane_b32 s20, v5", + "v_mov_b32_e32 v6, s20"]), "C") + + def test_c_readfirstlane_active_uniform_scalar_escapes_after_restore(self): + # Reading v5 inside narrowed EXEC produces lane-0's old value in a half where EXEC == 0; + # using that scalar after EXEC restore escapes the mask and must stay tier C (PR #2469 review). + self.tier("ps_c_rfl_escape", ps([ + "v_mov_b32_e32 v5, 7", "v_cmp_eq_u32_e32 vcc, 33, v0", + "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, 50", + "v_readfirstlane_b32 s20, v5", "s_mov_b64 exec, s[10:11]", + "v_mov_b32_e32 v6, s20"]), "C", contains=["cross-lane"]) + + def test_c_nonlinear_count_scaling_refused(self): + # Count as shift distance (1 << count) and 24-bit truncating multiply (v_mul_u32_u24) are nonlinear + # and must NOT qualify for wave-aggregated atomics (PR #2469 review). + self.tier("ps_c_atomic_shift_dist", ps([ + "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", + "s_bcnt1_i32_b64 s6, exec", "s_lshl_b32 s6, 1, s6", + "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", + "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, s6", + "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", "s_or_b64 exec, exec, s[14:15]", + "v_readfirstlane_b32 s7, v11", "v_add_nc_u32_e32 v13, s7, v10", "v_lshlrev_b32_e32 v13, 2, v13", + "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256", "s_mov_b64 exec, s[10:11]"]), "C", + contains=["lane-count"]) + self.tier("ps_c_atomic_mul_u24", ps([ + "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", + "s_bcnt1_i32_b64 s6, exec", "s_mul_i32 s6, s6, 0x100000", + "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", + "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v15, s6", + "v_mul_u32_u24_e32 v11, 1, v15", + "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", "s_or_b64 exec, exec, s[14:15]", + "v_readfirstlane_b32 s7, v11", "v_add_nc_u32_e32 v13, s7, v10", "v_lshlrev_b32_e32 v13, 2, v13", + "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256", "s_mov_b64 exec, s[10:11]"]), "C", + contains=["lane-count"]) + + def test_b_scaled_aggregated_atomic_and_global_atomic_add(self): + # Stride-scaled s_bcnt1 (s_lshl_b32 by 2 = 4 bytes/lane) in buffer_atomic_add and global_atomic_add. + self.tier("ps_b_atomic_scaled", ps([ + "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", + "s_bcnt1_i32_b64 s6, exec", "s_lshl_b32 s6, s6, 2", + "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", + "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, s6", + "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", "s_or_b64 exec, exec, s[14:15]", + "v_readfirstlane_b32 s7, v11", "v_lshlrev_b32_e32 v13, 2, v10", "v_add_nc_u32_e32 v13, s7, v13", + "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256", "s_mov_b64 exec, s[10:11]"]), "B", [], + ["aggregated-atomic", "elected-lane"]) + # global_atomic_add with glc has operand order (vdst, vaddr, vdata, saddr). + self.tier("ps_b_global_atomic", ps([ + "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", + "s_bcnt1_i32_b64 s6, exec", "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", + "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, s6", + "v_mov_b32_e32 v12, 0", "global_atomic_add v14, v12, v11, s[4:5] glc", "s_or_b64 exec, exec, s[14:15]", + "v_readfirstlane_b32 s7, v14", "v_add_nc_u32_e32 v13, s7, v10", "v_lshlrev_b32_e32 v13, 2, v13", + "global_store_dword v13, v0, s[4:5]", "s_mov_b64 exec, s[10:11]"]), "B", [], + ["aggregated-atomic", "elected-lane"]) + # -- tier C: each near miss of the idioms above def test_c_lane_count_exported(self): self.tier("ps_c_cnt", ps(["v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s6, vcc", "v_mov_b32_e32 v6, s6"]), @@ -361,6 +470,43 @@ class Execution(unittest.TestCase): self.assertEqual(whole, halves) self.assertEqual([w[0] for w in whole], [9 + k for k in range(64)]) + def test_b_spill_upper_half_lane_40_and_63_invariant(self): + # Lanes 40 and 63 do not exist on a 32-lane subgroup: parked scalar slots keep 64-lane and 2x32-lane exact. + tier, whole, halves = self.run_both("vs_b_spill_hi", vs([ + "v_writelane_b32 v20, s4, 40", "v_writelane_b32 v20, s5, 63", + "v_readlane_b32 s21, v20, 40", "v_readlane_b32 s22, v20, 63", + "s_add_u32 s23, s21, s22", "v_add_nc_u32_e32 v6, s23, v0"]), + push=[0, 0, 0, 0, 100, 23]) + self.assertEqual(tier, "B") + self.assertEqual(whole, halves) + self.assertEqual([w[0] for w in whole], [123 + k for k in range(64)]) + + def test_b_readfirstlane_uniform_under_narrowed_exec_invariant(self): + # Also test with only lane 33 active (lower half has empty EXEC): using s20 ONLY inside the + # narrowed block keeps 64-lane and 2x32-lane outputs identical. + tier, whole, halves = self.run_both("vs_b_rfl_narrow", vs([ + "v_mov_b32_e32 v5, 7", "v_cmp_eq_u32_e32 vcc, 33, v0", + "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, s4", + "v_readfirstlane_b32 s20, v5", "v_add_nc_u32_e32 v6, s20, v0", + "s_mov_b64 exec, s[10:11]"]), + push=[0, 0, 0, 0, 50]) + self.assertEqual(tier, "B") + self.assertEqual(whole, halves) + self.assertEqual([w[0] for w in whole], [83 if k == 33 else 0 for k in range(64)]) + + def test_c_readfirstlane_escape_after_restore_differs(self): + # Same narrowed-EXEC readfirstlane, but s20 escapes past EXEC restore: lower half gets lane-0 + # fallback (7) while upper half gets 50, so it MUST classify C. + tier, whole, halves = self.run_both("vs_c_rfl_escape", vs([ + "v_mov_b32_e32 v5, 7", "v_cmp_eq_u32_e32 vcc, 33, v0", + "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, 50", + "v_readfirstlane_b32 s20, v5", "s_mov_b64 exec, s[10:11]", + "v_mov_b32_e32 v6, s20"])) + self.assertEqual(tier, "C") + self.assertNotEqual(whole, halves) + self.assertEqual([w[0] for w in whole], [50] * 64) + self.assertEqual([w[0] for w in halves], [7] * 32 + [50] * 32) + def test_c_lane_count_differs(self): tier, whole, halves = self.run_both("vs_c_cnt", vs([ "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_bcnt1_i32_b64 s6, vcc", @@ -660,6 +806,126 @@ class SccVotePolarity(unittest.TestCase): "v_add_nc_u32_e32 v6, 3, v0", "s_mov_b64 exec, s[10:11]"]), "C", contains=["unsafe-vote-branch"]) +class KillExit(unittest.TestCase): + """The early exit of a pixel kill (`s_andn2_b64 live, live, exec/vcc`, `s_cbranch_scc0` to a block that only + empties EXEC from that mask, exports and ends): a half whose live mask is empty writes nothing there, and in the + wave its lanes stay off on the run side to the end. Tier A only when the exit is inert, the run side narrows EXEC + into the mask's quads before anything else and never widens it, and the vote is the mask's own.""" + tier = Classification.tier + run_both = Execution.run_both + + # -- tier A + def test_a_kill_wqm_and_exec(self): + self.tier("ps_kill_wqm", kill(KILL, RUN_WQM + ["v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), "A", [], []) + + def test_a_kill_cmpx_wqm_mov_exec(self): + self.tier("ps_kill_cmpx", kill( + ["s_mov_b64 s[20:21], exec", "v_cmpx_gt_u32_e32 40, v0", "s_andn2_b64 s[20:21], s[20:21], exec"], + ["s_wqm_b64 s[22:23], s[20:21]", "s_mov_b64 exec, s[22:23]", "v_add_nc_u32_e32 v6, 3, v0"], + EXIT_PS), "A", [], []) + + def test_a_kill_direct_narrowing(self): + for name, run in (("ps_kill_and", ["s_and_b64 exec, exec, s[20:21]"]), + ("ps_kill_mov", ["s_mov_b64 exec, s[20:21]"]), + ("ps_kill_wqm_exec", ["s_wqm_b64 exec, s[20:21]"])): + self.tier(name, kill(KILL, run + ["v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), "A", [], []) + self.tier("ps_kill_exit0", kill(KILL, RUN_WQM, ["s_mov_b64 exec, 0"] + EXIT_PS[1:]), "A", [], []) + + def test_a_kill_then_if_endif(self): + # a saveexec / restore pair after the narrowing restores a mask taken inside it: EXEC stays in the quads + self.tier("ps_kill_if", kill(KILL, RUN_WQM + [ + "v_cmp_eq_u32_e32 vcc, 1, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_cbranch_execz 1", + "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[12:13]"], EXIT_PS), "A", [], []) + + def test_a_kill_saveexec_first(self): + # the run side's first narrowing is a SAVEEXEC: EXEC = wqm mask & EXEC (inside), s[30:31] = the old EXEC + self.tier("ps_kill_saveexec", kill(KILL, ["s_wqm_b64 s[22:23], s[20:21]", "s_and_saveexec_b64 s[30:31], " + "s[22:23]", "v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), "A", [], []) + + # -- near misses: tier C unsafe-vote-branch + def test_c_exit_with_code_of_its_own(self): + for name, exit_ in ( + ("ps_kill_exit_vmov", ["v_mov_b32_e32 v6, 1"] + EXIT_PS), + ("ps_kill_exit_exp_first", ["exp mrt0 v6, v7, v5, v5 done vm", "s_mov_b64 exec, s[20:21]", + "s_endpgm"]), + ("ps_kill_exit_store", EXIT_PS[:1] + ["buffer_store_dword v6, v5, s[0:3], 0 offen"] + EXIT_PS[1:]), + ("ps_kill_exit_sgpr", EXIT_PS[:1] + ["s_mov_b32 s5, 1"] + EXIT_PS[1:]), + ("ps_kill_exit_other_mask", ["s_mov_b64 exec, s[10:11]"] + EXIT_PS[1:]), + ("ps_kill_exit_jumps_back", EXIT_PS[:2] + ["s_branch -8"])): # into the run side's s_and + self.tier(name, kill(KILL, RUN_WQM, exit_), "C", contains=["unsafe-vote-branch"]) + + def test_c_run_side_does_not_narrow(self): + self.tier("ps_kill_run_code", kill(KILL, ["v_mov_b32_e32 v6, 5"] + RUN_WQM, EXIT_PS), + "C", contains=["unsafe-vote-branch"]) + self.tier("ps_kill_run_other", kill(KILL, ["s_and_b64 exec, exec, s[10:11]"], EXIT_PS), + "C", contains=["unsafe-vote-branch"]) + + def test_c_saveexec_that_does_not_narrow(self): + # s_or_saveexec: EXEC = mask | EXEC, not inside; restoring the saved (old) EXEC widens again + self.tier("ps_kill_or_saveexec", kill(KILL, ["s_wqm_b64 s[22:23], s[20:21]", "s_or_saveexec_b64 s[30:31], " + "s[22:23]", "v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), + "C", contains=["unsafe-vote-branch"]) + self.tier("ps_kill_saveexec_restore", kill(KILL, ["s_wqm_b64 s[22:23], s[20:21]", "s_and_saveexec_b64 " + "s[30:31], s[22:23]", "s_mov_b64 exec, s[30:31]", + "v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), + "C", contains=["unsafe-vote-branch"]) + + def test_c_run_side_widens_again(self): + self.tier("ps_kill_widen", kill(KILL, RUN_WQM + ["s_mov_b64 exec, s[10:11]", "v_mov_b32_e32 v6, 9"], + EXIT_PS), "C", contains=["unsafe-vote-branch"]) + self.tier("ps_kill_or", kill(KILL, RUN_WQM + ["s_or_b64 exec, exec, s[10:11]"], EXIT_PS), + "C", contains=["unsafe-vote-branch"]) + + def test_c_mask_redefined_or_not_the_vote(self): + # the mask is rewritten after the vote (s_mov leaves SCC alone): the exit reads another value + self.tier("ps_kill_redef", kill(KILL + ["s_mov_b64 s[20:21], exec"], RUN_WQM, EXIT_PS), + "C", contains=["unsafe-vote-branch"]) + # SCC = (mask == 0): the branch to the "exit" is taken when the mask is not empty + self.tier("ps_kill_cmp_eq", kill(KILL + ["s_cmp_eq_u64 s[20:21], 0"], RUN_WQM, EXIT_PS), + "C", contains=["unsafe-vote-branch"]) + + def test_c_vm_export_before_the_vote(self): + self.tier("ps_kill_vm_first", kill(["exp mrt1 v6, v7, v5, v5 vm"] + KILL, RUN_WQM, EXIT_PS), + "C", contains=["unsafe-vote-branch"]) + + def test_shared_exit_of_two_kills_stays_c(self): + # conservative: the exit sets EXEC from a live mask the second kill redefined behind the first vote (stale) + second = ["v_cmp_gt_u32_e32 vcc, 50, v0", "s_andn2_b64 s[20:21], s[20:21], vcc"] + run = RUN_WQM + second + ["s_cbranch_scc0 5"] + RUN_WQM + self.tier("ps_kill_shared", kill(KILL, run, EXIT_PS), "C", contains=["tainted-exec"]) + + def test_mov_of_a_mask_is_not_a_vote(self): + # s_mov_b64 writes no SCC: the branch reads the lane-count compare before it, not a vote on the copy + self.tier("ps_mov_scc", ps([ + "v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s6, vcc", "s_cmp_eq_u32 s6, 5", + "s_mov_b64 s[24:25], vcc", "s_cbranch_scc0 3", "s_and_saveexec_b64 s[16:17], s[24:25]", + "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[16:17]"]), "C", contains=["lane-count"]) + + # -- execution: vertex shaders, 64 lanes against two halves of 32 (vertices < 40 killed: all of the first half) + def test_kill_exit_invariant(self): + tier, whole, halves = self.run_both("vs_kill", kill(KILL, RUN_WQM + [ + "v_mul_u32_u24_e32 v6, 3, v0", "v_mov_b32_e32 v7, 1"], EXIT_VS, "vs")) + self.assertEqual(tier, "A") + self.assertEqual(whole, halves) + # a vertex that is off writes nothing: the interpreter's outputs start at zero + self.assertEqual([w[:2] for w in whole], [(0, 0)] * 40 + [(3 * k, 1) for k in range(40, 64)]) + + def test_kill_exit_saveexec_invariant(self): + tier, whole, halves = self.run_both("vs_kill_saveexec", kill(KILL, [ + "s_wqm_b64 s[22:23], s[20:21]", "s_and_saveexec_b64 s[30:31], s[22:23]", + "v_mul_u32_u24_e32 v6, 3, v0", "v_mov_b32_e32 v7, 1"], EXIT_VS, "vs")) + self.assertEqual(tier, "A") + self.assertEqual(whole, halves) + self.assertEqual([w[:2] for w in whole], [(0, 0)] * 40 + [(3 * k, 1) for k in range(40, 64)]) + + def test_kill_exit_that_widens_differs_and_is_c(self): + tier, whole, halves = self.run_both("vs_kill_widen", kill(KILL, RUN_WQM + [ + "s_mov_b64 exec, s[10:11]", "v_mul_u32_u24_e32 v6, 3, v0", "v_mov_b32_e32 v7, 1"], EXIT_VS, "vs")) + self.assertEqual(tier, "C") + self.assertEqual([w[:2] for w in whole], [(3 * k, 1) for k in range(64)]) + self.assertEqual([w[:2] for w in halves[:32]], [(0, 0)] * 32) # the first half took the exit + + class Refusal(unittest.TestCase): def test_error_mode_refuses_tier_c(self): old = rdna2spirv.WAVE64_GRAPHICS @@ -715,5 +981,101 @@ class GeometryRing(unittest.TestCase): "ds_write2_b32 v14, v14, v14 offset0:0 offset1:1"]), ("C", ["lane-id"])) + + +def _ps_xy(lane): + """8x8 2x2-quad pixel coordinates per lane: lane 4k+{0,1,2,3} is TL, TR, BL, BR.""" + q, c = divmod(lane, 4) + return 2 * (q % 4) + (c & 1), 2 * (q // 4) + (c >> 1) + + +_SWIZZLE_OFFSETS = { + "offset:0x801b": "offset:swizzle(QUAD_PERM,3,2,1,0)", + "offset:0x41f": "offset:swizzle(SWAP,1)", + "offset:0x401f": "offset:swizzle(SWAP,16)", + "offset:0x1c": "offset:swizzle(BROADCAST,4,0)", +} + + +def _load_ps_w64_lines(name): + asm_path = os.path.join(os.path.dirname(HERE), "..", "runtime", "test", "shaders", f"{name}.asm") + out = [] + with open(asm_path, encoding="utf-8") as f: + for raw in f: + line = raw.strip() + if not line or line.startswith(";"): + continue + for hex_off, sym_off in _SWIZZLE_OFFSETS.items(): + line = line.replace(hex_off, sym_off) + out.append(line) + return out + + +def _run_ps_cut(asm, wave, push=None, memory=None): + words = [] + for half in range(64 // wave): + base = half * wave + res = wi.run_wave( + asm, + wave=wave, + push_constants=push, + inputs={0: lambda lane, b=base: ((_ps_xy(b + lane)[0] + 0.5) / 64.0, + (_ps_xy(b + lane)[1] + 0.5) / 64.0, 0.0, 0.0)}, + memory=memory, + ) + for o in res["outputs"]: + if o is None: # a killed lane exports nothing; the attachment keeps its clear value + words.append(None) + continue + mrt = o["%out_mrt0"] + words.append(tuple(v.bits if isinstance(v, wi.F) else v for v in mrt)) + return words + + +class PixelShaders(unittest.TestCase): + """TEST-722: run every runtime/test/shaders/ps_w64_*.asm fixture on spirv_wave_interp (wave 64 vs 2x32).""" + + def test_ps_w64_fixtures(self): + sys.path.insert(0, os.path.join(HERE, "..", "..", "runtime", "test", "shaders")) + import w64_graphics as wg + + ps_names = sorted(n for n in wg.FIXTURES if n.startswith("ps_w64_")) + self.assertGreaterEqual(len(ps_names), 17) # 17 when TEST-722 landed; new fixtures run here too + for name in ps_names: + with self.subTest(fixture=name): + ref_tier, ref_fn, env = wg.FIXTURES[name] + (tier, _, _), asm = meta_of(name, _load_ps_w64_lines(name)) + self.assertEqual(tier, ref_tier) + push = [int(x, 0) for x in env["VKH_SGPRS"].split(",")] if "VKH_SGPRS" in env else None + mem64 = {0: 0} if "VKH_HEAP" in env else None + mem32 = {0: 0} if "VKH_HEAP" in env else None + w64 = _run_ps_cut(asm, 64, push=push, memory=mem64) + for lane in range(64): + x, y = _ps_xy(lane) + exp = ref_fn(y * 64 + x) + if w64[lane] is None: + self.assertEqual(exp, (wg.CLEAR,) * 4, f"{name} wave64 lane {lane} was killed") + continue + for c in range(4): + if exp[c] is not None: + self.assertEqual(w64[lane][c], exp[c], f"{name} wave64 lane {lane} c{c}") + if name == "ps_w64_c_readlane": + with self.assertRaises(wi.UnsupportedConstruct): + _run_ps_cut(asm, 32, push=push) + continue + w32 = _run_ps_cut(asm, 32, push=push, memory=mem32) + if tier in ("A", "B"): + self.assertEqual(w32, w64) + else: + self.assertNotEqual(w32, w64) + if "VKH_HEAP" in env: + self.assertEqual(mem64[0], 16) + self.assertEqual(mem32[0], 16) + slots64 = {mem64[0x100 + 4 * k] for k in range(16)} + slots32 = {mem32[0x100 + 4 * k] for k in range(16)} + self.assertEqual(len(slots64), 16) + self.assertEqual(slots64, slots32) + + if __name__ == "__main__": unittest.main() diff --git a/tests/semantic/test_wave64_saveexec_b32.py b/tests/semantic/test_wave64_saveexec_b32.py new file mode 100644 index 000000000..3af99bc56 --- /dev/null +++ b/tests/semantic/test_wave64_saveexec_b32.py @@ -0,0 +1,216 @@ +"""Value tests for wave64 s_*_saveexec_b32 and s_andn{1,2}_wrexec_b32. + +On RDNA2 in wave64 mode, the 32-bit SOP1 forms operate strictly on EXEC_LO (lanes 0..31): + - s__saveexec_b32 D, S0: D = EXEC_LO; EXEC_LO = f(S0, EXEC_LO); SCC = (EXEC_LO != 0) + - s_andn{1,2}_wrexec_b32 D, S0: EXEC_LO = f(S0, EXEC_LO); D = EXEC_LO; SCC = (EXEC_LO != 0) + - EXEC_HI (lanes 32..63) is untouched. + - D receives a MASK_LO value (lanes 0..31 only), so whole-wave consumers like s_bcnt1_i32_b32 + count only the low half. + - Cross-half operands (exec_hi / vcc_hi / MASK_HI sources, or exec_hi / vcc_hi destinations) + transfer the 32-bit word across halves. + +Verified through rdna2spirv -> spirv_mini_interp.run_workgroup (64 lanes) and spirv-as/spirv-val +(native wave64 and --wave64-emulate). Standard library only; no GPU or game data. +""" +import os +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import support # noqa: E402 +import spirv_mini_interp as si # noqa: E402 +import lane_masks as lm # noqa: E402 + +rdna2spirv = support.rdna2spirv +SPIRV_AS = shutil.which("spirv-as") +SPIRV_VAL = shutil.which("spirv-val") + +FSSM_64 = bytes(0x138) + struct.pack("<4I", 0x88, 64, 1, 1) +VSHARP = [0, 0, 0x1000, 0x31016FAC] +M32 = 0xFFFFFFFF + +EXEC_FUNCS = { + "and": lambda s, e: (s & e) & M32, + "or": lambda s, e: (s | e) & M32, + "xor": lambda s, e: (s ^ e) & M32, + "andn1": lambda s, e: ((~s) & e) & M32, + "andn2": lambda s, e: (s & (~e)) & M32, + "orn1": lambda s, e: ((~s) | e) & M32, + "orn2": lambda s, e: (s | (~e)) & M32, + "nand": lambda s, e: (~(s & e)) & M32, + "nor": lambda s, e: (~(s | e)) & M32, + "xnor": lambda s, e: (~(s ^ e)) & M32, +} + + +def validate_spirv(spv): + if not (SPIRV_AS and SPIRV_VAL): + return + with tempfile.TemporaryDirectory() as tmp: + asm = os.path.join(tmp, "s.spvasm") + bin_ = os.path.join(tmp, "s.spv") + with open(asm, "w", encoding="utf-8", newline="\n") as f: + f.write(spv) + r1 = subprocess.run([SPIRV_AS, "--target-env", "vulkan1.3", asm, "-o", bin_], + capture_output=True, text=True) + if r1.returncode != 0: + raise AssertionError(f"spirv-as failed:\n{r1.stderr}") + r2 = subprocess.run([SPIRV_VAL, "--target-env", "vulkan1.3", bin_], + capture_output=True, text=True) + if r2.returncode != 0: + raise AssertionError(f"spirv-val failed:\n{r2.stderr}") + + +def run_w64(lines, *, validate_emulate=True): + """Translate as native wave64, validate with spirv-val (and optionally --wave64-emulate), + and run all 64 lanes in spirv_mini_interp.run_workgroup.""" + prev = rdna2spirv.WAVE64_EMULATE + try: + rdna2spirv.WAVE64_EMULATE = False + spv = support.translate_lines("cs_w64_saveexec_b32", lines + ["s_endpgm"], fssm=FSSM_64) + assert rdna2spirv.translate.last_gen.wave64 + validate_spirv(spv) + if validate_emulate: + rdna2spirv.WAVE64_EMULATE = True + spv_emu = support.translate_lines("cs_w64_saveexec_b32", lines + ["s_endpgm"], fssm=FSSM_64) + assert rdna2spirv.translate.last_gen.wave64 + validate_spirv(spv_emu) + finally: + rdna2spirv.WAVE64_EMULATE = prev + return si.run_workgroup( + spv, 64, 64, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=VSHARP + [0] * 28, + memory={}, + ) + + +def read_exec_and_state(lines, init_lo, init_hi): + """Setup EXEC = (init_hi << 32) | init_lo, run `lines`, then record: + out[0] = resulting EXEC_LO, out[1] = resulting EXEC_HI, out[2] = SCC (0/1), + out[3] = popcount(s8) via s_bcnt1_i32_b32, out[4] = s8 restored to EXEC_LO popcount.""" + prog = [ + "s_mov_b64 exec, -1", # ensure wave64 classification + f"s_mov_b32 exec_lo, {init_lo:#x}", + f"s_mov_b32 exec_hi, {init_hi:#x}", + *lines, + # Capture SCC before touching EXEC + "s_cselect_b32 s10, 1, 0", + # Capture current 64-bit EXEC into per-lane flag, then ballot via s_bcnt1 / per-lane stores + "v_mov_b32_e32 v10, 0", + "s_mov_b64 s[12:13], exec", + "s_mov_b64 exec, -1", + "v_cndmask_b32_e64 v10, 0, 1, s[12:13]", + # Store each lane's exec bit at byte 64 + 4*lane + "v_lshlrev_b32_e32 v11, 2, v0", + "v_add_nc_u32_e32 v11, 64, v11", + "buffer_store_dword v10, v11, s[0:3], 0 offen", + # Compute s_bcnt1_i32_b32 on s8 (the saved/written destination) to check MASK_LO tagging + "s_bcnt1_i32_b32 s11, s8", + # Store SCC (s10) at byte 0, bcnt(s8) (s11) at byte 4 from lane 0 + "v_cmpx_eq_u32_e32 0, v0", + "v_mov_b32_e32 v1, s10", + "v_mov_b32_e32 v2, s11", + "v_mov_b32_e32 v12, 0", "buffer_store_dword v1, v12, s[0:3], 0 offen", + "v_mov_b32_e32 v12, 4", "buffer_store_dword v2, v12, s[0:3], 0 offen", + ] + mem = run_w64(prog) + exec_lo = sum(((mem.get(64 + 4 * i, 0) & 1) << i) for i in range(32)) + exec_hi = sum(((mem.get(64 + 4 * (32 + i), 0) & 1) << i) for i in range(32)) + return exec_lo, exec_hi, mem.get(0), mem.get(4) + + +class Wave64SaveexecB32Tests(unittest.TestCase): + def test_all_ten_saveexec_b32_preserve_exec_hi_and_scc_low_half(self): + # Crucially: init_lo = 0x0000000F, s0 = 0x000000F0, init_hi = 0x000000FF. + # For s_and_saveexec_b32: new EXEC_LO = 0 while EXEC_HI stays 0x000000FF (non-zero!) -> SCC MUST be 0! + # Previously on main, set_exec(r) clobbered EXEC_HI to 0xF0 and scc_from_mask voted 1 over all 64 lanes. + init_lo, init_hi, s0 = 0x0000000F, 0x000000FF, 0x000000F0 + for kind, fn in EXEC_FUNCS.items(): + op = f"s_{kind}_saveexec_b32" + with self.subTest(op=op): + got_lo, got_hi, got_scc, got_bcnt = read_exec_and_state( + [f"{op} s8, {s0:#x}"], init_lo, init_hi + ) + want_lo = fn(s0, init_lo) + self.assertEqual(got_lo, want_lo) + self.assertEqual(got_hi, init_hi) # EXEC_HI untouched + self.assertEqual(got_scc, 1 if want_lo != 0 else 0) # SCC = (EXEC_LO != 0) only + self.assertEqual(got_bcnt, bin(init_lo).count("1")) # s8 holds MASK_LO (4, not 4+8=12) + + def test_wrexec_b32_preserves_exec_hi_and_scc_low_half(self): + # Case where new EXEC_LO is 0 while EXEC_HI is non-zero, and case where new EXEC_LO is non-zero. + for op, kind in (("s_andn2_wrexec_b32", "andn2"), ("s_andn1_wrexec_b32", "andn1")): + for init_lo, init_hi, s0 in ( + (0x000000FF, 0xA5A50000, 0x0000000F), # andn2 -> 0 (while EXEC_HI != 0); andn1 -> 0xF0 + (0x0000000F, 0x000000FF, 0x000000FF), # andn2 -> 0xF0; andn1 -> 0 (while EXEC_HI != 0) + ): + with self.subTest(op=op, init_lo=hex(init_lo), s0=hex(s0)): + got_lo, got_hi, got_scc, got_bcnt = read_exec_and_state( + [f"{op} s8, {s0:#x}"], init_lo, init_hi + ) + want_lo = EXEC_FUNCS[kind](s0, init_lo) + self.assertEqual(got_lo, want_lo) + self.assertEqual(got_hi, init_hi) + self.assertEqual(got_scc, 1 if want_lo != 0 else 0) + self.assertEqual(got_bcnt, bin(want_lo).count("1")) + + def test_cross_half_hi_source_and_exec_hi_dest(self): + # 1) Source is exec_hi (lanes 32..63 = 0x000000F0) applied to EXEC_LO (0x000000FF): + # new EXEC_LO = 0xF0 & 0xFF = 0xF0, EXEC_HI stays 0x000000F0. + got_lo, got_hi, got_scc, got_bcnt = read_exec_and_state( + ["s_and_saveexec_b32 s8, exec_hi"], init_lo=0x000000FF, init_hi=0x000000F0 + ) + self.assertEqual((got_lo, got_hi, got_scc, got_bcnt), (0x000000F0, 0x000000F0, 1, 8)) + + # 2) Destination is exec_hi: old EXEC_LO (0x00000033) copied into EXEC_HI, + # while EXEC_LO becomes (0x0F & 0x33) = 0x03. + got_lo2, got_hi2, got_scc2, _ = read_exec_and_state( + ["s_mov_b32 s8, 0", "s_and_saveexec_b32 exec_hi, 0x0000000f"], + init_lo=0x00000033, init_hi=0xFFFF0000, + ) + self.assertEqual((got_lo2, got_hi2, got_scc2), (0x00000003, 0x00000033, 1)) + + def test_vcc_lo_dest_keeps_vcc_hi_intact(self): + # Initialize VCC as a lane mask with vcc_hi = 0x000000AA (distinct from later exec_hi = 0x000000F0). + # s_and_saveexec_b32 vcc_lo, 0x0f must update only vcc_lo (lanes 0..31) to old exec_lo (0x55) while + # keeping vcc_hi = 0xAA (old mask_dst overwrote lanes 32..63 of %vcc with exec_hi = 0xF0). + prog = [ + "s_mov_b64 exec, -1", + "s_mov_b32 exec_lo, 0", + "s_mov_b32 exec_hi, 0x000000aa", + "v_cmp_lt_u32_e32 vcc, v0, 64", # vcc_lo = 0, vcc_hi = 0xAA (real lane mask) + "s_mov_b32 exec_lo, 0x00000055", + "s_mov_b32 exec_hi, 0x000000f0", + "s_and_saveexec_b32 vcc_lo, 0x0000000f", + "s_mov_b64 exec, -1", + "v_cndmask_b32_e64 v10, 0, 1, vcc", + "v_lshlrev_b32_e32 v11, 2, v0", + "buffer_store_dword v10, v11, s[0:3], 0 offen", + ] + mem = run_w64(prog) + vcc_lo = sum(((mem.get(4 * i, 0) & 1) << i) for i in range(32)) + vcc_hi = sum(((mem.get(4 * (32 + i), 0) & 1) << i) for i in range(32)) + self.assertEqual(vcc_lo, 0x00000055) + self.assertEqual(vcc_hi, 0x000000AA) + + def test_lane_masks_tags_b32_saveexec_and_wrexec_as_mask_lo(self): + s = lambda r, n=1: {"k": "sgpr", "r": r, "n": n} + use = {"op": "s_nop", "args": []} + ins = lambda op, *a: {"op": op, "args": list(a)} + for op in ("s_and_saveexec_b32", "s_andn2_wrexec_b32"): + masks, _ = lm.analyse([[ins(op, s(4), {"k": "imm", "v": 0xF}), use]], [[]]) + self.assertEqual(masks[id(use)], {4: lm.MASK_LO}) + masks64, _ = lm.analyse([[ins("s_and_saveexec_b64", s(4, 2), {"k": "imm", "v": -1}), use]], [[]]) + self.assertEqual(masks64[id(use)], {4: lm.MASK_LO, 5: lm.MASK_HI}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_wave64_vcc_data_branch.py b/tests/semantic/test_wave64_vcc_data_branch.py index 7898fa2ae..c088bf5fc 100644 --- a/tests/semantic/test_wave64_vcc_data_branch.py +++ b/tests/semantic/test_wave64_vcc_data_branch.py @@ -4,7 +4,9 @@ RDNA2 ISA: VCCZ/VCCNZ test the whole 64-bit register. A shader that writes vcc_l vcc_hi with s_mov_b32 is using VCC as ordinary scalar data, not as a lane mask: in the translation each lane holds the same low word in %vcc and the same high word in %vcc_hi. The old branch_condition() loaded only %vcc, so a high-only non-zero VCC looked zero. -A VCC that was a lane mask earlier and is then overwritten with data is a separate +Both SGPR-source and constant writes are covered: @ray3242's original reproducer uses +`s_mov_b32 vcc_lo, 0` / `s_mov_b32 vcc_hi, 0x8000000a`. A VCC that was a lane mask +earlier and is then overwritten with data is a separate dataflow limitation of #2544 and is not covered here. Each case is a synthetic 64-thread compute shader translated by tools/rdna2spirv.py and @@ -93,6 +95,7 @@ CASES = [ (0xA, 0x8000000A), (M32, M32), ] +CONST_CASES = CASES # @ray3242's reproducer uses constant writes, not SGPR sources class Wave64VccDataBranchTests(unittest.TestCase): @@ -105,6 +108,11 @@ class Wave64VccDataBranchTests(unittest.TestCase): "cs_w64_vcc_data_branch_" + suffix, WAVE64 + BUILD_DATA + observe(op)) cls.progs[("mask", op)] = translate_cs( "cs_w64_vcc_mask_branch_" + suffix, WAVE64 + BUILD_MASK + observe(op)) + for lo, hi in CONST_CASES: + cls.progs[("const", lo, hi, op)] = translate_cs( + f"cs_w64_vcc_const_branch_{suffix}_{lo:x}_{hi:x}", + WAVE64 + [("s_mov_b32 vcc_lo, " + hex(lo), 4), + ("s_mov_b32 vcc_hi, " + hex(hi), 4)] + observe(op)) def test_vcc_data_branch_checks_both_halves(self): for lo, hi in CASES: @@ -115,6 +123,15 @@ class Wave64VccDataBranchTests(unittest.TestCase): self.assertEqual(run(self.progs[("data", "s_cbranch_vccnz")], lo, hi), [7 if nz else 9] * 64) + def test_vcc_constant_writes_check_both_halves(self): + for lo, hi in CONST_CASES: + nz = bool((lo | hi) & M32) + with self.subTest(lo=hex(lo), hi=hex(hi)): + self.assertEqual(run(self.progs[("const", lo, hi, "s_cbranch_vccz")], 0, 0), + [9 if nz else 7] * 64) + self.assertEqual(run(self.progs[("const", lo, hi, "s_cbranch_vccnz")], 0, 0), + [7 if nz else 9] * 64) + def test_certified_vcc_lane_mask_keeps_whole_wave_vote(self): for op, taken in (("s_cbranch_vccz", 9), ("s_cbranch_vccnz", 7)): with self.subTest(op=op): diff --git a/tests/spirv_interp.py b/tests/spirv_interp.py index 2cf096b12..9307541f4 100644 --- a/tests/spirv_interp.py +++ b/tests/spirv_interp.py @@ -4,7 +4,9 @@ without a GPU. It only covers the straight-line, one-lane subset the translator produces for branch-free shaders: scalar/vector arithmetic, bit ops, bitcasts, the GLSL.std.450 functions used so far, and Function/Output variables. Anything else raises NotImplementedError (a test then fails loudly instead of passing on a guess). Floats are rounded to binary32 -after every operation. Texture, buffer and control-flow instructions are out of scope. +after every operation. An integer is always held as its unsigned 32-bit pattern, whatever the signedness of its +type; the instructions that read it as signed (OpS*, SMin, SMax) convert with s32() themselves, as SPIR-V defines +them on the bits and not on the type. Texture, buffer and control-flow instructions are out of scope. """ import math import re @@ -52,15 +54,61 @@ def s32(u): def half_to_float(h): - return struct.unpack(" f32; every non-NaN result is exact. struct's '> 15) << 31 + exp = (h >> 10) & 0x1F + frac = h & 0x3FF + if exp == 0x1F: + bits = sign | (0x7FC00000 if frac else 0x7F800000) # NaN: canonical quiet, payload dropped; infinity + elif exp == 0 and frac: + b = frac.bit_length() + bits = sign | ((b + 102) << 23) | ((frac << (24 - b)) & 0x7FFFFF) # subnormal half -> normal f32 + elif exp == 0: + bits = sign # +-0 + else: + bits = sign | ((exp + 112) << 23) | (frac << 13) # normal half -> f32, exact + return struct.unpack(" f16, round to nearest even; overflow gives infinity (struct's '> 63) << 15 + exp = (bits >> 52) & 0x7FF + mant = bits & ((1 << 52) - 1) + if exp == 0x7FF: + return sign | (0x7E00 if mant else 0x7C00) # NaN: canonical quiet, sign kept; infinity + if exp == 0: + return sign # +-0 and double subnormals sit far below the half grid + e = exp - 1023 + full = (1 << 52) | mant + if e < -14: + drop = 28 - e # subnormal grid: multiples of 2**-24 + n = full >> drop + rem = full & ((1 << drop) - 1) + if rem > (1 << (drop - 1)) or (rem == (1 << (drop - 1)) and n & 1): + n += 1 + if n > 0x3FF: # rounds up to the smallest normal + return sign | 0x0400 + return sign | n + n = full >> 42 # keep the top 11 significand bits, RNE the rest + rem = full & ((1 << 42) - 1) + if rem > (1 << 41) or (rem == (1 << 41) and n & 1): + n += 1 + if n > 0x7FF: # significand carry bumps the exponent + e += 1 + n = 0x400 + if e > 15: # overflow, incl. the 65520 RNE tie + return sign | 0x7C00 + return sign | ((e + 15) << 10) | (n & 0x3FF) class Result: @@ -106,7 +154,7 @@ def run(spvasm): if t == "Float": consts[res] = float(args[1]) if types[args[0]][1] == "64" else f32(float(args[1])) else: - consts[res] = int(args[1]) & M32 if t == "Int" and types[args[0]][2] == "0" else s32(int(args[1])) + consts[res] = int(args[1]) & M32 elif op == "OpConstantTrue": consts[res] = True elif op == "OpConstantFalse": @@ -142,11 +190,13 @@ def run(spvasm): "OpShiftLeftLogical": lambda a, b: (a << (b & 31)) & M32 if b < 32 else 0, "OpShiftRightLogical": lambda a, b: a >> b if b < 32 else 0, "OpFAdd": lambda a, b: f32(a + b), "OpFSub": lambda a, b: f32(a - b), "OpFMul": lambda a, b: f32(a * b), - "OpFDiv": lambda a, b: f32(a / b) if b else math.copysign(math.inf, a) if a else math.nan, + # x / +-0: infinity with the sign of x times the sign of the zero; 0 / 0 and NaN / 0 are NaN. + "OpFDiv": lambda a, b: f32(a / b) if b else + math.copysign(math.inf, math.copysign(1.0, a) * math.copysign(1.0, b)) if a and not math.isnan(a) else math.nan, "OpFOrdGreaterThan": lambda a, b: a > b, "OpFOrdLessThan": lambda a, b: a < b, "OpFOrdEqual": lambda a, b: a == b, "OpLogicalOr": lambda a, b: a or b, "OpLogicalAnd": lambda a, b: a and b, - "OpSLessThanEqual": lambda a, b: a <= b, "OpSGreaterThanEqual": lambda a, b: a >= b, + "OpSLessThanEqual": lambda a, b: s32(a) <= s32(b), "OpSGreaterThanEqual": lambda a, b: s32(a) >= s32(b), "OpULessThan": lambda a, b: a < b, "OpUGreaterThan": lambda a, b: a > b, "OpULessThanEqual": lambda a, b: a <= b, "OpUGreaterThanEqual": lambda a, b: a >= b, "OpFUnordNotEqual": lambda a, b: a != b, # true when either is NaN, as Python's != is @@ -199,7 +249,7 @@ def run(spvasm): if fn == "FClamp": return round_out(min(max(a[0], a[1]), a[2])) if fn in ("SMax", "SMin"): - return (max if fn == "SMax" else min)(*a) + return (max if fn == "SMax" else min)(*a, key=s32) if fn in ("UMax", "UMin"): return (max if fn == "UMax" else min)(*a) raise NotImplementedError("GLSL." + fn) @@ -231,8 +281,7 @@ def run(spvasm): elif t == "Float": val[res] = u2f(v) if isinstance(v, int) else v else: - bits = f2u(v) if isinstance(v, float) else v & M32 - val[res] = s32(bits) if types[args[0]][2] == "1" else bits + val[res] = f2u(v) if isinstance(v, float) else v & M32 elif op == "OpSelect": val[res] = get(args[2]) if get(args[1]) else get(args[3]) elif op in ARITH: @@ -263,7 +312,7 @@ def run(spvasm): elif op == "OpBitFieldSExtract": v, off, cnt = s32(get(args[1])), get(args[2]), get(args[3]) x = (v >> off) & ((1 << cnt) - 1) - val[res] = x - (1 << cnt) if x >> (cnt - 1) else x + val[res] = (x - (1 << cnt) if cnt and x >> (cnt - 1) else x) & M32 elif op == "OpBitFieldUExtract": val[res] = (get(args[1]) >> get(args[2])) & ((1 << get(args[3])) - 1) elif op == "OpBitCount": @@ -275,7 +324,8 @@ def run(spvasm): elif op == "OpConvertFToU": x = get(args[1]); val[res] = 0 if math.isnan(x) or x <= 0 else M32 if x >= 2**32 else int(x) elif op == "OpConvertFToS": - x = get(args[1]); val[res] = 0 if math.isnan(x) else max(-2**31, min(2**31 - 1, int(x))) + x = get(args[1]) + val[res] = 0 if math.isnan(x) else (-2**31 if x <= -2**31 else 2**31 - 1 if x >= 2**31 else int(x)) & M32 elif op == "OpIAddCarry": t = get(args[1]) + get(args[2]); val[res] = (t & M32, t >> 32) elif op == "OpISubBorrow": diff --git a/tests/test_amd_swizzle.py b/tests/test_amd_swizzle.py index 3ecd2873c..9f9b4f048 100644 --- a/tests/test_amd_swizzle.py +++ b/tests/test_amd_swizzle.py @@ -1,6 +1,6 @@ """amd_swizzle.load: parses addrlib's pattern tables without evaluating them as Python. - python -I tests/test_amd_swizzle.py + python -m pytest tests/test_amd_swizzle.py """ import pytest # noqa: E402 (keeps the CI bash loop from running this file) diff --git a/tests/test_analyze_4240_full.py b/tests/test_analyze_4240_full.py index 61b3c501f..92d3536ff 100644 --- a/tests/test_analyze_4240_full.py +++ b/tests/test_analyze_4240_full.py @@ -4,6 +4,8 @@ Everything is synthetic: an RPF9-like header, zlib streams and hand-built block headers. No game data is used. """ +import contextlib +import io import json import os import struct @@ -12,6 +14,7 @@ import sys import tempfile import unittest import zlib +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOL = os.path.join(ROOT, "tools", "analyze_4240_full.py") @@ -96,7 +99,7 @@ class Analyze4240Test(unittest.TestCase): def test_missing_input_is_one_error_line(self): missing = os.path.join(self.root, "missing.rpf") p = self.run_tool(missing) - self.assertEqual(p.returncode, 1, p.stderr) + self.assertEqual(p.returncode, 2, p.stderr) self.assertIn("does not exist", p.stderr) self.assertIn("missing.rpf", p.stderr) self.assertNotIn("Traceback", p.stderr) @@ -114,6 +117,30 @@ class Analyze4240Test(unittest.TestCase): self.assertNotIn("Traceback", p.stderr) self.assertIn("Processing " + good, p.stdout, "the next archive is still read") + def test_unreadable_archive_is_reported_and_later_archives_are_measured(self): + blocked = os.path.join(self.root, "locked.rpf") + make_archive(blocked, BLOCK_6330) + good = self.truncated_archive() + out = os.path.join(self.root, "stats.json") + stderr = io.StringIO() + + def open_archive(path, *args, **kwargs): + if path == blocked: + raise PermissionError(13, "input is locked", path) + return open(path, *args, **kwargs) + + with (mock.patch.object(A, "open", create=True, side_effect=open_archive), + mock.patch.object(sys, "argv", [TOOL, blocked, good, "--json", out]), + contextlib.redirect_stdout(io.StringIO()), + contextlib.redirect_stderr(stderr)): + self.assertEqual(A.main(), 1) + self.assertEqual(stderr.getvalue().splitlines(), + [f"ERROR: cannot read {blocked}: input is locked"]) + with open(out, encoding="utf-8") as fh: + doc = json.load(fh) + self.assertEqual(len(doc), 1) + self.assertEqual(doc[0]["errors"], 1) + def test_limit_below_one_is_refused(self): path = self.truncated_archive() for bad in ("0", "-1"): diff --git a/tests/test_anim_clips.py b/tests/test_anim_clips.py index 49347cc97..55653fca0 100644 --- a/tests/test_anim_clips.py +++ b/tests/test_anim_clips.py @@ -207,7 +207,8 @@ def animation(page, frames, tracks, sequences): def dictionary(name="synthetic@dict", sequences=None, frames=None, tracks=None, external=0, children=(), - external_hashes=(), parameters=1, times=None, axis=None): + external_hashes=(), parameters=1, times=None, axis=None, node=None, sample_lists=None, + node_axis_count=None): """One clip dictionary page: one `.clip`, one `.motion`, one `.motionmatcher`, one local pack with one animation.""" p = Page() pm = p.alloc(bytes(16)) @@ -249,22 +250,41 @@ def dictionary(name="synthetic@dict", sequences=None, frames=None, tracks=None, struct.pack_into(" child k + motion = self.motion(children=[(1, 2), (3, 4)], axis=([joaat32("speed")], [(0, 0.0), (1, 1.0)], 0.0, 1.0), + sample_lists=[[(0, 1.0, 1.0), (1, 1.0, 1.0)], [(1, 1.0, 1.0)]]) + stats = anim_clips.new_stats() + anim_clips.count_motion_blend(motion, stats) + self.assertEqual((stats["motion_samples:3:sample_k_is_child_k"], stats["motion_samples:3:every_list_one_item"], + stats["motion_samples:3:every_child_sampled"]), (0, 0, 1)) + + def test_malformed_node_keeps_the_time_table(self): + times = [(1.5, 1.5, [(0.0, 0.0), (1.5, 1.5)])] + motion = self.motion(children=[(1, 2)], times=times, node=(8, [(1, 0, 0)], 1), node_axis_count=0xFFFF) + self.assertIsNone(motion["node"]) # the axis array runs past the page + self.assertEqual(len(motion["times"]), 1) + + def test_child_out_of_range_is_counted(self): + motion = self.motion(children=[(1, 2)], axis=([joaat32("speed")], [(0, 0.0)], 0.0, 0.0), + sample_lists=[[(5, 1.0, 1.0)]]) + stats = anim_clips.new_stats() + anim_clips.count_motion_blend(motion, stats) + self.assertEqual((stats["motion_samples:3:children_in_range"], stats["motion_samples:3:every_child_sampled"]), + (0, 0)) + + def test_multi_axis_nodes(self): + for kind, n_axes in ((4, 2), (5, 3), (6, 4), (8, 5)): + axes = [(joaat32("speed") if i == 0 else 0xABC0 + i, i, 1) for i in range(n_axes)] + lists = [[(i % 2, 1.0, 1.0)] for i in range(4)] + motion = self.motion(children=[(1, 2), (3, 4)], node=(kind, axes, 4), sample_lists=lists) + k, axis = motion["node"] + self.assertEqual((k, axis["names"], axis["slots"], axis["sample_count"]), + (kind, [a[0] for a in axes], [(i, 1) for i in range(n_axes)], 4)) + self.assertNotIn("samples", axis) + stats = anim_clips.new_stats() + anim_clips.count_motion_blend(motion, stats) + self.assertEqual((stats[f"motion_node_axes:{kind}:{n_axes}"], + stats[f"motion_node_axis_name:{kind}:speed"], + stats[f"motion_node_axis_name:{kind}:unresolved"], + stats[f"motion_samples:{kind}:lists_equal_node_samples"], + stats[f"motion_samples:{kind}:every_child_sampled"], stats["motion_axes"]), + (1, 1, n_axes - 1, 1, 1, 0)) + + def test_type1_node(self): + motion = self.motion(children=[(1, 2)], node=(1, [], 1), sample_lists=[[(0, 1.0, 1.0)]]) + self.assertEqual(motion["node"], (1, {"names": [], "slots": [], "sample_count": 1})) + stats = anim_clips.new_stats() + anim_clips.count_motion_blend(motion, stats) + self.assertEqual((stats["motion_node_type:1"], stats["motion_node_axes:1:0"], + stats["motion_samples:1:sample_k_is_child_k"]), (1, 1, 1)) + + def test_sample_lists_of_a_two_node_motion_are_not_counted(self): + motion = self.motion(children=[(1, 2)], parameters=2, node=(1, [], 1), sample_lists=[[(0, 1.0, 1.0)]] * 3) + self.assertEqual(len(motion["samples"]), 3) + stats = anim_clips.new_stats() + anim_clips.count_motion_blend(motion, stats) + self.assertFalse([k for k in stats if k.startswith("motion_samples:")]) def test_delta2_round_trip(self): for n in (1, 2, 8, 9, 63, 64, 65, 129, 200): diff --git a/tests/test_anim_glb.py b/tests/test_anim_glb.py index 6c6bd02ff..9ba52de29 100644 --- a/tests/test_anim_glb.py +++ b/tests/test_anim_glb.py @@ -342,6 +342,31 @@ class ClipChannelTest(unittest.TestCase): self.assertNotIn(("mover", "translation"), out) self.assertEqual(tally["tracks_mover_skipped"], 1) + def test_single_frame_pose_window_keeps_only_that_frame(self): + anim_clips.decode_animation = lambda _s, _anim: ( + {0: [(float(k), 0.0, 0.0, 1.0) for k in range(5)], + 1: [(float(k * 10), 0.0, 0.0) for k in range(5)]}, + 5, + ) + out, _ = self.channels(2 / 30, 2 / 30, 1.0) + self.assertEqual(out[("mover", "translation")], [(0.0, (20.0, 0.0, 0.0))]) + # Off-grid start == end windows pick the nearest frame instead of falling back to frame 0. + out_mid, _ = self.channels(0.075, 0.075, 1.0) + self.assertEqual(out_mid[("mover", "translation")], [(0.0, (20.0, 0.0, 0.0))]) + out_hi, _ = self.channels(0.095, 0.095, 1.0) + self.assertEqual(out_hi[("mover", "translation")], [(0.0, (30.0, 0.0, 0.0))]) + + def test_select_clips_handles_non_hex_0x_names_and_bad_selectors(self): + d = { + "clips": [ + {"kind": "clip", "name": "other.clip", "hash": 0x11111111}, + {"kind": "clip", "name": "0x_intro.clip", "hash": 0x22222222}, + ] + } + self.assertEqual([c["hash"] for c in anim_glb.select_clips(d, ["0x_intro"])], [0x22222222]) + with self.assertRaisesRegex(anim_glb.ExportError, "0xbad"): + anim_glb.select_clips(d, ["0xbad"]) + class SamplerTimeTest(unittest.TestCase): def test_fractional_time_bounds_match_the_binary_accessor(self) -> None: diff --git a/tests/test_anim_index.py b/tests/test_anim_index.py index 021057f67..5843d0b23 100644 --- a/tests/test_anim_index.py +++ b/tests/test_anim_index.py @@ -502,6 +502,29 @@ class RigArchiveTest(unittest.TestCase): self.assertEqual(r["summary"]["rigsets"], 3) self.assertEqual(r["summary"]["entries"], 3) + def test_collect_skeletons_dir_matches_archive_classification(self): + carved = os.path.join(self.root, "carved_skels") + os.makedirs(carved) + big_skel = b"SKEL_Large\x00" + b"SKEL_Other\x00" + b"\x00" * 20000 + rbf0_with_skel = b"RBF0" + b"\x00" * 16 + b"SKEL_NotASkeleton\x00" + b"\x00" * 32 + with open(os.path.join(carved, "000000000100.bin"), "wb") as f: + f.write(self.skel) + with open(os.path.join(carved, "000000000200.bin"), "wb") as f: + f.write(big_skel) + with open(os.path.join(carved, "000000000300.bin"), "wb") as f: + f.write(self.front) + with open(os.path.join(carved, "000000000400.bin"), "wb") as f: + f.write(rbf0_with_skel) + got = anim_index.collect_skeletons_dir(carved) + self.assertEqual( + [(r["offset"], r["kind"], r["names"]) for r in got], + [ + (0x100, "plain-bone-table", ["SKEL_Second", "SKEL_Synthetic"]), + (0x200, "plain-bone-table", ["SKEL_Large", "SKEL_Other"]), + (0x300, "bone-table", ["SKEL_Front"]), + ], + ) + def test_cli_rejects_a_shared_rig_destination(self): out = os.path.join(self.root, "index.json") alias = os.path.join(self.root, ".", "index.json") diff --git a/tests/test_anim_skeleton_match.py b/tests/test_anim_skeleton_match.py new file mode 100644 index 000000000..8a680380a --- /dev/null +++ b/tests/test_anim_skeleton_match.py @@ -0,0 +1,66 @@ +"""Synthetic tests for tools/anim_skeleton_match.py (standard library only; no game data).""" +import json +import os +import sys +import tempfile +import unittest +import zlib + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import anim_skeleton_match as asm # noqa: E402 + + +class SkeletonMatchTests(unittest.TestCase): + def test_extract_and_compare_case_insensitive_and_joaat32(self): + skel_blob = b"hdr\x00SKEL_ROOT\x00SKEL_Head\x00SKEL_Pelvis\x00" + anim_streams = [ + asm.extract_skel_tokens(b"\x00SKEL_ROOT\x00SKEL_HEAD\x00"), + asm.extract_skel_tokens(b"\x00SKEL_Pelvis\x00SKEL_Unknown\x00"), + ] + summary = asm.compare_sets(asm.extract_skel_tokens(skel_blob), anim_streams) + self.assertEqual(summary["distinct_anim_tokens"], 4) + self.assertEqual(summary["distinct_skeleton_tokens"], 3) + self.assertEqual(summary["matched_exact"], 2) + self.assertEqual(summary["matched_case_insensitive"], 3) + self.assertEqual(summary["matched_joaat32"], 3) + self.assertEqual(summary["unmatched_case_insensitive"], 1) + self.assertEqual(summary["streams_all_matched_exact"], 0) + self.assertEqual(summary["streams_all_matched_ci"], 1) + self.assertEqual(summary["streams_any_matched_ci"], 2) + + def test_cli_synthetic_archives_and_overwrite_guard(self): + with tempfile.TemporaryDirectory() as tmp: + packs_p = os.path.join(tmp, "packs.rpf") + anim_p = os.path.join(tmp, "anim.rpf") + out_p = os.path.join(tmp, "report.json") + with open(packs_p, "wb") as f: + f.write(b"RPF9" + bytes(12) + zlib.compress(b"SKEL_ROOT\x00SKEL_Spine0\x00" + b"A" * 128)) + with open(anim_p, "wb") as f: + f.write(b"RPF9" + bytes(12) + zlib.compress(b"SKEL_ROOT\x00SKEL_Spine0\x00" + b"B" * 128)) + rc = asm.main([packs_p, anim_p, "--out", out_p]) + self.assertEqual(rc, 0) + with open(out_p, encoding="utf-8") as f: + data = json.load(f) + self.assertEqual(data["matched_exact"], 2) + self.assertEqual(data["unmatched_case_insensitive"], 0) + with self.assertRaises(SystemExit) as cm: + asm.main([packs_p, anim_p, "--out", packs_p]) + self.assertEqual(cm.exception.code, 2) + with self.assertRaises(SystemExit) as cm: + asm.main([packs_p, anim_p, "--out", os.path.join(tmp, "nodir", "rep.json")]) + self.assertEqual(cm.exception.code, 2) + with self.assertRaises(SystemExit) as cm: + asm.main([packs_p, anim_p, "--out", tmp]) + self.assertEqual(cm.exception.code, 2) + empty_p = os.path.join(tmp, "empty.rpf") + open(empty_p, "wb").close() + for bad_in in (os.path.join(tmp, "missing.rpf"), empty_p, tmp): + with self.subTest(bad_in=bad_in), self.assertRaises(SystemExit) as cm: + asm.main([bad_in, anim_p]) + self.assertEqual(cm.exception.code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_audio_config.py b/tests/test_audio_config.py index 9ddb03e03..13f198af1 100644 --- a/tests/test_audio_config.py +++ b/tests/test_audio_config.py @@ -224,13 +224,13 @@ class TestCli(unittest.TestCase): with open(blob, "wb") as f: f.write(b"\x00" * 4 + make_record(0x2000, 123_456)) missing = os.path.join(tmp, "missing") - cases = (([missing], missing, "does not exist"), - ([tmp, "--names", os.path.join(tmp, "no_pool.txt")], "no_pool.txt", "name pool"), - ([tmp, "--names", tmp], tmp, "name pool")) # a folder as the pool - for args, path, message in cases: + cases = (([missing], missing, "does not exist", 2), + ([tmp, "--names", os.path.join(tmp, "no_pool.txt")], "no_pool.txt", "name pool", 1), + ([tmp, "--names", tmp], tmp, "name pool", 1)) # a folder as the pool + for args, path, message, expected in cases: with self.subTest(message=message, args=[os.path.basename(x) for x in args]): p = subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) - self.assertEqual(p.returncode, 1) + self.assertEqual(p.returncode, expected) self.assertIn(path, p.stderr) self.assertIn(message, p.stderr) self.assertNotIn("Traceback", p.stderr) diff --git a/tests/test_audio_wav.py b/tests/test_audio_wav.py index b3c5c104c..4b1308f8d 100644 --- a/tests/test_audio_wav.py +++ b/tests/test_audio_wav.py @@ -287,6 +287,39 @@ class OpusInputSelectionTest(unittest.TestCase): self.assertEqual([stem for _, stem in found], ["opus"]) self.assertEqual(skipped, 2) + def test_plan_outputs_does_not_reserve_rejected_wav_slots_for_later_inputs(self) -> None: + from collections import Counter + from unittest.mock import patch + + src = os.path.join("fake_src") + out = os.path.join("fake_out") + p0 = os.path.join(src, "a.ogg.opus") + p1 = os.path.join(src, "a.ogg~2.opus") + items = [(p0, "a.ogg"), (p1, "a.ogg~2")] + src_dig = {p0: "D0", p1: "D1"} + wav_dig = { + os.path.join(out, "a.ogg.wav"): "DX", + os.path.join(out, "a.ogg~2.wav"): "DY", + os.path.join(out, "a.ogg~3.wav"): "D1", + os.path.join(out, "a.ogg~4.wav"): "D0", + } + dst_calls = Counter() + + def fake_digest(_ff, p, source=False): + if source: + return src_dig[p] + dst_calls[p] += 1 + return wav_dig.get(p) + + with patch.object(audio_wav, "audio_digest", side_effect=fake_digest), \ + patch("os.path.lexists", side_effect=lambda p: p in wav_dig), \ + patch("os.path.isfile", side_effect=lambda p: p in wav_dig): + planned, renamed, moved = audio_wav.plan_outputs(items, src, out, "ffmpeg") + self.assertEqual([(os.path.basename(p), stem) for p, stem in planned], + [("a.ogg.opus", "a.ogg~4"), ("a.ogg~2.opus", "a.ogg~3")]) + self.assertEqual((renamed, moved), (0, 2)) + self.assertEqual(max(dst_calls.values()), 1) + class GranuleTest(unittest.TestCase): def test_trim_requires_identifiable_matching_endpoints(self): diff --git a/tests/test_awc_names.py b/tests/test_awc_names.py index ad816941d..fdcf74625 100644 --- a/tests/test_awc_names.py +++ b/tests/test_awc_names.py @@ -170,6 +170,32 @@ class TestRules(unittest.TestCase): self.assertEqual(stats["family_min_size"], 2) self.assertEqual(stats["control_dialogue"] + stats["control_family"], 0) + def test_rejected_dialogue_hit_does_not_shadow_accepted_family_member(self): + d = A.Dictionary(["zz_fooau_abcd_01"]) + bases = ["zz_fooau_abcd"] + # Including SALT + zz_fooau_abcd_01 makes the salted control reject the dialogue rule; + # zz_fooau_abcd_01 must still be named via its 3-member family alongside _02 and _03. + index = self.index({ + "b0": [ + "zz_fooau_abcd_01", + "zz_fooau_abcd_02", + "zz_fooau_abcd_03", + A.SALT + "zz_fooau_abcd_01", + ] + }) + real, stats = A.name_source(d, bases, index) + self.assertFalse(stats["dialogue_rule"]) + self.assertEqual(stats["family_min_size"], 2) + self.assertEqual(stats["named"], 3) + self.assertEqual( + sorted(real.values()), + [ + ("zz_fooau_abcd_01", "family", 3), + ("zz_fooau_abcd_02", "family", 3), + ("zz_fooau_abcd_03", "family", 3), + ], + ) + class TestConversations(unittest.TestCase): def test_waves_per_label(self): @@ -298,6 +324,17 @@ class TestCli(unittest.TestCase): with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): A.main([ROOT]) + def test_malformed_banks_json(self): + with tempfile.TemporaryDirectory() as tmp: + words = write(os.path.join(tmp, "words.json"), json.dumps(["x"])) + for doc in ([1], [["Path"]]): + banks = write(os.path.join(tmp, "banks.json"), json.dumps(doc)) + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + self.assertEqual(A.main(["--words", words, banks]), 2) + self.assertEqual(err.getvalue().count("\n"), 1, err.getvalue()) + self.assertIn("awc_names: error:", err.getvalue()) + def test_missing_input(self): with contextlib.redirect_stderr(io.StringIO()): self.assertEqual(A.main(["/nonexistent", "--words", "/nonexistent.txt"]), 2) diff --git a/tests/test_bary_fallback_gs.py b/tests/test_bary_fallback_gs.py index f56d72c24..9bf22eda7 100644 --- a/tests/test_bary_fallback_gs.py +++ b/tests/test_bary_fallback_gs.py @@ -607,9 +607,9 @@ class TestMainAndCLI(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: missing = os.path.join(tmp, "nope") code, out, err = self._call_main(["bary_fallback_gs.py", missing]) - self.assertEqual(code, 1) + self.assertEqual(code, 2) self.assertEqual(out, "") - self.assertIn("not a directory", err) + self.assertIn("does not exist", err) file_path = os.path.join(tmp, "not_a_dir.txt") with open(file_path, "w", encoding="utf-8") as f: @@ -711,6 +711,20 @@ class TestMainAndCLI(unittest.TestCase): self.assertEqual(out, "") self.assertIn("translation index must be a JSON object", err) + def test_main_pair_rejects_non_object_entries(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + index_path = os.path.join(tmp, "index.json") + good = {"vs": {"stage": "vs"}, "ps": {"stage": "ps", "bary_fallback_input": {"location": 1}}} + for bad in ([], 1, None, "vs"): + for name in ("vs", "ps"): + with self.subTest(entry=name, value=bad): + with open(index_path, "w", encoding="utf-8", newline="\n") as f: + json.dump({**good, name: bad}, f) + code, out, err = self._call_main(["bary_fallback_gs.py", tmp, "--pair", "vs", "ps"]) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertEqual(err, f"{index_path}: index entry {name!r} must be a JSON object\n") + def test_cli_subprocess_isolated_mode(self): def run_cli(*args): return subprocess.run( @@ -735,9 +749,9 @@ class TestMainAndCLI(unittest.TestCase): missing = os.path.join(tmp, "missing") p = run_cli(missing) - self.assertEqual(p.returncode, 1) + self.assertEqual(p.returncode, 2) self.assertEqual(p.stdout, "") - self.assertIn("not a directory", p.stderr) + self.assertIn("does not exist", p.stderr) self.assertNotIn("Traceback", p.stderr) # Empty directory (no index.json) succeeds silently without spirv-as/spirv-val. diff --git a/tests/test_batch_glb.py b/tests/test_batch_glb.py index 0a42f3c94..997e38c9b 100644 --- a/tests/test_batch_glb.py +++ b/tests/test_batch_glb.py @@ -12,6 +12,7 @@ import struct import subprocess import sys import tempfile +import threading import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -142,7 +143,8 @@ class TestBatchGlb(unittest.TestCase): (tex_dir / "panel.png").write_bytes(blue_png) stats = batch_glb.batch_convert(str(in_dir), str(out_dir), texture_dir=str(tex_dir), jobs=1) - self.assertEqual(stats, {"total": 1, "succeeded": 1, "failed": 0}) + # batch_glb also names failures and dropped textures (d876da115); none here. + self.assertEqual(stats, {"total": 1, "succeeded": 1, "failed": 0, "failures": [], "dropped_textures": []}) glb = (out_dir / "panel.detail.glb").read_bytes() json_size, = struct.unpack_from(" None: + with tempfile.TemporaryDirectory() as in_dir, \ + tempfile.TemporaryDirectory() as out_dir, \ + tempfile.TemporaryDirectory() as tex_dir: + with open(os.path.join(tex_dir, "car_body.dds"), "wb") as f: + f.write(b"DDS " + b"\x00" * 20) # magic, then a truncated header + # Two groups, one material: two primitives that both want car_body.dds + with open(os.path.join(in_dir, "car_body.obj"), "w", encoding="utf-8", newline="\n") as f: + f.write("o car_body\n" + "v 0 0 0\nv 1 0 0\nv 0 1 0\n" + "g door\nusemtl car_body\nf 1 2 3\n" + "g hood\nusemtl car_body\nf 1 2 3\n") + + calls = [] + + def broken_decode(path, max_size=0): + calls.append(path) + raise ValueError("synthetic decode failure") + + real = dds_png.dds_file_to_png_bytes + dds_png.dds_file_to_png_bytes = broken_decode + try: + stats = batch_glb.batch_convert(in_dir, out_dir, up_axis="z", texture_dir=tex_dir) + finally: + dds_png.dds_file_to_png_bytes = real + + self.assertEqual(stats["succeeded"], 1) # the model still converts + self.assertEqual(len(calls), 1) # ...and the broken DDS is decoded once, then cached + drops = [(os.path.basename(m), os.path.basename(t), w) for m, t, w in stats["dropped_textures"]] + self.assertEqual([d[1] for d in drops], ["car_body.dds"]) # one line per texture, not per primitive + self.assertTrue(all("synthetic decode failure" in d[2] for d in drops)) + with open(os.path.join(out_dir, "car_body.glb"), "rb") as f: + self.assertNotIn(b"image/png", f.read()) # no texture, and it says so + + def test_broken_dds_shared_by_two_models_is_decoded_once_across_workers(self) -> None: + with tempfile.TemporaryDirectory() as in_dir, \ + tempfile.TemporaryDirectory() as out_dir, \ + tempfile.TemporaryDirectory() as tex_dir: + with open(os.path.join(tex_dir, "car_body.dds"), "wb") as f: + f.write(b"DDS " + b"\x00" * 20) + for name in ("model_a", "model_b"): # two models: the pool runs them in parallel + with open(os.path.join(in_dir, name + ".obj"), "w", encoding="utf-8", newline="\n") as f: + f.write("o %s\nv 0 0 0\nv 1 0 0\nv 0 1 0\nusemtl car_body\nf 1 2 3\n" % name) + + calls = [] + both_inside = threading.Barrier(2, timeout=2.0) # releases only if the lock is missing + + def slow_broken_decode(path, max_size=0): + calls.append(path) + try: + both_inside.wait() # a second thread proves the cache is not exclusive + except threading.BrokenBarrierError: + pass # alone inside: the cache held the second one out + raise ValueError("synthetic decode failure") + + real = dds_png.dds_file_to_png_bytes + dds_png.dds_file_to_png_bytes = slow_broken_decode + try: + stats = batch_glb.batch_convert(in_dir, out_dir, up_axis="z", texture_dir=tex_dir, jobs=2) + finally: + dds_png.dds_file_to_png_bytes = real + + self.assertEqual(stats["succeeded"], 2) + self.assertEqual(len(calls), 1) # one decode per batch, not one per worker + self.assertEqual(len(stats["dropped_textures"]), 2) # one line per model + + def test_empty_png_is_reported_not_silent(self) -> None: + with tempfile.TemporaryDirectory() as in_dir, \ + tempfile.TemporaryDirectory() as out_dir, \ + tempfile.TemporaryDirectory() as tex_dir: + with open(os.path.join(tex_dir, "car_body.png"), "wb") as f: + pass # exists, but zero bytes + with open(os.path.join(in_dir, "car_body.obj"), "w", encoding="utf-8", newline="\n") as f: + f.write("o car_body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n") + + stats = batch_glb.batch_convert(in_dir, out_dir, up_axis="z", texture_dir=tex_dir) + self.assertEqual(stats["succeeded"], 1) + self.assertEqual(len(stats["dropped_textures"]), 1) + _, tex, why = stats["dropped_textures"][0] + self.assertTrue(tex.endswith("car_body.png")) + self.assertTrue(why) + with open(os.path.join(out_dir, "car_body.glb"), "rb") as f: + self.assertNotIn(b"image/png", f.read()) + + def test_unreadable_png_is_reported_not_fatal(self) -> None: + with tempfile.TemporaryDirectory() as in_dir, tempfile.TemporaryDirectory() as out_dir: + with open(os.path.join(in_dir, "car_body.obj"), "w", encoding="utf-8", newline="\n") as f: + f.write("o car_body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n") + missing = os.path.join(in_dir, "deleted_mid_run.png") + + ok, path, err, dropped = batch_glb.convert_single( + (os.path.join(in_dir, "car_body.obj"), os.path.join(out_dir, "car_body.glb"), "z", + {"car_body": missing}, 0, batch_glb.TextureCache()) + ) + self.assertTrue(ok) + self.assertEqual(err, "") + self.assertEqual(len(dropped), 1) + self.assertEqual(dropped[0][0], missing) + self.assertTrue(os.path.isfile(os.path.join(out_dir, "car_body.glb"))) + + def test_failed_models_are_named_with_their_error(self) -> None: + with tempfile.TemporaryDirectory() as in_dir, tempfile.TemporaryDirectory() as out_dir: + with open(os.path.join(in_dir, "broken.obj"), "w", encoding="utf-8", newline="\n") as f: + f.write("o broken\nf 1 2 3\n") # faces with no vertices: parse_obj refuses + + stats = batch_glb.batch_convert(in_dir, out_dir, up_axis="z") + self.assertEqual((stats["succeeded"], stats["failed"]), (0, 1)) + self.assertEqual(len(stats["failures"]), 1) + path, err = stats["failures"][0] + self.assertTrue(path.endswith("broken.obj")) + self.assertTrue(err) + self.assertFalse(os.path.exists(os.path.join(out_dir, "broken.glb"))) + + def test_main_names_failures_and_dropped_textures(self) -> None: + import contextlib + import io + import subprocess + + with tempfile.TemporaryDirectory() as in_dir, \ + tempfile.TemporaryDirectory() as out_dir, \ + tempfile.TemporaryDirectory() as tex_dir: + with open(os.path.join(in_dir, "car_body.obj"), "w", encoding="utf-8", newline="\n") as f: + f.write("o car_body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n") + with open(os.path.join(in_dir, "broken.obj"), "w", encoding="utf-8", newline="\n") as f: + f.write("o broken\nf 1 2 3\n") + with open(os.path.join(tex_dir, "car_body.dds"), "wb") as f: + f.write(b"DDS " + b"\x00" * 20) + + result = subprocess.run( + [sys.executable, "-I", os.path.join(TOOLS, "batch_glb.py"), in_dir, out_dir, + "--textures", tex_dir], + capture_output=True, text=True, check=False, + ) + self.assertEqual(result.returncode, 1) + self.assertIn("broken.obj", result.stdout) + self.assertIn("texture", result.stdout) + self.assertIn("car_body.dds", result.stdout) + self.assertIn("not embedded", result.stdout) + self.assertIn("(1 failed, 1 unembedded texture)", result.stdout) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_bench_wave64.py b/tests/test_bench_wave64.py index d61ca4858..1c43f7c90 100644 --- a/tests/test_bench_wave64.py +++ b/tests/test_bench_wave64.py @@ -4,13 +4,16 @@ import contextlib import fnmatch import io import os +from pathlib import Path import sys +import tempfile import unittest from unittest.mock import patch ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "scripts")) +sys.path[:0] = [os.path.join(ROOT, "scripts"), os.path.join(ROOT, "tools")] import bench_wave64 # noqa: E402 +import rdna2spirv # noqa: E402 def bench(fail): @@ -102,5 +105,31 @@ class DriverSelectors(unittest.TestCase): self.assertFalse(self._matches(selector, other), f"{selector!r} must not match {other!r}") +class SchedulerSegments(unittest.TestCase): + def setUp(self) -> None: + self.spirv = Path(self.enterContext(tempfile.TemporaryDirectory())) / "shader.spv" + + def measure(self, assembly: str) -> tuple[int, int] | None: + self.spirv.with_suffix(".spvasm").write_text(assembly, encoding="utf-8", newline="\n") + return bench_wave64.segments(str(self.spirv)) + + def test_unpartitioned_scheduler(self) -> None: + assembly = "OpSwitch %pcv %sw_default 0 %blk0 1 %blk1 3 %blk3\n" + self.assertEqual(self.measure(assembly), (3, 1)) + + def test_partitioned_scheduler(self) -> None: + cases = " ".join(f"{case} %blk{case}" for case in (*range(16_383), 16_384)) + assembly = rdna2spirv.split_big_switch( + "%zero = OpConstant %uint 0\n" + "OpSelectionMerge %sw_merge None\n" + f"OpSwitch %pcv %sw_default {cases}\n" + "%sw_default = OpLabel\n" + "OpBranch %sw_merge\n" + ) + self.assertIn("OpSwitch %pcc %sw_default", assembly) + self.assertEqual(assembly.count("OpSwitch %pcv %swm"), 2) + self.assertEqual(self.measure(assembly), (16_384, 1)) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_buffer_bounds_probe.py b/tests/test_buffer_bounds_probe.py new file mode 100644 index 000000000..82af44d0c --- /dev/null +++ b/tests/test_buffer_bounds_probe.py @@ -0,0 +1,33 @@ +"""CPU-only unit tests for tools/buffer_bounds_probe.py (SHADER-341).""" +import os +import subprocess +import sys +import unittest + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +PROBE = os.path.join(REPO, "tools", "buffer_bounds_probe.py") + + +class BufferBoundsProbeTests(unittest.TestCase): + def test_self_test(self): + proc = subprocess.run([sys.executable, "-I", PROBE, "--self-test"], + capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout) + self.assertIn("self-test OK", proc.stdout) + + def test_non_gfx10_or_missing_oracle_exits_77(self): + env = {k: v for k, v in os.environ.items() + if not k.startswith("LEONIDA_HW_") and k != "LEONIDA_AMD_CLANG"} + env["LEONIDA_AMD_CLANG"] = os.path.join(REPO, "does_not_exist_clang") + proc = subprocess.run([sys.executable, "-I", PROBE], env=env, + capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 77, proc.stderr or proc.stdout) + + def test_bad_waves(self): + proc = subprocess.run([sys.executable, "-I", PROBE, "--waves", "16"], + capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 2, proc.stderr or proc.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_build_batch_launch.py b/tests/test_build_batch_launch.py new file mode 100644 index 000000000..104c6dfd6 --- /dev/null +++ b/tests/test_build_batch_launch.py @@ -0,0 +1,83 @@ +"""The Windows build scripts start their generated batch file from any folder name, `&` and `^` included. + + python -I tests/test_build_batch_launch.py + +`scripts/build_runtime.ps1` and `scripts/build_llvm_mc.ps1` write `_build.cmd` into the build folder and start it +with `Start-Process cmd.exe -ArgumentList ...`. With `/c "path"`, cmd.exe drops the quotes when the path holds a +special character such as `&` or `^` and then runs only the part before it. This test takes each script's launch +line as written and runs it on a stub batch in such folders: the stub must run, and its exit code must come back. +Windows only (PowerShell and cmd.exe); no compiler, no game files. +""" +import base64 +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +SCRIPTS = ("build_runtime.ps1", "build_llvm_mc.ps1") +LAUNCH = re.compile(r"^\$p = Start-Process cmd\.exe -ArgumentList (.+?) -NoNewWindow -PassThru\s*$", re.M) +FOLDERS = ("plain", "a & b", "a&b", "x^y", "sp (x)", "東京 & co") + + +def launch_arguments(script): + """The -ArgumentList expression of the script's one `$p = Start-Process cmd.exe` line.""" + found = LAUNCH.findall((ROOT / "scripts" / script).read_text(encoding="utf-8-sig")) + if len(found) != 1: + raise AssertionError(f"{script}: expected one `$p = Start-Process cmd.exe -ArgumentList ...` line, found " + f"{len(found)}; update tests/test_build_batch_launch.py together with the script") + return found[0] + + +def start(arguments, bat): + """Run `$p = Start-Process cmd.exe -ArgumentList ` with $bat set, as the script does; its exit code.""" + command = ("$ErrorActionPreference = 'Stop'\n" + "$bat = $env:LEONIDA_LAUNCH_BAT\n" + f"$p = Start-Process cmd.exe -ArgumentList {arguments} -NoNewWindow -PassThru\n" + "$null = $p.Handle\n" + "$p.WaitForExit()\n" + "exit $p.ExitCode\n") + encoded = base64.b64encode(command.encode("utf-16-le")).decode("ascii") + return subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], + env=dict(os.environ, LEONIDA_LAUNCH_BAT=str(bat)), capture_output=True, timeout=60) + + +@unittest.skipUnless(sys.platform == "win32", "requires Windows PowerShell and cmd.exe") +class BatchLaunchTest(unittest.TestCase): + def check(self, arguments): + """Folders the launch line fails in, as `name/exit code` strings.""" + broken = [] + with tempfile.TemporaryDirectory() as directory: + for name in FOLDERS: + folder = Path(directory) / name + folder.mkdir() + bat = folder / "_build.cmd" + ran = folder / "ran.txt" + for code in (0, 7): + bat.write_bytes(f'@echo off\r\necho ran> "%~dp0ran.txt"\r\nexit /b {code}\r\n'.encode("ascii")) + if ran.exists(): + ran.unlink() + result = start(arguments, bat) + if not ran.exists() or result.returncode != code: + broken.append(f"{name}/{code}->{result.returncode}") + return broken + + def test_each_script_starts_its_batch_in_any_folder(self): + for script in SCRIPTS: + with self.subTest(script=script): + self.assertEqual(self.check(launch_arguments(script)), [], + f"{script}'s launch line does not run the batch in these folders") + + def test_the_check_catches_a_launch_line_that_drops_the_quotes(self): + # The form both scripts used before: cmd.exe /c "path" loses the quotes around a path holding & or ^. + broken = self.check('"/c", "`"$bat`""') + self.assertIn("a & b/0->1", broken) + self.assertIn("x^y/7->1", broken) + self.assertFalse([b for b in broken if b.startswith(("plain/", "sp (x)/"))], broken) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_build_llvm_mc_batch.py b/tests/test_build_llvm_mc_batch.py index 504ea99fd..648a60efa 100644 --- a/tests/test_build_llvm_mc_batch.py +++ b/tests/test_build_llvm_mc_batch.py @@ -16,7 +16,7 @@ class BuildBatchTest(unittest.TestCase): start = text.index('$bat = Join-Path $Temp "_build.cmd"') writer = text[start:text.index("$p = Start-Process", start)] - with tempfile.TemporaryDirectory() as directory: + with tempfile.TemporaryDirectory(prefix="leonida & llvm ") as directory: work = Path(directory) / "LLVM 東京" work.mkdir() (work / "vcvars64.bat").write_bytes(b"@exit /b 0\r\n") @@ -30,9 +30,10 @@ class BuildBatchTest(unittest.TestCase): + writer, encoding="utf-8", newline="\n", ) - (work / "check-console.cmd").write_bytes( + console_check = work / "check-console.cmd" + console_check.write_bytes( b"@echo off\r\nchcp 437 >nul || exit /b 99\r\nchcp >before.txt\r\n" - b"call _build.cmd\r\nset \"build_exit=%errorlevel%\"\r\nchcp >after.txt\r\nexit /b %build_exit%\r\n" + b'call "%~dp0_build.cmd"\r\nset "build_exit=%errorlevel%"\r\nchcp >after.txt\r\nexit /b %build_exit%\r\n' ) startup = subprocess.STARTUPINFO() startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW @@ -48,7 +49,8 @@ class BuildBatchTest(unittest.TestCase): self.assertTrue(batch.startswith(b"@echo off\r\n")) self.assertIn(str(work).encode("utf-8"), batch) result = subprocess.run( - ["cmd.exe", "/d", "/c", "check-console.cmd"], cwd=work, timeout=30, + ["cmd.exe", "/d", "/c", r".\check-console.cmd"], cwd=work, timeout=30, + env={**os.environ, "NoDefaultCurrentDirectoryInExePath": "1"}, creationflags=subprocess.CREATE_NEW_CONSOLE, startupinfo=startup, capture_output=True, ) self.assertEqual(result.returncode, code, result.stdout + result.stderr) diff --git a/tests/test_build_runtime_batch.py b/tests/test_build_runtime_batch.py index d24c5a6ed..5cb7d5ff5 100644 --- a/tests/test_build_runtime_batch.py +++ b/tests/test_build_runtime_batch.py @@ -16,7 +16,7 @@ class BuildRuntimeBatchTest(unittest.TestCase): start = text.index('$bat = Join-Path $out "_build.cmd"') writer = text[start:text.index("$p = Start-Process", start)] - with tempfile.TemporaryDirectory(prefix="leonida batch ") as directory: + with tempfile.TemporaryDirectory(prefix="leonida & batch ") as directory: checkout = Path(directory) / "Leonida 東京" checkout.mkdir() (checkout / "vcvars64.bat").write_bytes(b"@exit /b 0\r\n") @@ -39,7 +39,7 @@ class BuildRuntimeBatchTest(unittest.TestCase): self.assertTrue(batch.startswith(b"@echo off\r\n")) self.assertIn(str(checkout).encode("utf-8"), batch) subprocess.run( - ["cmd.exe", "/d", "/c", str(batch_path)], cwd=directory, + ["cmd.exe", "/d", "/c", r".\_build.cmd"], cwd=directory, env={**os.environ, "NoDefaultCurrentDirectoryInExePath": "1"}, check=True, timeout=30, ) diff --git a/tests/test_build_runtime_fallback.py b/tests/test_build_runtime_fallback.py index ca4a14c7b..a1068d6ae 100644 --- a/tests/test_build_runtime_fallback.py +++ b/tests/test_build_runtime_fallback.py @@ -34,6 +34,16 @@ class FallbackBuildsTheHarnesses(unittest.TestCase): needed = set(run_gpu_tests.REQUIRED_TEST_PROGRAMS) | set(check.TEST_PROGRAMS) | {image_fuzz.HARNESS} self.assertEqual(needed - self.programs, set(), "missing from build_runtime.ps1's cl.exe fallback") + def test_every_harness_the_gpu_suite_starts_is_built(self): + """A harness run_gpu_tests.py or check.py starts by name, but the fallback did not build, fails its test + with "could not start" (ps_ssharp: vk_sampler_test.exe, WinError 2).""" + named = set() + for path in (ROOT / "scripts" / "run_gpu_tests.py", ROOT / "runtime" / "test" / "shaders" / "check.py"): + named |= set(re.findall(r'"(vk_[a-z0-9_]+)"', path.read_text(encoding="utf-8"))) + harnesses = {n for n in named if (ROOT / "runtime" / "test" / f"{n}.cpp").is_file()} + self.assertIn("vk_sampler_test", harnesses) + self.assertEqual(harnesses - self.programs, set(), "missing from build_runtime.ps1's cl.exe fallback") + def test_the_launcher_compiles_every_source_cmake_gives_gta6rt(self): """BUILD-680: main.cpp calls rt::fs::configure, but the fallback left out shims/file_system.cpp (LNK2019). Every source of CMake's add_executable(gta6rt ...) must be in the fallback's launcher list ($files).""" diff --git a/tests/test_bvh_gpu_smoke.py b/tests/test_bvh_gpu_smoke.py new file mode 100644 index 000000000..ada1d388f --- /dev/null +++ b/tests/test_bvh_gpu_smoke.py @@ -0,0 +1,186 @@ +"""tools/bvh_gpu_smoke.py without a GPU or game files: the heap image, the word count and the judging of runs, with +a fake vk_compute_test in place of the real one.""" +import struct +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) + +import bvh_gpu_smoke as smoke # noqa: E402 + + +def fake_runner(behaviour): + """A runner that writes the heap image plus per-program changes to the dump, as vk_compute_test's VKC_DUMP does. + behaviour: name -> ("ok", writes) | ("exit 1",) | ("validation",) | ("timeout",) | ("flaky", writes).""" + calls = {} + + def run(vkc, spv, init, dump, heap_words, validation, timeout): + name = Path(spv).stem + calls[name] = calls.get(name, 0) + 1 + kind = behaviour.get(name, ("ok", {})) + if kind[0] not in ("ok", "flaky"): + return kind[0], "boom" + heap = bytearray(Path(init).read_bytes()) + assert len(heap) == heap_words * 4 + for offset, word in kind[1].items(): + if kind[0] == "flaky" and calls[name] == 2: + word ^= 1 + struct.pack_into("= (3, 12): + shutil.rmtree(path, onexc=retry) + else: + shutil.rmtree(path, onerror=retry) + + def run(args, cwd=None): return subprocess.run([sys.executable, "-I", SCRIPT, *args], cwd=cwd, capture_output=True, text=True) @@ -65,7 +84,7 @@ def run(args, cwd=None): class CheckNoGameData(unittest.TestCase): def setUp(self): self.dir = tempfile.mkdtemp() - self.addCleanup(shutil.rmtree, self.dir) + self.addCleanup(rmtree, self.dir) def write(self, name, data): path = os.path.join(self.dir, name) diff --git a/tests/test_check_tiny_frame.py b/tests/test_check_tiny_frame.py new file mode 100644 index 000000000..8c5da0091 --- /dev/null +++ b/tests/test_check_tiny_frame.py @@ -0,0 +1,81 @@ +"""The verdict logic of runtime/test/check_tiny_frame.py on synthetic output: no loader, GPU or game files.""" +import importlib.util +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SPEC = importlib.util.spec_from_file_location("check_tiny_frame", ROOT / "runtime" / "test" / "check_tiny_frame.py") +check = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(check) + + +def good_output(extra_trace=(), drop=None, binding="shim"): + """What a passing run prints: the binding report, the numbered trace and the guest's verdict.""" + calls = [call for call in list(check.EXPECTED) if call != drop] + calls[10:10] = extra_trace # between the views and the list's commands + lines = ["tiny_frame.exe base=0000000140000000 size=61440 entry=+0x1000 shim=7 host=40 module=0 unimplemented=0", + f" {binding:<13} d3d12_xs.dll!D3D12XboxCreateDevice", + "running tiny_frame.exe"] + lines += [f"[d3d12-trace] #{number} {call}" for number, call in enumerate(calls, 1)] + lines += ["tiny_frame: PASS all 32 pixels are the clear colour (64, 128, 191, 255)", "tiny_frame: OK", + "game exited with code 0", ""] + return "\n".join(lines) + + +class CheckOutputTest(unittest.TestCase): + def test_a_passing_run_has_no_problems(self): + self.assertEqual(check.check_output(0, good_output()), []) + + def test_crlf_output_and_calls_between_the_expected_ones_are_accepted(self): + output = good_output(extra_trace=["XboxID3D12CommandQueue::GetDesc called"]).replace("\n", "\r\n") + self.assertEqual(check.check_output(0, output), []) + + def test_nonzero_exit_code(self): + self.assertIn("exit code 3", check.check_output(3, good_output())) + + def test_missing_verdict_and_failed_check(self): + output = good_output().replace("tiny_frame: OK", "tiny_frame: FAIL Signal\ntiny_frame: FAILED") + problems = check.check_output(0, output) + self.assertIn("the guest did not print `tiny_frame: OK`", problems) + self.assertIn("the guest reported a failed check", problems) + + def test_missing_loader_exit_line(self): + output = good_output().replace("game exited with code 0", "game exited with code 1") + self.assertIn("gta6rt did not report `game exited with code 0`", check.check_output(0, output)) + + def test_host_binding_is_reported(self): + problems = check.check_output(0, good_output(binding="host")) + self.assertEqual(problems, ["d3d12_xs.dll!D3D12XboxCreateDevice was not bound to the shim"]) + + def test_missing_call_names_the_first_one_out_of_order(self): + problems = check.check_output(0, good_output(drop="ID3D12CommandQueue::Signal ok")) + self.assertEqual(problems, ["the trace has no `ID3D12CommandQueue::Signal ok` at its place in the " + "first-frame order"]) + + def test_a_call_that_did_not_succeed_is_reported(self): + problems = check.check_output(0, good_output(extra_trace=["ID3D12Device::CreateHeap unsupported"])) + self.assertEqual(problems, ["traced calls that did not succeed: ID3D12Device::CreateHeap unsupported"]) + + def test_a_gap_in_the_numbering_is_an_invalid_trace(self): + output = good_output().replace("[d3d12-trace] #3 ", "[d3d12-trace] #4 ") + problems = check.check_output(0, output) + self.assertEqual(len(problems), 1) + self.assertTrue(problems[0].startswith("invalid trace sequence at entry 3")) + + def test_no_trace_at_all(self): + output = "\n".join(line for line in good_output().split("\n") if not line.startswith("[d3d12-trace]")) + self.assertEqual(check.check_output(0, output), ["the trace has no `D3D12XboxCreateDevice ok` at its place " + "in the first-frame order"]) + + +class SubsequenceTest(unittest.TestCase): + def test_repeated_entries_need_as_many_occurrences(self): + self.assertIsNone(check.ordered_subsequence(["a", "a", "b"], ["a", "x", "a", "b"])) + self.assertEqual(check.ordered_subsequence(["a", "a", "b"], ["a", "b"]), "a") + + def test_order_matters(self): + self.assertEqual(check.ordered_subsequence(["a", "b"], ["b", "a"]), "b") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ci_registration.py b/tests/test_ci_registration.py index a97f435b2..957fce6f8 100644 --- a/tests/test_ci_registration.py +++ b/tests/test_ci_registration.py @@ -22,13 +22,19 @@ drift) and fails on the three ways a test goes missing without CI turning red -- * a nested ``tests/*/test_*.cjs`` file that ``fnmatch`` matches across ``/`` but the non-recursive ``node --test tests/test_*.cjs`` command never runs. -Only the tracked test files and the workflow are read; no game files, no build tools, no pytest. +It also runs the ``check`` loop itself, taken from the workflow, under bash on a synthetic tree: the loop has +to run every file and then fail, since stopping at the first failure hides the files sorted after it. + +Only the tracked test files and the workflow are read; no game files, no build tools, no pytest. The loop check +needs bash (Git for Windows' on Windows) and skips without it, except on a GitHub runner. """ import ast import fnmatch import os import re +import shutil import subprocess +import sys import tempfile import unittest from unittest import mock @@ -69,6 +75,46 @@ def ci_rules(root): return markers, pruned.rstrip("/"), loop_glob, semantic.rstrip("/"), viewer +STDLIB_STEP = "Tests (standard library only, no game data)" + + +def step_script(root, step_name): + """The ``run: |`` block of the workflow step called ``step_name``, dedented, exactly as CI runs it.""" + lines = read(root, WORKFLOW).splitlines() + for i, line in enumerate(lines): + if line.strip() == f"- name: {step_name}": + step_indent = len(line) - len(line.lstrip()) + 2 + for j in range(i + 1, len(lines)): + text = lines[j] + if text.strip() and len(text) - len(text.lstrip()) < step_indent: + break # the next step: this one has no run block + if text.strip() == "run: |": + body = [] + for k in range(j + 1, len(lines)): + if lines[k].strip() and len(lines[k]) - len(lines[k].lstrip()) <= step_indent: + break + body.append(lines[k]) + indent = min(len(b) - len(b.lstrip()) for b in body if b.strip()) + return "\n".join(b[indent:] for b in body).strip("\n") + "\n" + raise AssertionError(f"ci.yml has no step named {step_name!r} with a `run: |` block; update " + "tests/test_ci_registration.py together with the workflow") + + +def git_bash(): + """The bash GitHub's `shell: bash` uses: Git for Windows' on Windows (not WSL's), PATH's elsewhere.""" + if os.name != "nt": + return shutil.which("bash") + git = shutil.which("git") + if git: + folder = os.path.dirname(os.path.realpath(git)) + for _ in range(3): + folder = os.path.dirname(folder) + for candidate in (os.path.join(folder, "bin", "bash.exe"), os.path.join(folder, "usr", "bin", "bash.exe")): + if os.path.isfile(candidate): + return candidate + return None + + def tracked_under_tests(root): try: result = subprocess.run(["git", "ls-files", "-z", "--", "tests"], cwd=root, capture_output=True, text=True) @@ -111,11 +157,17 @@ def matches_nonrecursive_glob(rel, pattern): return directory == pattern_dir and fnmatch.fnmatchcase(name, pattern_name) -def job_of(root, rel, rules): +def job_of(root: str, rel: str, rules: tuple[str, str, str, str, str]) -> str | None: """Which job runs ``rel``: 'stdlib', 'pytest', 'semantic', 'viewer', or None for no job at all.""" markers, pruned, loop_glob, semantic, viewer = rules if rel.startswith(semantic + "/"): - return "semantic" if fnmatch.fnmatchcase(rel.rsplit("/", 1)[-1], "test*.py") else None + directory, _, name = rel.rpartition("/") + # unittest discovery only descends into packages beneath its start directory. + while directory != semantic: + if not os.path.isfile(os.path.join(root, directory, "__init__.py")): + return None + directory = directory.rpartition("/")[0] + return "semantic" if fnmatch.fnmatchcase(name, "test*.py") else None if matches_nonrecursive_glob(rel, viewer): return "viewer" if rel.startswith(pruned + "/"): @@ -245,7 +297,7 @@ class RepositoryRegistrationTest(unittest.TestCase): self.assertEqual(unselected, [], "no CI job runs these test files: " + ", ".join(unselected) + "\n" "Rename them to tests/test_*.py (or tests/test_*.cjs), put them under tests/semantic/ " - "as test*.py, or add the pattern to the job that should run them in ci.yml.") + "as test*.py with an __init__.py in each nested directory, or add the pattern to ci.yml.") def test_every_selected_file_exposes_a_test_to_its_runner(self): # Selection is not execution: pytest imports a file it is handed and reports zero items without @@ -348,6 +400,80 @@ class RepositoryRegistrationTest(unittest.TestCase): self.assertFalse(has_main_guard(read(tmp, "tests/test_inequality_guard.py"))) self.assertEqual(selected["tests/test_nested_dir/test_nested.cjs"], None) + def test_semantic_selection_matches_discovery_through_packages(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + rules = ci_rules(ROOT) + semantic = rules[3] + cases = ("test_root.py", "packaged/test_packaged.py", "bare/test_bare.py", + "bare/leaf/test_bare_ancestor.py") + for case in cases: + path = os.path.join(tmp, semantic, case) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write("import unittest\nclass Case(unittest.TestCase):\n def test_ok(self):\n pass\n") + for package in ("packaged", "bare/leaf"): + with open(os.path.join(tmp, semantic, package, "__init__.py"), "w", encoding="utf-8", newline="\n") as f: + f.write("# Package for unittest discovery.\n") + + result = subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", semantic, "-v"], + cwd=tmp, capture_output=True, text=True, timeout=15, check=True) + for case in cases: + with self.subTest(case=case): + module = case.removesuffix(".py").replace("/", ".") + discovered = f"({module}.Case.test_ok)" in result.stderr + self.assertEqual(job_of(tmp, f"{semantic}/{case}", rules) == "semantic", discovered, result.stderr) + self.assertIn("Ran 2 tests", result.stderr) + + +class StdlibLoopTest(unittest.TestCase): + """The check job's loop runs every file and then fails, so one failure cannot hide the files after it.""" + + def test_loop_runs_past_a_failure_and_names_every_failed_file(self): + if not git_bash(): + # On a runner a missing bash would turn this check into a silent skip. + self.assertFalse(os.environ.get("GITHUB_ACTIONS"), "no bash found on the CI runner") + self.skipTest("needs bash (Git for Windows on Windows)") + script = step_script(ROOT, STDLIB_STEP) + markers = ci_rules(ROOT)[0] + failing = "import sys\nif __name__ == \"__main__\":\n sys.exit(1)\n" + passing = "import sys\nif __name__ == \"__main__\":\n sys.exit(0)\n" + with tempfile.TemporaryDirectory() as tmp: + os.makedirs(os.path.join(tmp, "tests", "semantic")) + files = { + "tests/test_a_fails.py": failing, + "tests/test_b_passes.py": passing, + "tests/test_c_fails.py": failing, + "tests/test_d_pytest.py": "import pytest\n" + failing, # the loop leaves it to pytest + "tests/semantic/test_e.py": failing, # pruned: unittest discover runs it + } + for rel, text in files.items(): + with open(os.path.join(tmp, rel), "w", encoding="utf-8", newline="\n") as f: + f.write(text) + with open(os.path.join(tmp, "step.sh"), "w", encoding="utf-8", newline="\n") as f: + f.write(script) + # The step calls `python`: a shim on PATH runs this interpreter (a POSIX box may only have `python3`). + bindir = os.path.join(tmp, "bin") + os.makedirs(bindir) + shim = os.path.join(bindir, "python") + with open(shim, "w", encoding="utf-8", newline="\n") as f: + f.write("#!/bin/sh\nexec '%s' \"$@\"\n" % sys.executable.replace("'", "'\\''")) + os.chmod(shim, 0o755) + env = dict(os.environ, PYTEST_FILE_MARKERS=markers, PATH=bindir + os.pathsep + os.environ.get("PATH", "")) + # GitHub runs `shell: bash` as `bash --noprofile --norc -eo pipefail {0}`. + result = subprocess.run([git_bash(), "--noprofile", "--norc", "-eo", "pipefail", "step.sh"], cwd=tmp, + env=env, capture_output=True, text=True, timeout=120) + out = result.stdout + result.stderr + self.assertNotEqual(result.returncode, 0, out) + ran = re.findall(r"^== (\S+)$", out, re.M) + self.assertEqual(ran, ["tests/test_a_fails.py", "tests/test_b_passes.py", "tests/test_c_fails.py"], out) + errors = re.findall(r"^::error file=(\S+)::", out, re.M) + self.assertEqual(errors, ["tests/test_a_fails.py", "tests/test_c_fails.py"], out) + + def test_step_script_reads_the_check_loop(self): + script = step_script(ROOT, STDLIB_STEP) + self.assertIn('python -I "$t"', script) + self.assertIn("-name 'test_*.py'", script) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_classify_carve.py b/tests/test_classify_carve.py index 9b786cf6a..a97ad60a0 100644 --- a/tests/test_classify_carve.py +++ b/tests/test_classify_carve.py @@ -266,6 +266,24 @@ class MainTests(unittest.TestCase): self.assertEqual(proc.stdout, "") self.assertEqual(sorted(os.listdir(self.root)), ["index.json"]) # no types.json was written + def test_types_json_directory_is_one_error_line(self): + self.archive("a", [{"head": RBF0_HEAD, "size": 1}]) + report = os.path.join(self.root, "types.json") + os.mkdir(report) + proc = subprocess.run( + [sys.executable, "-I", os.path.join(ROOT, "tools", "classify_carve.py"), self.root], + capture_output=True, text=True, + ) + self.assertEqual(proc.returncode, 2) + self.assertIn("types.json", proc.stderr) + self.assertIn("is a directory", proc.stderr) + self.assertIn("remove or rename", proc.stderr) + self.assertIn("before rerun", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(os.listdir(report), []) + self.assertEqual([n for n in os.listdir(self.root) if n.startswith(".types-")], []) + def test_help_prints_usage_and_writes_nothing(self): tool = os.path.join(ROOT, "tools", "classify_carve.py") for flag in ("-h", "--help"): diff --git a/tests/test_content_definitions.py b/tests/test_content_definitions.py index d55da392a..5e9ae6a23 100644 --- a/tests/test_content_definitions.py +++ b/tests/test_content_definitions.py @@ -121,15 +121,22 @@ class ContentTests(unittest.TestCase): with tempfile.TemporaryDirectory() as directory: self.make_carve(directory, [CHANGE, CONTENT, SETUP]) cmd = [sys.executable, '-I', os.path.join(ROOT, 'tools', 'content_definitions.py'), directory] - for extra, failed in (([], 0), ([os.path.join(directory, 'private.xml')], 1)): - result = subprocess.run(cmd + extra, capture_output=True, text=True) - self.assertEqual(result.returncode, failed, result.stderr) - self.assertEqual(json.loads(result.stdout), dict(documents=3, change_sets=1, contents=1, - setups=1, files=2, included_changesets=1, included_sets=1, groups=1, - other_xml=0, failed_inputs=failed)) - self.assertEqual(result.stderr, '') - self.assertNotIn('fixture', result.stdout) - self.assertNotIn(directory, result.stdout) + result = subprocess.run(cmd, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout), dict(documents=3, change_sets=1, contents=1, + setups=1, files=2, included_changesets=1, included_sets=1, groups=1, + other_xml=0, failed_inputs=0)) + self.assertEqual(result.stderr, '') + self.assertNotIn('fixture', result.stdout) + self.assertNotIn(directory, result.stdout) + + missing = os.path.join(directory, 'private.xml') + result = subprocess.run(cmd + [missing], capture_output=True, text=True) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertEqual(json.loads(result.stdout), dict(documents=3, change_sets=1, contents=1, + setups=1, files=2, included_changesets=1, included_sets=1, groups=1, + other_xml=0, failed_inputs=1)) + self.assertEqual(result.stderr.strip().splitlines(), [f'ERROR: {missing}: does not exist']) if __name__ == '__main__': diff --git a/tests/test_cpu_ref.py b/tests/test_cpu_ref.py index c27a19418..743b33ecb 100644 --- a/tests/test_cpu_ref.py +++ b/tests/test_cpu_ref.py @@ -489,6 +489,64 @@ class CpuRefTest(unittest.TestCase): with self.assertRaises(ValueError): cpu_ref.run(path, {"sgprs": {0: 1}}) + def test_bit_and_vop3_integer_ops(self): + r = self.execute(""" + v_mov_b32 v0, 0x00ff0001 + v_not_b32 v1, v0 + v_bfrev_b32 v2, 0x12345678 + v_ffbl_b32 v3, 0x00010100 + v_ffbh_u32 v4, 0x00010000 + v_ffbh_i32 v5, 0xfffffff0 + v_mov_b32 v15, 0x00ff00ff + v_xnor_b32 v6, 0x0f0f0f0f, v15 + v_bcnt_u32_b32 v7, 0xf0f0f0f0, 3 + v_add3_u32 v8, 10, 20, 30 + v_lshl_add_u32 v9, 3, 2, 5 + v_add_lshl_u32 v10, 3, 5, 2 + v_lshl_or_b32 v11, 3, 4, 1 + v_and_or_b32 v12, 0xf0, 0x3c, 1 + v_or3_b32 v13, 1, 2, 4 + v_xad_u32 v14, 0x5, 0x3, 10 + ; Edge cases: zero/all-ones, positive ffbh_i32, shift > 31, 32-bit overflow, overlapping or3/lshl_or + v_ffbl_b32 v16, 0 + v_ffbh_u32 v17, 0 + v_ffbh_i32 v18, 0 + v_ffbh_i32 v19, -1 + v_ffbh_i32 v20, 0x00100000 + v_lshl_add_u32 v21, 3, 33, 5 + v_add_lshl_u32 v22, 3, 5, 34 + v_lshl_or_b32 v23, 3, 33, 2 + v_add3_u32 v24, 0xffffffff, 2, 3 + v_bcnt_u32_b32 v25, 0xffffffff, 0xfffffffe + v_or3_b32 v26, 3, 6, 12 + s_endpgm + """) + self.assertEqual(self.vgpr(r, 1), 0xFF00FFFE) + self.assertEqual(self.vgpr(r, 2), 0x1E6A2C48) + self.assertEqual(self.vgpr(r, 3), 8) + self.assertEqual(self.vgpr(r, 4), 15) + self.assertEqual(self.vgpr(r, 5), 28) + self.assertEqual(self.vgpr(r, 6), 0xF00FF00F) + self.assertEqual(self.vgpr(r, 7), 19) + self.assertEqual(self.vgpr(r, 8), 60) + self.assertEqual(self.vgpr(r, 9), 17) + self.assertEqual(self.vgpr(r, 10), 32) + self.assertEqual(self.vgpr(r, 11), 49) + self.assertEqual(self.vgpr(r, 12), 0x31) + self.assertEqual(self.vgpr(r, 13), 7) + self.assertEqual(self.vgpr(r, 14), 16) + self.assertEqual(self.vgpr(r, 16), 0xFFFFFFFF) + self.assertEqual(self.vgpr(r, 17), 0xFFFFFFFF) + self.assertEqual(self.vgpr(r, 18), 0xFFFFFFFF) + self.assertEqual(self.vgpr(r, 19), 0xFFFFFFFF) + self.assertEqual(self.vgpr(r, 20), 11) + self.assertEqual(self.vgpr(r, 21), 11) # (3 << (33 & 31)) + 5 + self.assertEqual(self.vgpr(r, 22), 32) # 8 << (34 & 31) + self.assertEqual(self.vgpr(r, 23), 6) # (3 << 1) | 2 (overlapping bit 1, differs from +) + self.assertEqual(self.vgpr(r, 24), 4) # wrapped 32-bit sum + self.assertEqual(self.vgpr(r, 25), 30) # 32 + 0xfffffffe mod 2^32 (differs from 32 ^ 0xfffffffe) + self.assertEqual(self.vgpr(r, 26), 15) # overlapping 3 | 6 | 12 (differs from 3 ^ 6 ^ 12) + def test_malformed_register_assignments_are_cli_errors(self): path = self.write("s_endpgm") for option, assignment, flags in ( diff --git a/tests/test_crosslane_fuzz.py b/tests/test_crosslane_fuzz.py index 8b8552bdd..40623a023 100644 --- a/tests/test_crosslane_fuzz.py +++ b/tests/test_crosslane_fuzz.py @@ -633,5 +633,277 @@ class HarnessErrors(unittest.TestCase): self.assertIn("match 3, mismatch 0, hyp_only 0, rejected 0, harness_errors 0", out) +def mask_name(text): + """'vcc' / 'exec' / the first SGPR of 's[16:17]', as Wave.mask takes it.""" + m = re.fullmatch(r"s\[(\d+):\d+\]", text) + return int(m.group(1)) if m else text + + +def ext_gen(seed=1, group=64): + g = X.Gen(random.Random(seed), 64, group, ext=True) + g.masks += ["vcc", 16, 18, 20] + return g + + +class Ext(unittest.TestCase): + """--ext: the wave64 extension ops, each against values worked out by hand from the rule in the docstring.""" + + def test_only_wave64_programs_change(self): + self.assertEqual(X.make_program(5, 32, 24, ext=True).source(), X.make_program(5, 32, 24).source()) + a, b = X.make_program(5, 64, 24, ext=True), X.make_program(5, 64, 24, ext=True) + self.assertEqual(a.source(), b.source()) + self.assertEqual(a.expected()[0], b.expected()[0]) + self.assertNotEqual(a.source(), X.make_program(5, 64, 24).source()) + g32 = X.Gen(random.Random(1), 32, 32, ext=True) + for name, _ in X.Gen.EXT_WEIGHTS: + self.assertIsNone(getattr(g32, name)(), name) + + def test_every_ext_op_is_generated(self): + seen = set() + for seed in range(60): + p = X.make_program(seed, 64, 24, ext=True) + p.expected() # the model runs every op + seen |= {t for o in p.ops for t in getattr(o, "tags", {o.tag})} + self.assertLessEqual({"scan64", "mask_scc", "cselect64", "mask_test", "bfm", "wqm", "carry", "bpermute", + "permute", "swizzle", "lane_wrap", "loop"}, seen) + + def test_carry_in_and_out(self): + # 0xffffffff + 0 + carry-in: the sum wraps to 0 and carries exactly where the carry-in is set. Lanes 48-63 + # are off: they keep vD and their carry-out bit is 0. + o = draw(ext_gen(), "op_carry", lambda o: o.text.startswith("v_add_co_ci_u32_e64") and + len(set(operands(o.text)[i] for i in (0, 2, 3))) == 3) + d, mo, a, b, mi = operands(o.text) + d, a, b = int(d[1:]), int(a[1:]), int(b[1:]) + w = wave() + w.exec = (1 << 48) - 1 + w.v[a], w.v[b], w.v[d] = [0xFFFFFFFF] * 64, [0] * 64, [7] * 64 + w.set_mask(mask_name(mi), 0xFFFF0000FFFF00F0) + o.apply([w]) + self.assertEqual(w.mask(mask_name(mo)), 0x00000000FFFF00F0) + self.assertEqual([w.vr(d)[l] for l in (0, 4, 15, 16, 31, 47, 48, 63)], + [0xFFFFFFFF, 0, 0xFFFFFFFF, 0, 0, 0xFFFFFFFF, 7, 7]) + + def test_subrev_borrow(self): + # v_subrev_co: D = S1 - S0; 5 - 9 borrows, 9 - 5 does not. + o = draw(ext_gen(2), "op_carry", lambda o: o.text.startswith("v_subrev_co_u32_e64") and + len(set(operands(o.text)[i] for i in (0, 2, 3))) == 3) + d, mo, a, b = operands(o.text) + d, a, b = int(d[1:]), int(a[1:]), int(b[1:]) + w = wave() + w.v[a] = [9 if l < 40 else 5 for l in range(64)] + w.v[b] = [5 if l < 40 else 9 for l in range(64)] + o.apply([w]) + self.assertEqual(w.mask(mask_name(mo)), (1 << 40) - 1) + self.assertEqual((w.vr(d)[0], w.vr(d)[63]), (0xFFFFFFFC, 4)) + + def test_bpermute_stays_in_its_half_and_reads_0_from_an_inactive_lane(self): + o = draw(ext_gen(3), "op_bpermute", lambda o: "offset" not in o.text and + len(set(operands(o.text.split("\n")[0]))) == 3) + d, ad, dat = (int(t[1:]) for t in operands(o.text.split("\n")[0])) + self.assertEqual(o.text.split("\n")[1].strip(), "s_waitcnt lgkmcnt(0)") + w = wave() + w.exec = X.M64 & ~(1 << 5) & ~(1 << 40) + w.v[ad] = [4 * (l + 1) for l in range(64)] # lane l reads lane (l + 1) & 31 of its half + w.v[dat] = [100 + l for l in range(64)] + w.v[d] = [7] * 64 + o.apply([w]) + got = w.vr(d) + self.assertEqual([got[l] for l in (0, 4, 5, 6, 31, 32, 39, 40, 63)], [101, 0, 7, 107, 100, 133, 0, 7, 132]) + + def test_permute_scatters_and_the_highest_sender_wins(self): + g = ext_gen(4) + o = draw(g, "op_permute", lambda o: o.text.startswith("ds_permute_b32") and "offset" not in o.text and + len(set(operands(o.text.split("\n")[0]))) == 3) + d, ad, dat = (int(t[1:]) for t in operands(o.text.split("\n")[0])) + w = wave() + w.v[dat] = [100 + l for l in range(64)] + w.v[ad] = [0] * 64 # every lane sends to lane 0 of its half + o.apply([w]) + self.assertEqual([w.vr(d)[l] for l in (0, 1, 31, 32, 33)], [131, 0, 0, 163, 0]) + w.v[ad] = [4 * (l ^ 1) for l in range(64)] # a permutation: lane l sends to lane l ^ 1 + w.v[d] = [7] * 64 + w.exec = X.M64 & ~(1 << 2) # lane 2 neither sends nor is written + o.apply([w]) + self.assertEqual([w.vr(d)[l] for l in (0, 1, 2, 3, 62)], [101, 100, 7, 0, 163]) + + def test_permute_with_generated_addresses_is_a_permutation(self): + o = draw(ext_gen(5), "op_permute", lambda o: o.text.startswith("v_mad_u32_u24") and + len(set(operands(o.text.split("\n")[2].split(" offset")[0]))) == 3) + d, ad, dat = (int(t[1:]) for t in operands(o.text.split("\n")[2].split(" offset")[0])) + self.assertEqual(ad, X.PERM_V) + w = wave() + w.v[1] = list(range(64)) + w.v[dat] = [100 + l for l in range(64)] + o.apply([w]) + self.assertEqual(sorted(w.vr(d)[:32]), [100 + l for l in range(32)]) # each half is permuted in itself + self.assertEqual(sorted(w.vr(d)[32:]), [132 + l for l in range(32)]) + + def test_swizzle_modes(self): + g = ext_gen(6) + rev = draw(g, "op_swizzle", lambda o: "swizzle(REVERSE,8)" in o.text and + len(set(operands(o.text.split(" offset")[0]))) == 2) + d, v = (int(t[1:]) for t in operands(rev.text.split(" offset")[0])) + w = wave() + w.v[v] = [100 + l for l in range(64)] + self.assertFalse(rev.apply([w])) + self.assertEqual([w.vr(d)[l] for l in (0, 7, 8, 33)], [107, 100, 115, 138]) + w.exec = X.M64 & ~(1 << 7) # lane 0's source is off: it reads 0, reported apart + self.assertTrue(rev.apply([w])) + self.assertEqual((w.vr(d)[0], w.vr(d)[1]), (0, 106)) + quad = draw(g, "op_swizzle", lambda o: "QUAD_PERM" in o.text and + len(set(operands(o.text.split(" offset")[0]))) == 2) + d, v = (int(t[1:]) for t in operands(quad.text.split(" offset")[0])) + q = [int(x) for x in re.search(r"QUAD_PERM, (\d), (\d), (\d), (\d)", quad.text).groups()] + w = wave() + w.v[v] = [100 + l for l in range(64)] + quad.apply([w]) + self.assertEqual([w.vr(d)[l] for l in (0, 5, 62)], [100 + q[0], 104 + q[1], 160 + q[2]]) + bits = draw(g, "op_swizzle", lambda o: "BITMASK_PERM" in o.text and + len(set(operands(o.text.split(" offset")[0]))) == 2) + pat = re.search(r'BITMASK_PERM, "([01pi]{5})"', bits.text).group(1) + d, v = (int(t[1:]) for t in operands(bits.text.split(" offset")[0])) + w = wave() + w.v[v] = [100 + l for l in range(64)] + bits.apply([w]) + lane = 37 # lane 5 of the upper half + src = 0 + for i, ch in enumerate(pat): # bit 4 first + bit = 1 << (4 - i) + own = (lane & 31) & bit + src |= bit if ch == "1" else 0 if ch == "0" else own if ch == "p" else own ^ bit + self.assertEqual(w.vr(d)[lane], 100 + (32 | src), pat) + + def test_lane_select_wraps_at_64(self): + o = draw(ext_gen(7), "op_lane_wrap", lambda o: "v_readlane_b32" in o.text) + enc = int(re.search(r"s_mov_b32 s28, (\d+)", o.text).group(1)) + d, v = re.search(r"v_readlane_b32 s(\d+), v(\d+), s28", o.text).groups() + self.assertGreaterEqual(enc, 64) + w = wave() + w.v[int(v)] = [100 + l for l in range(64)] + o.apply([w]) + self.assertEqual(w.s[int(d)], 100 + (enc & 63)) + + def probe(self, text): + d, a, b = (int(x) for x in re.search(r"s_cselect_b32 s(\d+), s(\d+), s(\d+)", text).groups()) + return d, a, b + + def test_wrexec_and_saveexec_forms(self): + g = ext_gen(8) + wr = draw(g, "op_exec_logic", lambda o: o.text.startswith("s_andn2_wrexec_b64")) + dst, src = (mask_name(t) for t in operands(wr.text.split("\n")[0])) + w = wave() + w.exec = 0x00FF + w.set_mask(src, 0x0FF0) + wr.apply([w]) # EXEC = S0 & ~EXEC; D = EXEC + self.assertEqual((w.exec, w.mask(dst)), (0x0F00, 0x0F00)) + nor = draw(g, "op_exec_logic", lambda o: o.text.startswith("s_nor_saveexec_b64")) + dst, src = (mask_name(t) for t in operands(nor.text.split("\n")[0])) + w = wave() + w.exec = X.M64 & ~0xFF + w.set_mask(src, 0xF0) + nor.apply([w]) # D = EXEC; EXEC = ~(S0 | EXEC) = lanes 0-3 + self.assertEqual((w.exec, w.mask(dst)), (0x0F, X.M64 & ~0xFF)) + partial = X.Gen(random.Random(8), 64, 40, ext=True) + partial.masks += [16] + for _ in range(300): # a partial wave never gets a form that complements a mask + self.assertNotRegex(partial.op_exec_logic().text, r"s_(orn1|orn2|nand|nor|xnor)_") + + def test_bfm_and_wqm(self): + g = ext_gen(9) + bfm = draw(g, "op_bfm", lambda o: re.fullmatch(r"s_bfm_b64 s\[\d+:\d+\], s(\d+), s(\d+)", o.text) and + len(set(operands(o.text)[1:])) == 2) + dst, sa, sb = operands(bfm.text) + w = wave() + w.s[int(sa[1:])], w.s[int(sb[1:])] = 64 + 5, 128 + 40 # size 5 at offset 40: the counts are taken mod 64 + bfm.apply([w]) + self.assertEqual(w.mask(mask_name(dst)), 0x1F << 40) + wqm = draw(g, "op_wqm", lambda o: len(set(operands(o.text.split("\n")[0]))) == 2) + dst, src = (mask_name(t) for t in operands(wqm.text.split("\n")[0])) + w = wave() + if src == "exec": + w.exec = 0x0000000100000100 + else: + w.set_mask(src, 0x0000000100000100) + wqm.apply([w]) + self.assertEqual(w.mask(dst), 0x0000000F00000F00) + self.assertIsNone(X.Gen(random.Random(1), 64, 40, ext=True).op_bfm()) # full waves only + + def test_mask_scan_and_tests(self): + g = ext_gen(10) + ff0 = draw(g, "op_scan64", lambda o: o.text.startswith("s_ff0_i32_b64") and "exec" not in o.text) + d, m = operands(ff0.text) + w = wave() + w.set_mask(mask_name(m), (1 << 37) - 1) + ff0.apply([w]) + self.assertEqual(w.s[int(d[1:])], 37) + w.set_mask(mask_name(m), X.M64) + ff0.apply([w]) + self.assertEqual(w.s[int(d[1:])], 0xFFFFFFFF) + bit = draw(g, "op_mask_test", lambda o: o.text.startswith("s_bitcmp1_b64") and "exec" not in o.text and + len(set(self.probe(o.text))) == 3) + m, lane = operands(bit.text.split("\n")[0]) + d, a, b = self.probe(bit.text) # s_cselect_b32 sD, sA, sB: D = SCC ? A : B + w = wave() + w.s[a], w.s[b] = 111, 222 + w.set_mask(mask_name(m), 1 << int(lane)) + bit.apply([w]) + self.assertEqual(w.s[d], 111) + w.set_mask(mask_name(m), X.M64 & ~(1 << int(lane))) + bit.apply([w]) + self.assertEqual(w.s[d], 222) + + def test_loop_runs_each_lane_its_own_trip_count(self): + # Trip limit = lane & 3, all 64 lanes on: 64, 48, 32 and 16 lanes run iterations 1 to 4, and each lane adds + # the count of every iteration it runs: 64, 112, 144 or 160. + g = ext_gen(11) + g.LOOP_BODY = ("op_salu",) + loop = draw(g, "op_loop", lambda o: o.text.startswith("v_and_b32_e32 v24, 3, v") and + re.search(r"v_and_b32_e32 v24, 3, v(\d+)", o.text).group(1) != + re.search(r"v_add_nc_u32_e32 v(\d+), s\d+, v\d+", o.text).group(1)) + src = int(re.search(r"v_and_b32_e32 v24, 3, v(\d+)", loop.text).group(1)) + vx = int(re.search(r"v_add_nc_u32_e32 v(\d+), s\d+, v\d+", loop.text).group(1)) + k = re.search(r";@LOOP(\d+)", loop.text).group(1) + self.assertIn(f"s_cbranch_execnz @-{k}", loop.text) + w = wave() + w.v[src] = list(range(64)) + w.v[vx] = [1000] * 64 + loop.apply([w]) + self.assertEqual(w.exec, X.M64) # EXEC comes back from the break mask + self.assertEqual(w.mask(X.LOOP_S[0]), X.M64) + self.assertEqual([w.vr(vx)[l] for l in (0, 1, 2, 3, 60, 63)], [1064, 1112, 1144, 1160, 1064, 1160]) + w = wave() # a wave that enters with EXEC 0 runs the body once + w.exec = 0 + w.v[vx] = [1000] * 64 + loop.apply([w]) + self.assertEqual((w.exec, w.vr(vx)[0]), (0, 1000)) + + def test_branch_offsets_forward_and_back(self): + lines = ["a", ";@LOOP0", "b", "c", "s_cbranch_execnz @-0", "s_cbranch_execz @1", "d", ";@END1", "e"] + sizes = {0: 1, 2: 1, 3: 2, 4: 1, 5: 1, 6: 3, 8: 1} + out = X.branch_offsets(lines, sizes) + self.assertEqual(out[4], "s_cbranch_execnz -4") # back over b, c and the branch itself + self.assertEqual(out[5], "s_cbranch_execz 3") # forward over d + self.assertEqual([out[i] for i in (0, 1, 2, 3, 6, 7, 8)], [lines[i] for i in (0, 1, 2, 3, 6, 7, 8)]) + + def test_native_kernel_has_a_label_for_every_loop(self): + loops = 0 + for seed in range(40): + prog = X.make_program(seed, 64, 24, ext=True) + plain, guarded = prog.hw_lines(guard=False), prog.hw_lines(guard=True) + text = "\n".join(plain) + self.assertNotIn("@", text) + targets = re.findall(r"s_cbranch_\w+ (\.L\S+)", text) + for t in targets: + self.assertIn(t + ":", plain) + self.assertEqual(len(targets), len(set(targets))) + back = [t for t in targets if re.search(r"_B\d+$", t)] + loops += len(back) + for t in back: # a loop's label is above its branch + self.assertLess(plain.index(t + ":"), plain.index(f"s_cbranch_execnz {t}")) + labels = [ln for ln in plain if ln.endswith(":")] + self.assertEqual(len(guarded), 2 * (len(plain) - len(labels)) - 1 + len(labels)) + self.assertGreater(loops, 10) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_cs_wave_probe_spv.py b/tests/test_cs_wave_probe_spv.py new file mode 100644 index 000000000..4ed930ac7 --- /dev/null +++ b/tests/test_cs_wave_probe_spv.py @@ -0,0 +1,47 @@ +"""runtime/test/cs_wave_probe_spv.h is the SPIR-V of runtime/test/glsl/cs_wave_probe.comp (vk_compute_test's +subgroup probe). Run: python -I tests/test_cs_wave_probe_spv.py""" +import os +import re +import shutil +import struct +import subprocess +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +HEADER = os.path.join(ROOT, "runtime", "test", "cs_wave_probe_spv.h") +SOURCE = os.path.join(ROOT, "runtime", "test", "glsl", "cs_wave_probe.comp") + + +def header_words(): + with open(HEADER, encoding="utf-8") as f: + return [int(x, 16) for x in re.findall(r"0x([0-9a-f]{8})u", f.read())] + + +class WaveProbeSpirv(unittest.TestCase): + def test_header_is_spirv_1_5(self): + # Below 1.6, so varying subgroup sizes are not allowed in the probe either (as in the translator's output). + w = header_words() + self.assertEqual(w[0], 0x07230203) + self.assertEqual(w[1], 0x00010500) + + def test_header_matches_the_glsl(self): + glslang = shutil.which("glslangValidator") + if not glslang: + self.skipTest("glslangValidator is not on PATH") + version = subprocess.run([glslang, "--version"], capture_output=True, text=True).stdout + if "16.6.0" not in version: # another glslang may emit other (equally valid) code + self.skipTest("the header was generated with glslang 16.6.0") + with tempfile.TemporaryDirectory() as tmp: + out = os.path.join(tmp, "cs_wave_probe.spv") + subprocess.run([glslang, "-V", "--target-env", "vulkan1.2", "-Os", "-o", out, SOURCE], check=True, + stdout=subprocess.DEVNULL) + with open(out, "rb") as f: + data = f.read() + words = list(struct.unpack(f"<{len(data) // 4}I", data)) + # Word 2 is the generator (glslang's version); the rest must be what the header holds. + self.assertEqual(words[:2] + words[3:], header_words()[:2] + header_words()[3:]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cvt_norm_mods_probe.py b/tests/test_cvt_norm_mods_probe.py new file mode 100644 index 000000000..d6caea1a3 --- /dev/null +++ b/tests/test_cvt_norm_mods_probe.py @@ -0,0 +1,303 @@ +"""Unit tests for tools/cvt_norm_mods_probe.py (reference model, kernel assembly, FakeOracle verdicts, CLI). + +Standard library only; no GPU, no LLVM required (live assembly tests skip when unavailable), and no game files. +""" +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +TOOLS = Path(__file__).resolve().parents[1] / "tools" +sys.dont_write_bytecode = True +if str(TOOLS) not in sys.path: + sys.path.insert(0, str(TOOLS)) + +import cvt_norm_mods_probe as pr # noqa: E402 +from hw_oracle import asm, runner # noqa: E402 + + +def _eval_f32_src_mod(bits: int, expr: str) -> int: + if "|" in expr: + bits &= 0x7FFFFFFF + if expr.startswith("-"): + bits ^= 0x80000000 + return bits & pr.M32 + + +def _eval_f16_src_mod(bits16: int, expr: str) -> int: + bits16 &= pr.M16 + if "|" in expr: + bits16 &= 0x7FFF + if expr.startswith("-"): + bits16 ^= 0x8000 + return bits16 + + +class FakeOracle: + """Simulated hw_oracle backend parsing probe kernels and computing reference outputs.""" + + arch = "gfx1036" + device = "fake gfx1036" + + def __init__(self, *, bad_word: bool = False, wave64_diff: bool = False, error_msg: str | None = None): + self.bad_word = bad_word + self.wave64_diff = wave64_diff + self.error_msg = error_msg + self.closed = False + + def run(self, kernels, words=4): + del words + out = [] + for k in kernels: + if self.error_msg is not None: + out.append(self.error_msg) + continue + lines = k.lines + joined = "\n".join(lines) + m_sweep = re.search(r"v_add_nc_u32_e32 v11, (\d+), v10", joined) + if m_sweep: + base_word = int(m_sweep.group(1)) + m_op = re.search(r"(v_cvt_norm_[iu]16_f16)_e64", joined) + assert m_op is not None, joined + res = pr.expected_sweep_words(m_op.group(1))[base_word : base_word + 16384] + if self.bad_word: + res[0] ^= 1 + if self.wave64_diff and k.wave == 64: + res[0] ^= 1 + out.append(res) + continue + + regs: dict[str, int] = {} + res = [] + for ln in lines: + m_mov = re.match(r"v_mov_b32_e32 (v\d+), (0x[0-9a-fA-F]+|\d+)$", ln) + if m_mov: + regs[m_mov.group(1)] = int(m_mov.group(2), 0) & pr.M32 + continue + m_sdwa = re.match(r"(v_cvt_norm_[iu]16_f16)_sdwa v0, ([^ ]+)(.*)", ln) + if m_sdwa: + op, src_expr, tail = m_sdwa.groups() + snorm = op == "v_cvt_norm_i16_f16" + src = regs["v1"] + h = (src >> 16) & pr.M16 if "src0_sel:WORD_1" in tail else (src & pr.M16) + h = _eval_f16_src_mod(h, src_expr) + val16 = pr.expected_norm_f16(h, snorm) + seed = regs["v0"] + if "dst_sel:WORD_1" in tail: + w = (val16 << 16) | (seed & pr.M16) + elif "UNUSED_PRESERVE" in tail: + w = (seed & 0xFFFF0000) | val16 + elif "UNUSED_SEXT" in tail: + w = (0xFFFF0000 | val16) if (val16 & 0x8000) else val16 + else: + w = val16 + res.append(w & pr.M32) + continue + m_e64 = re.match(r"(v_cvt_norm_[iu]16_f16)_e64 v0, ([^ ]+)", ln) + if m_e64: + op, src_expr = m_e64.groups() + snorm = op == "v_cvt_norm_i16_f16" + h = _eval_f16_src_mod(regs["v1"] & pr.M16, src_expr) + val16 = pr.expected_norm_f16(h, snorm) + res.append((regs["v0"] & 0xFFFF0000) | val16) + continue + m_pk = re.match(r"(v_cvt_pknorm_[iu]16_f32) v0, ([^,]+), ([^ ]+)(?: clamp)?$", ln) + if m_pk: + op, s0_expr, s1_expr = m_pk.groups() + s0 = _eval_f32_src_mod(regs["v1"], s0_expr) + s1 = _eval_f32_src_mod(regs["v2"], s1_expr) + res.append(pr.expected_pknorm_f32(op, s0, s1)) + continue + + if res: + if self.bad_word: + res[0] ^= 1 + if self.wave64_diff and k.wave == 64: + res[0] ^= 1 + out.append(res) + return out + + def close(self): + self.closed = True + + +def _run_main(oracle, *args): + buf = io.StringIO() + err = io.StringIO() + with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf), redirect_stderr(err): + rc = pr.main(list(args)) + return rc, buf.getvalue(), err.getvalue() + + +class ReferenceModelTests(unittest.TestCase): + def test_self_test(self): + with redirect_stdout(io.StringIO()): + self.assertEqual(pr.self_test(), 0) + + def test_norm_f16_single_rounding_ties_and_edges(self): + # Single-rounding near +-0.5 vs f32 double-rounding + self.assertEqual(pr.expected_norm_f16(0x3800, True), 16384) + self.assertEqual(pr.expected_norm_f16(0x3801, True), 16399) + self.assertEqual(pr.expected_norm_f16(0xB801, True), (-16399) & 0xFFFF) + self.assertEqual(pr.expected_norm_f16(0x37FF, True), 16376) + self.assertEqual(pr.expected_norm_f16(0xB7FF, True), (-16376) & 0xFFFF) + self.assertEqual(pr.expected_norm_f16(0x3800, False), 32768) + self.assertEqual(pr.expected_norm_f16(0x3801, False), 32799) + self.assertEqual(pr.expected_norm_f16(0x37FF, False), 32752) + # Out-of-range, infinities, NaNs, subnormals + self.assertEqual(pr.expected_norm_f16(0x4000, True), 0x7FFF) + self.assertEqual(pr.expected_norm_f16(0xC000, True), 0x8001) + self.assertEqual(pr.expected_norm_f16(0xC000, False), 0) + self.assertEqual(pr.expected_norm_f16(0x7C00, False), 0xFFFF) + self.assertEqual(pr.expected_norm_f16(0xFC00, True), 0x8001) + self.assertEqual(pr.expected_norm_f16(0x7C01, True), 0) + self.assertEqual(pr.expected_norm_f16(0xFE00, False), 0) + self.assertEqual(pr.expected_norm_f16(0x0001, True), 0) + self.assertEqual(pr.expected_norm_f16(0x03FF, False), 4) + + def test_pknorm_f32_edges_and_near_ties(self): + self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x38400180, 0x00000000), 0x00000001) + self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x3C004101, 0xBF800000), 0x80010101) + self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_u16_f32", 0x37C000C0, 0x40000000), 0xFFFF0001) + self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_u16_f32", 0x3B008081, 0xBF800000), 0x00000081) + self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x7F800001, 0xFF800000), 0x80010000) + + def test_kernel_builders_have_unique_labels_and_endpgm(self): + kernels, meta = pr.build_jobs(list(pr.OPS), [32, 64]) + self.assertEqual(len(kernels), len(meta)) + labels = [] + for k in kernels: + self.assertEqual(k.lines[-2:], ["s_waitcnt vmcnt(0)", "s_endpgm"]) + for ln in k.lines: + if ln.endswith(":"): + labels.append(ln[:-1]) + self.assertEqual(len(labels), len(set(labels)), "duplicate loop labels across kernels") + + def test_kernels_assemble_when_amd_clang_available(self): + try: + clang = runner.find_clang() + except runner.Unavailable as e: + self.skipTest(str(e)) + for wave in (32, 64): + kernels, _ = pr.build_jobs(list(pr.OPS), [wave]) + text, _, _ = asm.module_text(kernels, "gfx1036", wave=wave) + with tempfile.TemporaryDirectory() as d: + s_path = Path(d) / "k.s" + o_path = Path(d) / "k.o" + with open(s_path, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + flags = ["-mwavefrontsize64"] if wave == 64 else [] + res = subprocess.run( + [clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1036", *flags, "-c", str(s_path), "-o", str(o_path)], + capture_output=True, + text=True, + ) + self.assertEqual(res.returncode, 0, res.stderr[:800]) + + def test_kernels_assemble_when_llvm_mc_available(self): + llvm_mc = os.environ.get("LLVM_MC") or shutil.which("llvm-mc") + if not llvm_mc or not os.path.isfile(llvm_mc): + self.skipTest("llvm-mc not found") + for wave in (32, 64): + kernels, _ = pr.build_jobs(list(pr.OPS), [wave]) + text, _, _ = asm.module_text(kernels, "gfx1036", wave=wave) + flags = ["-mattr=+wavefrontsize64"] if wave == 64 else [] + res = subprocess.run( + [llvm_mc, "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1036", *flags, "-filetype=obj", "-o", os.devnull], + input=text, + capture_output=True, + text=True, + ) + self.assertEqual(res.returncode, 0, res.stderr[:800]) + + +class ProbeCliTests(unittest.TestCase): + def test_fake_oracle_pass_and_json_lf(self): + oracle = FakeOracle() + with tempfile.TemporaryDirectory() as d: + report = os.path.join(d, "nested", "report.json") + rc, out, err = _run_main(oracle, "--json", report) + self.assertEqual(rc, 0, out + err) + self.assertTrue(oracle.closed) + self.assertIn("mismatches=0, wave_diffs=0", out) + with open(report, "rb") as f: + raw = f.read() + self.assertNotIn(b"\r\n", raw) + doc = json.loads(raw.decode("utf-8")) + self.assertEqual(doc["arch"], "gfx1036") + self.assertEqual(doc["waves"], [32, 64]) + self.assertEqual(doc["ops"], list(pr.OPS)) + self.assertEqual(doc["mismatches"], 0) + self.assertEqual(doc["wave_diffs"], 0) + self.assertEqual(doc["total_words"], 1050708) + + def test_fake_oracle_word_mismatch_exits_1(self): + rc, out, _ = _run_main(FakeOracle(bad_word=True), "--ops", "v_cvt_pknorm_i16_f32", "--waves", "32") + self.assertEqual(rc, 1, out) + self.assertIn("MISMATCH", out) + + def test_fake_oracle_wave_diff_exits_1(self): + rc, out, _ = _run_main(FakeOracle(wave64_diff=True), "--ops", "v_cvt_pknorm_u16_f32", "--waves", "32,64") + self.assertEqual(rc, 1, out) + self.assertIn("WAVE DIFF", out) + + def test_fake_oracle_harness_error_exits_2(self): + rc, out, _ = _run_main( + FakeOracle(error_msg="assembler rejected: test"), "--ops", "v_cvt_pknorm_i16_f32", "--waves", "32" + ) + self.assertEqual(rc, 2, out) + self.assertIn("harness error", out) + + def test_bad_cli_args_exit_2(self): + for bad_waves in ("", "16", "32,", "32,,64", "abc"): + with self.subTest(waves=bad_waves): + rc, _, err = _run_main(FakeOracle(), "--waves", bad_waves) + self.assertEqual(rc, 2) + self.assertIn("--waves", err) + for bad_ops in ("", "v_not_an_op", "v_cvt_norm_i16_f16,"): + with self.subTest(ops=bad_ops): + rc, _, err = _run_main(FakeOracle(), "--ops", bad_ops) + self.assertEqual(rc, 2) + self.assertIn("--ops", err) + + def test_json_directory_refused_and_unwritable_path_exits_2(self): + with tempfile.TemporaryDirectory() as d: + rc, _, err = _run_main(FakeOracle(), "--ops", "v_cvt_pknorm_i16_f32", "--waves", "32", "--json", d) + self.assertEqual(rc, 2) + self.assertIn("ERROR:", err) + self.assertNotIn("Traceback", err) + blocker = os.path.join(d, "file_not_dir") + with open(blocker, "wb") as f: + f.write(b"keep") + rc, _, err = _run_main( + FakeOracle(), "--ops", "v_cvt_pknorm_i16_f32", "--waves", "32", "--json", os.path.join(blocker, "r.json") + ) + self.assertEqual(rc, 2) + self.assertIn("ERROR: cannot write", err) + self.assertNotIn("Traceback", err) + + def test_non_gfx10_arch_exits_77(self): + oracle = FakeOracle() + oracle.arch = "gfx1100" + rc, out, _ = _run_main(oracle) + self.assertEqual(rc, 77, out) + self.assertTrue(oracle.closed) + + def test_unavailable_oracle_exits_77(self): + buf = io.StringIO() + with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("missing")), redirect_stdout(buf): + rc = pr.main(["--ops", "v_cvt_pknorm_i16_f32", "--waves", "32"]) + self.assertEqual(rc, 77) + self.assertIn("unavailable", buf.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_d16_format_probe.py b/tests/test_d16_format_probe.py index 744d3627b..c5c55d0a9 100644 --- a/tests/test_d16_format_probe.py +++ b/tests/test_d16_format_probe.py @@ -6,7 +6,9 @@ import io import json import os from contextlib import redirect_stderr, redirect_stdout +from fractions import Fraction from pathlib import Path +import random import re import subprocess import sys @@ -49,6 +51,44 @@ class Rules(unittest.TestCase): self.assertEqual(pr.models32("unorm", 16, 0xFFFF)["f32_rte"], 0x3F800000) self.assertEqual(pr.models32("unorm", 8, 0x80)["f32_rte"], 0x3F008081) # 128 / 255 + def test_round_frac_matches_the_fraction_form(self): + """round_frac works in integers; the Fraction form it replaced is the reference here, for f16 and f32 and + both modes: 16-bit format quotients, the first and last significands of a binade exact, at a tie and just + under one (a tie at the last one carries into the next binade), the same for denormals, powers of two down + past the smallest denormal, random fractions in [-1, 1], and all of them negated.""" + def reference(x, prec, emin, rtz=False): + if x == 0: + return Fraction(0) + sign, a = (-1 if x < 0 else 1), abs(x) + e = a.numerator.bit_length() - a.denominator.bit_length() + if Fraction(2) ** e > a: + e -= 1 + if Fraction(2) ** (e + 1) <= a: + e += 1 + ulp = Fraction(2) ** (max(e, emin) - prec + 1) + q = a / ulp + return sign * (q.numerator // q.denominator if rtz else round(q)) * ulp + + rng = random.Random(161) + for prec, emin in ((11, -14), (24, -126)): + cases = {Fraction(v, 65535) for v in range(0, 65536, 97)} + cases |= {Fraction(v, 32767) for v in range(0, 32768, 89)} + for e in (-1, -2, -7, emin): # the binade [2^e, 2^(e+1)), ulp 2^(e - prec + 1) + ulp = Fraction(2) ** (e - prec + 1) + for m in (2 ** (prec - 1), 2 ** (prec - 1) + 1, 2 ** prec - 2, 2 ** prec - 1): # first and last + cases |= {m * ulp, (m + Fraction(1, 2)) * ulp, (m + Fraction(1, 3)) * ulp} # exact, tie, below + ulp = Fraction(2) ** (emin - prec + 1) # denormals: 0 < x < 2^emin, the same ulp + for m in (0, 1, 2, 3, 2 ** (prec - 1) - 1): + cases |= {m * ulp, (m + Fraction(1, 2)) * ulp, (m + Fraction(1, 4)) * ulp} + cases |= {Fraction(1, 2 ** j) for j in range(prec - emin + 3)} # down to under the smallest denormal + cases |= {Fraction(rng.randrange(-(1 << 40), 1 << 40), rng.randrange(1 << 40, 1 << 41)) + for _ in range(400)} + cases |= {-c for c in cases} + for x in sorted(cases): + for rtz in (False, True): + self.assertEqual(pr.round_frac(x, prec, emin, rtz), reference(x, prec, emin, rtz), + (x, prec, emin, rtz)) + class Kernels(unittest.TestCase): def test_descriptor_word3(self): diff --git a/tests/test_d3d12_xs_surface.py b/tests/test_d3d12_xs_surface.py index f2e6ce19a..274dab600 100644 --- a/tests/test_d3d12_xs_surface.py +++ b/tests/test_d3d12_xs_surface.py @@ -31,6 +31,13 @@ def test_iid_block_is_alphabetical(): assert S.check_iid_order() == [] +def test_unrecovered_console_iids_stay_outside_the_table(): + # SCARAB's provenance says the runtime does not export these; they must not acquire a + # guessed ordinal or GUID value from ordering. + assert len(S.UNRECOVERED_CONSOLE_IIDS) == 4 + assert S.check_unrecovered_console_iids() == [] + + def test_standard_iids_match_sdk(): um, _shared = S.find_sdk_include() if not um: @@ -99,16 +106,14 @@ if __name__ == "__main__": test_data_classes() test_guid_values() test_iid_block_is_alphabetical() + test_unrecovered_console_iids_stay_outside_the_table() test_sdk_include_override_accepts_a_trailing_separator() test_sdk_discovery_sorts_versions_numerically() - um, _shared = S.find_sdk_include() - if um: - errors, checked, _um = S.check_sdk() - assert errors == [], errors - assert checked == 83 - if os.environ.get("SCARAB_REF"): - errors, _notes = S.check_scarab(os.environ["SCARAB_REF"]) - assert errors == [], errors - else: - print("SCARAB cross-check skipped: SCARAB_REF is not set") + # Call the two optional checks through their real definitions so this runner cannot drift from them; both + # raise unittest.SkipTest when their inputs (SDK headers, SCARAB_REF) are absent. + for optional in (test_standard_iids_match_sdk, test_scarab_cross_check): + try: + optional() + except unittest.SkipTest as skip: + print(f"skipped: {skip}") print("ok") diff --git a/tests/test_dds_png.py b/tests/test_dds_png.py index 59f4edab9..295e0b0ee 100644 --- a/tests/test_dds_png.py +++ b/tests/test_dds_png.py @@ -348,13 +348,15 @@ class HeaderTests(unittest.TestCase): dds.parse_dds_header(dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=b"XXXX")) self.assertIn("FourCC", str(ctx.exception)) - def test_rejects_non_32_bit_rgb(self): - with self.assertRaises(dds.DdsError) as ctx: - dds.parse_dds_header( - dds_buffer(4, 4, flags=DDPF_RGB, bit_count=24, - masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0)) - ) - self.assertIn("24", str(ctx.exception)) + def test_rejects_non_24_or_32_bit_rgb(self): + for bit_count in (8, 16): + with self.subTest(bit_count=bit_count): + with self.assertRaises(dds.DdsError) as ctx: + dds.parse_dds_header( + dds_buffer(4, 4, flags=DDPF_RGB, bit_count=bit_count, + masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0)) + ) + self.assertIn("bit count", str(ctx.exception)) def test_rejects_zero_rgb_masks(self): with self.assertRaises(dds.DdsError): @@ -518,6 +520,79 @@ class UncompressedTests(unittest.TestCase): self.assertEqual(pixels(rgba), [(9, 8, 7, 6)]) +class Rgb24Tests(unittest.TestCase): + """Legacy 24-bit RGB layouts (D3DFMT_R8G8B8 stores bytes B, G, R; no alpha).""" + + def test_bgr8_header_and_opaque_decode(self): + payload = bytes((0x10, 0x20, 0x30, 0x40, 0x50, 0x60)) + data = dds_buffer( + 2, 1, payload, flags=DDPF_RGB, bit_count=24, + masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000), + ) + info = dds.parse_dds_header(data) + self.assertEqual(info["format"], "BGR8") + self.assertIsNone(info["dxgi_format"]) + self.assertEqual(info["data_offset"], 128) + self.assertEqual(dds.decode_dds(data), + (2, 1, bytes((0x30, 0x20, 0x10, 255, 0x60, 0x50, 0x40, 255)))) + + def test_rgb8_byte_order(self): + payload = bytes((0x10, 0x20, 0x30, 0x40, 0x50, 0x60)) + data = dds_buffer( + 2, 1, payload, flags=DDPF_RGB, bit_count=24, + masks=(0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000), + ) + self.assertEqual(dds.parse_dds_header(data)["format"], "RGB8") + self.assertEqual(dds.decode_dds(data), + (2, 1, bytes((0x10, 0x20, 0x30, 255, 0x40, 0x50, 0x60, 255)))) + + def test_padded_rows_are_removed(self): + # width 2 -> 6 data bytes per row, padded to the 8-byte pitch some writers emit. + payload = bytes((1, 2, 3, 4, 5, 6)) + b"\x99" * 2 + bytes((7, 8, 9, 10, 11, 12)) + b"\x99" * 2 + data = dds_buffer( + 2, 2, payload, flags=DDPF_RGB, bit_count=24, pitch=8, + masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000), + ) + self.assertEqual(pixels(dds.decode_dds(data)[2]), + [(3, 2, 1, 255), (6, 5, 4, 255), (9, 8, 7, 255), (12, 11, 10, 255)]) + + def test_alpha_flag_with_zero_mask_still_decodes(self): + # Some writers set DDPF_ALPHAPIXELS on 24-bit headers with a zero alpha mask. + payload = bytes((1, 2, 3)) + data = dds_buffer( + 1, 1, payload, flags=DDPF_RGB | DDPF_ALPHAPIXELS, bit_count=24, + masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000), + ) + self.assertEqual(dds.decode_dds(data), (1, 1, bytes((3, 2, 1, 255)))) + + def test_pitch_and_truncation_errors_are_reported(self): + header = dict(flags=DDPF_RGB, bit_count=24, + masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000)) + with self.assertRaisesRegex(dds.DdsError, "pitch"): + dds.decode_dds(dds_buffer(2, 2, b"\x00" * 6, pitch=5, **header)) + with self.assertRaisesRegex(dds.DdsError, "Truncated"): + dds.decode_dds(dds_buffer(2, 2, b"\x00" * 9, pitch=6, **header)) + + def test_unsupported_24_bit_mask_layouts_are_rejected(self): + for masks in ((0x000000FF, 0x00000000, 0x00000000, 0x00000000), + (0x000000FF, 0x000000FF, 0x000000FF, 0x00000000), + (0x00000FFF, 0x000FF000, 0x0FF00000, 0x00000000)): + with self.subTest(masks=masks): + data = dds_buffer(1, 1, flags=DDPF_RGB, bit_count=24, masks=masks) + with self.assertRaisesRegex(dds.DdsError, "24-bit RGB bitmask layout"): + dds.decode_dds(data) + + def test_png_preview_round_trip(self): + payload = bytes((0x10, 0x20, 0x30, 0x40, 0x50, 0x60)) + data = dds_buffer( + 2, 1, payload, flags=DDPF_RGB, bit_count=24, + masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000), + ) + png = dds.dds_to_png_bytes(data) + self.assertEqual(png[:8], dds.PNG_SIGNATURE) + self.assertEqual(struct.unpack(">II", png[16:24]), (2, 1)) + + class AlphaModeTests(unittest.TestCase): def test_premultiplied_rgba_and_bgra_decode_to_straight_alpha(self): for dxgi, rgba in ((28, (64, 32, 16, 128)), (87, (16, 32, 64, 128))): diff --git a/tests/test_docs_design_rows.py b/tests/test_docs_design_rows.py index 5da04ba59..876438cf0 100644 --- a/tests/test_docs_design_rows.py +++ b/tests/test_docs_design_rows.py @@ -1,4 +1,5 @@ -"""Each table in docs/design.md, docs/README.md and docs/testing.md names a topic once. +"""Each table in docs/design.md, docs/README.md and docs/testing.md names a topic once, and every row has the +same number of cells as its header. python -I tests/test_docs_design_rows.py @@ -8,6 +9,11 @@ other lacks, and a reader who stops at the first one misses the rest. On 2026-11 times; the docs index and the testing guide's "Known problems" had the same pattern. This test fails on a repeated first cell within one table of those pages, where the first cell is the topic (other pages repeat it on purpose, e.g. one row per benchmark size). No game files or build tools. + +The second check is the table's shape: a rule that writes a literal pipe (`|v|` in a list of source modifiers) +has to escape it as `\\|`, or GitHub reads it as a separator, renders the row into columns the header does not +have and drops the tail of the rule — text lost in a page nobody re-reads. On 2026-11-22 eighteen rows of the +contract table had that shape (four to thirteen cells against a three-cell header). """ import os import unittest @@ -16,6 +22,46 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PAGES = ("design.md", "README.md", "testing.md") +def unescaped_pipes(line): + """How many table separators a row really has: a cell that needs a literal pipe writes it ``\\|``.""" + count, i = 0, 0 + while i < len(line): + if line[i] == "\\": # the next character is literal, pipe or not + i += 2 + continue + if line[i] == "|": + count += 1 + i += 1 + return count + + +def mis_shaped_rows(lines): + """[(line, cells, header cells)] for rows whose cell count differs from their table's header. + + A rule that lists modifiers (`|v|`, `-|v|`) has to escape those pipes as `\\|`. Left raw, GitHub reads each one + as a separator and renders the row into columns the header does not have, dropping the tail of the rule, so the + table silently loses text instead of failing. + """ + found = [] + header, in_fence = None, False + for n, line in enumerate(lines, 1): + if line.lstrip().startswith("```"): + in_fence = not in_fence + if in_fence or not line.startswith("|"): + header = None + continue + cells = unescaped_pipes(line) + if set(line.strip()) <= set("|-: "): # the |---| rule carries the header's shape + header = cells + continue + if header is None: + header = cells + continue + if cells != header: + found.append((n, cells, header)) + return found + + def repeated_topics(lines): """[(topic, [1-based line numbers])] for first cells that appear more than once in one table.""" found = [] @@ -50,6 +96,19 @@ class DesignTableRows(unittest.TestCase): "| EXEC | in a code block |", "```"] self.assertEqual(repeated_topics(lines), [("EXEC", [3, 5])]) + def test_checker_finds_a_stray_pipe_but_not_an_escaped_one(self): + lines = ["| Topic | Rule |", "|---|---|", "| EXEC | writes |v| |", "| LDS | fine |", "", + "| Topic | Rule |", "|---|---|", "| EXEC | writes \\|v\\| |", "```", "| x | a | b |", "```"] + self.assertEqual(mis_shaped_rows(lines), [(3, 5, 3)]) + + def test_each_page_has_rows_its_header_can_hold(self): + for page in PAGES: + with self.subTest(page=page): + with open(os.path.join(ROOT, "docs", page), encoding="utf-8") as f: + lines = f.read().split("\n") + wrong = mis_shaped_rows(lines) + self.assertEqual(wrong, [], f"rows to fix in docs/{page} (line, cells, header cells): {wrong}") + def test_each_page_names_each_topic_once_per_table(self): for page in PAGES: with self.subTest(page=page): diff --git a/tests/test_docs_env_vars.py b/tests/test_docs_env_vars.py new file mode 100644 index 000000000..916bc5cf9 --- /dev/null +++ b/tests/test_docs_env_vars.py @@ -0,0 +1,97 @@ +"""Every LEONIDA_* / GTA6RT_* environment variable the runtime and make_game.py read is named in a document. + + python -I tests/test_docs_env_vars.py + +`runtime/README.md` documents the runtime's variables one by one, but five that the `xgameruntime` shim reads +(`LEONIDA_DEVICE_TYPE` and four more) were in no document at all. This collects the variable names that appear as +string literals in `runtime/src`, `runtime/shims` and `make_game.py` and checks that each is written in some +tracked Markdown file. Sources and Markdown only: no build, no GPU, no game files. +""" +import os +import re +import subprocess +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +# A variable name as a string literal: "LEONIDA_X", L"LEONIDA_X" or 'LEONIDA_X'. +LITERAL = re.compile(r"""["']((?:LEONIDA|GTA6RT)_[A-Z0-9_]+)["']""") +CODE = ("runtime/src/", "runtime/shims/", "make_game.py") +# Set by the runtime for itself, not by a person: gta6rt passes the first to the copy of itself it starts with the +# image base reserved (runtime/src/base_reservation.h), and the second is a name that is only looked up to make +# the CRT build its environment table (runtime/shims/process.cpp). +INTERNAL = {"LEONIDA_BASE_RESERVED", "LEONIDA_RT_ENV_INIT"} + + +def tracked_files(): + try: + out = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout + return [p for p in out.splitlines() if p] + except (OSError, subprocess.CalledProcessError): + found = [] + for root, dirs, files in os.walk(ROOT): + dirs[:] = [d for d in dirs if d not in (".git", "build", "__pycache__", "third_party")] + found += [os.path.relpath(os.path.join(root, f), ROOT).replace(os.sep, "/") for f in files] + return found + + +def read(rel): + with open(os.path.join(ROOT, rel), encoding="utf-8", errors="replace") as f: + return f.read() + + +def variables_read(sources): + """{variable: first "file:line" that names it} over `sources` ({name: text}).""" + found = {} + for name in sorted(sources): + for number, line in enumerate(sources[name].splitlines(), 1): + for variable in LITERAL.findall(line): + found.setdefault(variable, f"{name}:{number}") + return found + + +def undocumented(sources, pages): + """[(variable, where it is read)] for variables no page of `pages` ({name: text}) names as a whole word.""" + text = "\n".join(pages.values()) + return [(variable, where) for variable, where in sorted(variables_read(sources).items()) + if variable not in INTERNAL and not re.search(rf"(? 2 else "" + if not BOLD_ID.match(first): + continue + if first in seen: + found.append((seen[first], n, first)) + else: + seen[first] = n + return found + + +def markdown_files(): + try: + out = subprocess.run(["git", "ls-files", "*.md"], cwd=ROOT, capture_output=True, text=True, check=True).stdout + files = out.split() + except (OSError, subprocess.CalledProcessError): + files = [os.path.relpath(os.path.join(r, f), ROOT).replace(os.sep, "/") + for r, d, fs in os.walk(ROOT) if ".git" not in r for f in fs if f.endswith(".md")] + return [f for f in files if not f.startswith("third_party/")] + + +class RepeatedTableIds(unittest.TestCase): + def test_checker_flags_a_repeated_bold_id_only(self): + text = "\n".join([ + "| # | Scope |", "|---|---|", + "| **M2** | new text |", "| **M3** | x |", "| **M2** | old text |", # repeated: flagged + "| 1k | a |", "| 1k | b |", # plain values: not checked + "", + "| # | Scope |", "|---|---|", "| **M2** | another table |", # a new table starts over + "```", "| **M3** | in a fence |", "| **M3** | in a fence |", "```", + ]) + self.assertEqual(repeated_ids(text), [(3, 5, "**M2**")]) + + def test_docs_have_no_repeated_table_ids(self): + found = [] + for path in markdown_files(): + with open(os.path.join(ROOT, path), encoding="utf-8") as f: + found += [f"{path}:{a} and :{b} ({name})" for a, b, name in repeated_ids(f.read())] + self.assertEqual(found, [], "a table row repeated under the same bold ID (keep the current one): " + + "; ".join(found)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_f32_fuzz.py b/tests/test_f32_fuzz.py index e9b273357..dcefbdf12 100644 --- a/tests/test_f32_fuzz.py +++ b/tests/test_f32_fuzz.py @@ -92,6 +92,30 @@ class HarnessTests(unittest.TestCase): self.assertEqual(status, "skip") self.assertIn("denormal", detail) + def test_fmamk_madmk_operand_order_and_translator(self): + # S0 * K + S2 = 2.0 * 3.0 + 4.0 = 10.0 (whereas S0 * S2 + K would be 11.0). + vals = [0] * len(ff.SEED_REGS) + vals[0], vals[1] = ff.bits(2.0), ff.bits(4.0) + srcs = [(0, {}), ("k", ff.bits(3.0)), (1, {})] + for op in ("v_fmamk_f32", "v_madmk_f32"): + with self.subTest(op=op): + got_model = ff.model(op, vals, srcs, []) + self.assertEqual(got_model, [ff.bits(10.0), 0]) + self.assertEqual(ff.line(op, vals, srcs, False, []), + f"{op} v8, v0, 0x{ff.bits(3.0):x}, v1") + status, words = ff.run_translated(ff.listing(op, vals, srcs, False, [])[0]) + self.assertEqual((status, words[:2]), ("ok", got_model)) + + +class CliTests(unittest.TestCase): + TOOL = os.path.join(ROOT, "tools", "f32_fuzz.py") + + def test_no_arguments_prints_usage(self): + r = subprocess.run([sys.executable, "-I", self.TOOL], capture_output=True, text=True, timeout=5) + self.assertEqual(r.returncode, 2, r.stderr) + self.assertIn("usage:", r.stderr) + self.assertNotIn("Traceback", r.stderr) + class HardwareOracle(unittest.TestCase): """--oracle hw: kernel text, verdicts, GFX11 skips and the exit-77 contract (no GPU needed), plus a run on the @@ -117,7 +141,7 @@ class HardwareOracle(unittest.TestCase): def test_removed_opcodes_are_skipped_not_substituted(self): from hw_oracle import asm - for op in ("v_mad_f32", "v_mac_f32", "v_madak_f32", "v_mad_legacy_f32"): + for op in ("v_mad_f32", "v_mac_f32", "v_madak_f32", "v_madmk_f32", "v_mad_legacy_f32"): self.assertIn(op, asm.valu_skip_reason(op, "gfx1150")) self.assertIn(op, asm.valu_skip_reason(op, "gfx1030")) self.assertIsNone(asm.valu_skip_reason(op, "gfx1013")) @@ -198,20 +222,6 @@ class HardwareOracle(unittest.TestCase): r = subprocess.run([sys.executable, "-I", self.TOOL, "--oracle", "gpu"], capture_output=True, text=True) self.assertEqual(r.returncode, 2) - def test_fmamk_madmk_operand_order_and_translator(self): - # S0 * K + S2 = 2.0 * 3.0 + 4.0 = 10.0 (whereas S0 * S2 + K would be 11.0). - vals = [0] * len(ff.SEED_REGS) - vals[0], vals[1] = ff.bits(2.0), ff.bits(4.0) - srcs = [(0, {}), ("k", ff.bits(3.0)), (1, {})] - for op in ("v_fmamk_f32", "v_madmk_f32"): - with self.subTest(op=op): - got_model = ff.model(op, vals, srcs, []) - self.assertEqual(got_model, [ff.bits(10.0), 0]) - self.assertEqual(ff.line(op, vals, srcs, False, []), - f"{op} v8, v0, 0x{ff.bits(3.0):x}, v1") - status, words = ff.run_translated(ff.listing(op, vals, srcs, False, [])[0]) - self.assertEqual((status, words[:2]), ("ok", got_model)) - def test_on_hardware(self): from hw_oracle import runner try: diff --git a/tests/test_first_light.py b/tests/test_first_light.py index 23d588fd0..953803b64 100644 --- a/tests/test_first_light.py +++ b/tests/test_first_light.py @@ -201,6 +201,184 @@ class ShaderPreparationTests(unittest.TestCase): self.assertEqual(manifest[stage]["fssm_sha256"], stage + "-fixture") +LINK_KINDS = ("symlink", "junction") if os.name == "nt" else ("symlink",) + + +def link_folder(kind: str, link: Path, target: Path) -> bool: + """Make a directory symlink or a Windows junction; False where this machine does not allow it.""" + if kind == "junction": + made = subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], capture_output=True) + return made.returncode == 0 + try: + os.symlink(target, link, target_is_directory=True) + except (OSError, NotImplementedError): + return False + return True + + +class RunFolderTests(unittest.TestCase): + """first_light/dxbc and first_light/spirv hold one run's pair, whatever an earlier run left there. + + Fully synthetic: the containers are a few hand-written bytes, and the unpacker, the disassembler and the + translator are replaced by stand-ins that, like the real tools, take every file in the folder they are given. + """ + + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory(prefix="first-light-run-folders-") + self.addCleanup(tmp.cleanup) + self.tmp = Path(tmp.name) + self.work = self.tmp / "work" + self.staged = self.work / "first_light" / "dxbc" + self.spirv = self.work / "first_light" / "spirv" + carved = self.work / "shaders" / "dxbc" + carved.mkdir(parents=True) + entries = [ + {"name": "vertex", "file": "vertex.dxbc", "stage": "vs"}, + {"name": "first", "file": "first.dxbc", "stage": "ps"}, + {"name": "second", "file": "second.dxbc", "stage": "ps"}, + ] + (carved / "index.json").write_text(json.dumps(entries), encoding="utf-8", newline="\n") + for entry in entries: + (carved / entry["file"]).write_bytes(entry["name"].encode("ascii")) + self.handed = [] # per translator run: the listings it was given + + def tools(self, argv: list[str]) -> None: + tool = Path(argv[0]).name + src = Path(argv[1]) + if tool == "fssm_unpack.py": + (src / "fssm").mkdir(exist_ok=True) + for container in sorted(src.glob("*.dxbc")): + (src / "fssm" / f"{container.stem}.fssm").write_bytes(container.read_bytes()) + return + out = Path(argv[argv.index("--out") + 1]) + out.mkdir(exist_ok=True) + if tool == "shader_disasm.py": + for blob in sorted(src.glob("*.fssm")): + (out / f"{blob.stem}.s").write_bytes(blob.read_bytes()) + return + self.assertEqual(tool, "rdna2spirv.py") + stages = {Path(e["file"]).stem: e["stage"] + for e in json.loads((src.parent / "index.json").read_text(encoding="utf-8"))} + index_path = out / "index.json" # the translator merges a small run into an index it finds + index = json.loads(index_path.read_text(encoding="utf-8")) if index_path.is_file() else {} + listings = sorted(src.glob("*.s")) + for listing in listings: + (out / f"{listing.stem}.spv").write_bytes(b"spv " + listing.read_bytes()) + index[listing.stem] = {"stage": stages.get(listing.stem, "?"), "fssm_sha256": listing.stem} + index_path.write_text(json.dumps(index), encoding="utf-8", newline="\n") + self.handed.append([listing.stem for listing in listings]) + + def prepare(self, ps: str, *extra: str) -> None: + with patch.object(fl, "run", side_effect=self.tools), redirect_stdout(io.StringIO()): + self.assertEqual(fl.main(["--game", str(self.tmp), "--work", str(self.work), "--no-fit", + "--vs", "vertex", "--ps", ps, *extra]), 0) + + def files(self, folder: Path) -> list[str]: + return sorted(p.relative_to(folder).as_posix() for p in folder.rglob("*") if p.is_file()) + + def test_a_second_run_holds_only_its_own_pair(self) -> None: + other_out = self.work / "first_light" / "out_first" + self.prepare("first", "--out", str(other_out)) + self.assertEqual(self.handed, [["first", "vertex"]]) + (self.staged / "leftover.dxbc").write_bytes(b"leftover") # a container no run selected + (self.spirv / "leftover.spvasm").write_bytes(b"leftover") + carved_before = {name: (self.work / "shaders" / "dxbc" / name).read_bytes() + for name in self.files(self.work / "shaders" / "dxbc")} + other_out_before = {name: (other_out / name).read_bytes() for name in self.files(other_out)} + + self.prepare("second") + + self.assertEqual(self.handed[1], ["second", "vertex"]) + self.assertEqual(self.files(self.staged), + ["disasm/second.s", "disasm/vertex.s", "fssm/second.fssm", "fssm/vertex.fssm", + "index.json", "second.dxbc", "vertex.dxbc"]) + self.assertEqual(self.files(self.spirv), ["index.json", "second.spv", "vertex.spv"]) + translated = json.loads((self.spirv / "index.json").read_text(encoding="utf-8")) + self.assertEqual({stem: meta["stage"] for stem, meta in translated.items()}, + {"second": "ps", "vertex": "vs"}) + out = self.work / "first_light" / "out" + self.assertEqual((out / "ps.dxbc").read_bytes(), b"second") + self.assertEqual((out / "ps.spv").read_bytes(), b"spv second") + # Only the two run folders are emptied: the carve and the other run's --out are as they were. + self.assertEqual({name: (self.work / "shaders" / "dxbc" / name).read_bytes() + for name in self.files(self.work / "shaders" / "dxbc")}, carved_before) + self.assertEqual({name: (other_out / name).read_bytes() for name in self.files(other_out)}, + other_out_before) + self.assertEqual((other_out / "ps.dxbc").read_bytes(), b"first") + + def linked(self, kind: str, where: str) -> tuple[Path, Path]: + """A work folder whose first_light/ is a link of this kind to a folder outside it.""" + work, outside = self.tmp / kind / "work", self.tmp / kind / "outside" + (outside / "dxbc").mkdir(parents=True) + for keep in (outside / "keep.dxbc", outside / "dxbc" / "keep.dxbc"): + keep.write_bytes(b"keep") + link = work / "first_light" / where + link.parent.mkdir(parents=True) + if not link_folder(kind, link, outside): + self.skipTest(f"cannot create a {kind} here") + return work, outside + + def test_a_link_inside_a_run_folder_is_removed_not_followed(self) -> None: + for kind in LINK_KINDS: + with self.subTest(kind=kind): + work, outside = self.linked(kind, os.path.join("dxbc", "link")) + staged = work / "first_light" / "dxbc" + self.assertEqual(fl.reset_run_folders(str(work)), str(staged)) + self.assertEqual(os.listdir(staged), []) + self.assertEqual(self.files(outside), ["dxbc/keep.dxbc", "keep.dxbc"]) + + def test_a_run_folder_that_is_a_link_is_refused(self) -> None: + for kind in LINK_KINDS: + with self.subTest(kind=kind): + work, outside = self.linked(kind, "spirv") + staged = work / "first_light" / "dxbc" + staged.mkdir() + (staged / "earlier.dxbc").write_bytes(b"earlier") + with self.assertRaises(SystemExit) as refused: + fl.reset_run_folders(str(work)) + self.assertIn(str(work / "first_light" / "spirv"), str(refused.exception)) + self.assertNotIn("\n", str(refused.exception)) + self.assertEqual(self.files(outside), ["dxbc/keep.dxbc", "keep.dxbc"]) + self.assertEqual(os.listdir(staged), ["earlier.dxbc"]) # refused before anything is removed + + def test_a_first_light_folder_that_is_a_link_is_refused(self) -> None: + for kind in LINK_KINDS: + with self.subTest(kind=kind): + work, outside = self.linked(kind, "") + with self.assertRaises(SystemExit) as refused: + fl.reset_run_folders(str(work)) + self.assertIn(str(work / "first_light"), str(refused.exception)) + self.assertNotIn("\n", str(refused.exception)) + self.assertEqual(self.files(outside), ["dxbc/keep.dxbc", "keep.dxbc"]) + + def test_a_linked_first_light_with_no_run_folders_is_refused_too(self) -> None: + # Nothing stale lies behind the link, so only the check of first_light itself can refuse it; without that + # check the new dxbc was created in the folder the link points to, outside the work folder. + for kind in LINK_KINDS: + with self.subTest(kind=kind): + work, outside = self.tmp / kind / "work", self.tmp / kind / "outside" + outside.mkdir(parents=True) + work.mkdir() + if not link_folder(kind, work / "first_light", outside): + self.skipTest(f"cannot create a {kind} here") + with self.assertRaises(SystemExit) as refused: + fl.reset_run_folders(str(work)) + self.assertIn(str(work / "first_light"), str(refused.exception)) + self.assertNotIn("\n", str(refused.exception)) + self.assertEqual(os.listdir(outside), []) + + def test_a_file_that_cannot_be_removed_stops_the_run(self) -> None: + self.prepare("first") + held = self.staged / "first.dxbc" + denied = PermissionError(13, "Permission denied", str(held)) + with patch.object(fl.shutil, "rmtree", side_effect=denied), self.assertRaises(SystemExit) as stopped: + self.prepare("second") + self.assertIn(str(held), str(stopped.exception)) + self.assertIn("Permission denied", str(stopped.exception)) + self.assertNotIn("\n", str(stopped.exception)) + self.assertEqual(self.handed, [["first", "vertex"]]) # nothing was translated from the stale folder + + class OracleTests(unittest.TestCase): """The readback oracle on synthetic images: the controls run without a GPU or a game package.""" @@ -315,6 +493,13 @@ class TexturedOracleTests(unittest.TestCase): pixels[1 * 4 + 1] = list(probe) return struct.pack("<64f", *(v for pixel in pixels for v in pixel)) + @staticmethod + def _make_raw(width: int, height: int, overrides: dict[tuple[int, int], tuple[float, float, float, float]]) -> bytes: + pixels = [[CLEAR] * 4 for _ in range(width * height)] + for (x, y), rgba in overrides.items(): + pixels[y * width + x] = list(rgba) + return struct.pack(f"<{width * height * 4}f", *(v for pixel in pixels for v in pixel)) + def test_accepts_expected_textured_image(self): check_image(self.image(), self.manifest) @@ -407,6 +592,107 @@ class TexturedOracleTests(unittest.TestCase): self.assertEqual(blob[:8], struct.pack("= 1) + manifest = { + "width": 32, + "height": 32, + "min_coverage": 0.01, + "max_coverage": 0.99, + "clear_pixel": [31, 31], + "clear": -1.0, + "texture": {"width": 1, "height": 1}, + "rgba_tolerance": 0.02, + "rgba_probes": probes, + } + # Build synthetic image: covered pixels in the triangle set to red vs magenta fallback. + covered_pixels = { + (px, py) + for py in range(32) + for px in range(32) + if fl.uv_at(verts, indices, px, py, 32, 32) is not None + } + self.assertTrue(len(covered_pixels) > 0) + red_img = self._make_raw( + 32, 32, + {pos: (1.0, 0.0, 0.0, 1.0) for pos in covered_pixels}, + ) + res = fl.check_image(red_img, manifest) + self.assertEqual(res["covered"], len(covered_pixels)) + magenta_img = self._make_raw( + 32, 32, + {pos: (1.0, 0.0, 1.0, 1.0) for pos in covered_pixels}, + ) + with self.assertRaises(AssertionError): + fl.check_image(magenta_img, manifest) + # Empty-probe textured manifest and fallback-indistinguishable expected colour are both rejected. + empty_manifest = dict(manifest, rgba_probes=[]) + with self.assertRaises(AssertionError): + fl.check_image(magenta_img, empty_manifest) + magenta_manifest = dict( + manifest, + rgba_probes=[{"pixel": probes[0]["pixel"], "uv": [0.0, 0.0], "rgba": [1.0, 0.0, 1.0, 1.0]}], + ) + with self.assertRaises(AssertionError): + fl.check_image(magenta_img, magenta_manifest) + + def test_nan_channels_rejected(self): + nan = float("nan") + # NaN in centre_rgba must fail (abs(NaN) > tol is False without an explicit finiteness check). + with self.assertRaises(AssertionError): + fl.check_image(self.image(centre=(nan, 0.4, 0.6, 1.0)), self.manifest) + # NaN in rgba_probes must fail. + with self.assertRaises(AssertionError): + fl.check_image(self.image(probe=(0.8, nan, 0.1, 1.0)), self.manifest) + # NaN in clear_pixel must fail. + raw_clear_nan = self._make_raw( + 4, 4, + { + (0, 0): (nan, -1.0, -1.0, -1.0), + (1, 1): (0.8, 0.2, 0.1, 1.0), + (2, 1): (0.2, 0.4, 0.6, 1.0), + (1, 2): (0.2, 0.4, 0.6, 1.0), + (2, 2): (0.2, 0.4, 0.6, 1.0), + }, + ) + with self.assertRaises(AssertionError): + fl.check_image(raw_clear_nan, self.manifest) + + def test_transparent_unorm_fragments_counted_as_covered(self): + # Valid transparent-red UNORM fragments (alpha == 0.0) must be counted as covered by + # distinguishing them from the -1.0 clear sentinel rather than requiring alpha > 0.5. + manifest = { + "width": 4, + "height": 4, + "min_coverage": 0.2, + "max_coverage": 0.9, + "centre_pixel": [2, 2], + "centre_rgba": [1.0, 0.0, 0.0, 0.0], + "clear_pixel": [0, 0], + "clear": -1.0, + "texture": {"width": 1, "height": 1}, + "rgba_tolerance": 0.02, + "rgba_probes": [{"pixel": [1, 1], "uv": [0.0, 0.0], "rgba": [1.0, 0.0, 0.0, 0.0]}], + } + overrides = {(x, y): (1.0, 0.0, 0.0, 0.0) for x in (1, 2) for y in (1, 2)} + raw = self._make_raw(4, 4, overrides) + res = fl.check_image(raw, manifest) + self.assertEqual(res["covered"], 4) + self.assertAlmostEqual(res["ratio"], 0.25) + if __name__ == "__main__": sys.exit(unittest.main()) diff --git a/tests/test_first_light_mesh_draw.py b/tests/test_first_light_mesh_draw.py new file mode 100644 index 000000000..96be1f207 --- /dev/null +++ b/tests/test_first_light_mesh_draw.py @@ -0,0 +1,81 @@ +"""First Light must not render geometry left by an earlier preparation run.""" + +import json +from pathlib import Path +import struct +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import first_light + + +class FirstLightMeshDrawTests(unittest.TestCase): + def setUp(self) -> None: + self.work = Path(self.enterContext(tempfile.TemporaryDirectory())) + self.out = self.work / "out" + self.out.mkdir() + self.mesh = self.out / "mesh.bin" + self.mesh.write_bytes(b"previous mesh placeholder") + dxbc = self.work / "shaders" / "dxbc" + spirv = self.work / "first_light" / "spirv" + dxbc.mkdir(parents=True) + spirv.mkdir(parents=True) + picks = [] + for stage in ("vs", "ps"): + (dxbc / f"{stage}.dxbc").touch() + (spirv / f"{stage}.spv").touch() + picks.append({"stage": stage, "name": stage, "file": f"{stage}.dxbc"}) + self.enterContext(patch.multiple( + first_light, + ensure_carve=lambda *args: "stub-index", + choose=lambda *args: picks, + translate=lambda *args: {"vs": {}, "ps": {}}, + find_harness=lambda *args: "stub-harness", + )) + self.draw = self.enterContext(patch.object(first_light.subprocess, "run", side_effect=self.write_readback)) + + @staticmethod + def write_readback(arguments: list[str], *, env: dict[str, str], check: bool) -> None: + if not Path(env["VKH_DRAW_MESH"]).is_file(): + raise AssertionError("the harness received no mesh") + pixels = (0.0, 0.0, 0.0, 1.0) * 2 + (-1.0,) * 8 + Path(arguments[3]).write_bytes(struct.pack("<16f", *pixels)) + + def prepare(self, *args: str) -> int: + return first_light.main([ + "--game", str(self.work), "--work", str(self.work), "--out", str(self.out), + "--no-fit", "--width", "2", "--height", "2", *args, + ]) + + def test_run_without_obj_never_draws_the_previous_mesh(self) -> None: + with self.assertRaisesRegex(SystemExit, "requires an OBJ with faces"): + self.prepare("--run") + self.draw.assert_not_called() + self.assertFalse((self.out / "image.raw").exists()) + + def test_prepare_without_obj_is_allowed_but_cannot_be_replayed(self) -> None: + self.assertEqual(self.prepare(), 0) + self.draw.assert_not_called() + manifest = json.loads((self.out / "manifest.json").read_text(encoding="utf-8")) + self.assertEqual((manifest["vertex_count"], manifest["index_count"]), (0, 0)) + self.assertFalse(self.mesh.is_file()) # a run without an OBJ removes the previous run's mesh.bin (95ebfb8e9) + with self.assertRaisesRegex(SystemExit, "requires an OBJ with faces"): + first_light.main(["--check", "--out", str(self.out)]) + self.draw.assert_not_called() + + def test_check_can_replay_a_manifest_for_prepared_geometry(self) -> None: + vertices = [(0.0, 0.0, 0.5, 0.0, 0.0), (1.0, 0.0, 0.5, 1.0, 0.0), (0.0, 1.0, 0.5, 0.0, 1.0)] + first_light.write_mesh(self.mesh, vertices, [0, 1, 2]) + (self.out / "manifest.json").write_text( + '{"width": 2, "height": 2, "vertex_count": 3, "index_count": 3, "files": {"mesh": "mesh.bin"}}', + encoding="utf-8", newline="\n", + ) + self.assertEqual(first_light.main(["--check", "--out", str(self.out)]), 0) + self.draw.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_first_light_stale_mesh.py b/tests/test_first_light_stale_mesh.py new file mode 100644 index 000000000..b87da4b04 --- /dev/null +++ b/tests/test_first_light_stale_mesh.py @@ -0,0 +1,47 @@ +"""first_light: a preparation run without an OBJ must not leave (and then draw) the mesh.bin of an earlier run. + +The carve, translation and draw are stubbed; the folders hold placeholder bytes only. No game data, no GPU. +""" +import os +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tools")) +import first_light # noqa: E402 + + +class StaleMesh(unittest.TestCase): + def test_run_without_obj_drops_old_mesh(self): + with tempfile.TemporaryDirectory() as tmp: + work, out, game = (os.path.join(tmp, n) for n in ("work", "out", "game")) + os.makedirs(os.path.join(work, "first_light", "spirv")) + os.makedirs(os.path.join(work, "shaders", "dxbc")) + os.makedirs(out) + os.makedirs(game) + picked = [{"stage": "vs", "file": "a.dxbc", "name": "a"}, {"stage": "ps", "file": "b.dxbc", "name": "b"}] + for e in picked: + stem = os.path.splitext(e["file"])[0] + for path in (os.path.join(work, "first_light", "spirv", stem + ".spv"), + os.path.join(work, "shaders", "dxbc", e["file"])): + with open(path, "wb") as f: + f.write(b"x") + mesh = os.path.join(out, "mesh.bin") + with open(mesh, "wb") as f: + f.write(b"old mesh") + seen = [] + saved = (first_light.ensure_carve, first_light.choose, first_light.translate, first_light.run_draw) + first_light.ensure_carve = lambda g, w: "index" + first_light.choose = lambda i, v, p: picked + first_light.translate = lambda w, p: {"vs": {}, "ps": {}} + first_light.run_draw = lambda a, m, o: seen.append(os.path.exists(mesh)) + try: + first_light.main(["--game", game, "--work", work, "--out", out, "--no-fit", "--run"]) + finally: + (first_light.ensure_carve, first_light.choose, first_light.translate, first_light.run_draw) = saved + self.assertEqual(seen, [False]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_first_look_rebuild.py b/tests/test_first_look_rebuild.py new file mode 100644 index 000000000..ef1345158 --- /dev/null +++ b/tests/test_first_look_rebuild.py @@ -0,0 +1,70 @@ +"""scripts/first_look.ps1 rebuilds runtime\\build\\gta6rt.exe when it is older than the runtime sources. + + python -I tests/test_first_look_rebuild.py + +A gta6rt.exe from before a pull still runs, but its dry run reports the old shim table: the day-one import to-do list +would be wrong without any error. The script used to build the loader only when it was missing. No game files. +""" +import os +import shutil +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "first_look.ps1" +PE_INSPECT_STUB = ( + "from pathlib import Path\n" + "import sys\n" + "report = Path(sys.argv[-1]) / (Path(sys.argv[1]).name + '.json')\n" + "report.write_text('{\"imports\":[],\"sections\":[]}', encoding='utf-8', newline='\\n')\n" +) +# The build script leaves a marker; the loader is replaced by an alias that echoes its arguments. +BUILD_STUB = "Set-Content -Path (Join-Path $PSScriptRoot 'built.txt') -Value 'built'\n" +RUN = r""" +$ErrorActionPreference = 'Stop' +Set-Alias -Name (Join-Path $PWD 'runtime\build\gta6rt.exe') -Value Write-Output +& .\scripts\first_look.ps1 -Exe (Join-Path $PWD 'fixture.exe') +""" + + +@unittest.skipUnless(os.name == "nt", "Windows PowerShell diagnostics script") +class FirstLookRebuildTest(unittest.TestCase): + def run_case(self, source_newer): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for folder in ("scripts", "tools", "runtime/build", "runtime/src"): + (root / folder).mkdir(parents=True) + shutil.copyfile(SCRIPT, root / "scripts" / SCRIPT.name) + (root / "scripts" / "build_runtime.ps1").write_text(BUILD_STUB, encoding="utf-8") + (root / "tools" / "pe_inspect.py").write_text(PE_INSPECT_STUB, encoding="utf-8", newline="\n") + (root / "fixture.exe").write_bytes(b"MZ") + loader = root / "runtime" / "build" / "gta6rt.exe" + source = root / "runtime" / "src" / "pe_loader.cpp" + loader.write_bytes(b"") + source.write_text("// source\n", encoding="utf-8") + now = time.time() + older, newer = now - 3600, now + os.utime(loader, (newer, newer) if not source_newer else (older, older)) + os.utime(source, (newer, newer) if source_newer else (older, older)) + env = {k: v for k, v in os.environ.items() if k.upper() != "PSMODULEPATH"} + env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env["PATH"] + run = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", + "-Command", RUN], cwd=root, env=env, capture_output=True, text=True, timeout=60) + return (root / "scripts" / "built.txt").is_file(), run.stdout + run.stderr + + def test_a_loader_older_than_the_sources_is_rebuilt(self): + built, out = self.run_case(source_newer=True) + self.assertTrue(built, out) + self.assertIn("rebuilding it first", out) + + def test_an_up_to_date_loader_is_used_as_it_is(self): + built, out = self.run_case(source_newer=False) + self.assertFalse(built, out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_fragment_children.py b/tests/test_fragment_children.py new file mode 100644 index 000000000..1e60f22c6 --- /dev/null +++ b/tests/test_fragment_children.py @@ -0,0 +1,229 @@ +"""Synthetic-data tests for tools/fragment_children.py (ASSET-261, the fragment child-drawable census). + + python -I tests/test_fragment_children.py + +Every byte here is built by the test: synthetic fragment system pages inside a synthetic RPF9-style archive +made of page-aligned zlib streams. No game file, value or name is used. +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import zlib + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOL = os.path.join(ROOT, "tools", "fragment_children.py") +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import fragment_children as fc # noqa: E402 + +S = 0x50000000 + + +def drawable(b, at, shader=S + 0x10, lod=True): + """A minimal drawable record at `at` that passes the tool's body test (and the decoder's header test).""" + struct.pack_into(" None: self.translations = {"upscaler_00": ("c" * 64, "s" * 64, b"synthetic module")} self.assertEqual(self.run_step(), ["fspx_unpack.py", "rdna2spirv.py"]) diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index b4a4b696b..0f7aa7cad 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -10,6 +10,7 @@ import io import json import os import struct +import subprocess import sys import tempfile import unittest @@ -177,6 +178,62 @@ class Cli(unittest.TestCase): code = fspx_unpack.main(list(argv)) return code, out.getvalue(), err.getvalue() + def disassemble(self, body): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + src = os.path.join(tmp.name, "one.fspx") + with open(src, "wb") as f: + f.write(make_fspx([(0, kind0()), (6, program())])) + mc = os.path.join(tmp.name, "fake_mc.py") + with open(mc, "w", encoding="utf-8", newline="\n") as f: + f.write(body) + out = os.path.join(tmp.name, "out") + env = dict(os.environ, LLVM_MC=f'"{sys.executable}" "{mc}"') + result = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "fspx_unpack.py"), + src, "--out", out, "--disasm"], capture_output=True, text=True, env=env) + return result, out + + def test_disassembly_error_writes_no_listing(self): + result, out = self.disassemble("import sys\n" + "print('\\ts_endpgm')\n" + "sys.stderr.write('error: disassembly stopped\\nextra detail\\n')\n" + "sys.exit(23)\n") + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertEqual(result.stderr.splitlines(), ["one: error: disassembly stopped"]) + self.assertIn("1 input(s) failed", result.stdout) + self.assertEqual(os.listdir(os.path.join(out, "disasm")), []) + self.assertEqual(os.listdir(os.path.join(out, "fspx")), []) + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + self.assertEqual(json.load(f), []) + + def test_empty_disassembly_writes_no_listing(self): + result, out = self.disassemble("print(' ')\n") + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertEqual(result.stderr.splitlines(), ["one: no output"]) + self.assertEqual(os.listdir(os.path.join(out, "disasm")), []) + self.assertEqual(os.listdir(os.path.join(out, "fspx")), []) + + def test_disassembly_with_invalid_words_keeps_listing(self): + result, out = self.disassemble("import sys\n" + "print('\\ts_endpgm')\n" + "sys.stderr.write('warning: invalid instruction encoding\\n')\n") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stderr, "") + with open(os.path.join(out, "disasm", "one.s"), encoding="utf-8") as f: + listing = f.read() + self.assertIn("1 invalid words", listing) + self.assertIn("\ts_endpgm", listing) + self.assertIn("warning: invalid instruction encoding", listing) + + def test_clean_disassembly_keeps_listing(self): + result, out = self.disassemble("print('\\ts_endpgm')\n") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stderr, "") + with open(os.path.join(out, "disasm", "one.s"), encoding="utf-8") as f: + listing = f.read() + self.assertIn("0 invalid words", listing) + self.assertIn("\ts_endpgm", listing) + def test_dll_like_file(self): c = Containers().container() with tempfile.TemporaryDirectory() as t: diff --git a/tests/test_fspx_unpack_out.py b/tests/test_fspx_unpack_out.py new file mode 100644 index 000000000..a8a0e2588 --- /dev/null +++ b/tests/test_fspx_unpack_out.py @@ -0,0 +1,96 @@ +"""Unit tests for the tools/fspx_unpack.py output-directory guard: an unusable --out (a regular file +at --out, a regular file above the unpack target, or a regular file where fspx/disasm must be +created) must give one stderr line and exit 2 at main start, before any input is read, instead of +a raw OSError traceback. + + python -I tests/test_fspx_unpack_out.py + +Zero game data: every fixture is a plain synthetic file built here. +""" +import contextlib +import io +import os +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import fspx_unpack # noqa: E402 + +INPUT_NAME = "payload.bin" +GARBAGE_INPUT = b"not an fspx payload" # never parsed: the guard refuses before any input is read + + +class FspxOutputDirGuardTests(unittest.TestCase): + def run_unpack(self, out, disasm=False): + with tempfile.TemporaryDirectory() as t: + source = os.path.join(t, INPUT_NAME) + with open(source, "wb") as f: + f.write(GARBAGE_INPUT) + err, out_text = io.StringIO(), io.StringIO() + with contextlib.redirect_stderr(err), contextlib.redirect_stdout(out_text): + rc = fspx_unpack.main([source, "--out", out] + (["--disasm"] if disasm else [])) + return rc, err.getvalue(), out_text.getvalue() + + def test_regular_file_at_out_gives_one_line_and_exit_2(self): + with tempfile.TemporaryDirectory() as t: + blocker = os.path.join(t, "blocker") + with open(blocker, "wb") as f: + f.write(b"x") + rc, err, _ = self.run_unpack(blocker) + self.assertEqual(rc, 2) + self.assertEqual(err.count("\n"), 1) + self.assertTrue(err.startswith("cannot create output directory ")) + self.assertIn(os.path.join(blocker, "fspx"), err) + self.assertFalse(os.path.exists(os.path.join(blocker, "fspx"))) + + def test_regular_file_above_out_gives_one_line_and_exit_2(self): + with tempfile.TemporaryDirectory() as t: + blocker = os.path.join(t, "blocker") + with open(blocker, "wb") as f: + f.write(b"x") + child = os.path.join(blocker, "child") + rc, err, _ = self.run_unpack(child) + self.assertEqual(rc, 2) + self.assertEqual(err.count("\n"), 1) + self.assertTrue(err.startswith("cannot create output directory ")) + self.assertFalse(os.path.exists(child)) + + def test_regular_file_where_fspx_belongs_gives_one_line_and_exit_2(self): + with tempfile.TemporaryDirectory() as t: + fspx_file = os.path.join(t, "fspx") + with open(fspx_file, "wb") as f: + f.write(b"x") + rc, err, _ = self.run_unpack(t) + self.assertEqual(rc, 2) + self.assertEqual(err.count("\n"), 1) + self.assertIn(fspx_file, err) + with open(fspx_file, "rb") as f: # the blocker stays a regular file, not replaced + self.assertEqual(f.read(), b"x") + + def test_disasm_dir_refusal_names_the_disasm_dir(self): + with tempfile.TemporaryDirectory() as t: + os.makedirs(t, exist_ok=True) + disasm_file = os.path.join(t, "disasm") + with open(disasm_file, "wb") as f: + f.write(b"x") + rc, err, _ = self.run_unpack(t, disasm=True) + self.assertEqual(rc, 2) + self.assertEqual(err.count("\n"), 1) + self.assertIn(disasm_file, err) + self.assertFalse(os.path.isdir(disasm_file)) + + def test_valid_out_still_unpacks_and_reports_failed_inputs(self): + with tempfile.TemporaryDirectory() as t: + rc, err, out = self.run_unpack(os.path.join(t, "unpack")) + self.assertEqual(rc, 1) # the garbage input fails parsing, as before the guard + self.assertIn("no FSPX payload found", err) + self.assertIn("0 FSPX program(s) unpacked", out) + self.assertTrue(os.path.isdir(os.path.join(t, "unpack", "fspx"))) + self.assertTrue(os.path.isfile(os.path.join(t, "unpack", "index.json"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_fssm_header.py b/tests/test_fssm_header.py index 932e7cbbe..4ee910894 100644 --- a/tests/test_fssm_header.py +++ b/tests/test_fssm_header.py @@ -359,15 +359,19 @@ class CliTest(unittest.TestCase): json.dump(data, f) self.assertEqual(fssm_header.stage_index(self.fssm_dir), {"a": "ps", "b": "ps"}) - def test_stage_index_skips_malformed_rows_and_normalizes_subpaths(self): + def test_stage_index_skips_malformed_or_conflicting_rows_and_normalizes_subpaths(self): with open(os.path.join(self.dir, "index.json"), "w", encoding="utf-8") as f: json.dump([ {"missing_file": True, "stage": "ps"}, {"file": None, "stage": "ps"}, {"file": "a.dxbc", "stage": None}, {"file": "dxbc/a.dxbc", "stage": "ps"}, + {"file": "other/a.dxbc", "stage": "ps"}, + {"file": "dxbc\\b.dxbc", "stage": "vs"}, + {"file": "x/conflict.dxbc", "stage": "vs"}, + {"file": "y/conflict.dxbc", "stage": "ps"}, ], f) - self.assertEqual(fssm_header.stage_index(self.fssm_dir), {"a": "ps"}) + self.assertEqual(fssm_header.stage_index(self.fssm_dir), {"a": "ps", "b": "vs"}) def test_unindexed_blob_falls_back_to_table_only_tally(self): unlisted = os.path.join(self.fssm_dir, "unlisted.fssm") @@ -382,6 +386,11 @@ class CliTest(unittest.TestCase): self.assertEqual(tally["entries"], 2) self.assertEqual(tally["entry_counts"], {"2": 1}) self.assertEqual(tally["read_methods"], {"interp": 1, "mov": 1}) + p_txt = subprocess.run([sys.executable, "-I", TOOL, unlisted], + capture_output=True, text=True) + self.assertEqual(p_txt.returncode, 0, p_txt.stderr) + self.assertIn("(no inspected blob in index.json: counted every blob with a non-empty table as a PS)", + p_txt.stdout) diff --git a/tests/test_fuzzer_work_isolation.py b/tests/test_fuzzer_work_isolation.py new file mode 100644 index 000000000..bbd432d31 --- /dev/null +++ b/tests/test_fuzzer_work_isolation.py @@ -0,0 +1,103 @@ +"""The translator fuzzers must not remove or overwrite files in a caller's --work folder.""" +import contextlib +import io +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import lds_fuzz +import valu_fuzz + + +class FuzzerWorkIsolation(unittest.TestCase): + def test_existing_files_and_other_runs_survive(self): + cases = ( + (lds_fuzz, [], lds_fuzz.programs(1, 1, (32,))[0]), + (valu_fuzz, ["--family", "f16"], valu_fuzz.programs("f16", 1, 1, (32,))[0]), + ) + for module, extra, program in cases: + with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + sentinels = {} + for subdir in ("disasm", "fssm", "spirv"): + path = root / subdir / "keep.txt" + path.parent.mkdir() + path.write_bytes(b"caller data") + sentinels[path] = b"caller data" + for suffix in (".asm", ".bin"): + path = root / (program.name + suffix) + path.write_bytes(b"caller artifact") + sentinels[path] = b"caller artifact" + + def assemble(cmd, **kwargs): + return subprocess.CompletedProcess(cmd, 0, "s_endpgm\n", "") + + def translate(cmd, **kwargs): + listing_dir = Path(cmd[3]) + out = Path(cmd[cmd.index("--out") + 1]) + out.mkdir(parents=True, exist_ok=True) + index = {} + for listing in listing_dir.glob("*.s"): + index[listing.stem] = {} + (out / (listing.stem + ".spv")).write_bytes(b"synthetic") + (out / "index.json").write_text(json.dumps(index), encoding="utf-8", newline="\n") + return subprocess.CompletedProcess(cmd, 0, "", "") + + outputs = [] + for _ in range(2): + output = io.StringIO() + argv = [module.__name__ + ".py", "--programs", "1", "--wave", "32", "--work", str(root), *extra] + with (patch.object(sys, "argv", argv), + patch.object(module.mc_command, "run", side_effect=assemble), + patch.object(module.subprocess, "run", side_effect=translate), + patch.object(module, "run_gpu", return_value=(77, "synthetic skip")), + contextlib.redirect_stdout(output)): + self.assertEqual(module.main(), 2) # no GPU programs ran + outputs.append(output.getvalue()) + for path, content in sentinels.items(): + self.assertTrue(path.exists(), f"{module.__name__} removed {path}") + self.assertEqual(path.read_bytes(), content, f"{module.__name__} overwrote {path}") + + runs = sorted(p for p in root.iterdir() if p.is_dir() and p.name not in {"disasm", "fssm", "spirv"}) + self.assertEqual(len(runs), 2, "each invocation needs its own retained output folder") + for run in runs: + self.assertTrue((run / (program.name + ".asm")).is_file()) + self.assertTrue((run / "spirv" / "index.json").is_file()) + self.assertNotEqual(runs[0], runs[1]) + self.assertTrue(any(str(runs[0]) in out for out in outputs)) + self.assertTrue(any(str(runs[1]) in out for out in outputs)) + + def test_failed_translation_reports_retained_output_and_creates_parent(self): + for module, extra in ((lds_fuzz, []), (valu_fuzz, ["--family", "f16"])): + with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: + parent = Path(tmp) / "new" / "work" + output = io.StringIO() + argv = [module.__name__ + ".py", "--programs", "1", "--wave", "32", "--work", str(parent), *extra] + with (patch.object(sys, "argv", argv), + patch.object(module, "translate", side_effect=RuntimeError("synthetic failure")), + contextlib.redirect_stdout(output)): + self.assertEqual(module.main(), 2) + runs = list(parent.iterdir()) + self.assertEqual(len(runs), 1) + self.assertTrue(runs[0].is_dir()) + self.assertIn(str(runs[0]), output.getvalue()) + self.assertIn("synthetic failure", output.getvalue()) + + def test_model_only_does_not_create_a_work_folder(self): + for module, extra in ((lds_fuzz, []), (valu_fuzz, ["--family", "f16"])): + with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: + parent = Path(tmp) / "not-created" + argv = [module.__name__ + ".py", "--programs", "1", "--wave", "32", "--model-only", + "--work", str(parent), *extra] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(module.main(), 0) + self.assertFalse(parent.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_gamedata_reader.py b/tests/test_gamedata_reader.py index c79c3516a..b378b86a7 100644 --- a/tests/test_gamedata_reader.py +++ b/tests/test_gamedata_reader.py @@ -258,6 +258,12 @@ class Dispatch(unittest.TestCase): class Run(unittest.TestCase): + BAD_DOCUMENTS = ( + ("truncated array", b'1 2 3 4'), + ("unknown encoding", b''), + ("unsupported encoding", b''), + ) + def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) @@ -280,6 +286,37 @@ class Run(unittest.TestCase): s = R.run([self.dir], root_filter="COther", reader=R.Reader(root_handlers={}, type_handlers={})) self.assertEqual(s["documents"], 1) + def test_conversion_and_encoding_errors_do_not_abort_batch(self): + bad = os.path.join(self.tmp.name, "bad.xml") + good = os.path.join(self.dir, "c.xml") + for name, data in self.BAD_DOCUMENTS: + with self.subTest(name=name): + with open(bad, "wb") as f: + f.write(data) + s = R.run([bad, good], reader=R.Reader(root_handlers={}, type_handlers={})) + self.assertEqual((s["documents"], s["roots"], s["not_well_formed"]), (1, 1, 1)) + self.assertEqual(s["per_root_documents"], {"COther": 1}) + self.assertEqual(sum(s["parse_errors"].values()), 1) + + def test_cli_continues_after_conversion_and_encoding_errors(self): + bad = os.path.join(self.tmp.name, "bad.xml") + good = os.path.join(self.dir, "c.xml") + for name, data in self.BAD_DOCUMENTS: + with self.subTest(name=name): + with open(bad, "wb") as f: + f.write(data) + out = os.path.join(self.tmp.name, name) + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "gamedata_reader.py"), + bad, good, "--out", out], capture_output=True, text=True, timeout=10) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("1 documents read, 1 roots, 1 not well-formed", r.stdout) + self.assertNotIn("Traceback", r.stderr) + files = os.listdir(out) + self.assertEqual(len(files), 1) + self.assertTrue(files[0].startswith("COther_")) + with open(os.path.join(out, files[0]), encoding="utf-8") as f: + self.assertEqual(json.load(f), {"x": 2}) + def test_cli_prints_counts_and_writes_json(self): out = os.path.join(self.tmp.name, "json", "nested") r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "gamedata_reader.py"), self.dir, "--out", out], diff --git a/tests/test_gamedata_xml_report_paths.py b/tests/test_gamedata_xml_report_paths.py index 1758b6340..3b048d9aa 100644 --- a/tests/test_gamedata_xml_report_paths.py +++ b/tests/test_gamedata_xml_report_paths.py @@ -4,6 +4,8 @@ Run with ``python -I tests/test_gamedata_xml_report_paths.py``. Set ``LEONIDA_GA copy of the tool to use as a negative control (main's version tracebacks on a missing folder and a directory, and overwrites inputs). All inputs are hand-built; no game data is used. """ +import contextlib +import io import json import os import pathlib @@ -11,9 +13,15 @@ import subprocess import sys import tempfile import unittest +from unittest import mock ROOT = pathlib.Path(__file__).resolve().parent.parent TOOL = pathlib.Path(os.environ.get("LEONIDA_GAMEDATA_XML", str(ROOT / "tools" / "gamedata_xml.py"))) +for folder in (str(ROOT), str(ROOT / "tools")): + if folder not in sys.path: + sys.path.insert(0, folder) +import gamedata_xml + XML = (b'\n' b'fixture') @@ -166,5 +174,79 @@ class ReportPathTest(unittest.TestCase): self.assertTrue(js.is_file() and csv_path.is_file(), result.stderr) +class PrefilterTest(unittest.TestCase): + def make_carve(self, folder): + carve = pathlib.Path(folder) / "x.rpf" + carve.mkdir() + (carve / "index.json").write_text(json.dumps({"files": []}), encoding="utf-8") + return carve + + def run_main(self, *args): + calls = [] + real = gamedata_xml.same_report_path + + def counting(first, second): + calls.append((first, second)) + return real(first, second) + + with mock.patch.object(gamedata_xml, "same_report_path", counting), \ + mock.patch.object(sys, "argv", ["gamedata_xml.py", *map(str, args)]), \ + contextlib.redirect_stdout(io.StringIO()), \ + contextlib.redirect_stderr(io.StringIO()): + try: + code = gamedata_xml.main() + except SystemExit as exc: + return calls, exc.code + return calls, code + + def test_existing_reports_skip_the_per_file_guard(self): + for flag, name in (("--json", "report.json"), ("--csv", "report.csv")): + with self.subTest(flag=flag), tempfile.TemporaryDirectory() as td: + carve = self.make_carve(td) + out = pathlib.Path(td) / name + out.write_text("old report", encoding="utf-8") + calls, code = self.run_main(carve, flag, out) + self.assertEqual(code, 0) + self.assertEqual(calls, []) + self.assertTrue(out.is_file()) + + def test_hard_link_report_still_calls_the_guard(self): + with tempfile.TemporaryDirectory() as td: + carve = self.make_carve(td) + alias = pathlib.Path(td) / "report.json" + os.link(carve / "index.json", alias) + calls, code = self.run_main(carve, "--json", alias) + self.assertEqual(code, 2) + self.assertGreater(len(calls), 0) + + def test_input_named_report_still_calls_the_guard(self): + with tempfile.TemporaryDirectory() as td: + folder = pathlib.Path(td) / "tree" + folder.mkdir() + doc = folder / "nested.xml" + doc.write_bytes(XML) + before = doc.read_bytes() + calls, code = self.run_main(folder, "--json", doc) + self.assertEqual(code, 2) + self.assertGreater(len(calls), 0) + self.assertEqual(doc.read_bytes(), before) + + def test_symlinked_xml_report_still_calls_the_guard(self): + with tempfile.TemporaryDirectory() as td: + folder = pathlib.Path(td) / "tree" + folder.mkdir() + report = pathlib.Path(td) / "report.json" + report.write_text("old report", encoding="utf-8") + alias = folder / "alias.xml" + try: + alias.symlink_to(report) + except OSError: + self.skipTest("symbolic links unavailable") + calls, code = self.run_main(folder, "--json", report) + self.assertEqual(code, 2) + self.assertGreater(len(calls), 0) + self.assertEqual(report.read_text(encoding="utf-8"), "old report") + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_gdk_runtime_calls.py b/tests/test_gdk_runtime_calls.py new file mode 100644 index 000000000..8b75b1237 --- /dev/null +++ b/tests/test_gdk_runtime_calls.py @@ -0,0 +1,542 @@ +"""Unit tests for tools/gdk_runtime_calls.py and tools/gen_gdk_runtime_classes.py. + +The image is built here: a .text section of hand-assembled xgameruntime.lib-style thunks (the CFG form that loads the +slot into rax and calls a dispatch routine, also with the slot copied into rax from another register, `call +[rax+disp8]`, and `call [r10+disp32]` with a stack argument), a .rdata section with the class and interface ids, and +.pdata function bounds. The ids and method names come from the +committed tools/gdk_runtime_classes.json; the docs tree for the generator is a made-up one. No game files. + + python -I tests/test_gdk_runtime_calls.py +""" +import contextlib +import io +import json +import os +import shutil +import struct +import sys +import tempfile +import unittest +import uuid + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS_DIR = os.path.join(ROOT, "tools") +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) + +import gdk_runtime_calls as grc # noqa: E402 +import gen_gdk_runtime_classes as gen # noqa: E402 + +THREADING = "073b7dcb-1fcf-4030-94be-e3c9eb623428" # XThreadingImpl, also IXThreadingImpl +NETWORKING = "37e56907-2f10-41e8-b72f-36edb185331a" # XNetworkingImpl +NETWORKING2 = "bf2346b2-39af-4658-b5ea-44713c7e83b3" # IXNetworkingImpl2 +PACKAGE = "af406016-e850-4aa8-a88d-2f3dcb9dac7e" # XPackageImpl +PACKAGE3 = "e2a4734b-2f4a-456d-aa8f-d065e04fb209" # IXPackageImpl3 +STORE = "0dd112ac-7c24-448c-b92b-3960fb5bd30c" # XStoreImpl: present, no thunk +UNKNOWN_CLASS = "11111111-2222-3333-4444-555555555555" +UNKNOWN_IFACE = "66666666-7777-8888-9999-aaaaaaaaaaaa" + +IMAGE_BASE = 0x180000000 +TEXT_RVA, TEXT_RAW, TEXT_SIZE = 0x1000, 0x400, 0x1000 +RDATA_RVA, RDATA_RAW, RDATA_SIZE = 0x3000, 0x1400, 0x1000 +GUIDS = {THREADING: 0x3000, NETWORKING: 0x3010, NETWORKING2: 0x3020, PACKAGE: 0x3030, PACKAGE3: 0x3040, + STORE: 0x3050, UNKNOWN_CLASS: 0x3060, UNKNOWN_IFACE: 0x3070} +CACHE_RVA = 0x3090 # zeroed .rdata: a global a thunk passes in r8, not an id +PDATA_RVA = 0x3800 +LABELS = {} # the assembled functions' RVAs, filled by build_image() +SERVED_SOURCE = ("constexpr GUID kThreadingClass = {0x073b7dcb, 0x1fcf, 0x4030, " + "{0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}};\n") + + +class Asm: + """Bytes at an RVA, with labels and rel8/rel32 fields resolved at the end.""" + + def __init__(self, base: int): + self.base, self.buf, self.labels, self.fixups = base, bytearray(), {}, [] + + def here(self) -> int: + return self.base + len(self.buf) + + def label(self, name: str) -> None: + self.labels[name] = self.here() + + def raw(self, text: str) -> None: + self.buf += bytes.fromhex(text) + + def rel(self, text: str, target, size: int = 4) -> None: + """An instruction ending in a displacement to `target` (a label or an RVA), counted from its end.""" + self.raw(text) + self.fixups.append((len(self.buf), size, target)) + self.buf += bytes(size) + + def finish(self) -> bytes: + for pos, size, target in self.fixups: + t = self.labels[target] if isinstance(target, str) else target + self.buf[pos:pos + size] = struct.pack(" None: + """lea r8,[rsp+out]; the id leas; call helper; test eax,eax; js done. iface_id None: mov rdx,rcx.""" + a.raw(f"4C8D4424{out_disp:02X}") # lea r8,[rsp+out] + if iface_id: + a.rel("488D15", GUIDS[iface_id]) # lea rdx,[iid] + a.rel("488D0D", GUIDS[class_id]) # lea rcx,[clsid] + if not iface_id: + a.raw("488BD1") # mov rdx,rcx + a.rel("E8", "helper") + a.raw("85C0") # test eax,eax + a.rel("78", done, 1) # js done + + +def build_code(a: Asm) -> list[tuple[int, int]]: + """The functions; returns their (begin, end) for .pdata.""" + funcs = [] + + def begin(name): + a.label(name) + return a.here() + + def end(start): + funcs.append((start, a.here())) + a.raw("CC" * (-len(a.buf) % 16)) + + s = begin("entry") + a.raw("4883EC28") # sub rsp,28h + a.rel("E8", "thunk1") + a.rel("E8", "thunk2") + a.rel("E8", "stub3") # through an incremental-link style jmp stub + a.raw("4883C428C3") # add rsp,28h; ret + end(s) + + s = begin("helper") + a.raw("33C0C3") # xor eax,eax; ret + end(s) + s = begin("dispatch") + a.raw("FFE0") # jmp rax (the CFG dispatch routine) + end(s) + + # thunk1, CFG form: XThreadingImpl (class id as interface id), slot 12 = XTaskQueueCreate(mode, mode, &queue) + s = begin("thunk1") + a.raw("4883EC38") + query(a, 0x28, THREADING, None, "done1") + a.raw("488B4C2428" "488B01") # mov rcx,[rsp+28h]; mov rax,[rcx] + a.raw("BA01000000" "41B802000000" "4C8D4C2430") # mov edx,1; mov r8d,2; lea r9,[rsp+30h] + a.raw("488B4060") # mov rax,[rax+60h] + a.rel("E8", "dispatch") + a.raw("488B4C2428" "488B01" "488B4010") # Release: slot 2 + a.rel("E8", "dispatch") + a.label("done1") + a.raw("4883C438C3") + end(s) + + # thunk2, call [rax+disp8]: XNetworkingImpl as IXNetworkingImpl2, slot 15 = XNetworkingGetConnectivityHint(&hint) + s = begin("thunk2") + a.raw("53" "4883EC30" "488BD9") # push rbx; sub rsp,30h; mov rbx,rcx + query(a, 0x28, NETWORKING, NETWORKING2, "done2") + a.raw("488B4C2428" "488B01" "488BD3") # mov rcx,[rsp+28h]; mov rax,[rcx]; mov rdx,rbx + a.raw("FF5078") # call [rax+78h] + a.raw("488B4C2428" "488B01" "FF5010") # Release + a.label("done2") + a.raw("4883C4305BC3") + end(s) + + # thunk3, call [r10+disp32] and a stack argument: XPackageImpl as IXPackageImpl3, slot 40 = + # XPackageRegisterPackageInstalled(queue, context, callback, &token) + s = begin("thunk3") + a.raw("4883EC48") + query(a, 0x38, PACKAGE, PACKAGE3, "done3") + a.raw("488B4C2438" "4C8B11") # mov rcx,[rsp+38h]; mov r10,[rcx] + a.raw("33D2" "4533C0" "4533C9") # xor edx,edx; xor r8d,r8d; xor r9d,r9d + a.raw("48C744242000000000") # mov qword ptr [rsp+20h],0 + a.raw("41FF9240010000") # call [r10+140h] + a.raw("488B4C2438" "4C8B11" "41FF5210") # Release through r10 + a.label("done3") + a.raw("4883C448C3") + end(s) + + # thunk4: ids the table doesn't know, slot 5, no arguments; nothing calls it. It calls thunkA first, as the + # library's thunks call the XThreadAssertNotTimeSensitive thunk. + s = begin("thunk4") + a.raw("4883EC38") + a.rel("E8", "thunkA") + query(a, 0x28, UNKNOWN_CLASS, UNKNOWN_IFACE, "done4") + a.raw("488B4C2428" "488B01" "488B4028") # mov rax,[rax+28h] + a.rel("E8", "dispatch") + a.raw("488B4C2428" "488B01" "488B4010") + a.rel("E8", "dispatch") + a.label("done4") + a.raw("4883C438C3") + end(s) + + # thunkA: XThreadingImpl slot 29 = XThreadAssertNotTimeSensitive, the slot load as disp32; only thunk4 calls it. + s = begin("thunkA") + a.raw("4883EC38") + query(a, 0x28, THREADING, THREADING, "doneA") + a.raw("488B4C2428" "488B01" "488B80E8000000") # mov rax,[rax+0E8h] + a.rel("E8", "dispatch") + a.raw("488B4C2428" "488B01" "488B4010") + a.rel("E8", "dispatch") + a.label("doneA") + a.raw("4883C438C3") + end(s) + + # thunkB: XThreadingImpl slot 16 = XTaskQueueDispatch(queue, port, timeout). rdx holds no id, r8 a global (the + # object's cache), and the method pointer reaches rax through r11. + s = begin("thunkB") + a.raw("4883EC38") + a.rel("4C8D05", CACHE_RVA) # lea r8,[cache] + a.rel("488D0D", GUIDS[THREADING]) # lea rcx,[clsid] + a.raw("33D2") # xor edx,edx + a.rel("E8", "helper") + a.raw("85C0") + a.rel("78", "doneB", 1) + a.rel("488B0D", CACHE_RVA) # mov rcx,[cache] + a.raw("488B01" "4C8B9880000000") # mov rax,[rcx]; mov r11,[rax+80h] + a.raw("33D2" "41B801000000" "4183C9FF") # xor edx,edx; mov r8d,1; or r9d,-1 + a.raw("498BC3") # mov rax,r11 + a.rel("E8", "dispatch") + a.rel("488B0D", CACHE_RVA) + a.raw("488B01" "488B4010") # Release + a.rel("E8", "dispatch") + a.label("doneB") + a.raw("4883C438C3") + end(s) + + # thunkC: a helper call whose ids come from a register, not a RIP-relative lea: listed, not followed. + s = begin("thunkC") + a.raw("4883EC38" "4C8D442428" "488BCB" "488BD3") # lea r8,[rsp+28h]; mov rcx,rbx; mov rdx,rbx + a.label("callC") + a.rel("E8", "helper") + a.raw("85C0") + a.rel("78", "doneC", 1) + a.raw("488B4C2428" "488B01" "488B4018") # slot 3 + a.rel("E8", "dispatch") + a.raw("488B4C2428" "488B01" "488B4010") + a.rel("E8", "dispatch") + a.label("doneC") + a.raw("4883C438C3") + end(s) + + a.label("stub3") # outside every function, like an ILT entry + a.rel("E9", "thunk3") + return funcs + + +def build_image(with_pdata: bool = True) -> bytes: + opt_size = 240 + buf = bytearray(RDATA_RAW + RDATA_SIZE) + buf[0:2] = b"MZ" + struct.pack_into(" dict: + return {c["class"] or c["class_id"]: c for c in report["classes"]} + + +def slots_of(cls: dict) -> dict: + return {(i["interface"], s["slot"]): s for i in cls["interfaces"] for s in i["slots"]} + + +class ImageTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.mkdtemp() + cls.table = grc.RuntimeTable.load(grc.DEFAULT_TABLE) + cls.path = cls.write("thunks.dll", build_image()) + cls.served = grc.served_classes(SERVED_SOURCE) + cls.report = grc.report(cls.path, cls.table, cls.served) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + @classmethod + def write(cls, name: str, data: bytes) -> str: + path = os.path.join(cls.tmp, name) + with open(path, "wb") as f: + f.write(data) + return path + + def test_helper_and_thunk_count(self): + self.assertEqual(self.report["helpers"], [f"rel {LABELS['helper']:#x}"]) + self.assertEqual(self.report["thunks"], 6) + # thunkC passes its ids in registers: listed, with no class read. + self.assertEqual(self.report["helper_calls_without_slot_call"], + [{"call": f"{LABELS['callC']:#x}", "class": None, "class_id": None, + "interface_id": None}]) + + def test_classes_slots_and_names(self): + classes = by_class(self.report) + self.assertEqual(set(classes), {"XThreadingImpl", "XNetworkingImpl", "XPackageImpl", UNKNOWN_CLASS}) + threading = slots_of(classes["XThreadingImpl"]) + self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 12)]["method"], "XTaskQueueCreate") + self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 12)]["args_estimate"], [3]) + self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 29)]["method"], "XThreadAssertNotTimeSensitive") + self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 29)]["args_estimate"], [0]) + # thunkB: no id in rdx, so the interface is the class id (not the global r8 points at); slot through r11. + self.assertEqual([i["interface_id"] for i in classes["XThreadingImpl"]["interfaces"]], [THREADING]) + dispatch = threading[("XThreadingImpl/IXThreadingImpl", 16)] + self.assertEqual((dispatch["method"], dispatch["args_estimate"]), ("XTaskQueueDispatch", [3])) + + networking = classes["XNetworkingImpl"] + self.assertEqual([i["interface_id"] for i in networking["interfaces"]], [NETWORKING2]) + hint = slots_of(networking)[("IXNetworkingImpl2", 15)] + self.assertEqual((hint["method"], hint["args_estimate"]), ("XNetworkingGetConnectivityHint", [1])) + + package = slots_of(classes["XPackageImpl"])[("IXPackageImpl3", 40)] + self.assertEqual((package["method"], package["args_estimate"]), ("XPackageRegisterPackageInstalled", [4])) + + def test_unknown_ids_are_reported(self): + unknown = by_class(self.report)[UNKNOWN_CLASS] + self.assertIsNone(unknown["class"]) + self.assertEqual(unknown["interfaces"][0]["interface"], "unknown") + self.assertEqual(unknown["interfaces"][0]["interface_id"], UNKNOWN_IFACE) + slot = unknown["interfaces"][0]["slots"][0] + self.assertEqual((slot["slot"], slot["method"], slot["args_estimate"]), (5, None, [0])) + + def test_served_flag(self): + classes = by_class(self.report) + self.assertIs(classes["XThreadingImpl"]["served"], True) + self.assertIs(classes["XPackageImpl"]["served"], False) + unserved = grc.report(self.path, self.table, None) + self.assertIsNone(by_class(unserved)["XThreadingImpl"]["served"]) + + def test_references(self): + classes = by_class(self.report) + threading = slots_of(classes["XThreadingImpl"]) + self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 12)]["referenced"], 1) + # thunkA is called only by thunk4, which nothing calls. + self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 29)]["referenced"], 0) + self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 16)]["referenced"], 0) + self.assertEqual(classes["XPackageImpl"]["referenced_thunks"], 1) # through the jmp stub + self.assertEqual(classes[UNKNOWN_CLASS]["referenced_thunks"], 0) + self.assertEqual(self.report["referenced_thunks"], 3) + + def test_unreached_known_ids(self): + unreached = {u["class"]: u for u in self.report["unreached_classes"]} + self.assertEqual(set(unreached), {"XStoreImpl"}) + self.assertEqual(unreached["XStoreImpl"]["ids"][0]["id"], STORE) + + def test_without_pdata_the_byte_window_finds_the_same_slots(self): + path = self.write("no_pdata.dll", build_image(with_pdata=False)) + r = grc.report(path, self.table, self.served) + self.assertEqual(r["pdata_functions"], 0) + self.assertEqual({(c["class"], s["slot"]) for c in r["classes"] for i in c["interfaces"] for s in i["slots"]}, + {(c["class"], s["slot"]) for c in self.report["classes"] for i in c["interfaces"] + for s in i["slots"]}) + self.assertIsNone(r["referenced_thunks"]) + + def test_main_writes_text_and_json_with_lf(self): + out = os.path.join(self.tmp, "out") + source = self.write("xgameruntime.cpp", SERVED_SOURCE.encode()) + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + rc = grc.main([self.path, "--out", out, "--runtime-source", source]) + self.assertEqual(rc, 0) + self.assertIn("not-served-referenced=XNetworkingImpl,XPackageImpl\n", stdout.getvalue()) + with open(os.path.join(out, "thunks.dll.gdk_calls.json"), "rb") as f: + raw = f.read() + self.assertNotIn(b"\r\n", raw) + self.assertEqual(json.loads(raw)["thunks"], 6) + with open(os.path.join(out, "thunks.dll.gdk_calls.txt"), "rb") as f: + text = f.read().decode("utf-8") + self.assertNotIn("\r\n", text) + self.assertIn("slot 12 XTaskQueueCreate", text) + self.assertIn("XPackageImpl as IXPackageImpl3: 40; referenced: 40", text) + self.assertIn("class id not read; interface not read", text) + + def test_main_names_repeated_inputs_and_refuses_a_file_as_out(self): + out = os.path.join(self.tmp, "out-twice") + stdout, stderr = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + self.assertEqual(grc.main([self.path, self.path, "--out", out]), 0) + self.assertEqual(grc.main([self.path, "--out", self.path]), 1) + self.assertTrue(os.path.isfile(os.path.join(out, "thunks.dll-2.gdk_calls.json"))) + self.assertIn("report written as thunks.dll-2.gdk_calls.txt/.json", stderr.getvalue()) + self.assertIn("path is a file, not a directory", stderr.getvalue()) + + def test_main_json_to_stdout(self): + stdout, stderr = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + rc = grc.main([self.path, "--json", "--runtime-source", os.path.join(self.tmp, "missing.cpp")]) + self.assertEqual(rc, 0) + self.assertIn("'served' is unknown", stderr.getvalue()) + doc = json.loads(stdout.getvalue()) + self.assertEqual(doc["images"][0]["file"], "thunks.dll") + self.assertIsNone(by_class(doc["images"][0])["XThreadingImpl"]["served"]) + + def test_truncated_image(self): + data = build_image() + cut = self.write("cut.dll", data[:TEXT_RAW + 0x100]) + r = grc.report(cut, self.table, self.served) + self.assertEqual(r["cut_off_sections"], [".text", ".rdata"]) + self.assertEqual(r["thunks"], 0) # the ids are gone with .rdata + stderr, stdout = io.StringIO(), io.StringIO() + with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(stdout): + self.assertEqual(grc.main([cut]), 1) + self.assertEqual(grc.main([self.write("head.dll", data[:0x100])]), 1) + self.assertEqual(grc.main([self.write("text.txt", b"not a PE image")]), 1) + self.assertIn("incomplete", stderr.getvalue()) + self.assertIn("not a readable PE image", stderr.getvalue()) + + +class DecoderTest(unittest.TestCase): + def test_lengths(self): + cases = { + "488D0D00000000": 7, # lea rcx,[rip+0] + "41FF9240010000": 7, # call [r10+140h] + "48C744242000000000": 9, # mov qword ptr [rsp+20h],0 + "E800000000": 5, # call rel32 + "660F1F440000": 6, # nop word ptr [rax+rax] + "C5F877": 3, # vzeroupper + "48B80000000000000000": 10, # mov rax,imm64 + "F6C101": 3, # test cl,1 + "F7C100000000": 6, # test ecx,imm32 + "4C8B11": 3, # mov r10,[rcx] + "0F8400000000": 6, # je rel32 + } + for text, size in cases.items(): + with self.subTest(text=text): + insn = grc.decode(bytes.fromhex(text), 0, 0x1000) + self.assertIsNotNone(insn) + self.assertEqual(insn.size, size) + + def test_operands(self): + lea = grc.decode(bytes.fromhex("488D1510000000"), 0, 0x1000) + self.assertEqual((lea.reg, lea.base, lea.target), (grc.RDX, grc.RIP, 0x1017)) + call = grc.decode(bytes.fromhex("41FF9240010000"), 0, 0) + self.assertEqual((call.base, call.disp, call.is_call()), (10, 0x140, True)) + self.assertIsNone(grc.decode(bytes.fromhex("48"), 0, 0)) # cut off after a REX prefix + + +class TableTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.table = grc.RuntimeTable.load(grc.DEFAULT_TABLE) + + def test_second_interface_starts_at_slot_3(self): + self.assertEqual(self.table.method("IXUserGamertagImpl", 3), ("XUserGetGamertag", None)) + self.assertEqual(self.table.interface_for("cef4fac0-7676-4a94-a119-4c43f9eb5b74"), "IXUserGamertagImpl") + + def test_unknown_entries_keep_their_slot(self): + self.assertEqual(self.table.method("IXPackageImpl3", 20), (None, None)) + self.assertEqual(self.table.method("IXPackageImpl3", 22), ("XPackageUnregisterPackageInstalled", None)) + self.assertEqual(self.table.method("IXPackageImpl3", 40), ("XPackageRegisterPackageInstalled", None)) + + def test_interfaces_without_layout(self): + names, no_layout = self.table.slot_table("IXSystemImpl5") + self.assertEqual(no_layout, ["IXSystemImpl2", "IXSystemImpl5"]) + self.assertEqual(self.table.method("IXSystemImpl5", 8), ("XSystemAllowFullDownloadBandwidth", None)) + self.assertEqual(self.table.method("IXSystemImpl5", 9), (None, None)) + self.assertIsNone(self.table.interfaces["IXSystemImpl5"]["methods"]) + + def test_class_id_used_as_interface_id(self): + self.assertEqual(self.table.interface_for("03f0fe74-fdd9-4e5c-b630-f9339c47acc5"), "IXDisplayImpl") + # XSystemImpl's class id is also IXSystemImpl's; a slot past it is named from the class's interface. + self.assertEqual(self.table.interface_for("e349bd1a-fc20-4e40-b99c-4178cc6b409f"), "IXSystemImpl") + self.assertEqual(self.table.method("IXSystemImpl", 6), ("XSystemHandleTrack", "IXSystemImpl5")) + + def test_served_classes(self): + other = ("constexpr GUID kOther = {0x1, 0x2, 0x3, {0, 0, 0, 0, 0, 0, 0, 0}};\n" # not a k...Class + "constexpr GUID kBadClass = {0x1, 0x2, 0x3, {0x100, 0, 0, 0, 0, 0, 0, 0}};\n") # not a GUID + self.assertEqual(grc.served_classes(SERVED_SOURCE + other), {THREADING: "kThreadingClass"}) + + def test_ranges(self): + self.assertEqual(grc.ranges([3, 4, 5, 9, 12, 13]), "3-5, 9, 12-13") + + +class GeneratorTest(unittest.TestCase): + PAGES = { + "README.md": "# XFooImpl\n\nClass Id: `aaaaaaaa-0000-0000-0000-000000000001`\n\n" + "Implements: [IXFooImpl3](IXFooImpl3.md), [IXFooExtraImpl](IXFooExtraImpl.md)\n", + "IXFooImpl.md": "# IXFooImpl\n\nInterface Id: `aaaaaaaa-0000-0000-0000-000000000001`\n\nInherits: IUnknown\n\n" + "Layout:\n- [XFooFirst](https://example.invalid/first)\n- *unknown*\n" + "- XFooPrivate (no docs)\n- *unknown* (perhaps an older [XFooFirst](https://example.invalid))\n" + "\nA closing paragraph.\n", + "IXFooImpl2.md": "# IXFooImpl2\n\nInterface Id: `aaaaaaaa-0000-0000-0000-000000000002`\n\n" + "Inherits: [IXFooImpl](IXFooImpl.md)\n\nNo layout is known for this one.\n", + "IXFooImpl3.md": "# IXFooImpl3\n\nInterface Id: `AAAAAAAA-0000-0000-0000-000000000003`\n\n" + "Inherits: [IXFooImpl2](IXFooImpl2.md)\n\nLayout:\n- [XFooThird](https://example.invalid)\n", + "IXFooExtraImpl.md": "# IXFooExtraImpl\n\nInterface Id: `aaaaaaaa-0000-0000-0000-0000000000ee`\n\n" + "Inherits: IUnknown\n\nLayout:\n- [XFooExtra](https://example.invalid)\n", + } + + def setUp(self): + self.root = tempfile.mkdtemp() + folder = os.path.join(self.root, "COM", "XFooImpl") + os.makedirs(folder) + for name, text in self.PAGES.items(): + with open(os.path.join(folder, name), "w", encoding="utf-8", newline="\n") as f: + f.write(text) + + def tearDown(self): + shutil.rmtree(self.root, ignore_errors=True) + + def test_parse(self): + doc = gen.build(self.root) + self.assertEqual(doc["classes"]["XFooImpl"], + {"id": "aaaaaaaa-0000-0000-0000-000000000001", "implements": ["IXFooImpl3", "IXFooExtraImpl"]}) + ifaces = doc["interfaces"] + self.assertEqual(ifaces["IXFooImpl"]["methods"], ["XFooFirst", None, "XFooPrivate", None]) + self.assertIsNone(ifaces["IXFooImpl2"]["methods"]) + self.assertEqual(ifaces["IXFooImpl3"]["id"], "aaaaaaaa-0000-0000-0000-000000000003") + self.assertEqual(ifaces["IXFooImpl3"]["inherits"], "IXFooImpl2") + self.assertIsNone(ifaces["IXFooExtraImpl"]["inherits"]) + self.assertEqual(gen.check(doc["classes"], ifaces), []) + table = grc.RuntimeTable(doc) + self.assertEqual(table.method("IXFooImpl3", 7), ("XFooThird", None)) + self.assertEqual(table.method("IXFooExtraImpl", 3), ("XFooExtra", None)) + self.assertEqual(table.slot_table("IXFooImpl3")[1], ["IXFooImpl2"]) + + def test_main_writes_lf_json_and_reports_broken_links(self): + os.remove(os.path.join(self.root, "COM", "XFooImpl", "IXFooExtraImpl.md")) + out = os.path.join(self.root, "table.json") + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(gen.main([self.root, "--out", out]), 0) + self.assertIn("IXFooExtraImpl, which has no page", stderr.getvalue()) + with open(out, "rb") as f: + raw = f.read() + self.assertNotIn(b"\r\n", raw) + self.assertIn("GPL-3.0", json.loads(raw)["licence"]) + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(gen.main([os.path.join(self.root, "missing"), "--out", out]), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_glb_inspect.py b/tests/test_glb_inspect.py index f5a9d8953..a5a3a16db 100644 --- a/tests/test_glb_inspect.py +++ b/tests/test_glb_inspect.py @@ -556,6 +556,133 @@ class GlbInspectTests(unittest.TestCase): self.assertTrue(any("input accessor type is VEC3, expected SCALAR" in issue for issue in issues)) self.assertTrue(any("path 'translation' expects VEC3 output, got VEC4" in issue for issue in issues)) + def test_non_object_sampler_is_an_issue_not_a_crash(self): + gltf = animated_gltf() + gltf["animations"][0]["samplers"] = [7] + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "sampler.glb") + out = os.path.join(folder, "report.json") + with open(path, "wb") as handle: + handle.write(glb(gltf, triangle_bin())) + result = self.run_tool(path, "--json", out) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertIn("issue: sampler[0] is not an object", result.stdout) + with open(out, encoding="utf-8") as handle: + animation = json.load(handle)["animations"][0] + self.assertEqual(animation["issues"], ["sampler[0] is not an object"]) + self.assertIsNone(animation["samplers"][0]["output_type"]) + + def test_oversized_integer_max_reports_no_duration_instead_of_crashing(self): + gltf = animated_gltf() + gltf["accessors"][2]["max"] = [10 ** 400] + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "huge.glb") + out = os.path.join(folder, "report.json") + with open(path, "wb") as handle: + handle.write(glb(gltf, triangle_bin())) + result = self.run_tool(path, "--json", out) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertIn("duration=(missing)", result.stdout) + with open(out, encoding="utf-8") as handle: + animation = json.load(handle)["animations"][0] + self.assertIsNone(animation["duration"]) + self.assertIsNone(animation["samplers"][0]["duration"]) + + def test_zero_keyframes_has_no_duration(self): + gltf = animated_gltf() + gltf["accessors"][2]["count"] = 0 + gltf["accessors"][3]["count"] = 0 + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "empty_keys.glb") + out = os.path.join(folder, "report.json") + with open(path, "wb") as handle: + handle.write(glb(gltf, triangle_bin())) + result = self.run_tool(path, "--json", out) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("duration=(missing)", result.stdout) + with open(out, encoding="utf-8") as handle: + animation = json.load(handle)["animations"][0] + self.assertIsNone(animation["duration"]) + self.assertEqual(animation["issues"], ["sampler[0] input accessor has no keyframes"]) + + def test_non_string_interpolation_is_unknown_not_linear(self): + gltf = animated_gltf() + gltf["animations"][0]["samplers"][0]["interpolation"] = 5 + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "interpolation.glb") + out = os.path.join(folder, "report.json") + with open(path, "wb") as handle: + handle.write(glb(gltf, triangle_bin())) + result = self.run_tool(path, "--json", out) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("interpolation: none", result.stdout) + with open(out, encoding="utf-8") as handle: + animation = json.load(handle)["animations"][0] + self.assertEqual(animation["interpolations"], []) + self.assertIsNone(animation["samplers"][0]["interpolation"]) + self.assertEqual(animation["issues"], ["sampler[0] has unknown interpolation 5"]) + + def test_wrong_typed_arrays_and_channels_are_reported(self): + gltf = { + "asset": {"version": "2.0"}, + "scenes": {}, "nodes": 5, "meshes": "x", "materials": {}, + "images": 3, "skins": {}, "animations": {}, "accessors": {}, + } + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "types.glb") + out = os.path.join(folder, "report.json") + with open(path, "wb") as handle: + handle.write(glb(gltf)) + result = self.run_tool(path, "--json", out) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("invalid types: scenes=dict nodes=int meshes=str", result.stdout) + with open(out, encoding="utf-8") as handle: + report = json.load(handle) + self.assertEqual(report["invalid_types"], { + "scenes": "dict", "nodes": "int", "meshes": "str", "materials": "dict", + "images": "int", "skins": "dict", "animations": "dict", "accessors": "dict", + }) + + animated = animated_gltf() + animated["animations"][0]["channels"] = {} + with open(path, "wb") as handle: + handle.write(glb(animated, triangle_bin())) + result = self.run_tool(path, "--json", out) + self.assertEqual(result.returncode, 0, result.stderr) + with open(out, encoding="utf-8") as handle: + animation = json.load(handle)["animations"][0] + self.assertEqual(animation["channel_count"], 0) + self.assertIn("animation channels is not an array", animation["issues"]) + + def test_cubic_spline_output_count_is_validated(self): + gltf = animated_gltf() + gltf["animations"][0]["samplers"][0]["interpolation"] = "CUBICSPLINE" + gltf["accessors"][3]["count"] = 6 + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "cubic.glb") + out = os.path.join(folder, "report.json") + with open(path, "wb") as handle: + handle.write(glb(gltf, triangle_bin())) + result = self.run_tool(path, "--json", out) + self.assertEqual(result.returncode, 0, result.stderr) + with open(out, encoding="utf-8") as handle: + animation = json.load(handle)["animations"][0] + self.assertEqual(animation["interpolations"], ["CUBICSPLINE"]) + self.assertEqual(animation["samplers"][0]["output_count"], 6) + self.assertEqual(animation["issues"], []) + + gltf["accessors"][3]["count"] = 5 + with open(path, "wb") as handle: + handle.write(glb(gltf, triangle_bin())) + result = self.run_tool(path, "--json", out) + self.assertEqual(result.returncode, 0, result.stderr) + with open(out, encoding="utf-8") as handle: + issues = json.load(handle)["animations"][0]["issues"] + self.assertTrue(any("has 5 output values for 2 keys with CUBICSPLINE interpolation" in issue + for issue in issues)) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_glb_skinning.py b/tests/test_glb_skinning.py index a3866bf17..0c579fbc4 100644 --- a/tests/test_glb_skinning.py +++ b/tests/test_glb_skinning.py @@ -300,6 +300,56 @@ class GlbSkinningTests(unittest.TestCase): self.assertNotEqual(0, proc.returncode) self.assertIn("joint index 2", proc.stderr) + def test_oversized_declared_max_is_a_one_line_error(self): + builder = Builder() + positions = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) + position_payload = b"".join(struct.pack("<3f", *point) for point in positions) + position = builder.add_accessor( + position_payload, 5126, "VEC3", len(positions), + minimum=[0.0, 0.0, 0.0], maximum=[10 ** 400, 1.0, 0.0], + ) + joints = builder.add_accessor(bytes((0, 0, 0, 0)) * 3, 5121, "VEC4", 3) + weights = builder.add_accessor( + struct.pack("<12f", *([1.0, 0.0, 0.0, 0.0] * 3)), 5126, "VEC4", 3, + ) + inverse = builder.add_accessor(struct.pack("<16f", *IDENTITY), 5126, "MAT4", 1) + mesh = {"name": "Body", "primitives": [{"attributes": { + "POSITION": position, "JOINTS_0": joints, "WEIGHTS_0": weights, + }}]} + nodes = [{"name": "Bone"}, {"name": "Body", "mesh": 0, "skin": 0}] + skins = [{"joints": [0], "inverseBindMatrices": inverse}] + data = build_glb(builder.document([mesh], nodes, skins, [0, 1]), builder.data) + + with self.assertRaises(glb_skinning.GlbSkinError) as caught: + glb_skinning.analyze_glb(data) + self.assertIn("accessors[0].max must be 3 finite number(s)", str(caught.exception)) + + path = self.write("huge_max.glb", data) + proc = self.run_tool(path) + self.assertNotEqual(0, proc.returncode) + lines = [line for line in proc.stderr.splitlines() if line.strip()] + self.assertEqual(1, len(lines), proc.stderr) + self.assertIn("accessors[0].max must be 3 finite number(s)", lines[0]) + self.assertNotIn("Traceback", proc.stderr) + + def test_skin_joint_must_reference_a_node_even_when_nodes_is_empty(self): + builder = Builder() + data = build_glb( + builder.document([], [], [{"joints": [5]}], []), + builder.data, + ) + report = glb_skinning.analyze_glb(data) + self.assertFalse(report["ok"]) + errors = "\n".join(report["errors"]) + self.assertIn("joint 0 references node 5", errors) + self.assertIn("the GLB has 0 nodes", errors) + + path = self.write("missing_joint_node.glb", data) + proc = self.run_tool(path) + self.assertNotEqual(0, proc.returncode) + self.assertIn("references node 5", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + def test_inverse_bind_matrices_count_mismatch(self): report = glb_skinning.analyze_glb(make_glb(ibm_count=1)) self.assertFalse(report["ok"]) diff --git a/tests/test_glb_writer.py b/tests/test_glb_writer.py index dd3a82f29..89a87ef16 100644 --- a/tests/test_glb_writer.py +++ b/tests/test_glb_writer.py @@ -927,6 +927,95 @@ f 1//1 2//2 3//3 self.assertEqual(len(prims), 1) self.assertEqual(len(prims[0]["indices"]), 3) + def test_parse_obj_single_line_face_remains_unchanged(self): + obj_text = "\n".join([ + "v 0 0 0", + "v 1 0 0", + "v 0 1 0", + "f 1 2 3", + ]) + prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") + self.assertEqual(prim["indices"], [0, 1, 2]) + + def test_parse_obj_joins_face_split_across_two_lines(self): + obj_text = "\n".join([ + "v 0 0 0", + "v 1 0 0", + "v 0 1 0", + "f 1 2 \\ ", + "3", + ]) + prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") + self.assertEqual(prim["indices"], [0, 1, 2]) + + def test_parse_obj_joins_face_split_across_three_lines(self): + obj_text = "\n".join([ + "v 0 0 0", + "v 1 0 0", + "v 0 1 0", + "f 1 \\", + "2 \\", + "3", + ]) + prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") + self.assertEqual(prim["indices"], [0, 1, 2]) + + def test_parse_obj_joins_face_split_immediately_after_keyword(self): + obj_text = "\n".join([ + "v 0 0 0", + "v 1 0 0", + "v 0 1 0", + "f \\", + "1 2 3", + ]) + prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") + self.assertEqual(prim["indices"], [0, 1, 2]) + + def test_parse_obj_continuation_skips_blank_and_comment_lines(self): + obj_text = "\r\n".join([ + "v 0 0 0", + "v 1 0 0", + "v 0 1 0", + "f 1 2 \\", + " # split after two corners", + "", + "3", + ]) + "\r\n" + prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") + self.assertEqual(prim["indices"], [0, 1, 2]) + + def test_parse_obj_backslash_inside_line_stays_an_invalid_token(self): + obj_text = "\n".join([ + "v 0 0 0", + "v 1 0 0", + "v 0 1 0", + "f 1 2\\ 3", + ]) + self.assertEqual(glb_writer.parse_obj(obj_text, is_path=False, up_axis="y"), []) + + def test_parse_obj_inline_comment_backslash_does_not_continue(self): + obj_text = "\n".join([ + "v 0 0 0", + "v 1 0 0", + "v 0 1 0", + "v 1 1 0", + "f 1 2 3 # keep this comment \\", + "f 1 2 4", + ]) + prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") + self.assertEqual(prim["indices"], [0, 1, 2, 0, 1, 3]) + + def test_parse_obj_continuation_before_inline_comment(self): + obj_text = "\n".join([ + "v 0 0 0", + "v 1 0 0", + "v 0 1 0", + "f 1 2 \\ # split before the comment", + "3", + ]) + prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") + self.assertEqual(prim["indices"], [0, 1, 2]) + def test_compute_bounds_calculation(self): prims = [ {"positions": [(-5.0, 1.0, 2.0), (10.0, -3.0, 8.0)]}, diff --git a/tests/test_hw_oracle.py b/tests/test_hw_oracle.py index 90e2b52bd..c290f04ef 100644 --- a/tests/test_hw_oracle.py +++ b/tests/test_hw_oracle.py @@ -310,7 +310,7 @@ class VcvarsScript(unittest.TestCase): out = os.path.join(work, "hw_oracle.exe") vcvars = os.path.join(work, "vcvars64.bat") argv = runner.build_command("vcvars", vcvars, src, out, work) - with open(argv[-1], "rb") as f: + with open(os.path.join(work, argv[-1]), "rb") as f: # the script runs with cwd=work return argv, f.read(), (src, out, vcvars) def test_paths_outside_ascii_are_written_as_utf8(self): @@ -337,7 +337,7 @@ class VcvarsScript(unittest.TestCase): work = os.path.join(tmp, "work") os.makedirs(work) argv = runner.build_command("vcvars", "vcvars64.bat", "hw_oracle.c", "hw_oracle.exe", work) - with open(argv[-1], "rb") as f: + with open(os.path.join(work, argv[-1]), "rb") as f: lines = f.read().decode("ascii").split("\r\n") self.assertEqual(lines[3], 'call "vcvars64.bat" >nul || exit /b 1') self.assertTrue(lines[4].startswith("cl /nologo /O1 hw_oracle.c /Fehw_oracle.exe /Fo")) @@ -351,6 +351,26 @@ class VcvarsScript(unittest.TestCase): self.assertEqual(runner.build_command("msvc", "cl.exe", "a.c", "a.exe", work)[0], "cl.exe") self.assertEqual(os.listdir(work), []) + @unittest.skipUnless(sys.platform == "win32", "runs the script through cmd.exe") + def test_the_script_runs_from_any_work_folder(self): + # A full path through `cmd.exe /c` loses its quotes when the folder holds & or ^, and a bare name is not + # found with NoDefaultCurrentDirectoryInExePath set. A stub vcvars shows the script got that far. + broken = [] + with tempfile.TemporaryDirectory() as tmp: + stub = os.path.join(tmp, "stub_vcvars.bat") + with open(stub, "wb") as f: + f.write(b'@echo off\r\necho reached> "%LEONIDA_TEST_MARKER%"\r\nexit /b 0\r\n') + for name in ("plain", "sp (x)", "a & b", "a&b", "x^y", self.NAME): + work = os.path.join(tmp, name) + os.makedirs(work) + marker = os.path.join(work, "reached.txt") + argv = runner.build_command("vcvars", stub, "hw_oracle.c", "hw_oracle.exe", work) + env = dict(os.environ, LEONIDA_TEST_MARKER=marker, NoDefaultCurrentDirectoryInExePath="1") + subprocess.run(argv, cwd=work, env=env, capture_output=True, timeout=60) # cl itself is absent + if not os.path.exists(marker): + broken.append(name) + self.assertEqual(broken, [], "build_hw_oracle.cmd did not run from these work folders") + class Unavailable(unittest.TestCase): def test_missing_tools_are_reported_not_raised_as_crashes(self): @@ -399,7 +419,7 @@ class Unavailable(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: argv = runner.build_command("vcvars", r"C:\VS 2022\vcvars64.bat", "a.c", "o.exe", tmp) self.assertEqual(argv[:3], ["cmd.exe", "/d", "/c"]) - script = Path(argv[3]).read_text(encoding="ascii") + script = (Path(tmp) / argv[3]).read_text(encoding="ascii") self.assertIn('call "C:\\VS 2022\\vcvars64.bat"', script) # quoted: the path has a space self.assertIn("cl /nologo /O1 a.c /Feo.exe", script) self.assertIn("Installer", script) # vcvars needs vswhere on PATH diff --git a/tests/test_image_d16_probe.py b/tests/test_image_d16_probe.py index 7f5192b43..0c0f61b1b 100644 --- a/tests/test_image_d16_probe.py +++ b/tests/test_image_d16_probe.py @@ -159,6 +159,71 @@ class Cli(unittest.TestCase): self.assertEqual(r.returncode, 2) self.assertIn("cube", r.stderr) + def test_bad_json_paths_rejected_before_open_oracle(self): + with tempfile.TemporaryDirectory() as tmp: + existing_dir = os.path.join(tmp, "dir") + os.mkdir(existing_dir) + file_ancestor = os.path.join(tmp, "file_ancestor") + with open(file_ancestor, "w", encoding="utf-8") as f: + f.write("x") + + bad_paths = [ + "", + " ", + "bad\x00out.json", + existing_dir, + os.path.join(tmp, "trailing") + os.sep, + os.path.join(file_ancestor, "sub", "out.json"), + ] + for bad in bad_paths: + with self.subTest(json_path=bad): + stderr = io.StringIO() + with mock.patch.object(runner, "open_oracle") as open_mock, \ + mock.patch.object(sys, "stderr", stderr): + rc = pr.main(["--json", bad]) + self.assertEqual(rc, 2) + self.assertIn("error:", stderr.getvalue()) + self.assertNotIn("Traceback", stderr.getvalue()) + open_mock.assert_not_called() + + def test_valid_nested_json_does_not_create_dirs_when_oracle_unavailable(self): + with tempfile.TemporaryDirectory() as tmp: + nested_dir = os.path.join(tmp, "a", "b") + json_path = os.path.join(nested_dir, "report.json") + stdout = io.StringIO() + with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("no gpu")), \ + mock.patch.object(sys, "stdout", stdout): + rc = pr.main(["--json", json_path]) + self.assertEqual(rc, 77) + self.assertFalse(os.path.exists(os.path.join(tmp, "a"))) + + def test_write_json_report_creates_parents_and_writes_lf_json(self): + with tempfile.TemporaryDirectory() as tmp: + out_path = os.path.join(tmp, "nested", "dir", "report.json") + payload = {"device": "fake", "arch": "gfx1036", "cases": {}} + err = pr.write_json_report(out_path, payload) + self.assertIsNone(err) + with open(out_path, "rb") as f: + raw = f.read() + self.assertNotIn(b"\r\n", raw) + self.assertEqual(json.loads(raw.decode("utf-8")), payload) + + def test_write_json_oserror_returns_2_without_traceback(self): + with tempfile.TemporaryDirectory() as tmp: + out_path = os.path.join(tmp, "report.json") + with mock.patch("builtins.open", side_effect=PermissionError("denied")): + err = pr.write_json_report(out_path, {"ok": True}) + self.assertIsNotNone(err) + self.assertIn("cannot write --json", err) + + stderr = io.StringIO() + with mock.patch("builtins.open", side_effect=OSError("disk full")), \ + mock.patch.object(sys, "stderr", stderr): + rc, _ = run_main(FakeOracle(), "--dims", "1d", "--formats", "r32_uint", "--json", out_path) + self.assertEqual(rc, 2) + self.assertIn("error:", stderr.getvalue()) + self.assertNotIn("Traceback", stderr.getvalue()) + class OnHardware(unittest.TestCase): @classmethod diff --git a/tests/test_image_fuzz_work_isolation.py b/tests/test_image_fuzz_work_isolation.py new file mode 100644 index 000000000..b0ec4ce2f --- /dev/null +++ b/tests/test_image_fuzz_work_isolation.py @@ -0,0 +1,174 @@ +"""image_fuzz must not overwrite a caller's --work files or reuse another run's outputs.""" +import contextlib +import io +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import image_fuzz as imf + + +class ImageFuzzWorkIsolation(unittest.TestCase): + def test_existing_files_and_previous_runs_survive(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "work" + root.mkdir() + build = Path(tmp) / "build" + build.mkdir() + (build / (imf.HARNESS + (".exe" if os.name == "nt" else ""))).touch() + names = ("disasm/ps_image_load.s", "disasm/vs_ids.s", "ps_image_load.dxbc", "vs_ids.dxbc", + "texels.bin", "spec.txt", "out.raw") + sentinels = {} + for name in names: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"caller data") + sentinels[path] = b"caller data" + + def assemble(cmd, **kwargs): + return subprocess.CompletedProcess(cmd, 0, "s_endpgm\n", "") + + def translate(work, pc_tail=False): + spirv = Path(work) / "spirv" + spirv.mkdir() + return str(spirv) + + def harness(cmd, **kwargs): + return subprocess.CompletedProcess(cmd, 77, "unsupported: synthetic test\n", "") + + outputs = [] + for _ in range(2): + out = io.StringIO() + argv = ["image_fuzz.py", "--programs", "1", "--formats", "R8G8B8A8_UNORM", + "--work", str(root), "--build", str(build)] + with (patch.object(sys, "argv", argv), patch.object(imf.mc_command, "run", side_effect=assemble), + patch.object(imf, "translate", side_effect=translate), + patch.object(imf.subprocess, "run", side_effect=harness), contextlib.redirect_stdout(out)): + self.assertEqual(imf.main(), 0) + outputs.append(out.getvalue()) + self.assertIn("1 skipped", outputs[-1]) + for path, content in sentinels.items(): + self.assertEqual(path.read_bytes(), content, f"image_fuzz overwrote {path}") + + runs = sorted(p for p in root.iterdir() if p.is_dir() and p.name != "disasm") + self.assertEqual(len(runs), 2) + for run in runs: + self.assertTrue((run / "disasm" / "ps_image_load.s").is_file()) + self.assertTrue((run / "texels.bin").is_file()) + self.assertTrue((run / "spec.txt").is_file()) + self.assertTrue(any(str(run) in output for output in outputs)) + self.assertNotEqual(runs[0], runs[1]) + + def test_concurrent_processes_get_distinct_folders(self): + child = r''' +import os +from pathlib import Path +import sys +sys.path.insert(0, sys.argv[1]) +import image_fuzz + +def run_case(*args, **kwargs): + (Path(args[4]) / "worker.bin").write_bytes(str(os.getpid()).encode("ascii")) + return True + +image_fuzz.run_case = run_case +sys.argv = ["image_fuzz.py", "--programs", "1", "--work", sys.argv[2]] +raise SystemExit(image_fuzz.main()) +''' + with tempfile.TemporaryDirectory() as tmp: + parent = Path(tmp) / "work" + parent.mkdir() + sentinel = parent / "texels.bin" + sentinel.write_bytes(b"caller data") + tools = str(Path(__file__).resolve().parents[1] / "tools") + command = [sys.executable, "-I", "-c", child, tools, str(parent)] + workers = [] + try: + for _ in range(2): + workers.append(subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True)) + results = [worker.communicate(timeout=20) for worker in workers] + finally: + for worker in workers: + if worker.poll() is None: + worker.kill() + worker.communicate() + paths = [] + for worker, (stdout, stderr) in zip(workers, results): + self.assertEqual(worker.returncode, 0, (stdout, stderr)) + lines = [line.removeprefix("work dir ") for line in stdout.splitlines() if line.startswith("work dir ")] + self.assertEqual(len(lines), 1, stdout) + paths.append(Path(lines[0])) + self.assertNotEqual(paths[0], paths[1]) + self.assertTrue(all(path.parent == parent for path in paths)) + self.assertNotEqual((paths[0] / "worker.bin").read_bytes(), (paths[1] / "worker.bin").read_bytes()) + self.assertEqual(sentinel.read_bytes(), b"caller data") + + def test_existing_file_as_work_reports_one_error(self): + with tempfile.TemporaryDirectory() as tmp: + parent = Path(tmp) / "not-a-directory" + parent.write_bytes(b"caller data") + script = Path(__file__).resolve().parents[1] / "tools" / "image_fuzz.py" + result = subprocess.run([sys.executable, "-I", str(script), "--programs", "1", "--work", str(parent)], + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=20) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("ERROR:", result.stderr) + self.assertEqual(len(result.stderr.splitlines()), 1, result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertEqual(parent.read_bytes(), b"caller data") + + def test_work_error_closes_an_open_hardware_oracle(self): + from hw_oracle import runner + + class Oracle: + arch = "gfx1030" + device = "synthetic device" + closed = False + + def close(self): + self.closed = True + + with tempfile.TemporaryDirectory() as tmp: + parent = Path(tmp) / "not-a-directory" + parent.write_bytes(b"caller data") + oracle = Oracle() + argv = ["image_fuzz.py", "--oracle", "hw", "--programs", "1", "--work", str(parent)] + stderr = io.StringIO() + with (patch.object(sys, "argv", argv), patch.object(runner, "open_oracle", return_value=oracle), + contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(stderr)): + self.assertEqual(imf.main(), 2) + self.assertTrue(oracle.closed) + self.assertIn("ERROR:", stderr.getvalue()) + self.assertEqual(parent.read_bytes(), b"caller data") + + def test_setup_failure_reports_the_retained_folder(self): + with tempfile.TemporaryDirectory() as tmp: + parent = Path(tmp) / "new" / "work" + out = io.StringIO() + argv = ["image_fuzz.py", "--programs", "1", "--work", str(parent)] + with (patch.object(sys, "argv", argv), + patch.object(imf, "assemble", side_effect=SystemExit("synthetic setup error")), + contextlib.redirect_stdout(out)): + with self.assertRaises(SystemExit): + imf.main() + runs = list(parent.iterdir()) + self.assertEqual(len(runs), 1) + self.assertTrue(runs[0].is_dir()) + self.assertIn(str(runs[0]), out.getvalue()) + + def test_self_test_does_not_create_a_work_folder(self): + with tempfile.TemporaryDirectory() as tmp: + parent = Path(tmp) / "not-created" + with (patch.object(sys, "argv", ["image_fuzz.py", "--self-test", "--work", str(parent)]), + patch.object(imf, "self_test", return_value=0)): + self.assertEqual(imf.main(), 0) + self.assertFalse(parent.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_image_load_typed.py b/tests/test_image_load_typed.py index c5e696f3b..98c782749 100644 --- a/tests/test_image_load_typed.py +++ b/tests/test_image_load_typed.py @@ -336,6 +336,56 @@ class LodQueryCoordinates(unittest.TestCase): class TypedGatherShaders(unittest.TestCase): + def test_a16_offset_gathers_preserve_offset_and_unpack_uv_lod(self) -> None: + fixture = Path(ROOT) / "tests/semantic/fixtures/gather_offset_a16.asm" + lines = [line for line in fixture.read_text(encoding="ascii").splitlines() + if line and not line.startswith(";")] + end = lines.index("s_waitcnt vmcnt(0)") + for explicit in (True, False): + with self.subTest(explicit_lod=explicit): + body = lines[:end] + if not explicit: + body[-1] = body[-1].replace("gather4_l_o", "gather4_lz_o").replace("v[4:6]", "v[4:5]") + m = Module(translate(body)) + + def source_register(value: str) -> int: + op, load = m.defs[value] + self.assertEqual(op, "OpLoad") + op, ptr = m.defs[load[1]] + self.assertEqual((op, ptr[1]), ("OpAccessChain", "%vgpr")) + return m.value(ptr[2], 0, 0) + + fields = [(source_register(a[1]), m.value(a[2], 0, 0), m.value(a[3], 0, 0)) + for _, op, a in m.order if op == "OpBitFieldSExtract"] + self.assertEqual(fields, [(4, 0, 6), (4, 8, 6)]) + + def source_half(value: str) -> tuple[int, int]: + while m.defs[value][0] == "OpBitcast": + value = m.defs[value][1][1] + extract_op, (_, pair, half) = m.defs[value] + self.assertEqual(extract_op, "OpCompositeExtract") + op, unpack = m.defs[pair] + self.assertEqual((op, unpack[2]), ("OpExtInst", "UnpackHalf2x16")) + return source_register(unpack[3]), int(half) + + if explicit: + uv, = [a[1] for _, op, a in m.order if op == "OpFMul" and a[0] == "%v2float"] + lod, = [a[3] for _, op, a in m.order if op == "OpExtInst" and a[2] == "FClamp"] + self.assertEqual(source_half(lod), (6, 0)) + else: + uv, = {a[2] for _, op, a in m.order if op == "OpImageGather"} + op, coord = m.defs[uv] + self.assertEqual(op, "OpCompositeConstruct") + self.assertEqual([source_half(c) for c in coord[1:]], [(5, 0), (5, 1)]) + + def test_a16_offset_gathers_with_status_stay_unsupported(self) -> None: + for op in ("image_gather4_l_o", "image_gather4_lz_o"): + addr = "v[4:6]" if op == "image_gather4_l_o" else "v[4:5]" + for status in ("tfe", "lwe"): + with self.subTest(op=op, status=status), self.assertRaises(rdna2spirv.Unsupported): + dest = "v[10:14]" if status == "tfe" else "v[10:13]" + translate([f"{op} {dest}, {addr}, s[0:7], s[8:11] dmask:0x2 dim:SQ_RSRC_IMG_2D a16 {status}"]) + def test_2d_lod_samples_use_matching_typed_views(self): instructions = (("image_sample_lz", "v[4:5]"), ("image_sample_l", "v[4:6]")) destinations = (("v[0:3]", ""), ("v[0:1]", " d16")) diff --git a/tests/test_inline_scan.py b/tests/test_inline_scan.py index 67b93feb5..3cee6d527 100644 --- a/tests/test_inline_scan.py +++ b/tests/test_inline_scan.py @@ -6,7 +6,9 @@ here line by line, so the test needs no game files, no dumpbin and no third-part python -I tests/test_inline_scan.py """ import os +import subprocess import sys +import tempfile import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -149,6 +151,41 @@ class InlineScanTests(unittest.TestCase): self.assertIn("checked 1, UNCHECKED 1", text) self.assertIn("+0x28 x1", text) + def test_scan_counts_the_instructions_it_read(self): + stats = {} + sites = list(inline_scan.scan(listing(*GUARDED), stats)) + self.assertEqual(stats["instructions"], len(GUARDED)) + self.assertIn(f"instructions scanned: {len(GUARDED)}", inline_scan.summarize(sites, stats["instructions"])) + + +class InlineScanCliTests(unittest.TestCase): + """An input with no instructions must not read as a clean image ("UNCHECKED 0").""" + + def run_cli(self, text): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "listing.txt") + with open(path, "w", encoding="utf-8", newline="") as f: + f.write(text) + return subprocess.run([sys.executable, "-I", os.path.join(TOOLS_DIR, "inline_scan.py"), path], + capture_output=True, text=True) + + def test_empty_input_exits_2_without_a_summary(self): + proc = self.run_cli("") + self.assertEqual(proc.returncode, 2) + self.assertIn("no instructions found", proc.stderr) + self.assertNotIn("UNCHECKED", proc.stdout) + + def test_text_that_is_not_a_listing_exits_2(self): + proc = self.run_cli("Microsoft (R) COFF/PE Dumper\nnot a disassembly\n") + self.assertEqual(proc.returncode, 2) + self.assertNotIn("UNCHECKED", proc.stdout) + + def test_a_listing_with_instructions_but_no_site_still_passes(self): + proc = self.run_cli("".join(listing("mov rax,rcx", "ret"))) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("instructions scanned: 2", proc.stdout) + self.assertIn("checked 0, UNCHECKED 0", proc.stdout) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_mad_denorm_probe.py b/tests/test_mad_denorm_probe.py index 7f62980a2..26153f01f 100644 --- a/tests/test_mad_denorm_probe.py +++ b/tests/test_mad_denorm_probe.py @@ -1,15 +1,19 @@ """CPU tests for tools/mad_denorm_probe.py (SHADER-340): RDNA1 mad/mac pre- and post-omod denormal flush. Standard library only; no GPU, no LLVM, no game files. """ +import contextlib +import io import os import sys import unittest +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.dont_write_bytecode = True sys.path.insert(0, os.path.join(ROOT, "tools")) import mad_denorm_probe as probe # noqa: E402 +from hw_oracle import runner as hw_runner # noqa: E402 class TranslatorTests(unittest.TestCase): @@ -35,6 +39,22 @@ class TranslatorTests(unittest.TestCase): self.assertEqual(by_what["subnorm * +inf + -1 -> -1"], probe.NEG_ONE) self.assertEqual(by_what["subnorm * qNaN + 1 -> 1"], probe.ONE) + def test_mode_sanity_rejects_broken_denorm_control(self): + class BrokenModeOracle: + device = "fake" + arch = "gfx1010" + + def run(self, kernels, words=1): + return [[probe.POS_ZERO] for _ in kernels] + + def close(self): + pass + + with mock.patch.object(hw_runner, "open_oracle", return_value=BrokenModeOracle()): + with contextlib.redirect_stdout(io.StringIO()): + rc = probe.main(["--oracle", "hw"]) + self.assertEqual(rc, 2) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_make_game_assets_decoder.py b/tests/test_make_game_assets_decoder.py index ec147c61e..cc8a242ef 100644 --- a/tests/test_make_game_assets_decoder.py +++ b/tests/test_make_game_assets_decoder.py @@ -6,6 +6,8 @@ does when an export finishes. python -I tests/test_make_game_assets_decoder.py """ import os +import shutil +import subprocess import sys import tempfile import unittest @@ -65,6 +67,19 @@ class AssetsDecoderTest(unittest.TestCase): os.remove(os.path.join(self.models, make_game.DECODER_RECORD)) self.assertEqual(self.export("d1"), ["models"]) + def test_an_exporter_that_cannot_be_built_keeps_the_old_export(self): + self.export("d1") + with mock.patch.object(make_game, "MODEL_ARCHIVES", ["scene.rpf"]), \ + mock.patch.object(make_game, "decoder_digest", lambda: "d2"), \ + mock.patch.object(make_game, "rpf9dump", side_effect=SystemExit(1)), \ + mock.patch.object(make_game, "log", lambda *a: None): + with self.assertRaises(SystemExit): + make_game.assets(os.path.join(self.work, "game"), self.work, False, 1) + self.assertTrue(os.path.isfile(os.path.join(self.models, "manifest.json"))) + with open(os.path.join(self.models, make_game.DECODER_RECORD), encoding="utf-8") as f: + self.assertEqual(f.read(), "d1\n") + self.assertEqual(self.export("d2"), ["models", "textures"]) + def test_the_digest_follows_the_exporter_sources(self): with tempfile.TemporaryDirectory() as tools: os.makedirs(os.path.join(tools, "rpf9dump")) @@ -78,6 +93,32 @@ class AssetsDecoderTest(unittest.TestCase): make_game.decoder_digest.cache_clear() self.assertNotEqual(*digests) + @unittest.skipUnless(shutil.which("git"), "needs git") + def test_the_digest_follows_an_uncommitted_submodule_edit(self): + with tempfile.TemporaryDirectory() as root: + sub = os.path.join(root, "third_party", "rpf9-explorer") + os.makedirs(sub) + src = os.path.join(sub, "Decoder.cs") + + def git(*args): + subprocess.run(["git", "-C", sub, "-c", "user.name=t", "-c", "user.email=t@example.invalid", + "-c", "commit.gpgsign=false", *args], check=True, capture_output=True) + + with open(src, "w", newline="\n") as f: + f.write("a\n") + git("init", "-q") + git("add", "Decoder.cs") + git("commit", "-q", "-m", "x") + digests = [] + for text in ("a\n", "b\n"): + with open(src, "w", newline="\n") as f: + f.write(text) + make_game.decoder_digest.cache_clear() + with mock.patch.object(make_game, "ROOT", root): + digests.append(make_game.decoder_digest()) + make_game.decoder_digest.cache_clear() + self.assertNotEqual(*digests) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_make_game_dry_run.py b/tests/test_make_game_dry_run.py index 7c64eee99..ead4eccee 100644 --- a/tests/test_make_game_dry_run.py +++ b/tests/test_make_game_dry_run.py @@ -318,7 +318,7 @@ class PipelineStageIsolationTest(unittest.TestCase): os.makedirs(spirv_dir, exist_ok=True) index_path = os.path.join(spirv_dir, "index.json") with open(index_path, "w", encoding="utf-8") as f: - f.write("{}") + f.write('{"shader_0": {}}') # a finished translation is never empty dummy_exe = os.path.join(self.tmp.name, "vk_pipeline_check.exe") with open(dummy_exe, "w", encoding="utf-8") as f: diff --git a/tests/test_make_game_empty_translation.py b/tests/test_make_game_empty_translation.py new file mode 100644 index 000000000..988bc12de --- /dev/null +++ b/tests/test_make_game_empty_translation.py @@ -0,0 +1,116 @@ +"""make_game.py: an empty translated shader index is a failed stage, not a finished one. + +Standard library only; no GPU, no Vulkan SDK, no game data: the shard processes and rdna2spirv.py are mocked. + + python -I tests/test_make_game_empty_translation.py +""" +import io +import json +import os +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +import make_game # noqa: E402 + + +def write(path, text): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + + +class Done: + def poll(self): + return 0 + + def wait(self): + return 0 + + def terminate(self): + pass + + def kill(self): + pass + + +class TranslateEmptyIndexTest(unittest.TestCase): + """translate(): a merge that published nothing is an error and must not leave a marker behind.""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.disasm = os.path.join(tmp.name, "dxbc", "disasm") + self.spirv = os.path.join(tmp.name, "spirv") + os.makedirs(self.disasm) + + def translate_with_index(self, text): + def fake_py(tool, *args): + if "--merge" in args: + write(os.path.join(self.spirv, "index.json"), text) + + with mock.patch.object(make_game, "log", lambda *a: None), \ + mock.patch.object(make_game, "py", side_effect=fake_py), \ + mock.patch.object(make_game.subprocess, "Popen", lambda *a, **k: Done()): + make_game.translate(self.disasm, self.spirv, 1) + + def test_an_empty_index_is_removed_with_the_plan_and_the_retry_fails(self): + for _ in range(2): + with self.assertRaises(SystemExit) as cm: + self.translate_with_index("{}") + self.assertEqual(cm.exception.code, 1) + self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) + self.assertFalse(os.path.exists(os.path.join(self.spirv, make_game.SHARD_PLAN))) + + def test_an_unreadable_index_is_removed(self): + with self.assertRaises(SystemExit) as cm: + self.translate_with_index("not json") + self.assertEqual(cm.exception.code, 1) + self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) + + def test_a_non_empty_index_is_kept(self): + self.translate_with_index(json.dumps({"shader_0": {"stage": "ps"}})) + with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f: + self.assertEqual(json.load(f), {"shader_0": {"stage": "ps"}}) + + +class RequireTranslatedShadersTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.work = tmp.name + self.spirv = os.path.join(self.work, "shaders", "spirv") + os.makedirs(self.spirv) + + def call(self): + err = io.StringIO() + with mock.patch("sys.stderr", err): + return make_game.require_translated_shaders(self.work), err.getvalue() + + def test_missing_index_names_the_stage(self): + with self.assertRaises(SystemExit) as cm: + self.call() + self.assertEqual(cm.exception.code, 1) + + def test_an_empty_index_is_refused(self): + write(os.path.join(self.spirv, "index.json"), "{}") + with self.assertRaises(SystemExit) as cm: + self.call() + self.assertEqual(cm.exception.code, 1) + + def test_an_unreadable_index_is_refused(self): + write(os.path.join(self.spirv, "index.json"), "not json") + with self.assertRaises(SystemExit) as cm: + self.call() + self.assertEqual(cm.exception.code, 1) + + def test_a_non_empty_index_is_accepted(self): + write(os.path.join(self.spirv, "index.json"), '{"shader_0": {}}') + self.assertEqual(self.call()[0], self.spirv) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_make_game_paths.py b/tests/test_make_game_paths.py index d40e3229f..f9f26168c 100644 --- a/tests/test_make_game_paths.py +++ b/tests/test_make_game_paths.py @@ -26,7 +26,6 @@ class BuildDestinationTest(unittest.TestCase): self.game = os.path.join(self.root, "game") os.mkdir(self.game) self.alias = os.path.join(self.root, "game-link") - self.link(self.game, self.alias) def link(self, target, path): if os.name == "nt": @@ -42,14 +41,14 @@ class BuildDestinationTest(unittest.TestCase): def run_build(self, game, out, work, rejected): argv = ["make_game.py", "--game", game, "--out", out, "--work", work, - "--stages", "shaders"] + "--stages", "runtime"] with ExitStack() as stack: stack.enter_context(patch.object(sys, "argv", argv)) stack.enter_context(patch("make_game.below_normal")) stack.enter_context(patch("make_game.check", return_value={})) stack.enter_context(patch("make_game.log")) preflight = stack.enter_context(patch("make_game.preflight")) - shaders = stack.enter_context(patch("make_game.shaders")) + build_runtime = stack.enter_context(patch("make_game.runtime")) stderr = stack.enter_context(patch("sys.stderr", new_callable=io.StringIO)) if rejected: with self.assertRaises(SystemExit) as error: @@ -57,13 +56,14 @@ class BuildDestinationTest(unittest.TestCase): self.assertEqual(error.exception.code, 1) self.assertIn("--out and --work must be outside the game folder", stderr.getvalue()) preflight.assert_not_called() - shaders.assert_not_called() + build_runtime.assert_not_called() else: self.assertEqual(make_game.main(), 0) preflight.assert_called_once() - shaders.assert_called_once() + build_runtime.assert_called_once() def test_destinations_through_game_link_are_rejected(self): + self.link(self.game, self.alias) for option in ("out", "work"): for suffix in ("", "new", os.path.join("new", "nested")): with self.subTest(option=option, suffix=suffix): @@ -73,6 +73,7 @@ class BuildDestinationTest(unittest.TestCase): self.assertFalse(os.path.exists(os.path.join(self.game, "new"))) def test_game_link_cannot_hide_destinations_in_real_game_folder(self): + self.link(self.game, self.alias) for option in ("out", "work"): with self.subTest(option=option): destinations = {name: os.path.join(self.root, name) for name in ("out", "work")} @@ -101,6 +102,33 @@ class BuildDestinationTest(unittest.TestCase): # Rejected: destination is the drive root itself self.run_build(drive, drive, os.path.join(self.root, "work"), rejected=True) + def test_drive_root_checks_entries_on_each_volume(self): + if os.name != "nt": + self.skipTest("Windows drive root check") + root = os.path.splitdrive(self.root)[0] + "\\" + other_root = "Z:\\" if root.upper() != "Z:\\" else "Y:\\" + junction = os.path.join(root, "MountedContent") + mounted_content = os.path.join(other_root, "Package") + + def realpath(path): + if os.path.normcase(path) == os.path.normcase(junction): + return mounted_content + return os.path.normpath(path) + + # A junction target on a different volume must not end the search before the matching entry. + for entries, protected in ( + (["MountedContent", "Content"], os.path.join(root, "Content")), + (["Content", "MountedContent"], mounted_content), + ): + with patch("os.listdir", return_value=entries), patch("os.path.realpath", side_effect=realpath): + for option in ("out", "work"): + with self.subTest(protected=protected, option=option): + destinations = {name: os.path.join(self.root, name) for name in ("out", "work")} + destinations[option] = os.path.join(protected, "build") + self.run_build(root, **destinations, rejected=True) + self.run_build(root, os.path.join(other_root, "Build"), + os.path.join(other_root, "Scratch"), rejected=False) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_make_game_pipeline_batches.py b/tests/test_make_game_pipeline_batches.py new file mode 100644 index 000000000..c9508fc67 --- /dev/null +++ b/tests/test_make_game_pipeline_batches.py @@ -0,0 +1,210 @@ +"""Pipeline batching and memory-crash recovery through the real make_game.pipelines orchestration. + +The child is a small scripted checker speaking the production CLI/file protocol. Each invocation is a real +process, with synthetic index entries and controlled exits; no GPU, compiler, game data or packages are needed. +""" +import contextlib +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) +import make_game # noqa: E402 + + +CHECKER = r''' +import json +import os +from pathlib import Path +import signal +import sys + +spirv, cache, *args = sys.argv[1:] +spirv, cache = Path(spirv), Path(cache) +config = json.loads((spirv / "control.json").read_text(encoding="utf-8")) +names = sorted(json.loads((spirv / "index.json").read_text(encoding="utf-8")), key=lambda n: n.encode("utf-8")) +def option(flag, default=None): + return args[args.index(flag) + 1] if flag in args else default +start = int(option("--start", 0)) +count = int(option("--count", len(names))) +selected = names[start:start + count] +skip_path = option("--skip-file") +skipped = Path(skip_path).read_text(encoding="utf-8").splitlines() if skip_path else [] +active = [name for name in selected if name not in skipped] +inflight = option("--inflight-file") +def record(event): + with (spirv / "calls.jsonl").open("a", encoding="utf-8", newline="\n") as f: + f.write(json.dumps(dict(event=event, pid=os.getpid(), selected=selected, active=active, args=args)) + "\n") +record("started") +if config.get("setup_error") or config.get("probe_setup_error") and count == 1 and option("--jobs") == "1": + print("no Vulkan physical devices found", file=sys.stderr) + sys.exit(config.get("setup_exit", 2)) +if config.get("interrupt") or config.get("interrupt_probe") and count == 1 and option("--jobs") == "1": + if os.name == "nt": + import ctypes + ctypes.windll.kernel32.ExitProcess(0xC000013A) + else: + os.kill(os.getpid(), signal.SIGTERM) +if config.get("crash_before_work"): + sys.exit(70) +crasher = config.get("crasher") +if crasher in active or len(active) > config.get("max_batch", 1000000): + if inflight: + suspects = [crasher] if crasher in active else active[:config.get("suspects", 2)] + Path(inflight).write_text("".join(n + "\tpipeline\n" for n in suspects), encoding="utf-8", newline="\n") + sys.exit(70) +# This stand-in's cache contains completed names so the test can detect lost checkpoints and repeated work. +completed = json.loads(cache.read_text(encoding="utf-8")) if cache.exists() else [] +cache.write_text(json.dumps(completed + active), encoding="utf-8", newline="\n") +record("completed") +if inflight: + Path(inflight).write_text("", encoding="utf-8", newline="\n") +sys.exit(1 if skipped and set(selected).intersection(skipped) or config.get("invalid") in active else 0) +''' + + +class PipelineBatchesTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory(prefix="pipeline batches ") + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.work = self.root / "work" + self.spirv = self.work / "shaders" / "spirv" + self.spirv.mkdir(parents=True) + self.out = self.root / "out" + self.names = [f"m_{i:02d}" for i in range(7)] + self.write_index(self.names) + self.child = self.root / "checker.py" + self.child.write_text(CHECKER, encoding="utf-8", newline="\n") + self.commands = [] + + def write_index(self, names): + (self.spirv / "index.json").write_text(json.dumps({n: {} for n in reversed(names)}), + encoding="utf-8", newline="\n") + + def invoke(self, control=None, range_support=True): + (self.spirv / "control.json").write_text(json.dumps(control or {}), encoding="utf-8", newline="\n") + def run(args, hint="", check=True, **kwargs): + args = [str(a) for a in args] + self.commands.append(args) + done = subprocess.run([sys.executable, "-I", str(self.child), *args[1:]], + capture_output=True, text=True, timeout=15) + if check and done.returncode: + raise SystemExit(1) + return done.returncode + def supports(exe, *options): + return range_support or "--start" not in options + logs, err = [], io.StringIO() + # create=True keeps the regression runnable on the old implementation, which lacks this constant. + with mock.patch.object(make_game, "pipeline_check_exe", return_value="synthetic-checker"), \ + mock.patch.object(make_game, "checker_supports", side_effect=supports), \ + mock.patch.object(make_game, "PIPELINE_BATCH_SIZE", 3, create=True), \ + mock.patch.object(make_game, "run", side_effect=run), \ + mock.patch.object(make_game, "log", side_effect=logs.append), contextlib.redirect_stderr(err): + try: + make_game.pipelines(str(self.work), str(self.out), jobs=2) + except SystemExit as exc: + return exc.code, logs, err.getvalue() + return 0, logs, err.getvalue() + + def calls(self, event=None): + path = self.spirv / "calls.jsonl" + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] if path.exists() else [] + return [row for row in rows if event is None or row["event"] == event] + + def test_bounded_processes_cover_the_sorted_index_and_tail(self): + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + completed = self.calls("completed") + self.assertEqual([r["selected"] for r in completed], [self.names[:3], self.names[3:6], self.names[6:]]) + self.assertEqual(len({r["pid"] for r in completed}), 3) + self.assertEqual(json.loads((self.out / "pipeline_cache.bin").read_text(encoding="utf-8")), self.names) + self.assertTrue(all(r["args"][r["args"].index("--jobs") + 1] == "2" for r in completed)) + + def test_collective_memory_crash_splits_without_skipping_healthy_modules(self): + code, logs, err = self.invoke({"max_batch": 2}) + self.assertEqual(code, 0, err) + # Diagnostic one-module probes are also successful; the final bounded work must still cover every name. + checked = {n for row in self.calls("completed") for n in row["active"]} + self.assertEqual(checked, set(self.names)) + self.assertFalse((self.out / "pipeline_crashes.txt").exists()) + self.assertTrue(any("smaller" in line for line in logs), logs) + + def test_a_real_crasher_stays_failed_when_later_batches_pass(self): + code, _, err = self.invoke({"crasher": "m_01"}) + self.assertNotEqual(code, 0) + self.assertEqual((self.out / "pipeline_crashes.txt").read_text(encoding="utf-8"), "m_01\n") + self.assertIn("m_01", err) + checked = {n for row in self.calls("completed") for n in row["active"]} + self.assertEqual(checked, set(self.names) - {"m_01"}) + + def test_one_inflight_module_is_not_blacklisted_when_it_survives_alone(self): + self.write_index(self.names[:2]) # small corpora need the same protection as multi-batch runs + code, _, err = self.invoke({"max_batch": 1, "suspects": 1}) + self.assertEqual(code, 0, err) + self.assertFalse((self.out / "pipeline_crashes.txt").exists()) + self.assertEqual({n for row in self.calls("completed") for n in row["active"]}, set(self.names[:2])) + + def test_interrupting_a_diagnostic_probe_stops_before_more_batches(self): + code, _, _ = self.invoke({"max_batch": 2, "interrupt_probe": True}) + self.assertNotEqual(code, 0) + self.assertEqual(len(self.calls()), 2) # the failed batch and the interrupted diagnostic probe + self.assertFalse((self.out / "pipeline_crashes.txt").exists()) + + def test_a_validation_failure_does_not_hide_the_remaining_batches(self): + code, _, _ = self.invoke({"invalid": "m_01"}) + self.assertNotEqual(code, 0) + self.assertEqual([n for row in self.calls("completed") for n in row["active"]], self.names) + self.assertFalse((self.out / "pipeline_crashes.txt").exists()) + + def test_setup_errors_and_interrupts_stop_immediately(self): + for control in ({"setup_error": True}, {"interrupt": True}): + with self.subTest(control=control): + trace = self.spirv / "calls.jsonl" + if trace.exists(): + trace.unlink() + self.commands.clear() + code, _, _ = self.invoke(control) + self.assertNotEqual(code, 0) + self.assertEqual(len(self.calls()), 1) + + def test_native_setup_exit_one_stops_instead_of_checking_every_range(self): + code, _, _ = self.invoke({"setup_error": True, "setup_exit": 1}) + self.assertNotEqual(code, 0) + self.assertEqual(len(self.calls()), 1) + + def test_native_setup_exit_one_in_a_probe_stops_before_splitting(self): + code, _, _ = self.invoke({"max_batch": 2, "probe_setup_error": True, "setup_exit": 1}) + self.assertNotEqual(code, 0) + self.assertEqual(len(self.calls()), 2) + self.assertFalse((self.out / "pipeline_crashes.txt").exists()) + + def test_a_crash_before_work_cannot_retry_forever_or_claim_success(self): + code, _, err = self.invoke({"crash_before_work": True}) + self.assertNotEqual(code, 0) + self.assertLessEqual(len(self.calls()), 4) + self.assertTrue(err) + + def test_an_older_checker_gets_no_unsupported_range_arguments(self): + code, _, err = self.invoke(range_support=False) + self.assertEqual(code, 0, err) + self.assertEqual(len(self.commands), 1) + self.assertNotIn("--start", self.commands[0]) + self.assertNotIn("--count", self.commands[0]) + + def test_small_indices_keep_the_single_run(self): + self.write_index(self.names[:2]) + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(len(self.commands), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_make_game_pipeline_preflight.py b/tests/test_make_game_pipeline_preflight.py index f74c8da26..b3460f39c 100644 --- a/tests/test_make_game_pipeline_preflight.py +++ b/tests/test_make_game_pipeline_preflight.py @@ -38,7 +38,7 @@ class PreflightEnv: spirv = os.path.join(self.work, "shaders", "spirv") os.makedirs(spirv) with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f: - f.write("{}") + f.write('{"shader_0": {}}') # a finished translation is never empty def assert_preflight_fails(self, stages, match): err = io.StringIO() @@ -149,6 +149,14 @@ class LinuxPipelineCheckTest(PreflightEnv, unittest.TestCase): self.assert_preflight_fails(["shaders", "pipelines"], "delete runtime/build/linux") build.assert_called_once() + def test_missing_built_checker_does_not_initialize_asset_submodule(self): + with mock.patch.object(make_game, "dotnet_sdk_ok", return_value=True), \ + mock.patch.object(make_game, "build_pipeline_check") as build, \ + mock.patch.object(make_game, "ensure_submodule") as initialize: + self.assert_preflight_fails(["shaders", "assets", "pipelines"], "delete runtime/build/linux") + build.assert_called_once() + initialize.assert_not_called() + def test_without_cmake_nothing_is_built(self): with mock.patch("shutil.which", side_effect=lambda t: None if t == "cmake" else "/bin/tool"), \ mock.patch.object(make_game, "build_pipeline_check") as build: diff --git a/tests/test_make_game_pipelines.py b/tests/test_make_game_pipelines.py index a505f8dab..5f18db342 100644 --- a/tests/test_make_game_pipelines.py +++ b/tests/test_make_game_pipelines.py @@ -3,6 +3,7 @@ Standard library only; no GPU, no Vulkan SDK, no game data: the checker is mocked. """ import io +import json import os import sys import tempfile @@ -26,7 +27,7 @@ class PipelinesJobsTest(unittest.TestCase): os.makedirs(self.game) os.makedirs(spirv) with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f: - f.write("{}") + f.write('{"shader_0": {}}') # a finished translation is never empty def checker_args(self, call): with mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"), \ @@ -120,6 +121,10 @@ class PipelinesCrashRetryTest(unittest.TestCase): args = [str(a) for a in args] self.calls.append(args) code = script(args, len(self.calls)) + if code in (0, 1) and "--inflight-file" in args: + # A native checker that finishes its shader pass clears this report, even on validation failure. + with open(args[args.index("--inflight-file") + 1], "w", encoding="utf-8", newline="\n") as f: + f.write("") if check and code != 0: # as run() does raise SystemExit(1) return code @@ -142,8 +147,14 @@ class PipelinesCrashRetryTest(unittest.TestCase): def skipped(self, args): return args[args.index("--skip-file") + 1] if "--skip-file" in args else None + def is_probe(self, args): + return ("--count" in args and args[args.index("--count") + 1] == "1" + and "--jobs" in args and args[args.index("--jobs") + 1] == "1") + def test_a_named_module_is_skipped_and_the_rest_checked(self): def script(args, n): + if self.is_probe(args): + return ABORT # it must reproduce alone before it is added to the crash list if n == 1: self.inflight_is("b_mod") return ABORT @@ -155,7 +166,7 @@ class PipelinesCrashRetryTest(unittest.TestCase): with mock.patch("sys.stderr", err): failed, logs = self.stage(script) self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 2) + self.assertEqual(len(self.calls), 3) self.assertIn("--inflight-file", self.calls[0]) self.assertIsNone(self.skipped(self.calls[0])) self.assertTrue(any("b_mod took vk_pipeline_check down" in m and "0x80000003" in m for m in logs), logs) @@ -165,7 +176,7 @@ class PipelinesCrashRetryTest(unittest.TestCase): def test_several_in_flight_are_tried_alone_and_only_the_crasher_is_skipped(self): def script(args, n): - if "--start" in args: # crashes_alone: the index is name-sorted, so a_mod=0, b_mod=1, c_mod=2 + if self.is_probe(args): # the global index is name-sorted, so a_mod=0, b_mod=1, c_mod=2 self.assertEqual(args[args.index("--count") + 1], "1") return ABORT if args[args.index("--start") + 1] == "2" else 0 if n == 1: @@ -177,15 +188,15 @@ class PipelinesCrashRetryTest(unittest.TestCase): with mock.patch("sys.stderr", io.StringIO()): failed, _ = self.stage(script) self.assertIsNotNone(failed) - starts = [c[c.index("--start") + 1] for c in self.calls if "--start" in c] + starts = [c[c.index("--start") + 1] for c in self.calls if self.is_probe(c)] self.assertEqual(starts, ["0", "2"]) - def test_a_crash_with_nothing_in_flight_is_not_retried(self): + def test_a_crash_with_nothing_in_flight_stops_after_reaching_one_entry(self): err = io.StringIO() with mock.patch("sys.stderr", err): failed, _ = self.stage(lambda args, n: ABORT) self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 1) + self.assertEqual(len(self.calls), 2) # range of 3, then its first single-entry subrange self.assertIn("no module could be named", err.getvalue()) def test_ctrl_c_is_not_retried(self): @@ -198,15 +209,20 @@ class PipelinesCrashRetryTest(unittest.TestCase): self.assertEqual(len(self.calls), 1) def test_the_retries_stop(self): - names = iter([f"m{i}" for i in range(20)]) + all_names = [f"m{i}" for i in range(20)] + with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump({name: {} for name in all_names}, f) + names = iter(all_names) def script(args, n): + if self.is_probe(args): + return ABORT self.inflight_is(next(names)) return ABORT err = io.StringIO() with mock.patch("sys.stderr", err): failed, _ = self.stage(script) self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), make_game.PIPELINE_CRASH_RETRIES + 1) + self.assertEqual(len([c for c in self.calls if not self.is_probe(c)]), make_game.PIPELINE_CRASH_RETRIES + 1) self.assertIn("still crashed after", err.getvalue()) def test_a_clean_run_is_one_call_and_an_old_skip_list_is_dropped(self): diff --git a/tests/test_make_game_platform.py b/tests/test_make_game_platform.py index d657ea780..4fa02e14f 100644 --- a/tests/test_make_game_platform.py +++ b/tests/test_make_game_platform.py @@ -455,7 +455,8 @@ class PipelineCheckExeTest(unittest.TestCase): self.touch("vk_pipeline_check.exe") work = os.path.join(self.tmp.name, "work") os.makedirs(os.path.join(work, "shaders", "spirv")) - open(os.path.join(work, "shaders", "spirv", "index.json"), "w").close() + with open(os.path.join(work, "shaders", "spirv", "index.json"), "w") as f: + f.write('{"shader_0": {}}') # a finished translation is never empty out = os.path.join(self.tmp.name, "out") with mock.patch.object(make_game.os, "name", "posix"), \ mock.patch.object(make_game, "log"), \ diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py index 2bb6639f7..e2af10a53 100644 --- a/tests/test_make_game_preflight.py +++ b/tests/test_make_game_preflight.py @@ -12,6 +12,7 @@ import json import os import re import shutil +import subprocess import sys import tempfile import unittest @@ -649,7 +650,29 @@ class PreflightPrerequisiteTest(PreflightTestBase): with mock.patch.object(make_game, "ROOT", tmp), \ mock.patch("shutil.which", return_value=None): self.assert_fails(make_game.ensure_submodule, - match="third_party/rpf9-explorer is missing. Download the project with:") + match="git clone --recursive https://github.com/ItsNotRexed/Leonida") + + def test_ensure_submodule_zip_with_git_does_not_say_install_git(self): + with tempfile.TemporaryDirectory() as tmp: + not_a_repo = subprocess.CompletedProcess([], 128) + with mock.patch.object(make_game, "ROOT", tmp), \ + mock.patch("shutil.which", return_value="/usr/bin/git"), \ + mock.patch("subprocess.run", return_value=not_a_repo): + err = self.assert_fails(make_game.ensure_submodule, + match="git clone --recursive https://github.com/ItsNotRexed/Leonida") + self.assertNotIn("Install Git", err) + + def test_ensure_submodule_failed_fetch_in_clone_names_the_fetch(self): + with tempfile.TemporaryDirectory() as tmp: + results = [subprocess.CompletedProcess([], 0), subprocess.CompletedProcess([], 1)] + with mock.patch.object(make_game, "ROOT", tmp), \ + mock.patch("shutil.which", return_value="/usr/bin/git"), \ + mock.patch("subprocess.run", side_effect=results), \ + mock.patch.object(make_game, "log"): + err = self.assert_fails(make_game.ensure_submodule, + match="fetching third_party/rpf9-explorer failed") + self.assertIn("git submodule update --init --recursive", err) + self.assertNotIn("Download ZIP", err) class GameDiscoveryTest(unittest.TestCase): @@ -868,6 +891,23 @@ class PreflightExportedAssetsSpaceTest(PreflightTestBase): self.assertFalse(make_game.assets_exported(work)) self.assert_fails(self.run_preflight, work, free_gb=220, match="about 330 GB is needed") + def test_stopped_export_counts_what_it_already_wrote(self): + # Before: a stopped export that had written 277 GB still asked for all 300 GB free, so it couldn't resume. + with tempfile.TemporaryDirectory() as work: + with mock.patch("make_game.tree_bytes", return_value=277 * 2**30): + self.run_preflight(work, free_gb=60) # 30 for the shaders + 300 - 277 + self.assert_fails(self.run_preflight, work, free_gb=40, match="about 53 GB is needed") + + def test_tree_bytes_sums_files_under_the_folder(self): + with tempfile.TemporaryDirectory() as work: + sub = os.path.join(work, "a", "b") + os.makedirs(sub) + for p, n in ((os.path.join(work, "x"), 3), (os.path.join(sub, "y"), 5)): + with open(p, "wb") as f: + f.write(b"\0" * n) + self.assertEqual(make_game.tree_bytes(work), 8) + self.assertEqual(make_game.tree_bytes(os.path.join(work, "missing")), 0) + def test_marker_with_other_contents_does_not_count(self): for ogg, xma in (("", self.XMA), (self.OGG, "something else\n"), (self.XMA, self.OGG)): with self.subTest(ogg=ogg, xma=xma), tempfile.TemporaryDirectory() as work: diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py index 13322b89f..df7705363 100644 --- a/tests/test_make_game_translator_flags.py +++ b/tests/test_make_game_translator_flags.py @@ -90,6 +90,24 @@ class TranslateFallbacksTest(unittest.TestCase): self.assertEqual(len(again), 2, again) # the parts were translated with other flags +class FailedShardTest(unittest.TestCase): + def test_a_failed_shard_removes_the_previous_index(self): + with tempfile.TemporaryDirectory() as spirv: + index = os.path.join(spirv, "index.json") + with open(index, "w", encoding="utf-8") as f: + json.dump({"old": True}, f) + + class FailingProc: + def wait(self): + return 1 + + with mock.patch.object(make_game.subprocess, "Popen", lambda *a, **k: FailingProc()), mock.patch.object(make_game, "py"), mock.patch.object(make_game, "log", lambda *a: None), self.assertRaises(SystemExit) as cm: + make_game.translate("disasm", spirv, 2) + self.assertEqual(cm.exception.code, 1) + self.assertFalse(os.path.exists(index)) + self.assertTrue(os.path.exists(os.path.join(spirv, make_game.SHARD_PLAN))) + + class RecordedFlagsTest(unittest.TestCase): """shaders() records the flags in spirv/translator_flags.txt and re-translates when they change.""" @@ -159,7 +177,11 @@ class MainWiringTest(unittest.TestCase): """main() parses the fallback flags and hands the same tuple to preflight() and shaders().""" def run_main(self, *extra_argv, per_vertex=None, max_push_constants=None): - argv = ["make_game.py", "--stages", "shaders", *extra_argv] + # An empty --out: main() reads the flags an existing translation was made with, and the default folder + # is the user's own. + out = tempfile.TemporaryDirectory() + self.addCleanup(out.cleanup) + argv = ["make_game.py", "--stages", "shaders", "--out", out.name, *extra_argv] with mock.patch.object(sys, "argv", argv), \ mock.patch("make_game.below_normal"), \ mock.patch("make_game.choose_game", return_value=os.path.abspath("C:/dummy_game")), \ @@ -214,5 +236,91 @@ class MainWiringTest(unittest.TestCase): self.assertEqual(make_game.runtime_gpu_max_push_constants(), want) +class ProbeFailureKeepsAutomaticFlagsTest(RecordedFlagsTest): + """A GPU probe that can't tell must not change the flags a finished translation was made with: one failed or + timed-out probe used to translate the whole corpus without the automatic flags, and the next run that could + ask translated it a third time. This runs the real main() and shaders() on one work folder.""" + + AUTOMATIC = ("--f16-interp-fallback", "--pc-tail-ubo") + + def build(self, *extra_argv, per_vertex, max_push_constants): + """One `make_game.py --stages shaders` run: (the fallbacks of each translation it started, its log).""" + translations, lines = [], [] + + def fake_py(tool, *args): + if tool == "shader_carve.py": + self.touch(self.dxbc, "index.json") + elif tool == "fssm_unpack.py": + self.touch(self.dxbc, "fssm_index.json") + elif tool == "shader_disasm.py": + self.touch(self.dxbc, "disasm", "shader.s") + + def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): + translations.append(tuple(fallbacks)) + self.touch(spirv, "index.json") + + argv = ["make_game.py", "--stages", "shaders", "--out", os.path.join(self.work, "out"), + "--work", self.work, *extra_argv] + with mock.patch.object(sys, "argv", argv), \ + mock.patch("make_game.below_normal"), \ + mock.patch("make_game.choose_game", return_value=os.path.join(self.work, "game")), \ + mock.patch("make_game.check", return_value={"expected_exe": "game.exe"}), \ + mock.patch("make_game.wave64_settings", return_value=(False, True)), \ + mock.patch("make_game.runtime_gpu_per_vertex", return_value=per_vertex), \ + mock.patch("make_game.runtime_gpu_max_push_constants", return_value=max_push_constants), \ + mock.patch("make_game.preflight"), \ + mock.patch.object(make_game, "py", fake_py), \ + mock.patch.object(make_game, "need", lambda *a: None), \ + mock.patch.object(make_game, "translate", fake_translate), \ + mock.patch.object(make_game, "llvm_mc_signature", return_value="test llvm-mc 21"), \ + mock.patch.object(make_game, "log", lambda *a: lines.append(" ".join(map(str, a)))): + self.assertEqual(make_game.main(), 0) + return translations, "\n".join(lines) + + def recorded(self): + with open(os.path.join(self.spirv, "translator_flags.txt"), encoding="utf-8") as f: + return f.read().strip() + + def test_a_probe_that_cannot_tell_keeps_both_automatic_flags(self): + self.assertEqual(self.build(per_vertex=False, max_push_constants=128)[0], [self.AUTOMATIC]) + translations, log = self.build(per_vertex=None, max_push_constants=None) + self.assertEqual(translations, []) + self.assertEqual(self.recorded(), " ".join(self.AUTOMATIC)) + for flag in self.AUTOMATIC: # it says what it did, once per flag + self.assertIn(f"whether it needs {flag}; the shaders were translated with it and it stays on", log) + self.assertNotIn("translating again", log) + # The probe answers again: the same flags, so nothing is translated a third time. + self.assertEqual(self.build(per_vertex=False, max_push_constants=128)[0], []) + + def test_each_probe_is_kept_on_its_own(self): + self.build(per_vertex=False, max_push_constants=128) + self.assertEqual(self.build(per_vertex=None, max_push_constants=128)[0], []) + self.assertEqual(self.build(per_vertex=False, max_push_constants=None)[0], []) + self.assertEqual(self.recorded(), " ".join(self.AUTOMATIC)) + + def test_a_probe_that_answers_still_decides(self): + # Another GPU, or a driver that now takes PerVertexKHR inputs and 144 bytes: translating again is right. + self.build(per_vertex=False, max_push_constants=128) + translations, log = self.build(per_vertex=True, max_push_constants=256) + self.assertEqual(translations, [()]) + self.assertIn("the fallback flags are now none", log) + self.assertEqual(self.recorded(), "") + + def test_a_failed_probe_adds_no_flag_to_a_folder_translated_without_it(self): + self.assertEqual(self.build(per_vertex=True, max_push_constants=256)[0], [()]) + translations, log = self.build(per_vertex=None, max_push_constants=None) + self.assertEqual(translations, []) + self.assertNotIn("stays on", log) + # A first build with no probe answer and no folder: no automatic flag, as before. + self.assertEqual(make_game.recorded_fallback_flags(os.path.join(self.work, "elsewhere")), ()) + + def test_the_other_flags_are_not_kept_by_a_failed_probe(self): + # Only the two flags the probe decides are kept; one the user stops passing is dropped as before. + self.build("--no-float-controls", per_vertex=False, max_push_constants=256) + self.assertEqual(self.recorded(), "--no-float-controls --f16-interp-fallback") + translations, _ = self.build(per_vertex=None, max_push_constants=None) + self.assertEqual(translations, [("--f16-interp-fallback",)]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_mc_command.py b/tests/test_mc_command.py index f579e9dc5..7f908c0c5 100644 --- a/tests/test_mc_command.py +++ b/tests/test_mc_command.py @@ -6,7 +6,9 @@ Windows runs llvm-mc through WSL (the official Windows LLVM build has no AMDGPU python -I tests/test_mc_command.py """ +import json import os +import shlex import subprocess import sys import tempfile @@ -40,6 +42,26 @@ class SplitCommandTest(unittest.TestCase): want = ["/opt/llvm 21/bin/llvm-mc", "--version"] self.assertEqual(mc_command.split_command(raw), want) + def test_windows_backslashes_and_literal_quotes_round_trip(self): + argv = [r"C:\Program Files\LLVM\bin\llvm-mc.exe", "", 'label="wide value"', + "C:\\output folder\\", r"plain\path", 'a\\"b'] + with mock.patch.object(mc_command.os, "name", "nt"): + self.assertEqual(mc_command.split_command(subprocess.list2cmdline(argv)), argv) + self.assertEqual(mc_command.split_command('llvm-mc "a""b"'), ["llvm-mc", 'a"b']) + + def test_posix_keeps_quotes_that_are_part_of_an_argument(self): + argv = ["llvm-mc", '"literal quotes"', "", '--label="wide value"'] + with mock.patch.object(mc_command.os, "name", "posix"): + self.assertEqual(mc_command.split_command(shlex.join(argv)), argv) + + @unittest.skipUnless(os.name == "nt", "Windows command line and subprocess") + def test_windows_subprocess_receives_literal_quotes_and_a_trailing_backslash(self): + want = ['"keep these quotes"', "C:\\output folder\\", ""] + command = [sys.executable, "-c", "import json, sys; print(json.dumps(sys.argv[1:]))", *want] + args = mc_command.split_command(subprocess.list2cmdline(command)) + result = mc_command.run(args, capture_output=True, check=True, text=True) + self.assertEqual(json.loads(result.stdout), want) + def test_windows_quoted_option_value_keeps_spaces_and_backslashes(self) -> None: executable = r"C:\Program Files\LLVM\bin\llvm-mc.exe" output = r"C:\shader builds\listing.s" diff --git a/tests/test_meshlet_page.py b/tests/test_meshlet_page.py index dc0f06811..9f6a9e66e 100644 --- a/tests/test_meshlet_page.py +++ b/tests/test_meshlet_page.py @@ -144,18 +144,39 @@ class DrawBindingTests(unittest.TestCase): struct.pack_into("") - failures = (out / "failures.txt").read_text().splitlines() + failures = (out / "failures.txt").read_text(encoding="utf-8-sig").splitlines() self.assertEqual(len(failures), 3) self.assertTrue(failures[1].startswith(f"{archive_name}\\000000000008 pso : "), failures[1]) self.assertEqual(failures[2], f"{archive_name}\\000000000010 pso : synthetic parser failure") diff --git a/tests/test_missing_input_exit_codes.py b/tests/test_missing_input_exit_codes.py new file mode 100644 index 000000000..908445162 --- /dev/null +++ b/tests/test_missing_input_exit_codes.py @@ -0,0 +1,64 @@ +"""BUILD-1046: a missing input path is a usage error (exit 2), not a failed run (exit 1). + +Each tool is run with a nonexistent positional input. All of them build their inputs themselves in this test; +no game file or asset is used. `image_query_probe.py --help` is bounded so its argument parsing cannot grow the +hardware-oracle startup cost back in. +""" +import os +import subprocess +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +TOOLS = os.path.join(ROOT, "tools") + +MISSING_INPUT_TOOLS = ( + "analyze_4240_full", + "audio_config", + "bary_fallback_gs", + "content_definitions", + "cpu_ref", + "gamedata_maps", + "navmesh_index", + "pe_inspect", + "rtti_scan", + "shader_disasm", + "tile_probe", +) + +# One process per tool; a hung import is a failure, not an infinite test. +TIMEOUT = 120 + + +def run_tool(tool, *args, timeout=TIMEOUT): + return subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool + ".py"), *args], + capture_output=True, text=True, timeout=timeout, errors="replace") + + +class MissingInputExitCodeTests(unittest.TestCase): + def test_missing_input_is_exit_2_with_one_error_line(self): + missing = os.path.join(HERE, "no-such-input-for-build-1046") + self.assertFalse(os.path.exists(missing), "the fixture path must not exist") + for tool in MISSING_INPUT_TOOLS: + with self.subTest(tool=tool): + p = run_tool(tool, missing) + self.assertEqual(p.returncode, 2, p.stderr) + self.assertNotIn("Traceback", p.stderr) + lines = p.stderr.strip().splitlines() + self.assertEqual(len(lines), 1, p.stderr) + self.assertTrue(lines[0].strip()) + self.assertTrue(lines[0].startswith("ERROR:"), p.stderr) + self.assertIn(missing, p.stderr) + + +class ImageQueryProbeHelpTests(unittest.TestCase): + def test_help_returns_promptly_without_the_hardware_oracle(self): + p = run_tool("image_query_probe", "--help", timeout=2) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertIn("--self-test", p.stdout) + self.assertNotIn("Traceback", p.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mission_tables.py b/tests/test_mission_tables.py index 17cbcd69e..43879eff1 100644 --- a/tests/test_mission_tables.py +++ b/tests/test_mission_tables.py @@ -205,6 +205,41 @@ class TestElement(unittest.TestCase): self.assertEqual(result["entities"], 1) self.assertEqual(result["entity_list"][0]["extra"], 0xFEEDFACE) + def test_multi_slot_record_with_invalid_first_slot_resolves_later_slots(self): + broken = bytearray(good_element(archetype=0xDEADBEEF)) + struct.pack_into("I", blob, 4, 16) + blob[16:20] = b"LGID" + struct.pack_into(">I", blob, 20, 8 + len(section_body)) + blob[24:] = section_body + result = M.parse_blob(bytes(blob), "small-pre.psin") + self.assertEqual(result["scan_bytes"], 16) + self.assertEqual(result["records"], 0) + self.assertEqual(result["entities"], 0) + def test_offset_outside_the_file_is_a_record_but_not_an_entity(self): blob = blob_with( [(0x100, record(0x11111111, 7, 0x180, 1)), diff --git a/tests/test_native_tool_paths.py b/tests/test_native_tool_paths.py new file mode 100644 index 000000000..9fc90d10f --- /dev/null +++ b/tests/test_native_tool_paths.py @@ -0,0 +1,134 @@ +"""Folders outside the ANSI code page reach the native tools in a form they can open. + + python -I tests/test_native_tool_paths.py + +On Windows, spirv-as, spirv-val and the GPU test programs read their command line in the ANSI code page, so a folder +name with a character outside it (a Cyrillic or CJK user name, as under %TEMP%) reached them as '?'. Every shader then +failed with "file does not exist". The folders here use a private-use character, which no ANSI code page maps. +tools/rdna2spirv.py's assemble_spirv now runs the tools in the output folder with relative names; run_gpu_tests.py +uses the work folder's 8.3 short name, or stops with one error line when there is none. Standard library only; no +game files. +""" +import io +import os +import shutil +import sys +import tempfile +import unittest +from unittest.mock import patch + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +sys.path.insert(0, os.path.join(ROOT, "scripts")) + +import rdna2spirv # noqa: E402 +import run_gpu_tests # noqa: E402 + +MARK = "\ue9c3" +MINIMAL_CS = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize 1 1 1 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%main = OpFunction %void None %fn +%entry = OpLabel +OpReturn +OpFunctionEnd +""" + + +@unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val") +class AssembleSpirv(unittest.TestCase): + def assemble(self, asm_dir, out_dir): + sa = os.path.join(asm_dir, "cs_min.spvasm") + sv = os.path.join(out_dir, "cs_min.spv") + with open(sa, "w", encoding="utf-8", newline="\n") as f: + f.write(MINIMAL_CS) + result = rdna2spirv.assemble_spirv(sa, sv) + self.assertEqual(result.returncode, 0, result.stderr + result.stdout) + with open(sv, "rb") as f: + self.assertEqual(f.read(4), b"\x03\x02\x23\x07") # the SPIR-V magic, little-endian + self.assertEqual([n for n in os.listdir(out_dir or ".") if n.endswith(".tmp")], [], "the staging file is removed") + + def test_a_folder_outside_the_code_page(self): + # Before: spirv-as got '...\shaders-?\cs_min.spvasm' and failed with "file does not exist". + with tempfile.TemporaryDirectory() as tmp: + out = os.path.join(tmp, "shaders-" + MARK) + os.makedirs(out) + self.assemble(out, out) + + def test_the_spvasm_in_another_folder(self): + with tempfile.TemporaryDirectory() as tmp: + asm_dir, out = os.path.join(tmp, "asm-" + MARK), os.path.join(tmp, "spv") + os.makedirs(asm_dir) + os.makedirs(out) + self.assemble(asm_dir, out) + + def test_a_relative_output_path(self): + with tempfile.TemporaryDirectory() as tmp: + cwd = os.getcwd() + os.chdir(tmp) + try: + self.assemble("", "") + finally: + os.chdir(cwd) + + +class NativeFolder(unittest.TestCase): + def test_a_path_the_code_page_holds_is_kept(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(run_gpu_tests.native_folder(tmp, ansi="utf-8"), tmp) + + def test_other_systems_keep_the_path(self): + with patch.object(run_gpu_tests.os, "name", "posix"): + self.assertEqual(run_gpu_tests.native_folder("/tmp/work-" + MARK), "/tmp/work-" + MARK) + + @unittest.skipUnless(os.name == "nt", "8.3 short names are a Windows thing") + def test_a_folder_outside_the_code_page_gets_its_short_name_or_none(self): + with tempfile.TemporaryDirectory() as tmp: + work = os.path.join(tmp, "leonida_gpu_work_" + MARK) + os.makedirs(work) + native = run_gpu_tests.native_folder(work) + if native is None: + self.skipTest("this volume keeps no 8.3 short names (the error path is tested below)") + native.encode("mbcs") # raises if the short name still has a character the code page lacks + self.assertNotIn(MARK, native) + self.assertTrue(os.path.samefile(native, work)) + + +class MainUsesTheNativeFolder(unittest.TestCase): + def run_main(self, native): + with tempfile.TemporaryDirectory() as tmp: + build = os.path.join(tmp, "build") + os.makedirs(build) + ext = ".exe" if os.name == "nt" else "" + for name in {*run_gpu_tests.TEST_PROGRAMS, *run_gpu_tests.REQUIRED_TEST_PROGRAMS}: + open(os.path.join(build, name + ext), "wb").close() + work = os.path.join(tmp, "work-" + MARK) + seen = [] + err = io.StringIO() + argv = ["run_gpu_tests.py", "--build", build, "--work", work] + with patch.object(sys, "argv", argv), patch("sys.stderr", err), patch("sys.stdout", io.StringIO()), \ + patch.object(run_gpu_tests, "native_folder", return_value=native), \ + patch.object(run_gpu_tests, "run_suite", side_effect=lambda a, w: seen.append(w) or 0): + code = run_gpu_tests.main() + self.assertTrue(os.path.isdir(work), "--work is created before its native spelling is asked for") + return code, seen, err.getvalue() + + def test_the_suite_runs_in_the_native_spelling(self): + code, seen, _ = self.run_main(r"C:\WORK-1~1") + self.assertEqual(code, 0) + self.assertEqual(seen, [r"C:\WORK-1~1"]) + + def test_no_native_spelling_is_one_error_line(self): + code, seen, err = self.run_main(None) + self.assertEqual(code, 2) + self.assertEqual(seen, [], "nothing runs") + self.assertIn("outside this PC's ANSI code page", err) + self.assertIn("--work", err) + self.assertEqual(len(err.strip().splitlines()), 1) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_navmesh_decode.py b/tests/test_navmesh_decode.py index 28df9a6fa..2ad3b48a6 100644 --- a/tests/test_navmesh_decode.py +++ b/tests/test_navmesh_decode.py @@ -179,7 +179,7 @@ def build_navmesh( poly_sizes=(3, 4), n_links=2, n_link_idx=3, - n_volumes=1, + n_volumes=2, water_poly=False, tiny_bm_cont=False, corrupt_checksum=False, @@ -243,6 +243,19 @@ def build_navmesh( if n_volumes and not corrupt_null_vol: vo = alloc(96 * n_volumes) struct.pack_into("> 3 for k in keys if k != 1} + words = [0x0000FF00 if k in parents else 0x00020001 for k in keys] table_end = 0x60 + nd.GRID_GROUP * groups bm_off = (table_end + 15) & ~15 payload_off = (bm_off + 32 + 15) & ~15 @@ -351,11 +375,11 @@ def build_grid( base = 0x60 + nd.GRID_GROUP * g buf[base + slot] = (k * 7) & 0x7F val = 0 if (dup_value and k == 1) else k - struct.pack_into(" 8 -> 64 -> 512 (depths 0..3), plus leaves 9, 10, 65. + keys = [1, 8, 64, 512, 9, 10, 65] + words = [0xFF00, 0xFF00, 0xFF00, 0x00007803, 0xFF00, 0x00060F01, 0x00000002] + good = build_grid(entries=7, keys=keys, words=words) + bad = [ + build_grid(entries=3, keys=[8, 9, 10]), # no root + build_grid(entries=3, keys=[1, 8, 72]), # 72 >> 3 == 9 is absent + build_grid(entries=3, keys=[1, 8, 16]), # 16 has its top bit at 4, not 3 or 6 + build_grid(entries=3, keys=[1, 0, 8]), # 0 is not a key + build_grid(entries=3, keys=[1, 8, 8]), # two slots share key 8 + build_grid(entries=3, keys=[1, 8, 9], words=[0x01, 0x01, 0x01]), # inner root without 0xff00 + build_grid(entries=3, keys=[1, 8, 64], words=[0xFF00, 0x01, 0x01]), # inner 8 without 0xff00 + ] + # 17 keys over two groups: 8 sits in slot 15 of group 0 and 9 in group 1, both parents of other keys. + two_groups = build_grid(groups=2, entries=17, keys=[1] + list(range(64, 78)) + [8, 9]) + # Payload pointer past the end: the table is accepted but the words are not read. + oob = bytearray(build_grid(entries=3)[0]) + struct.pack_into(" poly 2 + (100, 200, 300, 400, 500, 600, 0, 2, sector, sector, 0x0200, 0x0050, 63, 0), + # link 1: cross-tile poly 0 (s0=sector) -> poly 999 (s1=sector+1) + (110, 210, 310, 410, 510, 610, 0, 999, sector, sector + 1, 0x0400, 0x0040, 127, 0), + # link 2: cross-tile poly 888 (s0=sector-1) -> poly 2 (s1=sector) + (120, 220, 320, 420, 520, 620, 888, 2, sector - 1, sector, 0x0000, 0x0030, 254, 0), + ] + if link_indices is None: + # poly 0 gets links [0, 1], poly 1 gets [], poly 2 gets [2] + link_indices = [0, 1, 2] + + d4 = len(links) + d8 = len(link_indices) + sx, sy = sector & 0x1FF, sector >> 9 + x0, y0, dx, dy, dz = (sx - 256) * 128.0, (sy - 256) * 128.0, 128.0, 128.0, 16.0 + + struct.pack_into(" len(buf): + buf.extend(bytes(cur - len(buf))) + return off + + if has_links: + la = alloc(32 * d4) + lb = alloc(2 * d8) + for i, lk in enumerate(links): + rec = list(lk) + if i == d4 - 1: + if corrupt_link_heading: + rec[12] = 256 + if corrupt_link_pad: + rec[13] = 1 + if corrupt_link_sector: + rec[8] = sector + 5 + rec[9] = sector + 6 + if corrupt_link_poly_oob: + rec[8] = sector + rec[6] = n_polys + struct.pack_into("<6HHHIIHHHH", buf, la + 32 * i, *rec) + for k, li in enumerate(link_indices): + val = 1 if (corrupt_b0_endpoint and k == d8 - 1) else li + struct.pack_into(" 0: + lcnt -= 1 + hi9 = poly_hi9_flags[i] if i < len(poly_hi9_flags) else 0 + w20 = (hi9 << 23) | ((lstart & 0x1FFFF) << 6) | (lcnt & 0x3F) + struct.pack_into(" 0 and j > 0 and i + j < 1 + cov = {(x, y) for y in range(Hh) for x in range(W) if inside((x, y))} + quads = sorted({(x // 2, y // 2) for x, y in cov}, key=lambda q: (q[1], q[0])) + if empty_quads: + quads.insert(0, (99, 99)) # a quad with no covered pixel takes lanes 0..3 + lane, wave_of = {}, {} + for n, q in enumerate(quads): + for k in range(4): + p = (2 * q[0] + (k & 1), 2 * q[1] + (k >> 1)) + if swap_lanes: + k ^= 1 + lane[p], wave_of[p] = (n % 16) * 4 + k, n // 16 + entry, wqm = {}, {} + for p in cov: + w = wave_of[p] + entry[w] = entry.get(w, 0) | 1 << lane[p] + if helpers_at_entry: + for k in (1, 2, 3): + entry[w] |= 1 << lane[H.neighbour(p, k)] + for p in lane: + wqm[wave_of[p]] = wqm.get(wave_of[p], 0) | 1 << lane[p] + res = {n: {(x, y): H.CLEAR for y in range(Hh) for x in range(W)} for n in H.PROGRAMS} + for p in cov: + e, q = entry[wave_of[p]], wqm[wave_of[p]] + x, y = H.ndc(p) + res["masks"][p] = (lane[p], e & 0xFFFFFFFF, e >> 32, q & 0xFFFFFFFF) + res["self"][p] = (lane[p], q >> 32, u32(x), u32(y)) + nb = {k: H.ndc(H.neighbour(p, k)) for k in (1, 2, 3)} + if flat_helpers: + nb = {k: (x, y) if H.neighbour(p, k) not in cov else v for k, v in nb.items()} + res["nb12"][p] = (u32(nb[1][0]), u32(nb[1][1]), u32(nb[2][0]), u32(nb[2][1])) + res["nb3"][p] = (u32(nb[3][0]), u32(nb[3][1])) * 2 + i, j = H.bary(H.neighbour(p, 1)) + res["nowqm_ij"][p] = (u32(i), u32(j), 0xDEADBEEF, H.SENTINEL) + res["nowqm_masks"][p] = (lane[p], e & 0xFFFFFFFF, e >> 32, e & 0xFFFFFFFF) + res["helper_export"][p] = (0x3F800000,) * 4 + if helper_export: + outside = next(p for p in lane if p not in cov) + res["helper_export"][outside] = (0x3F800000,) * 4 + return res + + +class Analysis(unittest.TestCase): + def failing(self, res): + return [n for n, ok, _d in H.analyze(res) if not ok] + + def test_the_measured_behaviour_passes_every_check(self): + checks = H.analyze(model()) + self.assertEqual([n for n, ok, _d in checks if not ok], []) + self.assertEqual(len(checks), 10) + + def test_each_rule_broken_fails_its_check(self): + for flag, check in (("helpers_at_entry", "entry EXEC"), ("empty_quads", "quads packed"), + ("swap_lanes", "lane % 4"), ("helper_export", "an exp"), + ("flat_helpers", "after s_wqm a helper")): + with self.subTest(flag=flag): + failing = self.failing(model(**{flag: True})) + self.assertTrue(any(n.startswith(check) for n in failing), failing) + + def test_full_coverage_has_no_helpers_to_measure(self): + res = model() + for p in res["masks"]: + if res["masks"][p] == H.CLEAR: + for name in H.PROGRAMS: + res[name][p] = res[name][next(iter(q for q in res["masks"] if res["masks"][q] != H.CLEAR))] + self.assertIn("partial quads at the edge", self.failing(res)) + + def test_geometry(self): + self.assertEqual(H.bary((0, 0)), H.bary((0, 0))) + i, j = H.bary((0, 0)) + self.assertTrue(0 < i < 0.1 and 0 < j < 0.1) + self.assertEqual([H.neighbour((4, 6), k) for k in (1, 2, 3)], [(5, 6), (4, 7), (5, 7)]) + self.assertEqual(H.ndc((0, 0)), (-1 + 1 / 16, -1 + 1 / 16)) + + +class Programs(unittest.TestCase): + def test_every_program_ends_and_exports_once(self): + for name in H.PROGRAMS: + with self.subTest(name=name): + lines = H.program(name) + self.assertEqual(lines[-1], "s_endpgm") + self.assertEqual(sum(ln.startswith("exp ") for ln in lines), 1) + self.assertEqual("s_wqm_b64 exec, exec" in lines, H.PROGRAMS[name][0]) + + +@unittest.skipUnless(os.environ.get("LEONIDA_PS_ORACLE_BUILD"), "set LEONIDA_PS_ORACLE_BUILD to a runtime build " + "and select an AMD GPU (LEONIDA_VK_DEVICE) to measure helper lanes on hardware") +class OnHardware(unittest.TestCase): + def test_helper_lanes_at_a_triangle_edge(self): + try: + _device, res = H.measure(os.environ["LEONIDA_PS_ORACLE_BUILD"]) + except H.ps_oracle.Unavailable as e: + self.skipTest(str(e)) + self.assertEqual([(n, d) for n, ok, d in H.analyze(res) if not ok], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_psin_data.py b/tests/test_psin_data.py index 7408e71e2..ca052fe06 100644 --- a/tests/test_psin_data.py +++ b/tests/test_psin_data.py @@ -168,6 +168,17 @@ class TestWalk(unittest.TestCase): self.assertEqual(self.tree[f"{joaat('short'):08x}"], "abc") self.assertEqual(self.stats["short strings in place"], 1) + def test_struct_pointer_past_block_end_is_rejected(self): + # ItemThing is 8 bytes; pointing at offset 6 of an 8-byte block leaves only 2 bytes inside the block. + root = bytearray(0x90) + struct.pack_into(" `rdna2_decode.disasm_bytes` -> `rdna2spirv.translate` + -> `spirv_mini_interp` value verification. + - Optional full-suite parity test against `llvm-mc` across all `runtime/test/shaders/*.asm` when + `LLVM_MC` (or `llvm-mc` on PATH) is available. +""" +from __future__ import annotations + +import glob +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +TOOLS = os.path.join(ROOT, "tools") +SEMANTIC = os.path.join(HERE, "semantic") + +sys.dont_write_bytecode = True +for p in (TOOLS, SEMANTIC): + if p not in sys.path: + sys.path.insert(0, p) + +import rdna2_decode # noqa: E402 +import rdna2spirv # noqa: E402 +import shader_disasm # noqa: E402 +import shader_ir # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + + +def words(*ws: int) -> bytes: + return b"".join(struct.pack(" sgpr 7, src0=256+2) + w_rfl = (0x3F << 25) | (7 << 17) | (2 << 9) | (256 + 2) + # v_fmaak_f32 v8, v2, v3, 0x3f800000 (VOP2 op=0x2d, vdst=8, vsrc1=3, src0=256+2) + w_fmaak = (0x2D << 25) | (8 << 17) | (3 << 9) | (256 + 2) + # v_cmp_eq_u32_e32 vcc_lo, 0, v2 (VOPC op=0xc2, vsrc1=2, src0=128) + w_cmp = (0x3E << 25) | (0xC2 << 17) | (2 << 9) | 128 + code = words(w_mov, w_rfl, w_fmaak, 0x3F800000, w_cmp) + info = rdna2_decode.decode_bytes(code, wave32=True) + self.assertEqual(info["invalid"], 0) + self.assertEqual([i["op"] for i in info["insns"]], + ["v_mov_b32_e32", "v_readfirstlane_b32", "v_fmaak_f32", "v_cmp_eq_u32_e32"]) + self.assertEqual(info["insns"][0]["args"][1]["v"], 1.0) + self.assertEqual(info["insns"][1]["args"][0]["k"], "sgpr") + self.assertEqual(info["insns"][1]["args"][0]["r"], 7) + self.assertEqual(info["insns"][2]["args"][3], {"k": "imm", "v": 0x3F800000}) + self.assertEqual(info["insns"][3]["args"][0]["t"], "vcc_lo") + # Wave64 uses `vcc` instead of `vcc_lo`. + info64 = rdna2_decode.decode_bytes(words(w_cmp), wave32=False) + self.assertEqual(info64["insns"][0]["args"][0]["t"], "vcc") + + def test_vop3p_dot4_i8_with_opsel_that_llvm_mc_rejects(self): + # Raw RDNA2 hardware-measured word from docs/fspx.md & tests/semantic/test_alu_dot4_i8.py: + # 0xCC165008 0x0C0E0501 = v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1] + code = words(0xCC165008, 0x0C0E0501) + info = rdna2_decode.decode_bytes(code) + self.assertEqual(info["invalid"], 0) + ins = info["insns"][0] + self.assertEqual(ins["op"], "v_dot4_i32_i8") + self.assertEqual([a["r"] for a in ins["args"]], [8, 1, 2, 3]) + self.assertEqual(ins["mods"], ["op_sel:[0,1,0]", "op_sel_hi:[1,0,1]"]) + # Formatting + shader_ir re-parse round-trips identically. + line = rdna2_decode.format_insn(ins) + reparsed = shader_ir.parse_line(line) + self.assertEqual(reparsed["op"], ins["op"]) + self.assertEqual(reparsed["mods"], ins["mods"]) + + def test_smem_vcc_tuple_and_offsets(self): + # s_buffer_load_dwordx8 [s100..s105,vcc_lo,vcc_hi], s[0:3], null (SMEM op=0x0b, sdata=100, sbase=0, soff=125) + w0 = (0x3D << 26) | (0x0B << 18) | (100 << 6) | 0 + w1 = (125 << 25) + info = rdna2_decode.decode_bytes(words(w0, w1)) + self.assertEqual(info["invalid"], 0) + ins = info["insns"][0] + self.assertEqual(ins["op"], "s_buffer_load_dwordx8") + self.assertEqual(ins["args"][0], { + "k": "slist", "r": [100, 101, 102, 103, 104, 105, "vcc_lo", "vcc_hi"], "n": 8, + }) + self.assertEqual(ins["args"][2], {"k": "special", "t": "null", "neg": False, "abs": False}) + + def test_mubuf_mtbuf_mimg_global_ds_exp_vintrp(self): + # MUBUF: buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen (encoding verified against llvm-mc) + b_mubuf = bytes([0x00, 0x10, 0x0C, 0xE2, 0x05, 0x08, 0x01, 0x80]) + # MIMG BVH: image_bvh_intersect_ray v[20:23], [v2..v12], s[4:7] + b_bvh = bytes([0x07, 0x9F, 0x98, 0xF1, 0x02, 0x14, 0x01, 0x00, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x00, 0x00]) + # EXP: exp mrt0 v0, v1, v2, v3 done vm + w_exp0 = (0x3E << 26) | (1 << 12) | (1 << 11) | (0 << 4) | 0xF + w_exp1 = 0 | (1 << 8) | (2 << 16) | (3 << 24) + # VINTRP: v_interp_p1_f32 v2, v0, attr1.y (op=0, vdst=2, attr=1, chan=1, vsrc=0) + w_vint = (0x32 << 26) | (2 << 18) | (0 << 16) | (1 << 10) | (1 << 8) | 0 + # GLOBAL: global_store_dword v[4:5], v1, off offset:-4 (seg=2, op=0x1c, saddr=125) + w_glb0 = (0x37 << 26) | (0x1C << 18) | (2 << 14) | (0xFFC) + w_glb1 = (125 << 16) | (1 << 8) | 4 + code = b_mubuf + b_bvh + words(w_exp0, w_exp1, w_vint, w_glb0, w_glb1) + info = rdna2_decode.decode_bytes(code) + self.assertEqual(info["invalid"], 0) + self.assertEqual([i["op"] for i in info["insns"]], [ + "buffer_load_format_d16_xyzw", + "image_bvh_intersect_ray", + "exp", + "v_interp_p1_f32", + "global_store_dword", + ]) + self.assertEqual(info["insns"][1]["args"][1], {"k": "vlist", "r": list(range(2, 13))}) + self.assertEqual(info["insns"][1]["mods"], []) + self.assertEqual(info["insns"][2]["mods"], ["done", "vm"]) + self.assertEqual(info["insns"][3]["args"][2], {"k": "attr", "a": 1, "c": 1}) + self.assertEqual(info["insns"][4]["args"][2]["t"], "off") + self.assertEqual(info["insns"][4]["mods"], ["offset:-4"]) + + def test_roundtrip_binary_to_spirv_and_interpreter(self): + # Synthetic pixel shader binary: v_mov_b32 v0, 1.0; v_add_f32 v1, v0, 2.0; exp mrt0 v0, v1, v0, v1 done vm; s_endpgm + w_mov = (0x3F << 25) | (0 << 17) | (1 << 9) | 242 # v0 = 1.0 + w_add = (0x03 << 25) | (1 << 17) | (0 << 9) | 244 # v1 = 2.0 + v0 = 3.0 + w_exp0 = (0x3E << 26) | (1 << 12) | (1 << 11) | 0xF + w_exp1 = 0 | (1 << 8) | (0 << 16) | (1 << 24) + w_end = 0xBF810000 + code = words(w_mov, w_add, w_exp0, w_exp1, w_end) + + asm, bad, err = shader_disasm.disasm(code, "gfx1013", backend="python") + self.assertEqual(bad, 0) + self.assertEqual(err, "") + with tempfile.TemporaryDirectory() as tmp: + disasm_dir = os.path.join(tmp, "disasm") + os.mkdir(disasm_dir) + with open(os.path.join(tmp, "ps_dec.dxbc"), "wb") as f: + f.write(b"DXBC" + bytes(28)) + src = os.path.join(disasm_dir, "ps_dec.s") + with open(src, "w", encoding="utf-8") as f: + f.write("; ps_dec code 0x0..0x14 (python), gfx1013, 0 invalid words\n" + asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(src) + out = si.run_fragment(spv)["%out_mrt0"] + self.assertEqual(list(out), [0x3F800000, 0x40400000, 0x3F800000, 0x40400000]) + + def test_parity_with_llvm_mc_on_shader_fixtures(self): + mc = os.environ.get("LLVM_MC") or shutil.which("llvm-mc") or shutil.which("llvm-mc-18") + if not mc: + self.skipTest("llvm-mc not available") + asms = sorted(glob.glob(os.path.join(ROOT, "runtime", "test", "shaders", "*.asm"))) + self.assertGreater(len(asms), 50) + + def norm_op(op): + for suf in ("_e32", "_e64", "_sdwa", "_dpp"): + if op.endswith(suf): + op = op[:-len(suf)] + return op + + def norm_arg(a, op=""): + k = a["k"] + if k in ("vgpr", "sgpr"): + return (k, a["r"], a.get("n", 1), bool(a.get("neg")), bool(a.get("abs")), bool(a.get("sext"))) + if k == "imm": + # LLVM 18 disassembles SOPP branch offsets unsigned (0xfff0), LLVM 21/22 signed (-16). + mask = 0xFFFF if op in rdna2_decode._SOPP_BRANCHES else 0xFFFFFFFF + return ("imm", a["v"] & mask, bool(a.get("neg")), bool(a.get("abs"))) + if k == "fimm": + return ("fimm", round(a["v"], 6), bool(a.get("neg")), bool(a.get("abs"))) + if k in ("vlist", "slist"): + return (k, tuple(a["r"])) + if k == "attr": + return ("attr", a["a"], a["c"]) + return (k, a.get("t", ""), bool(a.get("neg")), bool(a.get("abs"))) + + checked = 0 + for path in asms: + with open(path, encoding="utf-8") as f: + txt = f.read() + m = re.search(r"^;\s*mattr:\s*(\S+)", txt, re.M) + mattr = m.group(1) if m else "" + wave32 = "-wavefrontsize32" not in mattr and "+wavefrontsize64" not in mattr + cmd = [mc, "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] + if mattr: + cmd.append("-mattr=" + mattr) + if os.path.basename(path) == "vs_clip.asm": + cmd.append("-defsym=PARAM_SLOT=1") + r = subprocess.run(cmd, input=txt, text=True, capture_output=True) + if r.returncode != 0 or "error:" in r.stderr: + continue + raw = bytearray() + for ln in r.stdout.splitlines(): + if "; encoding:" not in ln or ln.lstrip().startswith("."): + continue + ins = shader_ir.parse_line(ln) + if ins and ins["enc"]: + raw.extend(bytes.fromhex(ins["enc"])) + dcmd = [mc, "-disassemble", "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] + if mattr: + dcmd.append("-mattr=" + mattr) + dr = subprocess.run(dcmd, input=" ".join(f"0x{b:02x}" for b in raw), text=True, capture_output=True) + llvm_insns = [] + pc = 0 + for ln in dr.stdout.splitlines(): + if "; encoding:" not in ln or ln.lstrip().startswith("."): + continue + ins = shader_ir.parse_line(ln) + if ins and ins["enc"]: + ins["pc"] = pc + pc += len(ins["enc"]) // 2 + llvm_insns.append(ins) + dec = rdna2_decode.decode_bytes(bytes(raw), wave32=wave32) + self.assertEqual(dec["invalid"], 0, path) + self.assertEqual(len(dec["insns"]), len(llvm_insns), path) + for li, di in zip(llvm_insns, dec["insns"]): + self.assertEqual(di["enc"], li["enc"], path) + self.assertEqual(norm_op(di["op"]), norm_op(li["op"]), path) + self.assertEqual([norm_arg(x, di["op"]) for x in di["args"]], + [norm_arg(x, li["op"]) for x in li["args"]], + f"{path}: {li['op']}") + self.assertEqual(sorted(di["mods"]), sorted(li["mods"]), f"{path}: {li['op']}") + checked += 1 + self.assertGreater(checked, 5000) + + def test_sdwa_inline_constants_and_sgpr(self): + # Exact encodings from runtime/test/shaders/ps_sdwa_f16_const.asm: + # 1) v_add_f16_sdwa v2, 1.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0 + # 2) v_mul_f16_sdwa v3, 2.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_1 src1_sel:WORD_1 + # 3) v_add_f16_sdwa v4, s8, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0 + # 4) v_cvt_f16_u16_sdwa v5, 1.0 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 (VOP1 opc 0x50) + # 5) v_cmp_eq_u32_sdwa vcc_lo, 5, -1 src0_sel:WORD_0 src1_sel:WORD_0 (VOPC opc 0xc2, s0=133, s1=193) + raw = bytes([ + 0xF9, 0x02, 0x04, 0x64, 0xF2, 0x14, 0x85, 0x04, + 0xF9, 0x02, 0x06, 0x6A, 0xF4, 0x14, 0x81, 0x05, + 0xF9, 0x02, 0x08, 0x64, 0x08, 0x14, 0x85, 0x04, + 0xF9, 0xA0, 0x0A, 0x7E, 0xF2, 0x14, 0x85, 0x00, + 0xF9, 0x82, 0x85, 0x7D, 0x85, 0x00, 0x84, 0x84, + ]) + dec = rdna2_decode.decode_bytes(raw, wave32=True) + self.assertEqual(dec["invalid"], 0) + insns = dec["insns"] + self.assertEqual(len(insns), 5) + + self.assertEqual(insns[0]["op"], "v_add_f16_sdwa") + self.assertEqual(insns[0]["args"][1]["k"], "fimm") + self.assertEqual(insns[0]["args"][1]["v"], 1.0) + self.assertEqual(insns[0]["args"][2]["k"], "vgpr") + self.assertEqual(insns[0]["args"][2]["r"], 1) + + self.assertEqual(insns[1]["op"], "v_mul_f16_sdwa") + self.assertEqual(insns[1]["args"][1]["k"], "fimm") + self.assertEqual(insns[1]["args"][1]["v"], 2.0) + + self.assertEqual(insns[2]["op"], "v_add_f16_sdwa") + self.assertEqual(insns[2]["args"][1]["k"], "sgpr") + self.assertEqual(insns[2]["args"][1]["r"], 8) + + self.assertEqual(insns[3]["op"], "v_cvt_f16_u16_sdwa") + self.assertEqual(insns[3]["args"][1]["k"], "fimm") + self.assertEqual(insns[3]["args"][1]["v"], 1.0) + + self.assertEqual(insns[4]["op"], "v_cmp_eq_u32_sdwa") + self.assertEqual(insns[4]["args"][1]["k"], "imm") + self.assertEqual(insns[4]["args"][1]["v"], 5) + self.assertEqual(insns[4]["args"][2]["k"], "imm") + self.assertEqual(insns[4]["args"][2]["v"], -1) + + # Verify formatted text round-trips cleanly through shader_ir.parse_line. + text, bad = rdna2_decode.disasm_bytes(raw, wave32=True) + self.assertEqual(bad, 0) + parsed = [shader_ir.parse_line(ln) for ln in text.splitlines() if ln.strip()] + self.assertEqual(len(parsed), 5) + self.assertEqual(parsed[0]["args"][1]["k"], "fimm") + self.assertEqual(parsed[0]["args"][1]["v"], 1.0) + self.assertEqual(parsed[3]["args"][1]["k"], "fimm") + self.assertEqual(parsed[3]["args"][1]["v"], 1.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_rdna2spirv_cli.py b/tests/test_rdna2spirv_cli.py index 01f17ee1c..1d7f22f28 100644 --- a/tests/test_rdna2spirv_cli.py +++ b/tests/test_rdna2spirv_cli.py @@ -12,7 +12,7 @@ import subprocess import sys import tempfile import unittest -from contextlib import redirect_stdout +from contextlib import redirect_stderr, redirect_stdout from pathlib import Path from unittest import mock @@ -47,9 +47,9 @@ class SourceDiscovery(unittest.TestCase): def spirv_tool(cmd, **kwargs): tool = cmd[0] if tool == "spirv-as": - Path(cmd[3]).write_bytes(b"new module") + Path(kwargs.get("cwd", ""), cmd[3]).write_bytes(b"new module") elif tool == "spirv-val": - self.assertEqual(Path(cmd[-1]).read_bytes(), b"new module") + self.assertEqual(Path(kwargs.get("cwd", ""), cmd[-1]).read_bytes(), b"new module") else: self.fail(f"unexpected tool: {tool}") return subprocess.CompletedProcess(cmd, 0, "", "") @@ -248,6 +248,54 @@ class OutputFolderValidation(unittest.TestCase): self.assertEqual(target.read_text(encoding="utf-8"), "keep") +class OutputInsideInput(unittest.TestCase): + """--out equal to the input folder, or inside it, is refused before anything is written (BUILD-1044).""" + + def setUp(self): + self.tmp = Path(self.enterContext(tempfile.TemporaryDirectory())) + self.src = self.tmp / "disasm" + self.src.mkdir() + (self.src / "ps_x.s").write_text("\ts_endpgm\n", encoding="utf-8") + (self.tmp / "ps_x.dxbc").write_bytes(b"DXBC" + bytes(28)) + + def run_tool(self, out): + return subprocess.run([sys.executable, "-I", TOOL, str(self.src), "--out", os.fspath(out)], + capture_output=True, text=True, timeout=120) + + def assert_refused(self, out): + p = self.run_tool(out) + self.assertEqual(p.returncode, 2, p.stdout + p.stderr) + self.assertNotIn("Traceback", p.stderr) + self.assertEqual(len(p.stderr.strip().splitlines()), 1, p.stderr) + self.assertTrue(p.stderr.startswith("ERROR: --out "), p.stderr) + self.assertIn("separate output folder", p.stderr) + self.assertFalse((self.src / "ps_x.spvasm").exists()) + self.assertFalse((self.src / "ps_x.spv").exists()) + self.assertFalse((self.src / "index.json").exists()) + + def test_out_equal_to_the_input_folder_is_refused(self): + self.assert_refused(self.src) + + def test_out_inside_the_input_folder_is_refused(self): + out = self.src / "spirv" + self.assert_refused(out) + self.assertFalse(out.exists()) # refused before mkdir, not left as an empty folder + + def test_a_distinct_out_folder_still_translates(self): + out = self.tmp / "spirv" + + def spirv_tool(cmd, **kwargs): + if cmd[0] == "spirv-as": + Path(kwargs.get("cwd", ""), cmd[3]).write_bytes(b"new module") + return subprocess.CompletedProcess(cmd, 0, "", "") + + with mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(out)]), \ + mock.patch.object(rdna2spirv.subprocess, "run", side_effect=spirv_tool): + self.assertIsNone(rdna2spirv.main()) + self.assertTrue((out / "ps_x.spv").is_file()) + self.assertTrue((out / "index.json").is_file()) + + class ValidatedOutput(unittest.TestCase): def setUp(self): root = Path(self.enterContext(tempfile.TemporaryDirectory())) @@ -264,9 +312,9 @@ class ValidatedOutput(unittest.TestCase): def spirv_tool(cmd, **kwargs): tool = cmd[0] if tool == "spirv-as": - Path(cmd[3]).write_bytes(b"new module") + Path(kwargs.get("cwd", ""), cmd[3]).write_bytes(b"new module") elif tool == "spirv-val": - self.assertEqual(Path(cmd[-1]).read_bytes(), b"new module") + self.assertEqual(Path(kwargs.get("cwd", ""), cmd[-1]).read_bytes(), b"new module") if reject_at is None: self.assertFalse(self.module.exists(), "the binary was published before validation") else: @@ -283,6 +331,44 @@ class ValidatedOutput(unittest.TestCase): def test_existing_single_s_file_still_translates(self): self.assertIn("1 pass spirv-val", self.translate()) + def test_missing_assembler_is_one_setup_error(self): + err = io.StringIO() + with mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ + mock.patch.object(rdna2spirv.subprocess, "run", + side_effect=FileNotFoundError(2, "No such file or directory", "spirv-as")), \ + redirect_stdout(io.StringIO()), redirect_stderr(err): + code = rdna2spirv.main() + message = err.getvalue() + self.assertEqual(code, 2, message) + self.assertIn("spirv-as", message) + self.assertIn("SPIRV-Tools", message) + self.assertNotIn("Traceback", message) + self.assertEqual(len(message.strip().splitlines()), 1, message) + self.assertFalse(self.module.exists()) + self.assertEqual(list(self.out.glob("*.tmp")), []) + + def test_missing_validator_does_not_publish_the_module(self): + def spirv_tool(cmd, **kwargs): + if cmd[0] == "spirv-as": + Path(kwargs.get("cwd", ""), cmd[3]).write_bytes(b"new module") + return subprocess.CompletedProcess(cmd, 0, "", "") + raise FileNotFoundError(2, "No such file or directory", "spirv-val") + + err = io.StringIO() + with mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ + mock.patch.object(rdna2spirv.subprocess, "run", side_effect=spirv_tool), \ + redirect_stdout(io.StringIO()), redirect_stderr(err): + code = rdna2spirv.main() + message = err.getvalue() + self.assertEqual(code, 2, message) + self.assertIn("spirv-val", message) + self.assertIn("SPIRV-Tools", message) + self.assertNotIn("Traceback", message) + self.assertEqual(len(message.strip().splitlines()), 1, message) + self.assertFalse(self.module.exists()) + self.assertFalse(self.index.exists()) + self.assertEqual(list(self.out.glob("*.tmp")), []) + def test_validator_rejection_does_not_publish_binary(self): self.assertIn("INVALID: synthetic rejection", self.translate(reject_at="spirv-val")) self.assertFalse(self.module.exists()) diff --git a/tests/test_rdna2spirv_merge.py b/tests/test_rdna2spirv_merge.py index ec5c519dc..48bda8479 100644 --- a/tests/test_rdna2spirv_merge.py +++ b/tests/test_rdna2spirv_merge.py @@ -195,6 +195,17 @@ class MergeCliTest(unittest.TestCase): self.assertNotIn("Traceback", result.stderr) self.assertFalse((self.out / "index.json").exists()) + def test_cli_removes_the_previous_index_when_the_merge_fails(self): + # The old index describes the previous corpus; after a failed merge the parts no longer match it. + (self.out / "index.json").write_text(json.dumps({"old": {}}), encoding="utf-8") + self.part(0, {"a": {}}) + self.marker(0, 2) + self.marker(1, 2) + result = self.run_merge() + self.assertEqual(result.returncode, 2, result.stdout + result.stderr) + self.assertIn("ERROR: incomplete shard set", result.stderr) + self.assertFalse((self.out / "index.json").exists()) + def test_cli_merges_a_complete_set(self): self.part(0, {"a": {}}) self.part(1, {"b": {}}) diff --git a/tests/test_restofworld_model_join.py b/tests/test_restofworld_model_join.py index ad56543c0..782b35919 100644 --- a/tests/test_restofworld_model_join.py +++ b/tests/test_restofworld_model_join.py @@ -479,6 +479,31 @@ class ModelJoinTests(unittest.TestCase): sys3 + gfx3, ] + def test_joins_a_short_declared_final_system_page(self): + system, graphics = make_standalone_drawable_1x1() + first = bytearray(system[0].ljust(65536, b"\0")) + _write_page_map(first, 65536 - 64, sys_pages=2, gfx_pages=1) + struct.pack_into(""), # was reported as mem::H::?$Pool + (".?AV?$Map@_KPEBD@util@@", "util::Map"), + (".?AV?$Flags@W4Mode@gfx@@@gfx@@", "gfx::Flags"), + (".?AV?$Fixed@$0BA@$0?0$00@math@@", "math::Fixed<16, -1, 1>"), + (".?AV?$Tuple@$$V@core@@", "core::Tuple<>"), + (".?AV?$Tuple@HN$$QEAM@core@@", "core::Tuple"), + (".?AVInner@?$Outer@_N@core@@", "core::Outer::Inner"), + ): + with self.subTest(mangled=mangled): + self.assertEqual(rtti_scan.simple_name(mangled), name) + + def test_back_references(self): + # Inside a template the digits count that template's own names: 0 is Pair, 1 Node, 2 scene. + self.assertEqual(rtti_scan.simple_name(".?AV?$Pair@VNode@scene@@VEdge@2@@scene@@"), + "scene::Pair") + # A template that was named once is one back-reference: 2 is List. + self.assertEqual(rtti_scan.simple_name(".?AV?$Wrap@VIterator@?$List@H@core@@V123@@core@@"), + "core::Wrap::Iterator, core::List::Iterator>") + + def test_pointer_reference_array_and_function_arguments(self): + for mangled, name in ( + (".?AV?$Callback@$$A6AXAEBUEvent@ui@@H@Z@ui@@", "ui::Callback"), + (".?AV?$Sink@P6AXPEAX0@_E@io@@", "io::Sink"), + (".?AV?$Span@AEAY03$$CBH@io@@", "io::Span"), + (".?AV?$Ref@AEBQEAUNode@scene@@@scene@@", "scene::Ref"), + # A pointer to a function pointer or to an array goes inside the brackets, not after them. + (".?AV?$Cb@PEAP6AXH@Z@lab@@", "lab::Cb"), + (".?AV?$Cb@QEAP6AXH@Z@lab@@", "lab::Cb"), + (".?AV?$Cb@P6AP6AXH@ZXZ@lab@@", "lab::Cb"), + (".?AV?$Cb@AEAY03P6AXH@Z@lab@@", "lab::Cb"), + (".?AV?$Cb@PEAY03$$CBH@lab@@", "lab::Cb"), + (".?AV?$Arr@$$BY01H@lab@@", "lab::Arr"), + ): + with self.subTest(mangled=mangled): + self.assertEqual(rtti_scan.simple_name(mangled), name) + + def test_anonymous_namespace_and_local_classes(self): + for mangled, name in ( + (".?AVWorker@?A0x1234abcd@jobs@@", "jobs::`anonymous namespace'::Worker"), + (".?AV@?1??Run@Task@jobs@@QEAAXH@Z@", "`jobs::Task::Run'::`2'::"), + (".?AV@?0???0Task@jobs@@QEAA@XZ@", "`jobs::Task::Task'::`1'::"), + (".?AV@?0???RTask@jobs@@QEBAHH@Z@", "`jobs::Task::operator()'::`1'::"), + # A conversion operator is named after the type it returns: two of them in one class stay apart. + (".?AVX@?0???BObj@@QEBAHXZ@", "`Obj::operator int'::`1'::X"), + (".?AVX@?0???BObj@@QEBAP6AXH@ZXZ@", "`Obj::operator void (*)(int)'::`1'::X"), + (".?AV@?5???$Each@H@List@core@@SA_NPEBVNode@2@0@Z@", "`core::List::Each'::`6'::"), + (".?AV?$Holder@V@?1??Run@Task@jobs@@QEAAXH@Z@H@jobs@@", + "jobs::Holder<`jobs::Task::Run'::`2'::, int>"), + ): + with self.subTest(mangled=mangled): + self.assertEqual(rtti_scan.simple_name(mangled), name) + + def test_enum_and_union(self): + self.assertEqual(rtti_scan.simple_name(".?AW4Mode@gfx@@"), "gfx::Mode") + self.assertEqual(rtti_scan.simple_name(".?ATBits@gfx@@"), "gfx::Bits") + + def test_a_form_that_is_not_read_stays_mangled(self): + # No made-up scope chain: a pointer to a member function, a template cut short, a name that never ends, + # an array with a negative number of dimensions or a negative size. + for mangled in (".?AV?$Bind@P8Task@jobs@@EAAXXZ@jobs@@", ".?AV?$Pool@@", ".?AV?$Pool@H@", ".?AV9@@", + ".?AV?$Arr@$$BY?0H@lab@@", ".?AV?$Arr@$$BY0?1H@lab@@", ".?AV?$Arr@AEAY?0H@lab@@", + ".?AV" + "?$A@V" * 5000 + "@"): + with self.subTest(mangled=mangled[:40]): + self.assertEqual(rtti_scan.simple_name(mangled), mangled) + class RttiScanCoreTest(unittest.TestCase): def setUp(self): @@ -194,6 +263,31 @@ class RttiScanCoreTest(unittest.TestCase): self.assertEqual(vt_info["offset_in_object"], 0) self.assertEqual(vt_info["slots"], 3) + def test_class_local_to_a_function_and_template_base(self): + """A class declared inside a function has a name that ends with the function's `Z@`, not `@@`: its type + descriptor used to be missed, and with it the class and its vtable.""" + local = b".?AVJob@?1??Run@Task@jobs@@QEAAXH@Z@" + base = b".?AV?$Base@H@jobs@@" + rdata = bytearray(0x1000) + rdata[0x010:0x010 + len(base)] = base # TD at RVA 0x2000 + rdata[0x050:0x050 + len(local)] = local # TD at RVA 0x2040 + rdata[0x210:0x21A] = b".?AVNoise@" # one '@' after a plain name: not a descriptor name + rdata[0x080:0x09C] = struct.pack(""])]) + self.assertEqual([(v["rva"], v["class"], v["slots"]) for v in scanned["vtables"]], + [(0x2100, "`jobs::Task::Run'::`2'::Job", 1)]) + def test_multiple_and_virtual_inheritance(self): rdata = bytearray(0x1000) @@ -385,17 +479,35 @@ class RttiScanCoreTest(unittest.TestCase): self.assertTrue(by_name["Derived"]["multiple"]) self.assertEqual(by_name["Derived"]["bases"], ["Base"]) + def test_nonnull_chd_with_bad_signature_or_null_base_array_is_refused(self): + for name, signature, array_rva in (("bad signature", 7, 0x20A0), ("null array", 0, 0)): + with self.subTest(name=name): + rdata = bytearray(0x1000) + mangled = b".?AVInvalidHierarchy@@\0" + rdata[0x10:0x10 + len(mangled)] = mangled + rdata[0x40:0x58] = struct.pack("<6I", 1, 0, 0, 0x2000, 0x2080, 0x2040) + # A non-null CHD isolates signature validation from the null-RVA guard. + # nbase=1 also ensures a null array cannot be rejected accidentally by an out-of-bounds read. + rdata[0x80:0x90] = struct.pack("<4I", signature, 3, 1, array_rva) + rdata[0xA0:0xA4] = struct.pack(" bytes: + return b"".join(struct.pack("<4I", 0, 0, 0, count) for count in mandelbrot_counts(width)) + + +class MandelbrotReadbackTest(unittest.TestCase): + def run_frame(self, data: bytes | None) -> tuple[int, str]: + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + args = SimpleNamespace(filter="ps_mandelbrot.asm", build=directory, llvm_mc="unused") + + def launch(cmd: list[str], **kwargs: object) -> tuple[int, str]: + if cmd[0] == sys.executable: + (work / "spirv" / "ps_mandelbrot.spv").touch() + elif Path(cmd[0]).stem == "vk_harness": + if data is not None: + Path(cmd[-1]).write_bytes(data) + else: + self.fail(f"unexpected command: {cmd}") + return 0, "" + + output = io.StringIO() + with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), + patch.object(rgt, "spirv_as"), + patch.object(rgt, "run_cmd", side_effect=launch), + redirect_stdout(output)): + result = rgt.run_suite(args, directory) + return result, output.getvalue() + + def test_missing_empty_short_or_partial_frames_fail_the_test(self) -> None: + for label, data in ( + ("missing", None), ("empty", b""), ("one complete pixel", reference_frame(1)), + ("partial pixel", bytes(8)), + ): + with self.subTest(label=label): + result, output = self.run_frame(data) + self.assertEqual(result, 1, output) + self.assertIn("FAIL ps_mandelbrot", output) + # a frame that was never written is reported as a missing readback (TEST-837) before its size is read + self.assertIn("missing readback" if data is None else "expected 4096 pixels", output) + + def test_complete_frame_still_compares_the_iteration_counts(self) -> None: + correct = reference_frame(64) + result, output = self.run_frame(correct) + self.assertEqual(result, 0, output) + self.assertIn("4096/4096 iteration counts match", output) + wrong = bytearray(correct) + struct.pack_into(" tuple[int, str, list[str]]: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + trace = root / "launches.txt" + + def entry(name: str, status: int, properties: dict[str, object]) -> dict[str, object]: + (root / f"{name}.py").write_text( + "from pathlib import Path\n" + "with Path(__file__).with_name('launches.txt').open('a', encoding='utf-8', newline='\\n') as f:\n" + f" f.write({name!r} + '\\n')\n" + f"raise SystemExit({status})\n", + encoding="utf-8", newline="\n", + ) + return {"name": name, "command": [f"{WINDOWS_ROOT}/{name}.py"], + "properties": [{"name": key, "value": value} for key, value in properties.items()]} + + setup_props: dict[str, object] = {"SKIP_RETURN_CODE": 77, "DISABLED": disabled} + consumer_props: dict[str, object] = {"DEPENDS": ["setup"]} + if fixture: + setup_props["FIXTURES_SETUP"] = ["input"] + consumer_props["FIXTURES_REQUIRED"] = ["input"] + setup = entry("setup", setup_status, setup_props) + consumer = entry("consumer", 0, consumer_props) + tests = [consumer, setup] if fixture else [setup, consumer] + listing = root / "ctest.json" + listing.write_text(json.dumps({"tests": tests}), encoding="utf-8", newline="\n") + result = subprocess.run( + [sys.executable, "-I", str(RUNNER), "--tests", str(listing), "--windows-root", WINDOWS_ROOT, + "--root", directory, "--require", "consumer", "--wine", f'"{Path(sys.executable).as_posix()}"'], + capture_output=True, text=True, timeout=15, + ) + return result.returncode, result.stdout + result.stderr, trace.read_text(encoding="utf-8").splitlines() + + def test_fixture_setup_is_run_before_an_earlier_listed_consumer(self) -> None: + status, output, calls = self.run_fixture(0) + self.assertEqual(status, 0, output) + self.assertEqual(calls, ["setup", "consumer"]) + + def test_failed_setup_blocks_a_required_consumer(self) -> None: + status, output, calls = self.run_fixture(3) + self.assertEqual(status, 1, output) + self.assertEqual(calls, ["setup"]) + self.assertIn("[FAIL] consumer", output) + self.assertIn("failed fixture setup: setup", output) + + def test_skipped_or_disabled_setup_does_not_block(self) -> None: + for status, disabled, expected in ((77, False, ["setup", "consumer"]), (3, True, ["consumer"])): + with self.subTest(disabled=disabled): + code, output, calls = self.run_fixture(status, disabled=disabled) + self.assertEqual(code, 0, output) + self.assertEqual(calls, expected) + + def test_generic_depends_does_not_turn_an_optional_failure_into_a_block(self) -> None: + status, output, calls = self.run_fixture(3, fixture=False) + self.assertEqual(status, 0, output) + self.assertEqual(calls, ["setup", "consumer"]) + self.assertIn("[FAIL] setup", output) + self.assertIn("[PASS] consumer", output) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_run_wine_tests.py b/tests/test_run_wine_tests.py index c45b2cc88..c721273c6 100644 --- a/tests/test_run_wine_tests.py +++ b/tests/test_run_wine_tests.py @@ -473,6 +473,33 @@ class MainTest(unittest.TestCase): self.assertEqual(code, 2) self.assertIn("not the output of ctest", err) + def test_malformed_command_and_property_rows_are_rejected_before_launch(self): + for fields in ( + {"command": "D:/win/root/artifact/ok.py"}, + {"command": [42]}, + {"command": [self.command("ok.py")[0], "embedded\0null"]}, + {"properties": {"TIMEOUT": 10}}, + {"properties": [{"name": "TIMEOUT"}]}, + {"properties": [{"name": ["TIMEOUT"], "value": 10}]}, + {"name": []}, + ): + with self.subTest(fields=fields): + good = ctest_entry("ok", self.command("ok.py")) + with mock.patch.object(rwt, "DriveMap") as drive, \ + mock.patch.object(rwt, "run_test", return_value=("pass", "")) as launch: + code, _, err = self.run_main([good, good | fields]) + self.assertEqual(code, 2) + self.assertIn("not the output of ctest", err) + drive.assert_not_called() + launch.assert_not_called() + + def test_an_unbuilt_test_without_a_command_is_valid_inventory(self): + code, out, err = self.run_main([{"name": "unbuilt"}], "--require", "unbuilt") + self.assertEqual(code, 1) + self.assertIn("[FAIL] unbuilt", out) + self.assertIn("no command", out) + self.assertEqual(err, "") + def test_an_explicit_empty_tests_list_is_accepted(self): code, out, _ = self.run_main_json({"tests": []}) self.assertEqual(code, 0) diff --git a/tests/test_runner_calls_all_tests.py b/tests/test_runner_calls_all_tests.py new file mode 100644 index 000000000..f43e59b36 --- /dev/null +++ b/tests/test_runner_calls_all_tests.py @@ -0,0 +1,127 @@ +"""The __main__ runner of every standard-library test file actually runs its top-level test functions. + + python -I tests/test_runner_calls_all_tests.py + +tests/test_ci_registration.py sorts tests/test_*.py into CI jobs: a file without a PYTEST_FILE_MARKERS match but +with a __main__ guard runs in the standard-library loop as ``python -I tests/.py``, and pytest never +imports it. When such a runner forgets to call one of the file's top-level ``def test_*`` functions, those +checks run nowhere while the run still prints ok and exits 0 -- tests/test_cfg_structure.py carried a dead +test_depth() this way (PR #3122 fixes it), and tests/test_feature_scan.py had the sibling bug of swallowing its +only unrouted assert (PR #3051). This is the runner counterpart of tests/test_ci_registration.py: it reuses +that file's classification straight from the workflow (so it cannot drift from ci.yml) and fails for every +stdlib-mode file whose __main__ block neither names each top-level test function nor dispatches the whole set +through the ``globals()`` loop some runners use. Intentional non-calls live in RUNNER_SKIPS with their reason, +so a new dead test cannot hide behind a documented one. + +Only the tracked test files and the workflow are read; no game files, no build tools, no pytest. +""" +import ast +import os +import sys +import unittest + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import test_ci_registration as registration # noqa: E402 + +# Top-level test functions a stdlib-mode runner deliberately does not call. Every entry needs a reason; a name +# neither listed here nor reached by the runner fails the check below. +RUNNER_SKIPS = { + "tests/test_cfg_structure.py": { + # One-line wrapper around _check_random_graphs(), which the runner already calls; listing it would run + # the 18,000-graph sweep twice. + "test_random_graphs", + # Dead on upstream/main at 16282101: its four S.depth() asserts run nowhere. PR #3122 adds the call; + # drop this entry once that merges and the runner calls test_depth() first. + "test_depth", + }, + "tests/test_feature_scan.py": { + # Its __main__ runner calls every test_* through run_tests([... for ... in globals().items() ...]), a + # comprehension dispatches_tests() does not follow, so each top-level test is listed here. + "test_feature_scan", + "test_short_signature", + "test_part_payload_outside_container_is_unreadable", + "test_bad_shaders_folder_is_one_line", + "test_out_inside_corpus_is_a_usage_error", + "test_duplicate_shader_names_keep_file_stages", + "test_v_perm_b32_selectors", + "test_typed_buffers_and_psv0", + "test_a_test_that_raises_fails_the_run_and_the_rest_still_run", + "test_a_failed_check_fails_only_its_own_test", + }, +} + + +def runner_block(tree): + """The module's real ``if __name__ == "__main__":`` node, or None (a bare mention satisfies the loop's grep).""" + for node in tree.body: + if isinstance(node, ast.If) and "__main__" in ast.dump(node.test) and "__name__" in ast.dump(node.test): + return node + return None + + +def dispatches_tests(block): + """True when the runner runs its tests through a loop over module globals and calls the loop variable.""" + for node in ast.walk(block): + if not isinstance(node, ast.For): + continue + targets = {t.id for t in ast.walk(node.target) if isinstance(t, ast.Name)} + if not any(isinstance(n, ast.Call) and isinstance(n.func, ast.Name) + and n.func.id in ("globals", "locals", "vars") for n in ast.walk(node)): + continue + if any(isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id in targets + for n in ast.walk(node)): + return True + return False + + +def uncalled_tests(source): + """Top-level test functions the file's __main__ runner never runs; None when there is no real guard.""" + tree = ast.parse(source) + block = runner_block(tree) + if block is None: + return None # test_ci_registration already fails files the loop runs without a guard + if dispatches_tests(block): + return [] + names = {n.id for n in ast.walk(block) if isinstance(n, ast.Name)} + names |= {n.attr for n in ast.walk(block) if isinstance(n, ast.Attribute)} + return [node.name for node in tree.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name.startswith("test") and node.name not in names] + + +class RunnerCallsTestsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.rules = registration.ci_rules(registration.ROOT) + cls.files = [f for f in registration.claimed_test_files(registration.ROOT) + if registration.job_of(registration.ROOT, f, cls.rules) == "stdlib"] + + def test_the_scan_sees_the_stdlib_files(self): + # A classification that collapses to nothing must not turn the check below into a silent no-op. + self.assertGreaterEqual(len(self.files), 100, + f"only {len(self.files)} stdlib-mode test files found: {self.files[:5]}") + self.assertIn("tests/test_cfg_structure.py", self.files) + + def test_every_stdlib_runner_calls_its_test_functions(self): + dead = [] + for rel in self.files: + missing = uncalled_tests(registration.read(registration.ROOT, rel)) + if not missing: # None (no guard) and [] (every test reached) both pass + continue + skips = RUNNER_SKIPS.get(rel, ()) + dead += [f" {rel}: {name}() is defined but its __main__ runner never calls it, so the python -I loop " + f"runs it nowhere and still prints ok; call it, or add it to RUNNER_SKIPS with a reason" + for name in missing if name not in skips] + self.assertEqual(dead, [], "dead top-level tests in stdlib-mode runners:\n" + "\n".join(dead)) + + def test_a_dropped_call_is_flagged(self): + # Bite check on a file this PR does not touch: losing one runner call must be reported, not absorbed. + source = registration.read(registration.ROOT, "tests/test_lane_masks.py") + self.assertEqual(uncalled_tests(source), []) + sabotaged = source.replace(" test_straight_line()", " # dropped for the bite check", 1) + self.assertEqual(uncalled_tests(sabotaged), ["test_straight_line"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_runtime_paths.py b/tests/test_runtime_paths.py new file mode 100644 index 000000000..800cdb300 --- /dev/null +++ b/tests/test_runtime_paths.py @@ -0,0 +1,299 @@ +"""The Runtime workflow's path filter still lists every file under tools/ that its jobs read. + + python -I tests/test_runtime_paths.py + +``.github/workflows/runtime.yml`` starts on the paths it lists, not on everything outside an ignore list +(BUILD-856): a change to a tool the runtime build never reads should not queue a Windows, Wine and llvmpipe run. +The price is that the list can fall behind. If ``tools/rdna2spirv.py`` starts importing a new ``tools/foo.py``, +that pull request still runs Runtime (it touches ``rdna2spirv.py``), but a later one that changes only +``foo.py`` would skip the GPU tests without anyone noticing. This test recomputes what the jobs read and fails +when an entry is missing: + +* the seeds are the code that runs during the jobs: the CMake files under ``runtime/`` and the workflow's + ``jobs:``, with ``#`` comments removed, and the Python under ``runtime/`` plus the scripts the workflow runs. + A ``tools/`` a CMake line or a job step spells out is needed; so is a ``tools`` module a Python seed + imports (the scripts and shader checks put ``tools/`` on ``sys.path``) and a ``tools/`` file it names in a + string, such as ``os.path.join(TOOLS, "rdna2spirv.py")``; +* from there, each needed tool's sibling imports, the ``tools/`` data files it names (``gfx10_formats.json`` is + loaded by name, which a ``.py``-only scan misses), modules it loads with ``importlib`` and ``tools/`` + subdirectories it names, to a fixed point. + +Comments, docstrings and the C++, shader and header sources are not read as dependencies: a ``tools/`` in +them says where a table or a test came from, not that the build runs it, and counting those would make every +such note a required entry. + +It also checks that the ``push`` and ``pull_request`` lists are the same, and that no ``tools/`` entry names a +file that no longer exists. Listing more than the jobs need is allowed on purpose: an extra run costs one +queue slot, a missing entry loses the build for a tool the workflow reads. + +Only tracked sources and the workflow are read; no game files, no build tools, no PyYAML. +""" +import ast +import os +import re +import subprocess +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +WORKFLOW = ".github/workflows/runtime.yml" + +# Entries that are needed for reasons a source scan cannot see: the build's own trees, the workflow, and the +# file that decides the line endings every checked-out source gets. +ALWAYS = ("runtime/**", "third_party/**", WORKFLOW, ".gitattributes") + +TOOLS_REF = re.compile(r"tools/([A-Za-z0-9_][A-Za-z0-9_.-]*)") +SCRIPT_REF = re.compile(r"scripts/[A-Za-z0-9_./-]+\.py") + + +def read(root, rel): + with open(os.path.join(root, rel), encoding="utf-8", errors="replace") as f: + return f.read() + + +def path_lists(root): + """{event: [paths]} for the events that filter on paths, exactly as the workflow spells them.""" + text = read(root, WORKFLOW) + lists = {} + for event in ("push", "pull_request"): + match = re.search(r"^ %s:\n((?: .*\n)+)" % event, text, re.M) + if not match: + raise AssertionError(f"{WORKFLOW} has no `{event}:` trigger the way this test expects it") + body = match.group(1) + paths = re.search(r"^ paths:\n((?: - .*\n)+)", body, re.M) + if not paths: + raise AssertionError(f"{WORKFLOW} `{event}:` has no `paths:` list; update this test with the workflow") + lists[event] = [line.strip()[1:].strip().strip("\"'") for line in paths.group(1).splitlines()] + return lists + + +def covered(path, patterns): + for pattern in patterns: + if pattern.endswith("/**"): + if path.startswith(pattern[:-2]): + return True + elif path == pattern: + return True + return False + + +def tracked(root, top): + result = subprocess.run(["git", "ls-files", "-z", "--", top], cwd=root, capture_output=True, text=True) + if result.returncode == 0 and result.stdout: + return [n for n in result.stdout.split("\0") if n] + names = [] # no git: walk, as tests/test_docs_links.py does + for base, dirs, files in os.walk(os.path.join(root, top)): + dirs[:] = [d for d in dirs if d not in (".git", "__pycache__", "build")] + for name in files: + names.append(os.path.relpath(os.path.join(base, name), root).replace(os.sep, "/")) + return names + + +def python_refs(source): + """(modules, strings) of a Python file: what it imports, including importlib.import_module("x") and + __import__("x"), and its string constants other than docstrings. Comments never reach the AST.""" + try: + tree = ast.parse(source) + except SyntaxError: + return set(), set() + docstrings = set() + for node in ast.walk(tree): + if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) and node.body: + first = node.body[0] + if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant): + docstrings.add(id(first.value)) + modules, strings = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + modules.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0: + modules.add(node.module.split(".")[0]) + elif isinstance(node, ast.Call) and node.args and isinstance(node.args[0], ast.Constant): + func = node.func + name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "") + if name in ("import_module", "__import__") and isinstance(node.args[0].value, str): + modules.add(node.args[0].value.split(".")[0]) + if isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in docstrings: + strings.add(node.value) + return modules, strings + + +def strip_hash_comments(text): + """CMake and YAML without their # comments (a # inside a quoted string is rare enough in both to ignore).""" + return "\n".join(line.split("#", 1)[0] for line in text.splitlines()) + + +def needed(root): + """{tools entry: why} for everything under tools/ the Runtime jobs read.""" + tools = os.path.join(root, "tools") + entries = os.listdir(tools) + modules = {e[:-3] for e in entries if e.endswith(".py")} + data = {e for e in entries if os.path.isfile(os.path.join(tools, e)) and not e.endswith(".py")} + subdirs = {e for e in entries if os.path.isdir(os.path.join(tools, e)) and not e.startswith((".", "__"))} + + def entry(name): + name = name.rstrip(".") + if name in subdirs: + return f"tools/{name}/**" + if name in modules or name.endswith(".py") and name[:-3] in modules: + return f"tools/{name if name.endswith('.py') else name + '.py'}" + if name in data: + return f"tools/{name}" + return None + + def spelled(text): + for name in TOOLS_REF.findall(text): + first = name.split("/")[0] + yield first if first in subdirs else name + + def python_names(source, own_dir): + """tools/ entries a Python file imports or names in a string; own_dir's files shadow tools/.""" + imports, strings = python_refs(source) + names = {m + ".py" for m in imports + if m in modules and not (own_dir and os.path.exists(os.path.join(own_dir, m + ".py")))} + for s in strings: + names.update(spelled(s)) + base = s.rstrip("/").split("/")[-1] + if base in data or base in subdirs or base.endswith(".py") and base[:-3] in modules: + if not (own_dir and "/" not in s and os.path.exists(os.path.join(own_dir, base))): + names.add(base) + return names + + workflow = read(root, WORKFLOW) + # Only what the jobs run: the trigger's own list would make every listed entry "needed". + jobs = strip_hash_comments(workflow[workflow.find("\njobs:"):] if "\njobs:" in workflow else "") + found = {} + for name in spelled(jobs): + hit = entry(name) + if hit: + found.setdefault(hit, f"run by {WORKFLOW}") + runtime = tracked(root, "runtime") + cmake = [f for f in runtime if f.endswith(".cmake") or f.split("/")[-1] == "CMakeLists.txt"] + python = [f for f in runtime if f.endswith(".py")] + sorted(set(SCRIPT_REF.findall(jobs))) + for seed in cmake: + for name in spelled(strip_hash_comments(read(root, seed))): + hit = entry(name) + if hit: + found.setdefault(hit, f"named in {seed}") + for seed in python: + if os.path.isfile(os.path.join(root, seed)): + own = os.path.dirname(os.path.join(root, seed)) + for name in python_names(read(root, seed), own): + hit = entry(name) + if hit: + found.setdefault(hit, f"read by {seed}") + + queue = list(found) + while queue: + current = queue.pop() + if current.endswith("/**"): + sources = [f for f in tracked(root, current[:-3]) if f.endswith(".py")] + elif current.endswith(".py"): + sources = [current] + else: + continue + for source in sources: + for name in python_names(read(root, source), None): + hit = entry(name) + if hit and hit not in found: + found[hit] = f"via {source}" + queue.append(hit) + return found + + +def problems(root): + lists = path_lists(root) + issues = [] + events = sorted(lists) + for other in events[1:]: + if lists[other] != lists[events[0]]: + issues.append(f"the `{events[0]}` and `{other}` path lists differ") + patterns = lists[events[0]] + for must in ALWAYS: + if must not in patterns: + issues.append(f"{must}: missing (always needed)") + for script in sorted(set(SCRIPT_REF.findall(read(root, WORKFLOW)))): + if not covered(script, patterns): + issues.append(f"{script}: run by the workflow but not listed") + for path, why in sorted(needed(root).items()): + if not covered(path, patterns): + issues.append(f"{path}: missing ({why})") + for pattern in patterns: + if pattern.startswith("tools/") and not pattern.endswith("/**"): + if not os.path.exists(os.path.join(root, pattern)): + issues.append(f"{pattern}: listed but does not exist") + return issues + + +class RepositoryRuntimePathsTest(unittest.TestCase): + def test_the_scan_sees_the_repository(self): + found = needed(ROOT) + # The translator the GPU tests run through and the stub generator CMake runs at configure time. + self.assertIn("tools/rdna2spirv.py", found) + self.assertIn("tools/gen_d3d12_stubs.py", found) + + def test_every_tool_the_jobs_read_triggers_the_workflow(self): + issues = problems(ROOT) + self.assertFalse(issues, f"{WORKFLOW} path filter:\n" + "\n".join(f" {i}" for i in issues)) + + +class SyntheticTreeTest(unittest.TestCase): + """The scan flags what a path grep misses, on a tree built for the purpose.""" + + def build(self, tmp, listed): + def write(rel, text): + path = os.path.join(tmp, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + + paths = "".join(f' - "{p}"\n' for p in ALWAYS + ("scripts/**",) + tuple(listed)) + write(WORKFLOW, "name: Runtime\n\non:\n push:\n branches: [main]\n paths:\n" + paths + + " pull_request:\n paths:\n" + paths + "\njobs:\n x:\n steps:\n" + " - run: python3 -I scripts/run_gpu_tests.py\n") + write("runtime/CMakeLists.txt", "add_custom_command(COMMAND python tools/translator.py)\n") + write("scripts/run_gpu_tests.py", "import sys\nimport subgroup_info\n") + write("tools/translator.py", "import lanes\nimport json\nTABLE = 'formats.json'\nRUN = 'tools/runner.py'\n") + write("tools/runner.py", "X = 1\n") + write("tools/lanes.py", "import importlib\nM = importlib.import_module('late')\n") + write("tools/late.py", "ORACLE = 'oracle'\n") + write("tools/oracle/run.py", "import helper\n") + write("tools/helper.py", "X = 1\n") + write("tools/formats.json", "{}\n") + write("tools/subgroup_info.py", "X = 1\n") + write("tools/unrelated.py", "X = 1\n") + # Notes, not reads: none of these may make tools/unrelated.py a required entry. + write("runtime/src/table.h", "// generated by tools/unrelated.py\nconst char *k = \"tools/unrelated.py\";\n") + write("runtime/test/shaders/probe.asm", "; checked with tools/unrelated.py\n") + write("runtime/test/shaders/check.py", '"""Words from tools/unrelated.py."""\n# see tools/unrelated.py\n') + write("runtime/cmake/extra.cmake", "# tools/unrelated.py made this list\n") + + def test_a_complete_list_passes(self): + with tempfile.TemporaryDirectory() as tmp: + self.build(tmp, ["tools/translator.py", "tools/lanes.py", "tools/late.py", "tools/oracle/**", + "tools/helper.py", "tools/formats.json", "tools/subgroup_info.py", + "tools/runner.py"]) + self.assertEqual(problems(tmp), []) + self.assertNotIn("tools/unrelated.py", needed(tmp)) + + def test_each_kind_of_dependency_is_reported_when_missing(self): + with tempfile.TemporaryDirectory() as tmp: + self.build(tmp, ["tools/translator.py", "tools/gone.py"]) + issues = "\n".join(problems(tmp)) + for missing in ("tools/lanes.py", "tools/late.py", "tools/oracle/**", "tools/helper.py", + "tools/formats.json", "tools/subgroup_info.py", "tools/runner.py"): + self.assertIn(f"{missing}: missing", issues) + self.assertIn("tools/gone.py: listed but does not exist", issues) + + def test_lists_that_differ_are_reported(self): + with tempfile.TemporaryDirectory() as tmp: + self.build(tmp, []) + path = os.path.join(tmp, WORKFLOW) + text = read(tmp, WORKFLOW).replace(' paths:\n', ' paths:\n - "tools/extra.py"\n', 1) + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + self.assertTrue(any("path lists differ" in i for i in problems(tmp))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sampler_lod_probe.py b/tests/test_sampler_lod_probe.py index 25be060d9..a3174ddd3 100644 --- a/tests/test_sampler_lod_probe.py +++ b/tests/test_sampler_lod_probe.py @@ -13,10 +13,18 @@ sys.path.insert(0, os.path.join(ROOT, "tools", "hw_oracle")) import sampler_lod_probe as p # noqa: E402 -# What gfx1036 (Radeon iGPU, AMD 26.10.1) read for these rows: tools/sampler_lod_probe.py --oracle hw. -MEASURED = {"s_min2_lz": 2, "s_bias+2_lz": 2, "s_bias+2_max3_l3": 3, "l1.5": 2, "l0.5": 1, "l1.49": 1, - "s_min1.5_l0": 2, "t_min2.25_l0": 2, "t_min2.5_l0": 3, "t_min2.75_l0": 3, "base1_t_min2_l0": 2, - "mipnone_min2_l0": 0, "mipnone_t_min2.5": 2, "mipnone_base1_tmin3": 3} +# What gfx1036 (Radeon iGPU, AMD 26.10.1) read for every row, wave32 and wave64 alike: +# tools/sampler_lod_probe.py --oracle hw. All 43 are pinned, so a change to rdna2_level shows without a GPU. +MEASURED = { + "calib_lod0": 0, "calib_lod1": 1, "calib_lod2": 2, "calib_lod3": 3, "calib_lod4": 4, "calib_lod5": 5, + "calib_lod6": 6, "lz": 0, "s_min2_l0": 2, "s_min2_lz": 2, "s_max1_l4": 1, "s_max0_l3": 0, "s_bias+2_l1": 3, + "s_bias+2_lz": 2, "s_bias-1_l3": 2, "s_bias+2_max3_l3": 3, "s_bias+0.5_l1": 2, "l1.25": 1, "l1.5": 2, + "l1.75": 2, "mipnone_l3": 0, "mipnone_min2_l0": 0, "mipnone_t_min3_l0": 3, "mipnone_t_min2.25": 2, + "mipnone_t_min2.5": 2, "mipnone_base1_tmin3": 3, "t_min3_l1": 3, "t_min3_lz": 3, "t_min3_l5": 5, + "t_min2.5_l0": 3, "t_min2.5_l2.6": 3, "t_min2.25_l0": 2, "t_min2.75_l0": 3, "t_min2.25_lz": 2, "l0.5": 1, + "l2.5": 3, "s_min1.5_l0": 2, "s_max1.5_l4": 2, "l1.49": 1, "base1_l0": 1, "base1_s_min1_l0": 2, + "base1_t_min2_l0": 2, "base1_t_min2_lz": 2, +} def field(word, lo, width): @@ -52,6 +60,7 @@ class RowsTest(unittest.TestCase): def test_model_gives_the_measured_levels(self): by_name = {r[0]: r for r in p.rows()} + self.assertEqual(set(MEASURED), set(by_name), "every row is pinned to its measured level") for name, level in MEASURED.items(): _n, instr, lod, s, t = by_name[name] with self.subTest(name): diff --git a/tests/test_sandbox_pick.py b/tests/test_sandbox_pick.py new file mode 100644 index 000000000..2615bc0c7 --- /dev/null +++ b/tests/test_sandbox_pick.py @@ -0,0 +1,109 @@ +"""tools/sandbox.py: the shader pair is chosen by signature and descriptor layout, never by name.""" +import json +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools")) +import sandbox # noqa: E402 + +VS_TEXT = """\ts_load_dwordx4 s[0:3], s[8:9], null +\ts_load_dwordx4 s[20:23], s[8:9], 0x40 +\ts_load_dwordx4 s[16:19], s[8:9], 0x60 +\ts_buffer_load_dwordx4 s[24:27], s[0:3], 0x30 +\ts_buffer_load_dwordx16 s[0:15], s[20:23], 0x160 +\texp pos0 v0, v1, v2, v3 done +""" +PS_TEXT = """\ts_load_dwordx8 s[4:11], s[8:9], 0x20 +\timage_sample v[0:3], v[2:3], s[4:11], s[0:3] dmask:0xf dim:SQ_RSRC_IMG_2D +\texp mrt0 v0, v0, v1, v1 done compr vm +""" + + +def sig(*elems): + return [{"semantic": s, "semantic_index": 0, "mask": m} for s, m in elems] + + +VS_SIG = sig(("POSITION", 7), ("NORMAL", 7), ("TEXCOORD", 3)) +PS_SIG = sig(("SV_Position", 15), ("TEXCOORD", 3), ("COLOR", 15)) +PTR8 = [{"kind": "ptr32_lo", "sgpr": 8}] + + +class PickPair(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = self.tmp.name + os.makedirs(os.path.join(self.root, "spirv")) + os.makedirs(os.path.join(self.root, "dxbc", "disasm")) + self.index = {} + + def tearDown(self): + self.tmp.cleanup() + + def add(self, name, entry, text, spv=True): + self.index[name] = entry + with open(os.path.join(self.root, "dxbc", "disasm", name + ".s"), "w") as f: + f.write(text) + if spv: + open(os.path.join(self.root, "spirv", name + ".spv"), "wb").close() + + def pick(self): + with open(os.path.join(self.root, "spirv", "index.json"), "w") as f: + json.dump(self.index, f) + return sandbox.pick_pair(self.root) + + def names(self): + pair = self.pick() + return pair and tuple(os.path.splitext(os.path.basename(p))[0] for p in pair) + + def test_picks_matching_pair(self): + self.add("a_vs", {"stage": "vs", "input_signature": VS_SIG, "user_sgpr_reads": PTR8, "bindings": []}, VS_TEXT) + self.add("b_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8 + [{"kind": "const32", "sgpr": 9}], + "bindings": [0, 1, 2]}, PS_TEXT) + self.assertEqual(self.names(), ("a_vs", "b_ps")) + + def test_rejects_wrong_layout_and_signature(self): + self.add("a_vs", {"stage": "vs", "input_signature": VS_SIG, "user_sgpr_reads": PTR8, "bindings": []}, + VS_TEXT.replace("0x160", "0x100")) + self.add("c_vs", {"stage": "vs", "input_signature": VS_SIG[:2], "user_sgpr_reads": PTR8, "bindings": []}, VS_TEXT) + self.add("b_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8, "bindings": [0, 1, 2]}, PS_TEXT) + self.assertIsNone(self.pick()) + + def test_rejects_two_samples_and_missing_spirv(self): + self.add("a_vs", {"stage": "vs", "input_signature": VS_SIG, "user_sgpr_reads": PTR8, "bindings": []}, VS_TEXT) + self.add("b_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8, "bindings": [0, 1, 2]}, + PS_TEXT + PS_TEXT) + self.add("c_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8, "bindings": [0, 1, 2]}, + PS_TEXT, spv=False) + self.assertIsNone(self.pick()) + self.add("d_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8, "bindings": [0, 1, 2]}, PS_TEXT) + self.assertEqual(self.names(), ("a_vs", "d_ps")) + + def test_missing_index(self): + self.assertIsNone(sandbox.pick_pair(os.path.join(self.root, "nowhere"))) + + +class CheckFrame(unittest.TestCase): + def frame(self, pixels, w, h): + fd, path = tempfile.mkstemp(suffix=".ppm") + with os.fdopen(fd, "wb") as f: + f.write(b"P6\n%d %d\n255\n" % (w, h) + bytes(c for p in pixels for c in p)) + self.addCleanup(os.remove, path) + return path + + def test_empty_frame_fails(self): + ok, msg = sandbox.check_frame(self.frame([(140, 173, 217)] * 100, 10, 10), False) + self.assertFalse(ok) + self.assertIn("0 of 100", msg) + + def test_covered_frame(self): + px = [(140, 173, 217)] * 50 + [(64, 64, 64)] * 50 + self.assertTrue(sandbox.check_frame(self.frame(px, 10, 10), False)[0]) + self.assertFalse(sandbox.check_frame(self.frame(px, 10, 10), True)[0]) # textured needs colour variety + varied = [(140, 173, 217)] * 300 + [(i % 256, i // 256, 7) for i in range(300)] + self.assertTrue(sandbox.check_frame(self.frame(varied, 30, 20), True)[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_sandbox_scene.py b/tests/test_sandbox_scene.py new file mode 100644 index 000000000..920c660e3 --- /dev/null +++ b/tests/test_sandbox_scene.py @@ -0,0 +1,97 @@ +"""tools/sandbox_scene.py: entity world rows, nearest-first selection and the packed vertex layout.""" +import os +import sys +import struct +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools')) +import sandbox_scene + +class TestSandboxScene(unittest.TestCase): + def test_draw_rows(self): + result = sandbox_scene.draw_rows((0, 0, 0, 1), 1.0, 1.0, (10, 20, 30)) + self.assertAlmostEqual(result[0][0], 1.0, places=6) + self.assertAlmostEqual(result[0][1], 0.0, places=6) + self.assertAlmostEqual(result[0][2], 0.0, places=6) + self.assertAlmostEqual(result[1][0], 0.0, places=6) + self.assertAlmostEqual(result[1][1], 1.0, places=6) + self.assertAlmostEqual(result[1][2], 0.0, places=6) + self.assertAlmostEqual(result[2][0], 0.0, places=6) + self.assertAlmostEqual(result[2][1], 0.0, places=6) + self.assertAlmostEqual(result[2][2], 1.0, places=6) + self.assertAlmostEqual(result[3][0], 10.0, places=6) + self.assertAlmostEqual(result[3][1], 20.0, places=6) + self.assertAlmostEqual(result[3][2], 30.0, places=6) + + def test_draw_rows_rotation(self): + result = sandbox_scene.draw_rows((0, 0, -0.70710678, 0.70710678), 1, 1, (0, 0, 0)) + self.assertAlmostEqual(result[0][0], 0.0, places=6) + self.assertAlmostEqual(result[0][1], 1.0, places=6) + self.assertAlmostEqual(result[0][2], 0.0, places=6) + self.assertAlmostEqual(result[1][0], -1.0, places=6) + self.assertAlmostEqual(result[1][1], 0.0, places=6) + self.assertAlmostEqual(result[1][2], 0.0, places=6) + self.assertAlmostEqual(result[2][0], 0.0, places=6) + self.assertAlmostEqual(result[2][1], 0.0, places=6) + self.assertAlmostEqual(result[2][2], 1.0, places=6) + + def test_draw_rows_scale(self): + result = sandbox_scene.draw_rows((0, 0, 0, 1), 2.0, 3.0, (0, 0, 0)) + self.assertAlmostEqual(result[0][0], 2.0, places=6) + self.assertAlmostEqual(result[0][1], 0.0, places=6) + self.assertAlmostEqual(result[0][2], 0.0, places=6) + self.assertAlmostEqual(result[1][0], 0.0, places=6) + self.assertAlmostEqual(result[1][1], 2.0, places=6) + self.assertAlmostEqual(result[1][2], 0.0, places=6) + self.assertAlmostEqual(result[2][0], 0.0, places=6) + self.assertAlmostEqual(result[2][1], 0.0, places=6) + self.assertAlmostEqual(result[2][2], 3.0, places=6) + + def test_select_rows(self): + rows = [ + {"_pos": [1, 1, 0]}, + {"_pos": [5, 5, 0]}, + {"_pos": [20, 20, 0]}, + {"_pos": [3, 3, 0]} + ] + result = sandbox_scene.select_rows(rows, (0, 0), 10, 10) + self.assertEqual(len(result), 3) + self.assertAlmostEqual(result[0]["_pos"][0], 1.0, places=6) + self.assertAlmostEqual(result[0]["_pos"][1], 1.0, places=6) + self.assertAlmostEqual(result[1]["_pos"][0], 3.0, places=6) + self.assertAlmostEqual(result[1]["_pos"][1], 3.0, places=6) + self.assertAlmostEqual(result[2]["_pos"][0], 5.0, places=6) + self.assertAlmostEqual(result[2]["_pos"][1], 5.0, places=6) + + result = sandbox_scene.select_rows(rows, (0, 0), 10, 2) + self.assertEqual(len(result), 2) + self.assertAlmostEqual(result[0]["_pos"][0], 1.0, places=6) + self.assertAlmostEqual(result[0]["_pos"][1], 1.0, places=6) + self.assertAlmostEqual(result[1]["_pos"][0], 3.0, places=6) + self.assertAlmostEqual(result[1]["_pos"][1], 3.0, places=6) + + def test_mesh_bytes(self): + prim = { + "positions": [(0, 0, 0), (1, 0, 0), (0, 1, 0)], + "normals": [(0, 0, 1)] * 3, + "uvs": [(0, 0), (1, 0), (0, 1)], + "indices": [0, 1, 2] + } + b = sandbox_scene.mesh_bytes(prim) + self.assertEqual(len(b), 116) + self.assertEqual(tuple(struct.unpack_from(' None: + for width, signed, token, expected in ( + (8, 1, "0x80", 0xFFFFFF80), + (16, 1, "0x8000", 0xFFFF8000), + (16, 1, "-32768", 0xFFFF8000), + (16, 0, "0x8000", 0x00008000), + ): + with self.subTest(width=width, signed=signed, token=token): + asm = f'''OpCapability Shader +OpCapability Int{width} +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize 1 1 1 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%short = OpTypeInt {width} {signed} +%value = OpConstant %short {token} +%main = OpFunction %void None %fn +%entry = OpLabel +OpSelectionMerge %merge None +OpSwitch %value %merge {token} %case +%case = OpLabel +OpBranch %merge +%merge = OpLabel +OpReturn +OpFunctionEnd +''' + spv = spirv_asm.assemble(asm, target_env="vulkan1.2") + words = struct.unpack(f"<{len(spv) // 4}I", spv) + literals = {} + offset = 5 + while offset < len(words): + count, opcode = words[offset] >> 16, words[offset] & 0xFFFF + if opcode in (43, 251): # OpConstant, OpSwitch + literals[opcode] = words[offset + 3] + offset += count + self.assertEqual(literals, {43: expected, 251: expected}) + _validate(spv) + def test_hex_float_inf_nan_and_string_escapes_match_spirv_as(self): # Regression tests for PR #2251 review (@FreddyxS): # 1) Width-aware hex-float Inf and NaN payload spellings (f16, f32, f64). diff --git a/tests/test_spirv_gs_to_compute.py b/tests/test_spirv_gs_to_compute.py index 3bccc5ef7..2eb0e2ef5 100644 --- a/tests/test_spirv_gs_to_compute.py +++ b/tests/test_spirv_gs_to_compute.py @@ -139,6 +139,20 @@ def test_phi_from_entry_block_names_the_split_block(tmp_path): assert r.returncode == 0, r.stderr +@pytest.mark.skipif(not HAVE_SPIRV or not shutil.which("spirv-dis"), reason="needs SPIRV-Tools on PATH") +@pytest.mark.parametrize("target", ["vulkan1.0", "vulkan1.1", "vulkan1.2"]) +def test_cli_preserves_valid_capture_across_spirv_versions(tmp_path: Path, target: str) -> None: + source, output = tmp_path / "gs.spv", tmp_path / "cs.spv" + subprocess.run(["spirv-as", "--target-env", target, "-", "-o", source], input=PHI_GS, text=True, check=True) + subprocess.run(["spirv-val", "--target-env", target, source], check=True) + tool = os.path.join(ROOT, "tools", "spirv_gs_to_compute.py") + result = subprocess.run([sys.executable, "-I", tool, source, output], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + result = subprocess.run(["spirv-val", "--target-env", target, output], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert output.read_bytes()[4:8] == source.read_bytes()[4:8] + + @pytest.mark.skipif(not HAVE_SPIRV, reason="needs spirv-as and spirv-val on PATH") def test_lowers_in_bounds_geometry_interface_access_chains(tmp_path: Path) -> None: geometry = PHI_GS.replace( diff --git a/tests/test_spirv_gs_to_compute_bounds.py b/tests/test_spirv_gs_to_compute_bounds.py new file mode 100644 index 000000000..a3a02aecb --- /dev/null +++ b/tests/test_spirv_gs_to_compute_bounds.py @@ -0,0 +1,419 @@ +"""Unit and semantic execution tests for OutputVertices bounds in tools/spirv_gs_to_compute.py (SHADER-617). + +Verifies that: +- OpEmitVertex guards record/meta SSBO stores and %gsc_n increments on n < OutputVertices, so a geometry + shader emitting past OutputVertices drops excess vertices rather than overflowing into primitive p+1's + record slots or meta count slot; +- OpEndPrimitive and OpReturn stay strictly within primitive p's meta slice (count <= OutputVertices), + including OutputVertices == 0 and repeated OpEndPrimitive calls after dropped emits; +- OpPhi predecessors are rewritten across every split block — entry block, forward if/else branches + containing OpEmitVertex, and loop-header back-edges from a latch block containing OpEmitVertex. + +Standard library only (runs with `python -I tests/test_spirv_gs_to_compute_bounds.py` and under pytest). +No game data, no GPU required; runs spirv-as + spirv-val when available on PATH. +""" +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +import spirv_gs_to_compute as gsc # noqa: E402 + +MASK32 = 0xFFFFFFFF + + +def _make_gs(body_lines, max_verts=3, verts_in=3, topology="OutputTriangleStrip", extra_consts=""): + return f"""\ +OpCapability Shader +OpCapability Geometry +OpMemoryModel Logical GLSL450 +OpEntryPoint Geometry %main "main" %in_pos %out_pos +OpExecutionMode %main Triangles +OpExecutionMode %main Invocations 1 +OpExecutionMode %main {topology} +OpExecutionMode %main OutputVertices {max_verts} +OpDecorate %in_pos BuiltIn Position +OpDecorate %out_pos BuiltIn Position +%void = OpTypeVoid +%fn = OpTypeFunction %void +%bool = OpTypeBool +%uint = OpTypeInt 32 0 +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%u0 = OpConstant %uint 0 +%u1 = OpConstant %uint 1 +%u2 = OpConstant %uint 2 +%u3 = OpConstant %uint 3 +%u5 = OpConstant %uint 5 +%f0 = OpConstant %float 0 +%f1 = OpConstant %float 1 +%f2 = OpConstant %float 2 +%f3 = OpConstant %float 3 +%f4 = OpConstant %float 4 +%f5 = OpConstant %float 5 +%v_a = OpConstantComposite %v4float %f1 %f0 %f0 %f1 +%v_b = OpConstantComposite %v4float %f2 %f0 %f0 %f1 +%v_c = OpConstantComposite %v4float %f3 %f0 %f0 %f1 +%v_d = OpConstantComposite %v4float %f4 %f0 %f0 %f1 +%v_e = OpConstantComposite %v4float %f5 %f0 %f0 %f1 +{extra_consts}%arr = OpTypeArray %v4float %u{verts_in} +%ptr_in_arr = OpTypePointer Input %arr +%ptr_in_v4 = OpTypePointer Input %v4float +%ptr_out_v4 = OpTypePointer Output %v4float +%in_pos = OpVariable %ptr_in_arr Input +%out_pos = OpVariable %ptr_out_v4 Output +%main = OpFunction %void None %fn +""" + "\n".join(body_lines) + "\nOpFunctionEnd\n" + + +def run_capture_spvasm(spvasm, gid_x, prim_count, in_data, rec_buf, meta_buf): + """Execute a lowered GLCompute capture module for one invocation (GlobalInvocationId.x = gid_x). + + Models the exact instruction subset emitted by spirv_gs_to_compute.py and our synthetic GS fixtures, + and checks OpPhi incoming-block labels at runtime so any missed predecessor relabeling fails loudly. + """ + consts = {} + var_init = {} + blocks = {} + cur_lbl = None + in_main = False + + for raw in spvasm.splitlines(): + s = raw.strip() + if not s or s.startswith(";"): + continue + m = re.match(r"^(%\w+)\s*=\s*(Op\w+)(?:\s+(.*))?$", s) + if m: + res, op, rest = m.group(1), m.group(2), (m.group(3) or "").split() + else: + parts = s.split() + res, op, rest = None, parts[0], parts[1:] + + if op == "OpConstant": + typ, lit = rest[0], rest[1] + consts[res] = float(lit) if "float" in typ else int(lit) + elif op == "OpConstantComposite": + consts[res] = tuple(consts[x] for x in rest[1:]) + elif op == "OpVariable" and not in_main: + if len(rest) >= 3: + var_init[res] = consts[rest[2]] + else: + var_init[res] = None + elif op == "OpFunction": + in_main = (res == "%main") + elif op == "OpFunctionEnd": + in_main = False + elif in_main: + if op == "OpLabel": + cur_lbl = res + blocks[cur_lbl] = [] + elif cur_lbl is not None: + blocks[cur_lbl].append((res, op, rest)) + + assert blocks, "no basic blocks found in %main" + entry_lbl = next(iter(blocks)) + priv = {k: (v if v is not None else (0.0, 0.0, 0.0, 0.0)) for k, v in var_init.items()} + vals = dict(consts) + ptrs = {} + + lbl = entry_lbl + prev_lbl = None + steps = 0 + while True: + steps += 1 + assert steps < 10000, f"possible infinite loop at {lbl}" + insns = blocks[lbl] + # Evaluate all OpPhi instructions at block entry simultaneously using prev_lbl. + phi_updates = {} + i = 0 + while i < len(insns) and insns[i][1] == "OpPhi": + res, _, rest = insns[i] + pairs = list(zip(rest[1::2], rest[2::2])) + matched = [vals[v_id] for v_id, pred in pairs if pred == prev_lbl] + assert len(matched) == 1, ( + f"OpPhi {res} in {lbl} expected predecessor {prev_lbl}, got {[p for _, p in pairs]}" + ) + phi_updates[res] = matched[0] + i += 1 + vals.update(phi_updates) + + for res, op, rest in insns[i:]: + if op in ("OpSelectionMerge", "OpLoopMerge"): + continue + elif op == "OpReturn": + return + elif op == "OpBranch": + prev_lbl, lbl = lbl, rest[0] + break + elif op == "OpBranchConditional": + prev_lbl = lbl + lbl = rest[1] if vals[rest[0]] else rest[2] + break + elif op == "OpAccessChain": + base = rest[1] + idxs = [vals[x] for x in rest[2:]] + ptrs[res] = (base, tuple(idxs)) + elif op == "OpLoad": + src = rest[1] + if src == "%gsc_gid": + vals[res] = (gid_x, 0, 0) + elif src in priv: + vals[res] = priv[src] + else: + base, idxs = ptrs[src] + if base == "%gsc_in": + if idxs == (0,): + vals[res] = prim_count + elif len(idxs) == 2 and idxs[0] == 2: + vals[res] = in_data[idxs[1]] + elif len(idxs) == 3 and idxs[0] == 2: + vals[res] = in_data[idxs[1]][idxs[2]] + else: + raise AssertionError(f"unexpected %gsc_in load {idxs}") + elif base == "%gsc_rec": + vals[res] = rec_buf[idxs[1]] + elif base == "%gsc_meta": + vals[res] = meta_buf[idxs[1]] + else: + raise AssertionError(f"unexpected load from {base} {idxs}") + elif op == "OpStore": + dst, v = rest[0], vals[rest[1]] + if dst in priv: + priv[dst] = v + else: + base, idxs = ptrs[dst] + if base == "%gsc_rec": + assert idxs[0] == 0 and 0 <= idxs[1] < len(rec_buf), ( + f"OOB %gsc_rec store at index {idxs[1]} (len={len(rec_buf)})" + ) + rec_buf[idxs[1]] = v + elif base == "%gsc_meta": + assert idxs[0] == 0 and 0 <= idxs[1] < len(meta_buf), ( + f"OOB %gsc_meta store at index {idxs[1]} (len={len(meta_buf)})" + ) + meta_buf[idxs[1]] = v + else: + raise AssertionError(f"unexpected store to {base} {idxs}") + elif op == "OpCompositeExtract": + vals[res] = vals[rest[1]][int(rest[2])] + elif op == "OpIAdd": + vals[res] = (vals[rest[1]] + vals[rest[2]]) & MASK32 + elif op == "OpIMul": + vals[res] = (vals[rest[1]] * vals[rest[2]]) & MASK32 + elif op == "OpUGreaterThanEqual": + vals[res] = (vals[rest[1]] & MASK32) >= (vals[rest[2]] & MASK32) + elif op == "OpULessThan": + vals[res] = (vals[rest[1]] & MASK32) < (vals[rest[2]] & MASK32) + elif op == "OpIEqual": + vals[res] = (vals[rest[1]] & MASK32) == (vals[rest[2]] & MASK32) + elif op == "OpBitcast" or op == "OpCopyObject": + vals[res] = vals[rest[1]] + else: + raise AssertionError(f"unsupported op in test interpreter: {op} {rest}") + + +def maybe_validate_spirv(spvasm): + import spirv_asm + binary = spirv_asm.assemble(spvasm) + assert len(binary) >= 20 and binary[:4] == b"\x03\x02\x23\x07", "invalid SPIR-V binary magic" + sas, sval = shutil.which("spirv-as"), shutil.which("spirv-val") + if not (sas and sval): + return + with tempfile.TemporaryDirectory() as d: + sa = os.path.join(d, "cs.spvasm") + sv = os.path.join(d, "cs.spv") + with open(sa, "w", encoding="utf-8") as f: + f.write(spvasm) + subprocess.run([sas, "--target-env", "vulkan1.2", sa, "-o", sv], check=True) + subprocess.run([sval, "--target-env", "vulkan1.2", sv], check=True) + + +class TestSpirvGsToComputeEmitBounds(unittest.TestCase): + def test_over_emit_clamped_and_neighbor_primitive_uncorrupted(self): + # OutputVertices = 3, but GS emits 5 vertices + OpEndPrimitive + OpReturn. + gs = _make_gs([ + "%entry = OpLabel", + "OpStore %out_pos %v_a", "OpEmitVertex", + "OpStore %out_pos %v_b", "OpEmitVertex", + "OpStore %out_pos %v_c", "OpEmitVertex", + "OpStore %out_pos %v_d", "OpEmitVertex", + "OpStore %out_pos %v_e", "OpEmitVertex", + "OpEndPrimitive", + "OpReturn", + ], max_verts=3) + out, lay = gsc.rewrite(gs) + self.assertEqual(lay["max_verts"], 3) + self.assertEqual(len(re.findall(r"OpULessThan %bool %\w+ %gsc_k3\b", out)), 5) + maybe_validate_spirv(out) + + sentinel_rec = (99.0, 99.0, 99.0, 99.0) + sentinel_meta = 0xCAFEBABE + # Two primitives: p=0 uses rec[0..2], meta[0..3]; p=1 uses rec[3..5], meta[4..7]. + rec = [sentinel_rec] * 6 + meta = [sentinel_meta] * 8 + in_data = [(0.0, 0.0, 0.0, 1.0)] * 6 + + run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=in_data, rec_buf=rec, meta_buf=meta) + # Primitive 0 captured only its first 3 vertices and clamped count to 3. + self.assertEqual(rec[:3], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0), (3.0, 0.0, 0.0, 1.0)]) + self.assertEqual(meta[:4], [3, 0, 0, 1]) + # Primitive 1's records and meta count/flags must remain completely untouched. + self.assertEqual(rec[3:], [sentinel_rec] * 3) + self.assertEqual(meta[4:], [sentinel_meta] * 4) + + # Running primitive 1 afterwards writes cleanly into its own slice without affecting primitive 0. + run_capture_spvasm(out, gid_x=1, prim_count=2, in_data=in_data, rec_buf=rec, meta_buf=meta) + self.assertEqual(rec[:3], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0), (3.0, 0.0, 0.0, 1.0)]) + self.assertEqual(meta[:4], [3, 0, 0, 1]) + self.assertEqual(rec[3:], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0), (3.0, 0.0, 0.0, 1.0)]) + self.assertEqual(meta[4:], [3, 0, 0, 1]) + + # Out-of-range invocation (gid_x >= prim_count) returns immediately without touching buffers. + run_capture_spvasm(out, gid_x=2, prim_count=2, in_data=in_data, rec_buf=rec, meta_buf=meta) + self.assertEqual(meta, [3, 0, 0, 1, 3, 0, 0, 1]) + + def test_repeated_end_primitive_after_dropped_emit_stays_in_bounds(self): + # OutputVertices = 2: emit v_a, emit v_b, EndPrimitive, emit v_c (dropped), EndPrimitive, Return. + gs = _make_gs([ + "%entry = OpLabel", + "OpStore %out_pos %v_a", "OpEmitVertex", + "OpStore %out_pos %v_b", "OpEmitVertex", + "OpEndPrimitive", + "OpStore %out_pos %v_c", "OpEmitVertex", + "OpEndPrimitive", + "OpReturn", + ], max_verts=2) + out, _ = gsc.rewrite(gs) + maybe_validate_spirv(out) + + sentinel_rec = (-1.0, -1.0, -1.0, -1.0) + rec = [sentinel_rec] * 4 + meta = [0xDEAD] * 6 + run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=[], rec_buf=rec, meta_buf=meta) + self.assertEqual(rec[:2], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0)]) + self.assertEqual(meta[:3], [2, 0, 1]) + self.assertEqual(rec[2:], [sentinel_rec, sentinel_rec]) + self.assertEqual(meta[3:], [0xDEAD, 0xDEAD, 0xDEAD]) + + def test_zero_output_vertices_drops_all_emits(self): + gs = _make_gs([ + "%entry = OpLabel", + "OpStore %out_pos %v_a", "OpEmitVertex", + "OpEndPrimitive", + "OpReturn", + ], max_verts=0) + out, lay = gsc.rewrite(gs) + self.assertEqual(lay["max_verts"], 0) + maybe_validate_spirv(out) + + rec = [] + meta = [0x1111, 0x2222] + run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=[], rec_buf=rec, meta_buf=meta) + self.assertEqual(meta, [0, 0x2222]) + + def test_under_emit_preserves_exact_count_and_strip_flags(self): + gs = _make_gs([ + "%entry = OpLabel", + "OpStore %out_pos %v_a", "OpEmitVertex", + "OpEndPrimitive", + "OpStore %out_pos %v_b", "OpEmitVertex", + "OpEndPrimitive", + "OpReturn", + ], max_verts=4) + out, _ = gsc.rewrite(gs) + maybe_validate_spirv(out) + + sentinel_rec = (0.0, 0.0, 0.0, 0.0) + rec = [sentinel_rec] * 8 + meta = [99] * 10 + run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=[], rec_buf=rec, meta_buf=meta) + self.assertEqual(rec[:2], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0)]) + self.assertEqual(rec[2:4], [sentinel_rec, sentinel_rec]) + self.assertEqual(meta[:3], [2, 1, 1]) + self.assertEqual(meta[5:], [99] * 5) + + def test_phi_predecessors_updated_for_entry_and_branch_emits(self): + # %then emits a vertex and branches to %merge; %entry also branches directly to %merge. + # Both %entry and %then are split, so %merge's OpPhi must name their final merge labels. + gs = _make_gs([ + "%entry = OpLabel", + "OpStore %out_pos %v_a", + "OpEmitVertex", + "%cond = OpIEqual %bool %u0 %u0", + "OpSelectionMerge %merge None", + "OpBranchConditional %cond %then %merge", + "%then = OpLabel", + "OpStore %out_pos %v_b", + "OpEmitVertex", + "OpBranch %merge", + "%merge = OpLabel", + "%idx = OpPhi %uint %u1 %then %u0 %entry", + "%p = OpAccessChain %ptr_in_v4 %in_pos %idx", + "%v = OpLoad %v4float %p", + "OpStore %out_pos %v", + "OpEmitVertex", + "OpEndPrimitive", + "OpReturn", + ], max_verts=3) + out, _ = gsc.rewrite(gs) + maybe_validate_spirv(out) + + # Neither %entry nor %then should remain as OpPhi predecessors after splitting. + phi_line = next(ln.strip() for ln in out.splitlines() if "%idx = OpPhi" in ln) + self.assertNotIn(" %entry", phi_line) + self.assertNotIn(" %then", phi_line) + + in_data = [(10.0, 0.0, 0.0, 1.0), (20.0, 0.0, 0.0, 1.0), (30.0, 0.0, 0.0, 1.0)] + rec = [(0.0, 0.0, 0.0, 0.0)] * 3 + meta = [99] * 4 + # Runtime OpPhi predecessor check verifies %merge sees the exact split predecessor label. + run_capture_spvasm(out, gid_x=0, prim_count=1, in_data=in_data, rec_buf=rec, meta_buf=meta) + self.assertEqual(rec, [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0), (20.0, 0.0, 0.0, 1.0)]) + self.assertEqual(meta, [3, 0, 0, 1]) + + def test_loop_over_emit_updates_backedge_phi_and_clamps(self): + # Loop emits 5 times with OutputVertices = 3; %latch contains OpEmitVertex and branches back + # to %hdr whose OpPhi appears BEFORE %latch in the module. + gs = _make_gs([ + "%entry = OpLabel", + "OpBranch %hdr", + "%hdr = OpLabel", + "%i = OpPhi %uint %u0 %entry %i1 %latch", + "%more = OpULessThan %bool %i %u5", + "OpLoopMerge %exit %latch None", + "OpBranchConditional %more %body %exit", + "%body = OpLabel", + "OpBranch %latch", + "%latch = OpLabel", + "OpStore %out_pos %v_a", + "OpEmitVertex", + "%i1 = OpIAdd %uint %i %u1", + "OpBranch %hdr", + "%exit = OpLabel", + "OpEndPrimitive", + "OpReturn", + ], max_verts=3) + out, _ = gsc.rewrite(gs) + maybe_validate_spirv(out) + + phi_line = next(ln.strip() for ln in out.splitlines() if "%i = OpPhi" in ln) + self.assertIn(" %gsc_body", phi_line) + self.assertNotIn(" %latch", phi_line) + + sentinel_rec = (77.0, 77.0, 77.0, 77.0) + rec = [sentinel_rec] * 6 + meta = [0xBEEF] * 8 + run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=[], rec_buf=rec, meta_buf=meta) + self.assertEqual(rec[:3], [(1.0, 0.0, 0.0, 1.0)] * 3) + self.assertEqual(meta[:4], [3, 0, 0, 1]) + self.assertEqual(rec[3:], [sentinel_rec] * 3) + self.assertEqual(meta[4:], [0xBEEF] * 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_spirv_interp_bits.py b/tests/test_spirv_interp_bits.py index ad09f7b2d..06c85d7e4 100644 --- a/tests/test_spirv_interp_bits.py +++ b/tests/test_spirv_interp_bits.py @@ -6,6 +6,7 @@ tests/semantic/spirv_mini_interp.py). Hand-written SPIR-V only, standard library only. No translator, no game data. """ import os +import struct import sys import unittest @@ -89,5 +90,34 @@ class BitcastKeepsBits(unittest.TestCase): self.assertEqual(si.f2u(1.5), 0x3FC00000) # a plain float still converts as before +class HalfNanRuleTests(unittest.TestCase): + """si.half_to_float / si.float_to_half pin one NaN rule on every Python version. + + struct's ' double keeps it on every version) canonicalizes too + payload = struct.unpack(" infinity + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_spirv_interp_signs.py b/tests/test_spirv_interp_signs.py new file mode 100644 index 000000000..e703a752e --- /dev/null +++ b/tests/test_spirv_interp_signs.py @@ -0,0 +1,141 @@ +"""tests/spirv_interp.py holds an integer as its 32-bit pattern, whatever the signedness of its type. + + python -I tests/test_spirv_interp_signs.py + +SPIR-V defines the signed and unsigned instructions on the bits of their operands, not on the operand types: OpSLess* +of two uint values compares them as signed, and OpULess*, OpShiftRightLogical and OpConvertUToF of an int value +read it as unsigned. The interpreter used to keep a value of a signed type as a negative Python int and a value of +an unsigned type as a non-negative one, and used both raw, so every case below where the instruction and the type +disagree gave the wrong word. Also here: x / -0.0, which returned +inf for a positive x. + +Hand-written SPIR-V only, standard library only. No translator, no game data. +""" +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import spirv_interp as si # noqa: E402 + +MODULE = """\ +OpCapability Shader +%glsl = OpExtInstImport "GLSL.std.450" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" +%void = OpTypeVoid +%fn = OpTypeFunction %void +%bool = OpTypeBool +%uint = OpTypeInt 32 0 +%int = OpTypeInt 32 1 +%float = OpTypeFloat 32 +%c0 = OpConstant %uint 0 +%c1 = OpConstant %uint 1 +%c4 = OpConstant %uint 4 +%c8 = OpConstant %uint 8 +%c31 = OpConstant %uint 31 +%umin = OpConstant %uint 2147483648 +%umax = OpConstant %uint 4294967295 +%im8 = OpConstant %int -8 +%i1 = OpConstant %int 1 +%imin = OpConstant %int -2147483648 +%f1 = OpConstant %float 1 +%fm1 = OpConstant %float -1 +%f0 = OpConstant %float 0 +%fm0 = OpConstant %float -0.0 +%fbig = OpConstant %float -3e9 +%arr = OpTypeArray %uint %c4 +%null = OpConstantNull %arr +%_ptr_Function_arr = OpTypePointer Function %arr +%_ptr_Function_uint = OpTypePointer Function %uint +%vgpr = OpVariable %_ptr_Function_arr Function %null +%sgpr = OpVariable %_ptr_Function_arr Function %null +%main = OpFunction %void None %fn +%entry = OpLabel +{body}OpReturn +OpFunctionEnd +""" +STORE = "%p = OpAccessChain %_ptr_Function_uint %vgpr %c0\nOpStore %p %r\n" + + +def word(body): + """v0 after `body`, which leaves a uint, int or float in %r (a float is stored as its bits).""" + return si.run(MODULE.format(body=body + STORE)).vgpr[0] + + +def flag(compare): + return word(f"%c = {compare}\n%r = OpSelect %uint %c %c1 %c0\n") + + +def fbits(expr): + return word(f"%d = {expr}\n%r = OpBitcast %uint %d\n") + + +class SignedInstructionsOnUnsignedValues(unittest.TestCase): + def test_signed_compares_read_the_bits_as_signed(self): + # 0x80000000 is INT_MIN and 0xffffffff is -1 to a signed compare, whatever the type says. + self.assertEqual(flag("OpSLessThanEqual %bool %umin %c1"), 1) + self.assertEqual(flag("OpSGreaterThanEqual %bool %umin %c1"), 0) + self.assertEqual(flag("OpSLessThanEqual %bool %c1 %umax"), 0) + self.assertEqual(flag("OpSGreaterThanEqual %bool %c0 %umax"), 1) + self.assertEqual(flag("OpSLessThanEqual %bool %im8 %i1"), 1) # unchanged: -8 <= 1 + self.assertEqual(flag("OpSGreaterThanEqual %bool %umax %umax"), 1) # equal + + def test_smin_smax(self): + # min(INT_MIN, 1) and max(-1, 1), as bit patterns. + self.assertEqual(word("%r = OpExtInst %uint %glsl SMin %umin %c1\n"), 0x80000000) + self.assertEqual(word("%r = OpExtInst %uint %glsl SMax %umax %c1\n"), 1) + self.assertEqual(word("%r = OpExtInst %int %glsl SMin %im8 %i1\n"), 0xFFFFFFF8) + self.assertEqual(word("%r = OpExtInst %uint %glsl UMax %umax %c1\n"), 0xFFFFFFFF) + + +class UnsignedInstructionsOnSignedValues(unittest.TestCase): + def test_logical_shift_right(self): + # -8 is 0xfffffff8: a logical shift brings in zeros. + self.assertEqual(word("%r = OpShiftRightLogical %int %im8 %c1\n"), 0x7FFFFFFC) + self.assertEqual(word("%r = OpShiftRightLogical %int %imin %c31\n"), 1) + self.assertEqual(word("%r = OpShiftRightArithmetic %int %im8 %c1\n"), 0xFFFFFFFC) # unchanged + + def test_unsigned_compares(self): + self.assertEqual(flag("OpULessThan %bool %im8 %c1"), 0) # 0xfffffff8 < 1 is false + self.assertEqual(flag("OpUGreaterThan %bool %im8 %c1"), 1) + self.assertEqual(flag("OpULessThanEqual %bool %imin %umax"), 1) + self.assertEqual(flag("OpUGreaterThanEqual %bool %i1 %im8"), 0) + self.assertEqual(flag("OpIEqual %bool %im8 %im8"), 1) + + def test_convert_to_float(self): + self.assertEqual(fbits("OpConvertUToF %float %im8"), 0x4F800000) # 4294967288 rounds to 2^32 + self.assertEqual(fbits("OpConvertSToF %float %im8"), 0xC1000000) # -8.0 + self.assertEqual(fbits("OpConvertSToF %float %umax"), 0xBF800000) # -1.0 + self.assertEqual(fbits("OpConvertUToF %float %umax"), 0x4F800000) + + def test_results_are_bit_patterns(self): + # A negative result of a signed-typed instruction leaves as its 32-bit pattern and can feed any instruction. + self.assertEqual(word("%r = OpConvertFToS %int %fm1\n"), 0xFFFFFFFF) + self.assertEqual(word("%r = OpConvertFToS %int %fbig\n"), 0x80000000) # saturates at INT_MIN + self.assertEqual(word("%r = OpBitFieldSExtract %int %umax %c0 %c8\n"), 0xFFFFFFFF) + self.assertEqual(word("%x = OpBitFieldSExtract %int %umax %c0 %c8\n" + "%r = OpShiftRightLogical %int %x %c1\n"), 0x7FFFFFFF) + self.assertEqual(word("%x = OpBitcast %int %fm1\n%r = OpShiftRightLogical %int %x %c1\n"), 0x5FC00000) + self.assertEqual(word("%x = OpConvertFToS %int %fm1\n%c = OpULessThan %bool %x %c1\n" + "%r = OpSelect %uint %c %c1 %c0\n"), 0) + self.assertEqual(word("%r = OpIAdd %int %im8 %i1\n"), 0xFFFFFFF9) + self.assertEqual(word("%r = OpNot %int %im8\n"), 7) + + +class DivisionByZero(unittest.TestCase): + def test_sign_of_the_infinity(self): + self.assertEqual(fbits("OpFDiv %float %f1 %f0"), 0x7F800000) + self.assertEqual(fbits("OpFDiv %float %f1 %fm0"), 0xFF800000) + self.assertEqual(fbits("OpFDiv %float %fm1 %f0"), 0xFF800000) + self.assertEqual(fbits("OpFDiv %float %fm1 %fm0"), 0x7F800000) + + def test_zero_over_zero_is_a_nan(self): + for expr in ("OpFDiv %float %f0 %f0", "OpFDiv %float %fm0 %f0", "OpFDiv %float %f0 %fm0"): + with self.subTest(expr=expr): + w = fbits(expr) + self.assertEqual(w & 0x7F800000, 0x7F800000) + self.assertNotEqual(w & 0x007FFFFF, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_spirv_opt.py b/tests/test_spirv_opt.py new file mode 100644 index 000000000..71b3ada34 --- /dev/null +++ b/tests/test_spirv_opt.py @@ -0,0 +1,421 @@ +"""Tests for tools/spirv_opt.py (sound basic-block SPIR-V peephole optimizer, #884).""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = os.path.join(ROOT, "tools") +SEMANTIC = os.path.join(ROOT, "tests", "semantic") +for _p in (TOOLS, SEMANTIC): + if _p not in sys.path: + sys.path.insert(0, _p) + +import rdna2spirv # noqa: E402 +import spirv_opt # noqa: E402 +import support # noqa: E402 + +SPIRV_AS = shutil.which("spirv-as") +SPIRV_VAL = shutil.which("spirv-val") + + +def _validate(spvasm: str) -> None: + if not (SPIRV_AS and SPIRV_VAL): + return + with tempfile.TemporaryDirectory() as d: + sa, sv = os.path.join(d, "m.spvasm"), os.path.join(d, "m.spv") + with open(sa, "w", encoding="utf-8", newline="\n") as f: + f.write(spvasm) + for cmd in ( + [SPIRV_AS, sa, "-o", sv, "--target-env", "vulkan1.2"], + [SPIRV_VAL, "--target-env", "vulkan1.2", "--allow-offset-texture-operand", sv], + ): + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + raise AssertionError(f"{cmd[0]} failed:\n{r.stderr}") + + +class SpirvOptTests(unittest.TestCase): + def test_alu_chain_bit_exact_and_shrinks_significantly(self): + lines = [ + "v_mov_b32_e32 v1, 0x01020304", + "v_mov_b32_e32 v2, 0x05060708", + "v_mov_b32_e32 v3, 0x000003e8", + "v_dot4_i32_i8 v8, v1, v2, v3", + "v_dot4c_i32_i8 v8, v1, v2", + "v_add_f32_e32 v9, v8, 1.0", + "v_mul_f32_e32 v10, v9, 2.0", + "exp mrt0 v8, v9, v10, v8 done vm", + "s_endpgm", + ] + raw = support.translate_lines("ps_opt_alu", lines) + opt = spirv_opt.optimize(raw) + _validate(opt) + self.assertEqual(support.mrt0_words(opt), support.mrt0_words(raw)) + # Straight-line ALU chain should shed >50% of its lines (register traffic, %active loads, round-trip bitcasts, + # unused push-constant prologue loads, and duplicate pure expressions). + self.assertLess(len(opt.splitlines()), len(raw.splitlines()) * 0.5) + self.assertNotIn("OpLoad %bool %active", opt) + + def test_dynamic_register_indexing_preserved_soundly(self): + # v_movrels_b32 / s_movrels_b32 use dynamic OpAccessChain into %vgpr / %sgpr; optimizer must NOT + # drop stores or forward stale values across dynamic accesses. + lines = [ + "v_mov_b32_e32 v1, 0x11111111", + "v_mov_b32_e32 v2, 0x22222222", + "v_mov_b32_e32 v3, 0x33333333", + "s_mov_b32 m0, 1", + "v_movrels_b32_e32 v8, v1", # reads v[1 + 1] = v2 = 0x22222222 + "s_mov_b32 m0, 2", + "v_movrels_b32_e32 v9, v1", # reads v[1 + 2] = v3 = 0x33333333 + "v_movreld_b32_e32 v1, v8", # writes v[1 + 2] = v3 = 0x22222222 + "v_mov_b32_e32 v10, v3", # must observe the dynamic write -> 0x22222222, NOT stale 0x33333333! + "exp mrt0 v8, v9, v10, v2 done vm", + "s_endpgm", + ] + raw = support.translate_lines("ps_opt_dyn_reg", lines) + opt = spirv_opt.optimize(raw) + _validate(opt) + expected = [0x22222222, 0x33333333, 0x22222222, 0x22222222] + self.assertEqual(support.mrt0_words(raw), expected) + self.assertEqual(support.mrt0_words(opt), expected) + + def test_control_flow_and_exec_masking_preserved(self): + # Branches + exec masking across blocks: intra-block forwarding must reset at OpLabel boundaries. + lines = [ + "v_mov_b32_e32 v1, 10 ; encoding: [0x8a,0x02,0x02,0x7e]", + "v_mov_b32_e32 v2, 20 ; encoding: [0x94,0x02,0x04,0x7e]", + "v_mov_b32_e32 v8, 0 ; encoding: [0x80,0x02,0x10,0x7e]", + "s_mov_b32 s4, 0 ; encoding: [0x80,0x03,0x84,0xbe]", + "s_cmp_eq_u32 s4, 0 ; encoding: [0x04,0x80,0x06,0xbf]", + "s_cbranch_scc0 2 ; encoding: [0x02,0x00,0x84,0xbf]", + "v_add_nc_u32_e32 v8, v1, v2 ; encoding: [0x01,0x05,0x10,0x4a]", + "s_branch 1 ; encoding: [0x01,0x00,0x82,0xbf]", + "v_sub_nc_u32_e32 v8, v2, v1 ; encoding: [0x02,0x03,0x10,0x4c]", + "v_add_nc_u32_e32 v9, v8, 5 ; encoding: [0x85,0x10,0x12,0x4a]", + "exp mrt0 v8, v9, v1, v2 done vm ; encoding: [0x0f,0x18,0x00,0xf8,0x08,0x09,0x01,0x02]", + "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", + ] + raw = support.translate_lines("ps_opt_cf", lines) + opt = spirv_opt.optimize(raw) + _validate(opt) + self.assertEqual(support.mrt0_words(opt), support.mrt0_words(raw)) + self.assertEqual(support.mrt0_words(opt), [30, 35, 10, 20]) + # Non-divergent scalar-branch shader never stores %active: cross-block read-only propagation eliminates + # every OpLoad %bool %active and the dead %active OpVariable across all blocks. + self.assertNotIn("OpLoad %bool %active", opt) + self.assertNotIn("%active = OpVariable", opt) + + def test_cross_block_constant_folding_and_dead_func_vars(self): + # Constant integer/bit folding + algebraic identities across straight-line ALU. + lines = [ + "v_mov_b32_e32 v1, 2", + "v_lshlrev_b32_e32 v2, 2, v1", # 2 << (2 & 0x1f) -> folds (2 & 0x1f) and shift + "v_add_nc_u32_e32 v3, v2, 0", # + 0 identity + "v_xor_b32_e32 v4, v3, v3", # x ^ x -> 0 + "v_or_b32_e32 v5, v3, 0", # | 0 identity + "exp mrt0 v2, v3, v4, v5 done vm", + "s_endpgm", + ] + raw = support.translate_lines("ps_opt_fold", lines) + opt = spirv_opt.optimize(raw) + _validate(opt) + self.assertEqual(support.mrt0_words(opt), [8, 8, 0, 8]) + self.assertNotIn("OpBitwiseXor", opt) + self.assertNotIn("OpIAdd", opt) + # Unused Function-scope variables (%m0, %scc, %active, etc.) should be removed. + self.assertNotIn("%m0 = OpVariable", opt) + self.assertNotIn("%active = OpVariable", opt) + + def test_trivial_phi_and_dominator_cse_in_loop(self): + # Hand-crafted SPIR-V module exercising trivial OpPhi (identical incoming + self-loop) and + # dominator-tree OpAccessChain + Input OpLoad CSE across a structured loop. + spvasm = """ OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %in0 %out0 + OpExecutionMode %main OriginUpperLeft + OpDecorate %in0 Location 0 + OpDecorate %in0 Flat + OpDecorate %out0 Location 0 + %void = OpTypeVoid + %fn = OpTypeFunction %void + %bool = OpTypeBool + %uint = OpTypeInt 32 0 + %v4uint = OpTypeVector %uint 4 + %_ptr_In = OpTypePointer Input %uint + %_ptr_Out = OpTypePointer Output %v4uint + %_ptr_Fun = OpTypePointer Function %uint + %c0 = OpConstant %uint 0 + %c1 = OpConstant %uint 1 + %c4 = OpConstant %uint 4 + %true = OpConstantTrue %bool + %false = OpConstantFalse %bool + %in0 = OpVariable %_ptr_In Input + %out0 = OpVariable %_ptr_Out Output + %main = OpFunction %void None %fn + %entry = OpLabel + %local = OpVariable %_ptr_Fun Function %c0 + %v0 = OpLoad %uint %in0 + OpStore %local %v0 + OpBranch %head + %head = OpLabel + %phi = OpPhi %uint %v0 %entry %phi %cont + %i = OpPhi %uint %c0 %entry %inext %cont + OpLoopMerge %exit %cont None + OpBranch %body + %body = OpLabel + %v1 = OpLoad %uint %in0 + %sum = OpIAdd %uint %phi %v1 + %cond = OpULessThan %bool %i %c4 + OpSelectionMerge %merge None + OpBranchConditional %cond %cont %exit + %merge = OpLabel + OpUnreachable + %cont = OpLabel + %inext = OpIAdd %uint %i %c1 + OpBranch %head + %exit = OpLabel + %res = OpCompositeConstruct %v4uint %phi %v0 %c0 %c1 + OpStore %out0 %res + OpReturn + OpFunctionEnd +""" + _validate(spvasm) + opt = spirv_opt.optimize(spvasm) + _validate(opt) + # Trivial self-referential %phi must collapse to %v0, duplicate %v1 = OpLoad %in0 CSEs to %v0, + # dead %sum and dead %local OpVariable are eliminated. + self.assertNotIn("%phi = OpPhi", opt) + self.assertEqual(opt.count("OpLoad %uint %in0"), 1) + self.assertNotIn("%local = OpVariable", opt) + self.assertNotIn("%sum = OpIAdd", opt) + + def test_alias_signed_unsigned_index_volatile_and_aggregate_overlap(self): + # Regression tests for standalone memory aliasing cases (PR #2298 review): + # 1) Store 1 via %uint 0, store 2 via %int 0, load via first pointer -> must observe 2, not 1. + # 2) Store 1, Volatile store 2, ordinary load -> must NOT forward stale 1. + # 3) Store 1, Volatile load, store 2 -> must NOT kill store 1 before volatile load. + # 4) Store element 0 = 1, store whole array = {2, 2}, load element 0 -> must NOT forward stale 1. + spv_idx = """ OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %out0 + OpExecutionMode %main OriginUpperLeft + OpDecorate %out0 Location 0 + %void = OpTypeVoid + %fn = OpTypeFunction %void + %uint = OpTypeInt 32 0 + %int = OpTypeInt 32 1 + %c2 = OpConstant %uint 2 + %arr = OpTypeArray %uint %c2 + %v4uint = OpTypeVector %uint 4 + %_ptr_Fa = OpTypePointer Function %arr + %_ptr_Fu = OpTypePointer Function %uint + %_ptr_Out = OpTypePointer Output %v4uint + %u0 = OpConstant %uint 0 + %s0 = OpConstant %int 0 + %u1 = OpConstant %uint 1 + %u2 = OpConstant %uint 2 + %out0 = OpVariable %_ptr_Out Output + %main = OpFunction %void None %fn + %entry = OpLabel + %a = OpVariable %_ptr_Fa Function + %p0 = OpAccessChain %_ptr_Fu %a %u0 + %p1 = OpAccessChain %_ptr_Fu %a %s0 + OpStore %p0 %u1 + OpStore %p1 %u2 + %r = OpLoad %uint %p0 + %vec = OpCompositeConstruct %v4uint %r %u0 %u0 %u0 + OpStore %out0 %vec + OpReturn + OpFunctionEnd +""" + _validate(spv_idx) + opt_idx = spirv_opt.optimize(spv_idx) + _validate(opt_idx) + self.assertIn("OpCompositeConstruct %v4uint %u2 %u0 %u0 %u0", opt_idx) + + spv_vol_store = """ OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %out0 + OpExecutionMode %main OriginUpperLeft + OpDecorate %out0 Location 0 + %void = OpTypeVoid + %fn = OpTypeFunction %void + %uint = OpTypeInt 32 0 + %v4uint = OpTypeVector %uint 4 + %_ptr_Fu = OpTypePointer Function %uint + %_ptr_Out = OpTypePointer Output %v4uint + %u0 = OpConstant %uint 0 + %u1 = OpConstant %uint 1 + %u2 = OpConstant %uint 2 + %out0 = OpVariable %_ptr_Out Output + %main = OpFunction %void None %fn + %entry = OpLabel + %x = OpVariable %_ptr_Fu Function + OpStore %x %u1 + OpStore %x %u2 Volatile + %r = OpLoad %uint %x + %vec = OpCompositeConstruct %v4uint %r %u0 %u0 %u0 + OpStore %out0 %vec + OpReturn + OpFunctionEnd +""" + _validate(spv_vol_store) + opt_vs = spirv_opt.optimize(spv_vol_store) + _validate(opt_vs) + self.assertIn("OpStore %x %u2 Volatile", opt_vs) + self.assertIn("%r = OpLoad %uint %x", opt_vs) + self.assertIn("OpCompositeConstruct %v4uint %r %u0 %u0 %u0", opt_vs) + + spv_vol_load = """ OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %out0 + OpExecutionMode %main OriginUpperLeft + OpDecorate %out0 Location 0 + %void = OpTypeVoid + %fn = OpTypeFunction %void + %uint = OpTypeInt 32 0 + %v4uint = OpTypeVector %uint 4 + %_ptr_Fu = OpTypePointer Function %uint + %_ptr_Out = OpTypePointer Output %v4uint + %u0 = OpConstant %uint 0 + %u1 = OpConstant %uint 1 + %u2 = OpConstant %uint 2 + %out0 = OpVariable %_ptr_Out Output + %main = OpFunction %void None %fn + %entry = OpLabel + %x = OpVariable %_ptr_Fu Function + OpStore %x %u1 + %r = OpLoad %uint %x Volatile + OpStore %x %u2 + %vec = OpCompositeConstruct %v4uint %r %u0 %u0 %u0 + OpStore %out0 %vec + OpReturn + OpFunctionEnd +""" + _validate(spv_vol_load) + opt_vl = spirv_opt.optimize(spv_vol_load) + _validate(opt_vl) + self.assertIn("OpStore %x %u1", opt_vl) + self.assertIn("%r = OpLoad %uint %x Volatile", opt_vl) + self.assertIn("OpStore %x %u2", opt_vl) + + spv_agg = """ OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %out0 + OpExecutionMode %main OriginUpperLeft + OpDecorate %out0 Location 0 + %void = OpTypeVoid + %fn = OpTypeFunction %void + %uint = OpTypeInt 32 0 + %c2 = OpConstant %uint 2 + %arr = OpTypeArray %uint %c2 + %v4uint = OpTypeVector %uint 4 + %_ptr_Fa = OpTypePointer Function %arr + %_ptr_Fu = OpTypePointer Function %uint + %_ptr_Out = OpTypePointer Output %v4uint + %u0 = OpConstant %uint 0 + %u1 = OpConstant %uint 1 + %u2 = OpConstant %uint 2 + %a22 = OpConstantComposite %arr %u2 %u2 + %out0 = OpVariable %_ptr_Out Output + %main = OpFunction %void None %fn + %entry = OpLabel + %a = OpVariable %_ptr_Fa Function + %p0 = OpAccessChain %_ptr_Fu %a %u0 + OpStore %p0 %u1 + OpStore %a %a22 + %r = OpLoad %uint %p0 + %vec = OpCompositeConstruct %v4uint %r %u0 %u0 %u0 + OpStore %out0 %vec + OpReturn + OpFunctionEnd +""" + _validate(spv_agg) + opt_agg = spirv_opt.optimize(spv_agg) + _validate(opt_agg) + self.assertIn("OpStore %a %a22", opt_agg) + self.assertIn("%r = OpLoad %uint %p0", opt_agg) + self.assertIn("OpCompositeConstruct %v4uint %r %u0 %u0 %u0", opt_agg) + + def test_wave64_emulated_compute_validates_and_shrinks(self): + cs_lines = [ + "s_load_dwordx2 s[4:5], s[0:1], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32_e32 v1, 0x3f800000", + "v_add_f32_e32 v2, v1, 2.0", + "v_mul_f32_e32 v3, v2, 3.0", + "v_lshlrev_b32_e32 v4, 2, v0", + "ds_write_b32 v4, v3", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "ds_read_b32 v5, v4", + "s_waitcnt lgkmcnt(0)", + "v_cmp_lt_u32_e64 vcc, v0, 32", + "v_cndmask_b32_e64 v6, v5, v3, vcc", + "global_store_dword v4, v6, s[4:5]", + "s_endpgm", + ] + with tempfile.TemporaryDirectory() as d: + os.makedirs(os.path.join(d, "disasm")) + os.makedirs(os.path.join(d, "fspx")) + s_path = os.path.join(d, "disasm", "cs_opt_w64.s") + with open(s_path, "w", encoding="utf-8", newline="\n") as f: + f.write("; cs_opt_w64 code 0x0..0x100, gfx1013, 0 invalid words\n") + for ln in cs_lines: + f.write(f"\t{ln} ; encoding: [0x00,0x00,0x00,0x00]\n") + with open(os.path.join(d, "fspx", "cs_opt_w64.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump({"rsrc2": (8 << 1) | (16 << 15), "threads": [64, 1, 1]}, f) + old_w64, old_opt = rdna2spirv.WAVE64_EMULATE, rdna2spirv.OPT_SPIRV + try: + rdna2spirv.WAVE64_EMULATE = True + rdna2spirv.OPT_SPIRV = False + raw = rdna2spirv.translate(s_path) + rdna2spirv.OPT_SPIRV = True + opt = rdna2spirv.translate(s_path) + finally: + rdna2spirv.WAVE64_EMULATE, rdna2spirv.OPT_SPIRV = old_w64, old_opt + _validate(opt) + self.assertLess(len(opt.splitlines()), len(raw.splitlines())) + + def test_decorations_on_deleted_ids_removed_and_surviving_kept(self): + # Deleting a dead NoContraction float op must also drop its OpDecorate line so spirv-val stays clean, + # while a live NoContraction float op keeps its OpDecorate. + lines = [ + "v_mov_b32_e32 v1, 1.0", + "v_add_f32_e32 v2, v1, 2.0", # dead: overwritten below before any read + "v_mul_f32_e32 v2, v1, 3.0", # live: exported + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ] + raw = support.translate_lines("ps_opt_dec", lines) + opt = spirv_opt.optimize(raw) + _validate(opt) + self.assertEqual(support.mrt0_words(opt), support.mrt0_words(raw)) + self.assertIn("NoContraction", opt) + # Dead OpFAdd must be gone along with its decoration. + self.assertNotIn("OpFAdd", opt) + + def test_cli_round_trip(self): + raw = support.translate_lines("ps_opt_cli", [ + "v_mov_b32_e32 v1, 42", + "exp mrt0 v1, v1, v1, v1 done vm", + "s_endpgm", + ]) + with tempfile.TemporaryDirectory() as d: + src, dst = os.path.join(d, "in.spvasm"), os.path.join(d, "out.spvasm") + with open(src, "w", encoding="utf-8", newline="\n") as f: + f.write(raw) + rc = spirv_opt.main([src, "-o", dst]) + self.assertEqual(rc, 0) + with open(dst, encoding="utf-8") as f: + opt = f.read() + _validate(opt) + self.assertEqual(support.mrt0_words(opt), [42] * 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_swizzle_search.py b/tests/test_swizzle_search.py index 81eabf904..2b1a1e94a 100644 --- a/tests/test_swizzle_search.py +++ b/tests/test_swizzle_search.py @@ -4,6 +4,8 @@ """ from __future__ import annotations +import importlib.util +import io import itertools import os from pathlib import Path @@ -11,6 +13,7 @@ import subprocess import sys import tempfile import unittest +from unittest import mock ROOT = Path(__file__).resolve().parents[1] TOOLS_DIR = ROOT / "tools" @@ -390,6 +393,7 @@ class TestSwizzleSearchCliAndRender(unittest.TestCase): """Bad --bpe/--tile/--widths/--tiles must be usage errors, not arithmetic tracebacks.""" cases = [ (["--bpe", "0"], "--bpe must be at least 1"), + (["--bpe", "4"], "--bpe must be 8 or 16"), (["--tile", "0"], "--tile must be a multiple"), (["--tile", "1"], "--tile must be a multiple"), (["--tile", "3"], "--tile must be a multiple"), @@ -551,6 +555,103 @@ class TestSwizzleSearchCliAndRender(unittest.TestCase): self.assertEqual(header, b"\x89PNG\r\n\x1a\n") +def _load_swizzle_search_no_numpy(): + if HAVE_NUMPY: + return swizzle_search + spec = importlib.util.spec_from_file_location("swizzle_search_out_guard_test", str(TOOL)) + mod = importlib.util.module_from_spec(spec) + with mock.patch.dict(sys.modules, {"numpy": mock.MagicMock()}): + spec.loader.exec_module(mod) + return mod + + +class TestSwizzleSearchOutGuard(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.mod = _load_swizzle_search_no_numpy() + + def test_bad_out_paths_fail_before_search(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + blob = root / "blob.bin" + blob.write_bytes(bytes(64)) + existing_dir = root / "outdir" + existing_dir.mkdir() + regular_file = root / "notadir.txt" + regular_file.write_text("x", encoding="utf-8") + + bad_outs = ( + "", + " ", + "bad\x00out.png", + str(existing_dir), + str(root / "trailing") + os.sep, + str(regular_file / "sub" / "preview.png"), + ) + for bad in bad_outs: + with self.subTest(out=bad): + err = io.StringIO() + with mock.patch.object(self.mod, "search") as mock_search: + with mock.patch.object(sys, "stderr", err): + rc = self.mod.main([str(blob), "--out", bad]) + self.assertEqual(rc, 2) + mock_search.assert_not_called() + self.assertIn("ERROR:", err.getvalue()) + self.assertNotIn("Traceback", err.getvalue()) + + def test_valid_nested_out_creates_parent_dirs_and_handles_render_oserror(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + blob = root / "blob.bin" + blob.write_bytes(bytes(512)) + nested_out = root / "nested" / "sub" / "preview.png" + + with mock.patch.object(self.mod, "search", return_value=[(1.0, 64, "xyxy")]), \ + mock.patch.object(self.mod, "render") as mock_render: + rc = self.mod.main([str(blob), "--bpe", "8", "--tile", "128", "--widths", "64", "--out", str(nested_out)]) + self.assertIn(rc, (0, None)) + self.assertTrue((root / "nested" / "sub").is_dir()) + mock_render.assert_called_once() + + err = io.StringIO() + with mock.patch.object(self.mod, "search", return_value=[(1.0, 64, "xyxy")]), \ + mock.patch.object(self.mod, "render", side_effect=PermissionError("denied")), \ + mock.patch.object(sys, "stderr", err): + rc_err = self.mod.main([str(blob), "--bpe", "8", "--tile", "128", "--widths", "64", "--out", str(nested_out)]) + self.assertEqual(rc_err, 2) + self.assertIn("ERROR:", err.getvalue()) + self.assertIn("denied", err.getvalue()) + self.assertNotIn("Traceback", err.getvalue()) + + def test_nested_out_does_not_create_dirs_when_blob_missing(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + missing_blob = root / "missing.bin" + nested_out = root / "never_created" / "sub" / "preview.png" + err = io.StringIO() + with mock.patch.object(sys, "stderr", err): + rc = self.mod.main([str(missing_blob), "--out", str(nested_out)]) + self.assertEqual(rc, 2) + self.assertFalse((root / "never_created").exists()) + self.assertIn("ERROR:", err.getvalue()) + + def test_render_valueerror_unknown_extension_returns_exit_2(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + blob = root / "blob.bin" + blob.write_bytes(bytes(512)) + bad_ext_out = root / "preview.unrecognized" + err = io.StringIO() + with mock.patch.object(self.mod, "search", return_value=[(1.0, 64, "xyxy")]), \ + mock.patch.object(self.mod, "render", side_effect=ValueError("unknown file extension: .unrecognized")), \ + mock.patch.object(sys, "stderr", err): + rc = self.mod.main([str(blob), "--bpe", "8", "--tile", "128", "--widths", "64", "--out", str(bad_ext_out)]) + self.assertEqual(rc, 2) + self.assertIn("ERROR:", err.getvalue()) + self.assertIn("unknown file extension: .unrecognized", err.getvalue()) + self.assertNotIn("Traceback", err.getvalue()) + + def test_preview_with_no_fitting_layout_reports_the_problem(tmp_path=None): """Module-level compatibility wrapper for pytest with tmp_path fixture.""" if not HAVE_NUMPY: diff --git a/tests/test_tex_export.py b/tests/test_tex_export.py index 0f2617a02..60222ce4d 100644 --- a/tests/test_tex_export.py +++ b/tests/test_tex_export.py @@ -293,6 +293,26 @@ def test_blob_cache_is_reused_for_the_same_blob(eq, tmp_path): assert T.export_one(t2, carve, str(tmp_path / "out"), cache) == "ok:first" +def test_blob_cache_distinguishes_different_gpu_chains_at_same_offset(eq, tmp_path): + carve, expected = build_case(eq, tmp_path, 10, top_first=True) + with open(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin"), "rb") as f: + blob = f.read() + os.remove(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin")) + cut = 12345 + write_blob(carve, "x.rpf", 0x1000, blob[:cut]) + write_blob(carve, "x.rpf", 0x9000, blob[cut:]) + cache = {} + out = str(tmp_path / "out") + short = texture(10, "R16G16B16A16_FLOAT", 16, 16, mips=1, gpu=0x1000, gpu_size=cut) + assert T.export_one(short, carve, out, cache) == "ok:first" + chained = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2, q_index=4, + gpu=0x1000, gpu_size=len(blob), + gpu_chain=[[0x1000, cut], [0x9000, len(blob) - cut]]) + assert T.export_one(chained, carve, out, cache) == "ok:first" + with open(os.path.join(out, "x.rpf", chained["export"]["file"]), "rb") as f: + assert f.read()[148:] == expected + + @pytest.mark.parametrize("fmt", [9999, 6, 7, 8]) # 6-8: 12-byte R32G32B32 has no SW_4K_S equation def test_unsupported_format_is_reported(fmt): assert T.export_one(texture(fmt, "X", 4, 4, 1), "unused", "unused", {}) == "unsupported format" diff --git a/tests/test_tex_headers.py b/tests/test_tex_headers.py index 60512535f..0232d5d08 100644 --- a/tests/test_tex_headers.py +++ b/tests/test_tex_headers.py @@ -988,5 +988,206 @@ class CliInputTest(unittest.TestCase): self.assertNotIn("Traceback", p.stderr) +class TestTextureDictionaryParsing(unittest.TestCase): + def _create_synthetic_page(self, name0=b"waterfog2", name1=b"waterfog", fmt=95, w=128, h=128, mips=1, b6=7): + buf = bytearray(400) + names_chunk = name0 + b"\x00" + name1 + b"\x00" + buf[0x140:0x140 + len(names_chunk)] = names_chunk + struct.pack_into("> 16) is 5 + data = self._create_synthetic_page(mips=5, b6=42) + res = tex_headers.parse_texture_dict_page(data) + self.assertEqual(len(res), 2) + self.assertEqual(res[0]["b6"], 42) + self.assertEqual(res[0]["mips"], 5) + self.assertEqual(res[1]["b6"], 42) + self.assertEqual(res[1]["mips"], 5) + + def test_truncated_buffer_raises_value_error(self): + with self.assertRaises(ValueError): + tex_headers.parse_texture_dict_page(b"\x00" * 399) + + def test_all_zeros_returns_empty_list(self): + # Null pointers return no texture records + res = tex_headers.parse_texture_dict_page(b"\x00" * 400) + self.assertEqual(res, []) + + def test_invalid_pointer_tag_skipped(self): + buf = bytearray(self._create_synthetic_page()) + # Pointer without 0x5... tag (e.g. 0x10000040) + struct.pack_into("_e64 s10, v1, v2` + self.assertEqual(le_bytes(*p.words("lt", "f16", (0, 0))), [0x0A, 0x00, 0xC9, 0xD4, 0x01, 0x05, 0x02, 0x00]) + self.assertEqual(le_bytes(*p.words("gt", "u16", (0, 0))), [0x0A, 0x00, 0xAC, 0xD4, 0x01, 0x05, 0x02, 0x00]) + self.assertEqual(le_bytes(*p.words("lt", "i16", (0, 0))), [0x0A, 0x00, 0x89, 0xD4, 0x01, 0x05, 0x02, 0x00]) + # `v_cmp_lt_f16_e64 s10, -v1, v2` + self.assertEqual(le_bytes(*p.words("lt", "f16", (0, 0), True))[7], 0x20) + + def test_opsel_sits_where_llvm_mc_puts_it_on_v_add_nc_u16(self): + # llvm-mc for `v_add_nc_u16 v0, v1, v2 op_sel:[1,0,0]` / [0,1,0] / [1,1,0]: byte 1 = 0x08 / 0x10 / 0x18 + self.assertEqual(p.OPSEL_SRC0 >> 8, 0x08) + self.assertEqual(p.OPSEL_SRC1 >> 8, 0x10) + self.assertEqual(le_bytes(*p.words("lt", "f16", (1, 1)))[1], 0x18) # the finding's d4c9180a + + def test_control_answers(self): + self.assertEqual(p.control_answer((0, 0), True), 0x000C) + self.assertEqual(p.control_answer((1, 1), True), 0x0340) + self.assertEqual({p.control_answer(s, False) for _n, s in p.control_rows()}, {0x000C}) + + +class RowsTest(unittest.TestCase): + def test_names_are_unique(self): + rows = p.rows() + self.assertEqual(len({r[0] for r in rows}), len(rows)) + + def test_every_kind_and_opsel_bit_has_a_row_that_tells_the_hypotheses_apart(self): + telling = [r for r in p.rows() if p.answer(r, True) != p.answer(r, False)] + for kind in ("f16", "u16", "i16"): + for opsel in ((1, 0), (0, 1), (1, 1)): + with self.subTest(kind=kind, opsel=opsel): + self.assertTrue(any(r[2] == kind and r[4] == opsel for r in telling)) + + def test_i16_reads_the_high_half_signed(self): + row = next(r for r in p.rows() if r[0] == "i16_lt_opsel01") + self.assertEqual(p.half_value(0x8000, "i16"), -32768) + self.assertEqual(p.answer(row, True), 0) # 5 < 3: false + row = next(r for r in p.rows() if r[0] == "i16_lt_opsel10") + self.assertEqual(p.answer(row, True), 1) # -32768 < 7 + + def test_kernel_builds(self): + rows = p.rows() + lines = p.kernel(rows) + self.assertEqual(sum(ln.startswith(".long 0xd4") for ln in lines), len(rows)) + self.assertEqual(sum(ln.startswith(".long 0xd703") for ln in lines), len(p.control_rows())) + self.assertEqual("\n".join(lines).count("global_store_b32"), len(rows) + len(p.control_rows())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vertex_types.py b/tests/test_vertex_types.py index 1212dd10c..2bf0fbece 100644 --- a/tests/test_vertex_types.py +++ b/tests/test_vertex_types.py @@ -294,6 +294,63 @@ class BlockRunTests(unittest.TestCase): measure_stream(block(with_group=False)) +def block_with_streams(extra, grid=GRID): + """block() with more (slot, tag, per-vertex bytes) streams appended after its own, before the group.""" + n = grid * grid + buf = bytearray(block(grid=grid, with_group=False)) + for slot, tag, data in extra: + struct.pack_into(" 0 exactly when -v" side; w = 3 is the other + for w, agree in ((0, True), (3, False)): + _, out = measure(block27(word27(1, 0, 0, w))) + t = out["tag27"] + self.assertEqual(t["11:vertices"], self.N) + self.assertEqual(t["11:unit"], self.N) + self.assertEqual(t[f"11:w{w}"], self.N) + self.assertEqual(t["11:perp_face"], t["11:perp_face_n"]) + self.assertEqual(t["11:uv3_along_u"], t["11:uv3_n"]) + self.assertEqual(t["11:uv3_w_plus_minus_v"], t["11:uv3_along_u"] if agree else 0) + + def test_vector_along_the_normal_fails_the_checks(self): + _, out = measure(block27(word27(0, 0, 1, 3))) + t = out["tag27"] + self.assertEqual(t["11:unit"], self.N) + self.assertEqual(t["11:perp_face"], 0) + self.assertNotIn("11:uv3_along_u", t) + + def test_non_unit_vectors_are_counted(self): + _, out = measure(block27(word27(0.5, 0, 0, 3))) + self.assertEqual(out["tag27"]["11:unit"], 0) + + def test_no_0x27_slot_no_counts(self): + _, out = measure(block()) + self.assertEqual(out["tag27"], {}) + + class Rpf9ValidationTests(unittest.TestCase): """RPF9 archive header validation in iter_blocks (contract shared with rpf9_names.scan_archive).""" diff --git a/tests/test_viewer_serve.py b/tests/test_viewer_serve.py index 88c2a551c..e770d28df 100644 --- a/tests/test_viewer_serve.py +++ b/tests/test_viewer_serve.py @@ -313,9 +313,86 @@ class HandlerTest(unittest.TestCase): opened.assert_not_called() def test_the_viewer_page_itself_is_served(self): - status, _, body = raw_request(self.port, "/index.html", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 200) - self.assertIn(b"viewer", body) + # http.server itself folds a leading "//" into "/" before the handler sees the path. + for target in ("/index.html", "/", "/?x=1", "/index.html?v=2", "/index.html#pos", "//index.html"): + for method in ("GET", "HEAD"): + with self.subTest(target=target, method=method): + status, head, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}", + method=method) + self.assertEqual(status, 200) + self.assertIn("content-type: text/html", head.lower()) + if method == "GET": + self.assertIn(b"viewer", body) + + def test_nothing_else_outside_world_is_served(self): + # These reached SimpleHTTPRequestHandler unguarded: on Windows /NUL opened the device (200, empty) and + # the stream, trailing-dot and trailing-space forms returned the page or the server's own source. + site = Path(self._tmp.name) / "site" + (site / "other.txt").write_text("other-bytes", encoding="utf-8") + (site / "sub").mkdir(exist_ok=True) + (site / "sub" / "index.html").write_text("nested", encoding="utf-8") + targets = ("/NUL", "/nul.html", "/CON", "/COM1", "/CONIN%24", "/index.html::$DATA", "/index.html::%24DATA", + "/index.html.", "/index.html%20", "/index.html/", "/INDEX.HTML", "/index%2Ehtml", + "/./index.html", "/sub/../index.html", "/other.txt", "/other.txt::$DATA", + "/sub/", "/sub/index.html", "/../secret.txt", "/%2e%2e/secret.txt", "/..%5csecret.txt", + "/world", "/worldx/ok.bin", "/favicon.ico") + with mock.patch("builtins.open", side_effect=AssertionError("a refused path reached open")) as opened: + for method in ("GET", "HEAD"): + for target in targets: + with self.subTest(method=method, target=target): + status, head, body = raw_request(self.port, target, method=method) + self.assertEqual(status, 404) + self.assertIn("cache-control: no-store", head.lower()) + for leaked in (b"viewer", b"<title>nested", b"other-bytes", b"secret", b"world-bytes"): + self.assertNotIn(leaked, body) + opened.assert_not_called() + + def test_translate_path_refuses_what_send_head_refuses(self): + handler = serve.Handler.__new__(serve.Handler) # no socket: only the path mapping is under test + handler.directory = str(Path(self._tmp.name) / "site") + handler.world = None + for target in ("/NUL", "/index.html::$DATA", "/index.html.", "/other.txt", "/world/ok.bin"): + with self.subTest(target=target): + self.assertEqual(handler.translate_path(target), "") + self.assertTrue(handler.translate_path("/index.html").endswith("index.html")) + + +class NoWorldHandlerTest(unittest.TestCase): + """Without --world the page is still served and /world/ is simply absent (the viewer shows test terrain).""" + + def test_world_paths_are_404_and_the_page_is_served(self): + with tempfile.TemporaryDirectory() as tmp: + site = Path(tmp) / "site" + (site / "world").mkdir(parents=True) + (site / "index.html").write_text("<title>viewer", encoding="utf-8") + (site / "world" / "world.json").write_text("{}", encoding="utf-8") + + class QuietHandler(serve.Handler): + world = None + + def log_message(self, *args): + pass + + server = http.server.ThreadingHTTPServer( + ("127.0.0.1", 0), functools.partial(QuietHandler, directory=str(site))) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + port = server.server_address[1] + status, _, body = raw_request(port, "/", host=f"127.0.0.1:{port}") + self.assertEqual(status, 200) + self.assertIn(b"viewer", body) + # A world folder that happens to sit in the viewer folder is not served: /world/ exists only + # with --world, behind safe_world_path. + for target in ("/world/world.json", "/world/NUL", "/world/world.json::$DATA"): + with self.subTest(target=target): + status, _, body = raw_request(port, target, host=f"127.0.0.1:{port}") + self.assertEqual(status, 404) + self.assertNotIn(b"{}", body) + finally: + server.shutdown() + server.server_close() + thread.join(5) def test_the_viewer_root_serves_index_html(self): # Opening http://127.0.0.1:8765/ is how the viewer is started, and HEAD must agree with GET. @@ -525,6 +602,53 @@ class PortArgumentTest(unittest.TestCase): self.assertIn("--port 0", result.stderr) self.assertNotIn("Traceback", result.stderr) + def test_a_second_viewer_on_the_same_port_is_refused(self): + """Two real viewers. With SO_REUSEADDR set, Windows let the second one bind the port the first was serving: + it printed its URL and never got a request. The test above holds the port with a plain socket, which + Windows does refuse to share, so it did not see this.""" + first = subprocess.Popen([sys.executable, "-I", str(VIEWER / "serve.py"), "--port", "0"], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + second = None + try: + line = first.stdout.readline() # it is serving now + self.assertIn("viewer: http://127.0.0.1:", line) + port = urllib.parse.urlsplit(line.split()[1]).port + second = subprocess.Popen([sys.executable, "-I", str(VIEWER / "serve.py"), "--port", str(port)], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + out, err = second.communicate(timeout=20) + except subprocess.TimeoutExpired: + self.fail(f"a second viewer is serving port {port} next to the first one") + finally: + for proc in (first, second): + if proc is not None: + if proc.poll() is None: + proc.kill() + proc.communicate() + self.assertEqual(second.returncode, 2, err) + self.assertEqual(out, "") + self.assertIn(f"can't listen on port {port}", err) + self.assertNotIn("Traceback", err) + + def test_a_restart_binds_the_port_a_closed_viewer_just_served(self): + handler = functools.partial(serve.Handler, directory=str(VIEWER)) + port = 0 + with mock.patch.object(serve.Handler, "log_message", lambda *args: None): + for _ in range(3): + server = serve.ViewerServer(("127.0.0.1", port), handler) + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with socket.create_connection(("127.0.0.1", port), timeout=10) as client: + client.sendall(f"GET / HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\n\r\n".encode("ascii")) + self.assertTrue(client.recv(64).startswith(b"HTTP/1.0 200")) + finally: + server.shutdown() + server.server_close() + thread.join(10) + self.assertFalse(thread.is_alive(), "the server thread is still running after shutdown()") + @unittest.skipIf(os.name == "nt", "sends SIGINT, which a Windows child started this way does not get") def test_ctrl_c_stops_the_viewer_without_a_traceback(self): import signal diff --git a/tests/test_viewer_streaming.cjs b/tests/test_viewer_streaming.cjs index 18d07d593..358edf2ab 100644 --- a/tests/test_viewer_streaming.cjs +++ b/tests/test_viewer_streaming.cjs @@ -293,6 +293,62 @@ test('the bounds overlay creates helpers on the first G press and reuses them', helpers.forEach((helper, i) => assert.equal(boundsGroup.children[i], helper)); }); +test('Shift speeds the camera up and Ctrl slows it down, on either side of the keyboard', async () => { + class Vector3 { + constructor(x = 0, y = 0, z = 0) { Object.assign(this, { x, y, z }); } + set(x, y, z) { return Object.assign(this, { x, y, z }); } + fromArray([x, y, z]) { return this.set(x, y, z); } + add(v) { return this.set(this.x + v.x, this.y + v.y, this.z + v.z); } + sub(v) { return this.set(this.x - v.x, this.y - v.y, this.z - v.z); } + addScaledVector(v, s) { return this.set(this.x + v.x * s, this.y + v.y * s, this.z + v.z * s); } + crossVectors(a, b) { return this.set(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); } + lengthSq() { return this.x * this.x + this.y * this.y + this.z * this.z; } + normalize() { const n = Math.sqrt(this.lengthSq()) || 1; return this.set(this.x / n, this.y / n, this.z / n); } + } + const handlers = new Map(); + let frame; + const camera = await vm.runInNewContext(`(async () => { ${viewerModule}\nreturn camera; })()`, { + THREE: { + WebGLRenderer: class { + domElement = { addEventListener() {} }; + info = { render: { calls: 0, triangles: 0 } }; + setPixelRatio() {} setSize() {} render() {} + setAnimationLoop(callback) { frame = callback; } + }, + Scene: class { add() {} }, + PerspectiveCamera: class { + position = new Vector3(); + quaternion = { setFromEuler() {} }; + getWorldDirection(v) { return v.set(0, 0, -1); } + }, + DirectionalLight: class { position = { set() {} }; }, + Clock: class { getDelta() { return 0.1; } }, + Color: class {}, Fog: class {}, HemisphereLight: class {}, MeshStandardMaterial: class {}, Euler: class {}, + Group: class { add() {} }, + Vector3, + }, + document: { body: { prepend() {} }, getElementById: () => ({}), addEventListener() {} }, + addEventListener: (type, handler) => handlers.set(type, handler), + devicePixelRatio: 1, innerWidth: 800, innerHeight: 600, URLSearchParams, location: { search: '' }, + performance: { now: () => 0 }, + fetch: manifestResponse({ spawn: [0, 0, 0], chunks: [] }), GLTFLoader: class {}, + }); + // One frame is 0.1 s at the default 40 m/s, so E alone climbs 4 m. + const climb = (...modifiers) => { + for (const code of ['KeyE', ...modifiers]) handlers.get('keydown')({ code }); + const before = camera.position.y; + frame(); + for (const code of ['KeyE', ...modifiers]) handlers.get('keyup')({ code }); + return camera.position.y - before; + }; + const close = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1e-9, `${actual} is not ${expected}`); + close(climb(), 4); + close(climb('ShiftLeft'), 20); + close(climb('ShiftRight'), 20); + close(climb('ControlLeft'), 0.8); + close(climb('ControlRight'), 0.8); +}); + const begin = html.indexOf('// ---------- chunk streaming ----------'); const end = html.indexOf('// ---------- main loop ----------', begin); assert(begin >= 0 && end > begin, 'viewer streaming section must exist'); @@ -300,10 +356,17 @@ const source = html.slice(begin, end); const settle = () => new Promise(setImmediate); function fixture(count = 1) { const requests = [], added = [], disposed = []; - let now = 0; + const timers = new Map(); + let now = 0, nextTimer = 0; class Group { add() {} } const context = vm.createContext({ performance: { now: () => now }, + setTimeout(callback, delay) { + const id = ++nextTimer; + timers.set(id, { at: now + delay, callback }); + return id; + }, + clearTimeout: id => timers.delete(id), THREE: { MeshStandardMaterial: class {}, Group, DoubleSide: 2, LoaderUtils: { extractUrlBase: url => url.slice(0, url.lastIndexOf('/') + 1) || './' } }, AbortController, @@ -335,6 +398,15 @@ function fixture(count = 1) { const object = () => ({ traverse(fn) { fn({ geometry: { dispose() { disposed.push(this); } } }); } }); return { context, requests, added, disposed, state: context.state, object, frame(time = now) { now = time; context.state.stream(); }, + async advanceTimers(time) { + now = time; + for (const [id, { at, callback }] of timers) { + if (at > now) continue; + timers.delete(id); + callback(); + } + await settle(); + }, async fail(index, time = now) { now = time; requests[index].reject(new Error('synthetic load failure')); await settle(); }, @@ -384,6 +456,60 @@ test('a transient failure retries only after backoff, then loads the chunk', asy assert.equal(f.requests.length, 2); }); +test('stalled chunk headers and bodies release their slots at the download deadline', async () => { + const f = fixture(5); + f.frame(); + await f.advanceTimers(20000); + f.requests[0].headers(); // Receiving headers does not restart the deadline. + await settle(); + assert(f.requests[0].completeBody); + await f.advanceTimers(29999); + assert.equal(f.state.inflight, 4); + assert.equal(f.state.failed, 0); + + await f.advanceTimers(30000); + assert(f.requests.every(request => request.signal.aborted)); + assert.equal(f.requests[0].parse, undefined); + assert.equal(f.state.inflight, 0); + assert.equal(f.state.failed, 4); + f.frame(); + assert.deepEqual(f.requests.slice(4).map(request => request.url), ['4.glb']); + f.frame(30999); + assert.equal(f.requests.length, 5); + f.frame(31000); + assert.deepEqual(f.requests.slice(5).map(request => request.url), ['0.glb', '1.glb', '2.glb']); +}); + +test('repeated download timeouts use the existing attempt budget', async () => { + const f = fixture(); + f.frame(); + await f.advanceTimers(30000); + f.frame(31000); + await f.advanceTimers(61000); + f.frame(62999); + assert.equal(f.requests.length, 2); + f.frame(63000); + await f.advanceTimers(93000); + f.frame(100000); + assert.equal(f.state.failed, 3); + assert.equal(f.state.inflight, 0); + assert.equal(f.requests.length, 3); +}); + +test('a completed download clears its deadline before GLB parsing finishes', async () => { + const f = fixture(); + f.frame(); + await f.receive(0); + await f.advanceTimers(30000); + assert.equal(f.requests[0].signal.aborted, false); + assert.equal(f.state.inflight, 1); + const obj = f.object(); + await f.finish(0, obj); + assert.deepEqual(f.added, [obj]); + assert.equal(f.state.inflight, 0); + assert.equal(f.state.failed, 0); +}); + test('permanent failure stops after three attempts with increasing delays', async () => { const f = fixture(); f.frame(); await f.fail(0); diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 8de7264f2..346ec07dc 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py @@ -820,6 +820,18 @@ class QueryTest(unittest.TestCase): res, _vk = self._run_query(FakeDevice(fragment_shader_barycentric=bary, driver_id=driver)) self.assertIs(res["per_vertex_inputs"], want) + def test_stage_caps_preserve_graphics_stage_bits(self): + supported = 0x01 | 0x08 | 0x10 | 0x20 + required = 0x10 | 0x20 + device = FakeDevice(subgroup_supported_stages=supported, required_subgroup_size_stages=required, + max_compute_workgroup_subgroups=17) + vk = FakeVulkan(devices=(device,)) + with mock.patch.object(vk_info, "load_vulkan", return_value=vk): + result = vk_info.query(stage_caps=True) + self.assertEqual(result["supported_subgroup_stages"], supported) + self.assertEqual(result["required_subgroup_size_stages"], required) + self.assertEqual(result["max_compute_workgroup_subgroups"], 17) + def test_rdna2_amd_windows(self): """#857: RDNA2 by PCI device ID, and only under AMD's proprietary driver (RADV takes the same modules).""" amd, radv = vk_info.VK_DRIVER_ID_AMD_PROPRIETARY, 3 diff --git a/tests/test_vs_input_survey.py b/tests/test_vs_input_survey.py index e511e1fd9..9c0520a15 100644 --- a/tests/test_vs_input_survey.py +++ b/tests/test_vs_input_survey.py @@ -76,6 +76,43 @@ def test_vs_input_survey(): check(out.returncode == 0 and "exp prim 1" in out.stdout and "NGG markers present" in out.stdout, "a primitive export flips the verdict away from legacy") check("a_vs" not in out.stdout and "c_vs" not in out.stdout, "the summary prints counts, not shader names") + + # bad inputs and outputs: one error line, exit 2, no traceback, and index.json is never overwritten + tool = os.path.join(ROOT, "scripts", "vs_input_survey.py") + + def cli(*args): + return subprocess.run([sys.executable, "-I", tool, *args], capture_output=True, text=True) + + with tempfile.TemporaryDirectory() as tmp: + d = os.path.join(tmp, "dxbc") + os.mkdir(d) + plain = os.path.join(tmp, "plain") + with open(plain, "w") as f: + f.write("x") + idx = os.path.join(d, "index.json") + cases = { + "missing folder": [os.path.join(tmp, "nope")], + "a file as the folder": [plain], + "folder without index.json": [d], + } + for what, args in cases.items(): + r = cli(*args) + check(r.returncode == 2 and "Traceback" not in r.stderr and len(r.stderr.strip().splitlines()) == 1, + f"{what}: one error line, exit 2") + for what, body in (("junk bytes", b"\xff\xfe\x80"), ("empty file", b""), ("not a list", b'{"a": 1}'), + ("a list of non-objects", b"[1, 2]")): + with open(idx, "wb") as f: + f.write(body) + r = cli(d) + check(r.returncode == 2 and "Traceback" not in r.stderr and len(r.stderr.strip().splitlines()) == 1, + f"index.json {what}: one error line, exit 2") + with open(idx, "w") as f: + f.write("[]") + r = cli(d, "--json", os.path.join(plain, "sub", "r.json")) + check(r.returncode == 2 and "Traceback" not in r.stderr, "--json under a regular file: one error, exit 2") + r = cli(d, "--json", idx) + with open(idx) as f: + check(r.returncode == 2 and f.read() == "[]", "--json equal to index.json is refused and leaves it alone") assert failures == 0, f"{failures} vs_input_survey check(s) failed" diff --git a/tests/test_vs_input_survey_rbw.py b/tests/test_vs_input_survey_rbw.py new file mode 100644 index 000000000..eb9ad00b8 --- /dev/null +++ b/tests/test_vs_input_survey_rbw.py @@ -0,0 +1,190 @@ +"""Unit tests for read-before-write operand classification in scripts/vs_input_survey.py. + + python -I tests/test_vs_input_survey_rbw.py + +Uses small synthetic RDNA2 instruction listings only; no game data. +""" +import json +import os +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +sys.path.insert(0, os.path.join(ROOT, "scripts")) + +import shader_ir # noqa: E402 +import vs_input_survey as V # noqa: E402 + + +def parse(lines): + return [shader_ir.parse_line(line) for line in lines] + + +class ReadBeforeWriteTests(unittest.TestCase): + def test_carry_in_carry_out_writes_both_vdst_and_sdst(self): + # v_add_co_ci_u32_e64 writes v1 and s[2:3], and reads v0, v2, s[4:5]; s[2:3] is not RBW. + insns = parse([ + "\tv_add_co_ci_u32_e64 v1, s[2:3], v0, v2, s[4:5]", + "\ts_or_b64 s[6:7], s[2:3], s[2:3]", + "\tv_sub_co_ci_u32_e64 v3, s[8:9], v1, v2, s[2:3]", + "\tv_subrev_co_ci_u32_e64 v4, s[10:11], v3, v2, s[8:9]", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, {4, 5}) + self.assertEqual(read_v, {0, 2}) + + def test_dual_dest_valu_ops_write_scalar_carry_or_scale(self): + insns = parse([ + "\tv_mad_u64_u32 v[0:1], s[2:3], v4, v5, v[6:7]", + "\tv_mad_i64_i32 v[8:9], s[10:11], v0, v1, v[6:7]", + "\tv_div_scale_f32 v12, s[12:13], v4, v5, v6", + "\tv_div_scale_f64 v[14:15], s[14:15], v[8:9], v[0:1], v[6:7]", + "\ts_and_b64 s[16:17], s[2:3], s[10:11]", + "\ts_or_b64 s[18:19], s[12:13], s[14:15]", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, set()) + self.assertEqual(read_v, {4, 5, 6, 7}) + + def test_v_cmp_two_arg_implicit_vcc_reads_both_operands(self): + # Implicit-VCC 2-operand form has no explicit destination: v0 is a source, not written. + insns = parse([ + "\tv_cmp_lt_f32_e32 v0, v1", + "\tv_mov_b32_e32 v2, v0", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, set()) + self.assertEqual(read_v, {0, 1}) + + def test_v_cmp_three_arg_writes_explicit_scalar_dest(self): + insns = parse([ + "\tv_cmp_eq_u32_e64 s[2:3], v0, v1", + "\ts_mov_b64 s[4:5], s[2:3]", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, set()) + self.assertEqual(read_v, {0, 1}) + + def test_nsa_vlist_and_vcctuple_slist_operands(self): + # NSA image_sample reads every VGPR in [v0, v3]; VCCTuple slist writes s100..s105 and reads s2..s3 + # as well as unwritten slist sources [s12, s13, s14, s15]. + insns = parse([ + "\ts_load_dwordx8 [s100, s101, s102, s103, s104, s105, vcc_lo, vcc_hi], s[2:3], 0x0", + "\ts_buffer_load_dword s20, [s12, s13, s14, s15], 0x0", + "\timage_sample v[4:7], [v0, v3], [s100, s101, s102, s103, s104, s105, vcc_lo, vcc_hi], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, {2, 3, 8, 9, 10, 11, 12, 13, 14, 15}) + self.assertEqual(read_v, {0, 3}) + + def test_tbuffer_and_scalar_stores_have_no_destination(self): + insns = parse([ + "\ttbuffer_store_format_xyzw v[0:3], v4, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen", + "\ts_store_dword s8, s[0:1], 0x0", + "\ts_buffer_store_dword s9, s[12:15], 0x0", + "\tv_mov_b32_e32 v5, v0", + "\ts_mov_b32 s10, s8", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, {0, 1, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15}) + self.assertEqual(read_v, {0, 1, 2, 3, 4}) + + def test_atomics_distinguish_glc_and_global_vs_buffer(self): + # Non-glc buffer/global atomics write nothing; glc global_atomic writes vdst at args[0] without reading it; + # glc buffer_atomic both reads and writes vdata at args[0]. + insns = parse([ + "\tbuffer_atomic_add v0, v1, s[0:3], 0 offen", + "\tglobal_atomic_add v2, v3, s[4:5]", + "\tglobal_atomic_add v4, v2, v3, s[4:5] glc", + "\tbuffer_atomic_add v5, v4, s[0:3], 0 offen glc", + "\tv_add_nc_u32_e32 v6, v4, v5", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, {0, 1, 2, 3, 4, 5}) + self.assertEqual(read_v, {0, 1, 2, 3, 5}) + + def test_ds_non_returning_vs_returning_ops(self): + # Non-returning ds_add_u32 / ds_store_b32 / ds_gws_init do not write args[0]; + # ds_add_rtn_u32, ds_read_b32, ds_ordered_count, ds_swizzle/permute/bpermute, and ds_append/consume do. + insns = parse([ + "\tds_add_u32 v0, v1", + "\tds_store_b32 v2, v3", + "\tds_gws_init v14 gds", + "\tds_ordered_count v5, v1 offset:772 gds", + "\tds_add_rtn_u32 v4, v0, v1", + "\tds_read_b32 v6, v4", + "\tds_swizzle_b32 v7, v5 offset:0x0", + "\tds_permute_b32 v8, v6, v7", + "\tds_bpermute_b32 v9, v7, v8", + "\tds_append v10 gds", + "\tds_consume v11 gds", + "\tv_add_nc_u32_e32 v12, v5, v10", + "\tv_add_nc_u32_e32 v13, v9, v11", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, set()) + self.assertEqual(read_v, {0, 1, 2, 3, 14}) + + def test_flat_and_image_atomics_with_and_without_glc(self): + # Non-glc flat/image atomics write no destination; glc flat_atomic writes vdst without reading it; + # glc image_atomic reads and writes vdata at args[0]. + insns = parse([ + "\tflat_atomic_add v[0:1], v2", + "\timage_atomic_add v3, v4, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D", + "\tflat_atomic_add v5, v[0:1], v2 glc", + "\timage_atomic_add v6, v5, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D glc", + "\tv_add_nc_u32_e32 v7, v5, v6", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, {0, 1, 2, 3, 4, 5, 6, 7}) + self.assertEqual(read_v, {0, 1, 2, 3, 4, 6}) + + def test_sgpr_rmw_and_dot_accumulate_and_v_swap(self): + insns = parse([ + "\ts_addk_i32 s4, 16", + "\ts_bitset1_b32 s5, 3", + "\tv_fmac_f32_e32 v10, v11, v12", + "\tv_mac_f32_e32 v13, v11, v12", + "\tv_dot2c_f32_f16 v14, v11, v12", + "\tv_dot4c_i32_i8 v1, v2, v3", + "\tv_dot8c_i32_i4 v15, v2, v3", + "\tv_writelane_b32 v16, s4, 0", + "\tv_swap_b32 v6, v7", + "\tv_mov_b32_e32 v8, v7", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, {4, 5}) + self.assertEqual(read_v, {1, 2, 3, 6, 7, 10, 11, 12, 13, 14, 15, 16}) + + def test_vcc_carry_out_forms(self): + insns = parse([ + "\tv_add_co_u32_e32 v1, vcc_lo, v0, v2", + "\tv_add_co_ci_u32_e32 v3, vcc_lo, v1, v4, vcc_lo", + ]) + read_s, read_v = V.read_before_write(insns) + self.assertEqual(read_s, set()) + self.assertEqual(read_v, {0, 2, 4}) + + def test_survey_counts_nsa_vertex_and_instance_ids(self): + # End-to-end check: a VS that reads v0 and v3 only through an NSA vlist lands in the v0+v3 family. + with tempfile.TemporaryDirectory() as tmp: + os.makedirs(os.path.join(tmp, "disasm")) + listing = ( + "; nsa_vs\n" + "\timage_load v[4:7], [v0, v3], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D\n" + "\texp pos0 v4, v5, v6, v7 done\n" + "\ts_endpgm\n" + ) + with open(os.path.join(tmp, "disasm", "nsa_vs.s"), "w", encoding="utf-8", newline="\n") as f: + f.write(listing) + with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump([{"name": "nsa_vs", "file": "nsa_vs.dxbc", "stage": "vs"}], f) + result = V.survey(tmp) + self.assertEqual(result["input_vgprs_read"], {"v0": 1, "v3": 1}) + self.assertEqual(result["families"], {"reads v0 (vertex id) and v3 (instance id)": 1}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vs_packed_inputs.py b/tests/test_vs_packed_inputs.py new file mode 100644 index 000000000..708eafe77 --- /dev/null +++ b/tests/test_vs_packed_inputs.py @@ -0,0 +1,90 @@ +"""SHADER-644: packed VS ISG1 elements that share a register. + +The fetch-call path replaces a driver fetch with one vec4 Vulkan input per ISG1 +register. Two elements in the same register (for example xy and zw) must not +create two OpVariable declarations with the same name. + +Run from the repository root: python -m pytest tests/test_vs_packed_inputs.py +Every shader and DXBC container here is synthetic; no game data is used. +""" +import re +import struct + +import pytest + +import rdna2spirv +from conftest import make_dxbc, requires_tools + +pytestmark = requires_tools + +# s_swappc_b64 marks the driver fetch. All eight components of registers 0 and 1 +# are read before being written, matching two ISG1 elements in register 0. +VS_PACKED = """ + s_swappc_b64 s[4:5], s[4:5] + v_add_f32 v1, v4, v5 + v_add_f32 v2, v6, v7 + exp pos0 v1, v2, v1, v1 done + exp param0 v4, v5, v6, v7 + s_endpgm +""" + +VS_TWO_REGISTERS = """ + s_swappc_b64 s[4:5], s[4:5] + v_add_f32 v1, v4, v8 + v_add_f32 v2, v7, v11 + exp pos0 v1, v2, v1, v1 done + exp param0 v4, v5, v6, v7 + exp param1 v8, v9, v10, v11 + s_endpgm +""" + + +def isg1(elements): + """ISG1 chunk: elements are (register, system value, component mask, component type).""" + payload = bytearray(struct.pack(" int: all_stats, status = [], 0 for path in args.inputs: if not os.path.exists(path): - print(f"ERROR: {path} does not exist", file=sys.stderr) - status = 1 + # A missing input is a usage error (2); a folder that exists but is not an archive is a read error (1). + print(f"ERROR: {path}: does not exist", file=sys.stderr) + status = max(status, 2) continue if not os.path.isfile(path): # A folder passed for an archive used to reach open() and end the whole run with PermissionError. print(f"ERROR: {path} is not a file", file=sys.stderr) - status = 1 + status = max(status, 1) continue print(f"Processing {path}...") try: @@ -299,6 +300,10 @@ def main() -> int: print(f"ERROR: {e}", file=sys.stderr) status = 1 continue + except OSError as e: + print(f"ERROR: cannot read {path}: {e.strerror or e}", file=sys.stderr) + status = max(status, 1) + continue all_stats.append(stats) print(f" Streams: {stats['streams']}") @@ -341,4 +346,4 @@ if __name__ == "__main__": sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass - sys.exit(main()) \ No newline at end of file + sys.exit(main()) diff --git a/tools/anim_clips.py b/tools/anim_clips.py index 4930bc2e6..2287ae467 100644 --- a/tools/anim_clips.py +++ b/tools/anim_clips.py @@ -162,11 +162,18 @@ def motion_times(s, at): return out +# Where a multi-axis node keeps its sample count (the number of +0x90 sample lists of a one-node `.motion`) +NODE_SAMPLE_COUNT_AT = {4: 0x90, 5: 0x90, 6: 0x50, 8: 0xA0} + + def parameter_node(s, at, parameters): """The node that places a `.motion`'s children in parameter space: the pointer at +0x138 when +0x58 is 1; when +0x58 is 2, +0x120 points at a block whose +0x18 is the node. A node starts {u64 0, u32 type, u32 0}. - Type 3 is one sampled axis: {array of u32 name hashes, array of (u32 sample index, f32 value) sorted by - value, f32 min, f32 max}. Other types are not decoded. -> (type, axis or None) or None""" + Types 3, 4, 5, 6 and 8 have 1, 2, 3, 4 and 5 axes: +0x10 is an array of 8-byte {u32 name hash, u16, u16}. + Type 3 is one sampled axis: then an array of (u32 sample index, f32 value) sorted by value, f32 min, f32 max. + Types 4, 5, 6 and 8 keep their sample count at NODE_SAMPLE_COUNT_AT; the rest of them is not decoded. + Type 1 has no axes and its sample count (1) at +0x20. + -> (type, axis or None) or None; axis = {names, slots, sample_count, and for type 3 samples, min, max}""" if parameters == 1: node = s.ptr(at + 0x138) elif parameters == 2: @@ -177,16 +184,37 @@ def parameter_node(s, at, parameters): if node is None or s.u64(node) != 0 or s.u32(node + 12) != 0: return None kind, axis = s.u32(node + 8), None - if kind == 3: + if kind == 1: + axis = {"names": [], "slots": [], "sample_count": s.u32(node + 0x20)} + elif kind == 3 or kind in NODE_SAMPLE_COUNT_AT: names, nn = s.array(node + 0x10) - samples, ns = s.array(node + 0x20) - if names is not None and samples is not None: - axis = {"names": [s.u32(names + 4 * i) for i in range(nn)], - "samples": [(s.u32(samples + 8 * i), s.f32(samples + 8 * i + 4)) for i in range(ns)], - "min": s.f32(node + 0x30), "max": s.f32(node + 0x34)} + if names is not None: + axis = {"names": [s.u32(names + 8 * i) for i in range(nn)], + "slots": [(s.u16(names + 8 * i + 4), s.u16(names + 8 * i + 6)) for i in range(nn)]} + if kind == 3: + samples, ns = s.array(node + 0x20) + if samples is None: + return kind, None + axis.update(samples=[(s.u32(samples + 8 * i), s.f32(samples + 8 * i + 4)) for i in range(ns)], + min=s.f32(node + 0x30), max=s.f32(node + 0x34), sample_count=ns) + else: + axis["sample_count"] = s.u32(node + NODE_SAMPLE_COUNT_AT[kind]) return kind, axis +def motion_samples(s, at): + """`.motion` +0x90: one {ptr, u16 count} list per sample of the parameter node, each item a 12-byte + {u32 child index, f32, f32}. A one-node `.motion` has as many lists as its node has samples, so type-3 sample + index k plays child list[k][0]. -> [[(child, f32, f32)]] ([] when +0x90 is null)""" + p, n = s.array(at + 0x90) + out = [] + for i in range(n if p is not None else 0): + items, count = s.array(p + 16 * i) + out.append([(s.u32(items + 12 * j), s.f32(items + 12 * j + 4), s.f32(items + 12 * j + 8)) + for j in range(count)] if items is not None else []) + return out + + def parse_clip(s, at): kind = s.u32(at + 0x20) if kind >= 16: # +0x20 is a pointer: a parametric clip that refers to packs outside the dictionary @@ -207,11 +235,18 @@ def parse_clip(s, at): motion["parameters"] = s.u32(at + 0x58) except (DecodeError, struct.error): pass - try: + try: # read apart: a malformed node must not mark a readable time table unreadable motion["times"] = motion_times(s, at) + except (DecodeError, struct.error): + motion["times"] = None + try: motion["node"] = parameter_node(s, at, motion["parameters"]) except (DecodeError, struct.error): - motion["times"], motion["node"] = None, None + motion["node"] = None + try: + motion["samples"] = motion_samples(s, at) + except (DecodeError, struct.error): + motion["samples"] = None return motion # `.motionmatcher`: a 16-byte id at +0x28, name at +0x38 return {"kind": "motionmatcher", "name": s.string(at + 0x38), "animations": []} @@ -706,6 +741,12 @@ def count_motion_blend(c, stats): stats[f"motion_node_type:{kind}"] += 1 if axis is None: return + count_motion_samples(c, kind, axis, stats) + if kind != 3: + stats[f"motion_node_axes:{kind}:{len(axis['names'])}"] += 1 + for h in axis["names"]: + stats[f"motion_node_axis_name:{kind}:" + AXIS_NAMES.get(h, "unresolved")] += 1 + return values = [v for _i, v in axis["samples"]] stats["motion_axes"] += 1 stats["motion_axis_samples"] += len(values) @@ -719,6 +760,29 @@ def count_motion_blend(c, stats): stats["motion_axis_name:" + AXIS_NAMES.get(h, f"0x{h:08x}")] += 1 +def count_motion_samples(c, kind, axis, stats): + """Counts for the +0x90 sample lists of a one-node `.motion` (+0x58 == 1) against its node (no values).""" + lists = c.get("samples") + if c["parameters"] != 1 or lists is None: + return + children = len(c["children"]) + mapped = [items[0][0] for items in lists if items] + pre = f"motion_samples:{kind}:" + stats[pre + "motions"] += 1 + stats[pre + "lists_equal_node_samples"] += len(lists) == axis["sample_count"] + stats[pre + "lists_more_than_children"] += len(lists) > children + stats[pre + "every_list_one_item"] += all(len(items) == 1 for items in lists) + stats[pre + "children_in_range"] += all(ch < children for items in lists for ch, _a, _b in items) + stats[pre + "every_child_sampled"] += {ch for items in lists for ch, _a, _b in items} == set(range(children)) + stats[pre + "sample_k_is_child_k"] += (len(lists) == children and all(len(items) == 1 for items in lists) and + mapped == list(range(children))) + for items in lists: + for _ch, a, b in items: + stats[pre + "items"] += 1 + stats[pre + "items_first_float_1"] += a == 1.0 + stats[pre + "items_second_float_1"] += b == 1.0 + + def new_stats(): return collections.Counter() diff --git a/tools/anim_glb.py b/tools/anim_glb.py index d02f792c2..42aa30b0d 100644 --- a/tools/anim_glb.py +++ b/tools/anim_glb.py @@ -435,7 +435,13 @@ def select_clips(dictionary, wanted): return clips out = [] for w in wanted: - hits = [c for c in clips if clip_label(c) == w or (w.lower().startswith("0x") and c["hash"] == int(w, 16))] + wanted_hash = None + if w.lower().startswith("0x"): + try: + wanted_hash = int(w, 16) + except ValueError: + wanted_hash = None + hits = [c for c in clips if clip_label(c) == w or (wanted_hash is not None and c["hash"] == wanted_hash)] require(hits, f"clip {w!r} is not in the dictionary") out.extend(hits) return out @@ -454,8 +460,14 @@ def clip_channels(s, dictionary, clip, joint_by_hash, root_motion, tally): rate = entry["rate"] if entry["rate"] and math.isfinite(entry["rate"]) and entry["rate"] > 0 else 1.0 step = anim["duration"] / (frames - 1) if frames > 1 and anim["duration"] > 0 else 1.0 / 30 start = entry["start"] if math.isfinite(entry["start"]) else 0.0 - end = entry["end"] if math.isfinite(entry["end"]) and entry["end"] > start else anim["duration"] - keep = [k for k in range(frames) if start - 1e-4 <= k * step <= end + 1e-4] or [0] + end = entry["end"] if math.isfinite(entry["end"]) and entry["end"] >= start else anim["duration"] + keep = [k for k in range(frames) if start - 1e-4 <= k * step <= end + 1e-4] + fallback = not keep + if fallback: + target_time = 0.5 * (start + end) if end >= start else start + keep = [min(range(frames), key=lambda k: abs(k * step - target_time))] if frames else [] + if not keep: + continue tally["animations"] += 1 for t, (bone, ttype, fmt) in enumerate(anim["tracks"]): path = TRACK_PATHS.get(ttype) @@ -479,7 +491,10 @@ def clip_channels(s, dictionary, clip, joint_by_hash, root_motion, tally): if (target, path) in channels: tally["tracks_overridden"] += 1 # a frame kept by the 1e-4 tolerance before `start` would get a slightly negative time - channels[(target, path)] = [(max(0.0, (k * step - start) / rate), tuple(tracks[t][k])) for k in keep] + if fallback: + channels[(target, path)] = [(0.0, tuple(tracks[t][k])) for k in keep] + else: + channels[(target, path)] = [(max(0.0, (k * step - start) / rate), tuple(tracks[t][k])) for k in keep] return channels diff --git a/tools/anim_index.py b/tools/anim_index.py index bf913ed6a..bd8479a08 100644 --- a/tools/anim_index.py +++ b/tools/anim_index.py @@ -329,14 +329,23 @@ def collect_skeletons_dir(path): out = [] for name in sorted(os.listdir(path)): full = os.path.join(path, name) - if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")) or os.path.getsize(full) > 16384: + if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")): continue + size = os.path.getsize(full) with open(full, "rb") as f: - data = f.read() + head = f.read(5) + if size > 16384 and head != b"SKEL_": + continue + data = head + f.read() + m = re.match(r"([0-9a-fA-F]{6,})", name) + offset = int(m.group(1), 16) if m else 0 + sig = classify(data, offset, len(data))["signature"] + if not (sig == "skeleton-names" or (size <= 16384 and sig.startswith("raw:"))): + continue if b"SKEL_" in data or b"PH_" in data: - m = re.match(r"([0-9a-fA-F]{6,})", name) - record = parse_skel_names(data, int(m.group(1), 16) if m else 0) - record["kind"] = "motion-matcher" if b"motionmatcher" in data else "bone-table" + record = parse_skel_names(data, offset) + record["kind"] = ("plain-bone-table" if sig == "skeleton-names" + else ("motion-matcher" if b"motionmatcher" in data else "bone-table")) if record["distinct"] or record["hashes_present"]: out.append(record) return out diff --git a/tools/anim_skeleton_match.py b/tools/anim_skeleton_match.py new file mode 100644 index 000000000..7523bb6e8 --- /dev/null +++ b/tools/anim_skeleton_match.py @@ -0,0 +1,149 @@ +"""Match `anim.rpf` `SKEL_*` bone lists against decoded skeleton name tables in `packs.rpf` (ASSET-231). + + python -I tools/anim_skeleton_match.py [--out ] + +Reads both archives in place using `anim_index.scan_rpf`, extracts `SKEL_[A-Za-z0-9_]+` tokens from +inflated streams, and compares the animation bone set against the model skeletons (both exact and +case-insensitive, plus `joaat32` of lowercased ASCII). Writes counts only (no bone names, offsets +or archive bytes) when `--out` is given. Standard library only; no game data. +""" +import argparse +import json +import mmap +import os +import re +import sys +import zlib + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +import anim_index # noqa: E402 +from report_paths import same_report_path # noqa: E402 + +SKEL_RE = re.compile(rb"SKEL_[A-Za-z0-9_]+") + + +def joaat32(name: str) -> int: + """RAGE joaat32 over the lowercased bone name, encoded as hashdict.joaat does (latin-1, '?' for the rest).""" + h = 0 + for b in name.lower().encode("latin-1", "replace"): + h = (h + b) & 0xFFFFFFFF + h = (h + (h << 10)) & 0xFFFFFFFF + h = (h ^ (h >> 6)) & 0xFFFFFFFF + h = (h + (h << 3)) & 0xFFFFFFFF + h = (h ^ (h >> 11)) & 0xFFFFFFFF + h = (h + (h << 15)) & 0xFFFFFFFF + return h + + +def extract_skel_tokens(data: bytes) -> set[str]: + """Return distinct `SKEL_[A-Za-z0-9_]+` tokens present in `data`.""" + if b"SKEL_" not in data: + return set() + return {m.decode("ascii") for m in SKEL_RE.findall(data)} + + +def scan_archive_skel(path: str) -> dict: + """Scan an RPF archive's zlib streams and return stream/token counts and the `SKEL_*` token sets.""" + rows, _ = anim_index.scan_rpf(path) + per_stream = [] + all_tokens = set() + with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: + for row in rows: + off = row["offset"] + try: + data = zlib.decompress(m[off:off + row["stored"] + 16]) + except zlib.error: + continue + toks = extract_skel_tokens(data) + if toks: + per_stream.append(toks) + all_tokens |= toks + return {"streams": len(rows), "skel_streams": len(per_stream), "per_stream": per_stream, "tokens": all_tokens} + + +def compare_sets(skel_tokens: set[str], anim_per_stream: list[set[str]]) -> dict: + """Compare animation `SKEL_*` streams/tokens against a model skeleton token set (counts only).""" + anim_tokens = set().union(*anim_per_stream) if anim_per_stream else set() + skel_lower = {t.lower() for t in skel_tokens} + skel_hashes = {joaat32(t) for t in skel_tokens} + exact = anim_tokens & skel_tokens + ci = {t for t in anim_tokens if t.lower() in skel_lower} + hashed = {t for t in anim_tokens if joaat32(t) in skel_hashes} + all_exact_streams = sum(1 for s in anim_per_stream if s <= skel_tokens) + all_ci_streams = sum(1 for s in anim_per_stream if all(t.lower() in skel_lower for t in s)) + any_ci_streams = sum(1 for s in anim_per_stream if any(t.lower() in skel_lower for t in s)) + return { + "distinct_anim_tokens": len(anim_tokens), + "distinct_skeleton_tokens": len(skel_tokens), + "matched_exact": len(exact), + "matched_case_insensitive": len(ci), + "matched_joaat32": len(hashed), + "unmatched_case_insensitive": len(anim_tokens) - len(ci), + "anim_skel_streams": len(anim_per_stream), + "streams_all_matched_exact": all_exact_streams, + "streams_all_matched_ci": all_ci_streams, + "streams_any_matched_ci": any_ci_streams, + } + + +def _check_input(ap, label: str, path: str) -> None: + if not os.path.exists(path): + ap.error(f"{label} not found: {path}") + if os.path.isdir(path): + ap.error(f"{label} is a directory: {path}") + try: + if os.path.getsize(path) == 0: + ap.error(f"{label} is empty: {path}") + except OSError as exc: + ap.error(f"cannot read {label} ({path}): {exc}") + + +def _check_output(ap, out_path: str, inputs: tuple[str, ...]) -> None: + if any(same_report_path(out_path, inp) for inp in inputs): + ap.error("--out must not overwrite an input archive") + if os.path.isdir(out_path): + ap.error(f"--out is a directory: {out_path}") + parent = os.path.dirname(os.path.abspath(out_path)) + if not os.path.isdir(parent): + ap.error(f"--out parent directory does not exist: {parent}") + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Match anim.rpf SKEL_* bone lists against packs.rpf skeletons (ASSET-231).") + ap.add_argument("packs", help="Path to packs.rpf") + ap.add_argument("anim", help="Path to anim.rpf") + ap.add_argument("--out", help="Optional JSON output path (counts only)") + a = ap.parse_args(argv) + _check_input(ap, "packs", a.packs) + _check_input(ap, "anim", a.anim) + if a.out: + _check_output(ap, a.out, (a.packs, a.anim)) + try: + packs = scan_archive_skel(a.packs) + anim = scan_archive_skel(a.anim) + except (OSError, ValueError) as exc: + ap.error(str(exc)) + summary = compare_sets(packs["tokens"], anim["per_stream"]) + summary["packs_streams"] = packs["streams"] + summary["packs_skel_streams"] = packs["skel_streams"] + summary["anim_streams"] = anim["streams"] + text = json.dumps(summary, indent=2) + print(text) + if a.out: + try: + with open(a.out, "w", encoding="utf-8", newline="\n") as fh: + fh.write(text + "\n") + except OSError as exc: + ap.error(f"cannot write --out ({a.out}): {exc}") + return 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/audio_config.py b/tools/audio_config.py index ad6cf97ba..48ff5244c 100644 --- a/tools/audio_config.py +++ b/tools/audio_config.py @@ -263,7 +263,8 @@ def main(): ap.error("require 1 <= min-ms <= max-ms") if not os.path.exists(a.src): - sys.exit(f"{a.src}: does not exist") + print(f"ERROR: {a.src}: does not exist", file=sys.stderr) + return 2 if a.join and not os.path.isdir(a.src): ap.error("--join applies to a directory, not a single file") try: diff --git a/tools/audio_wav.py b/tools/audio_wav.py index 1d35c02ee..3525134fc 100644 --- a/tools/audio_wav.py +++ b/tools/audio_wav.py @@ -328,7 +328,7 @@ def plan_outputs(items, src, out, ffmpeg): for group in groups.values(): repaired.update(native_collisions(group, named, target, unprobed)) repaired.update(unprobed) - counters, digests = {}, {} + counters, digests, dest_digests = {}, {}, {} def holds_own_audio(i, stem): """True if stem.wav is free or already holds input i's decoded audio.""" @@ -342,15 +342,20 @@ def plan_outputs(items, src, out, ffmpeg): elif len(digests) % 100 == 0: print(f" Checked {len(digests)} input recordings...", flush=True) digests[i] = audio_digest(ffmpeg, path, source=True) - if digests[i] and os.path.isfile(dst) and audio_digest(ffmpeg, dst, source=False) == digests[i]: - return True + if digests[i] and os.path.isfile(dst): + if dst not in dest_digests: + dest_digests[dst] = audio_digest(ffmpeg, dst, source=False) + if dest_digests[dst] == digests[i]: + return True print(f" Keeping {dst}: its audio could not be verified for {path}.", file=sys.stderr) return False def allocate(i, base): """Give input i the first unreserved name of base, base~2, ... that is free or holds its audio.""" base_key = key(base) - stem, n = base, counters.get(base_key, 2) + first = counters.get(base_key, 2) + stem, n = (base, 2) if first == 2 else (f"{base}~{first}", first + 1) + skipped_unreserved = False while True: candidate = key(stem) if candidate not in reserved: @@ -358,9 +363,10 @@ def plan_outputs(items, src, out, ffmpeg): raise OSError(f"cannot distinguish names in a read-only directory and verify {stem}.wav") if holds_own_audio(i, stem): break - reserved[candidate] = i + skipped_unreserved = True stem, n = f"{base}~{n}", n + 1 - counters[base_key] = n + if not skipped_unreserved: + counters[base_key] = n reserved[candidate] = i named[i] = (named[i][0], stem) diff --git a/tools/awc_names.py b/tools/awc_names.py index 78b449b35..039b184cf 100644 --- a/tools/awc_names.py +++ b/tools/awc_names.py @@ -116,8 +116,12 @@ def load_banks(source: str) -> dict: grouped[label].append(int(row["stream"], 16) & M29) return dict(grouped) banks = doc.get("Banks", doc) if isinstance(doc, dict) else doc + if not isinstance(banks, list): + raise ValueError("expected a list of banks") out = {} for bank in banks: + if not isinstance(bank, dict): + raise ValueError(f"expected each bank to be an object, got {type(bank).__name__}") out[bank["Path"]] = [int(s["Id"], 16) & M29 for s in bank.get("Streams") or []] return out if os.path.isfile(source): @@ -217,14 +221,15 @@ def family_ok(names) -> bool: return len(nums) == 2 and nums[1] - nums[0] == 1 -def attack(dictionary: Dictionary, bases: list, index: Index, salt: str) -> dict: - """{(bank number, id): (name, rule, family size)}; ``salt`` != '' is the control run.""" - found = {} +def _attack_split(dictionary: Dictionary, bases: list, index: Index, salt: str) -> tuple: + """Separate dialogue and best family hits per (bank number, id) before control filtering.""" + dialogue_hits = {} for w in dictionary.words: if DIALOGUE.match(w): name = salt + w - for b in index.by_id.get(joaat(name) & M29, ()): - found[(b, joaat(name) & M29)] = (name, "dialogue", 99) + h = joaat(name) & M29 + for b in index.by_id.get(h, ()): + dialogue_hits[(b, h)] = (name, "dialogue", 99) suffix_bytes = [_enc(s) for s in SUFFIXES] families = collections.defaultdict(dict) # (bank, base) -> {id: (name, verbatim)} by_id = index.by_id @@ -237,11 +242,21 @@ def attack(dictionary: Dictionary, bases: list, index: Index, salt: str) -> dict verbatim = (base + s) in dictionary.wordset for b in banks: families[(b, base)][i] = (salt + base + s, verbatim) + family_hits = {} for (b, _base), members in families.items(): if family_ok(n for n, _v in members.values()) and any(v for _n, v in members.values()): + size = len(members) for i, (name, _v) in members.items(): - found.setdefault((b, i), (name, "family", len(members))) - return found + prev = family_hits.get((b, i)) + if prev is None or size > prev[2]: + family_hits[(b, i)] = (name, "family", size) + return dialogue_hits, family_hits + + +def attack(dictionary: Dictionary, bases: list, index: Index, salt: str) -> dict: + """{(bank number, id): (name, rule, family size)}; ``salt`` != '' is the control run.""" + dialogue_hits, family_hits = _attack_split(dictionary, bases, index, salt) + return {**family_hits, **dialogue_hits} def _distinct(found: dict, rule: str, kmin: int = 0) -> int: @@ -250,21 +265,28 @@ def _distinct(found: dict, rule: str, kmin: int = 0) -> int: def name_source(dictionary: Dictionary, bases: list, index: Index) -> tuple: """Accepted names and the per-source statistics, after the salted control picks the thresholds.""" - real = attack(dictionary, bases, index, "") - control = attack(dictionary, bases, index, SALT) - keep_dialogue = _distinct(control, "dialogue") < CONTROL_LIMIT * max(_distinct(real, "dialogue"), 1) + real_dlg, real_fam = _attack_split(dictionary, bases, index, "") + ctrl_dlg, ctrl_fam = _attack_split(dictionary, bases, index, SALT) + keep_dialogue = _distinct(ctrl_dlg, "dialogue") < CONTROL_LIMIT * max(_distinct(real_dlg, "dialogue"), 1) kmin = None for k in FAMILY_SIZES: - r, c = _distinct(real, "family", k), _distinct(control, "family", k) + r, c = _distinct(real_fam, "family", k), _distinct(ctrl_fam, "family", k) if r and c < CONTROL_LIMIT * r: kmin = k break - def keep(v): - return (v[1] == "dialogue" and keep_dialogue) or (v[1] == "family" and kmin is not None and v[2] >= kmin) + def combine(dlg, fam): + accepted = {} + if kmin is not None: + for key, val in fam.items(): + if val[2] >= kmin: + accepted[key] = val + if keep_dialogue: + accepted.update(dlg) + return accepted - real = {k: v for k, v in real.items() if keep(v)} - control = {k: v for k, v in control.items() if keep(v)} + real = combine(real_dlg, real_fam) + control = combine(ctrl_dlg, ctrl_fam) stats = { "banks": len(index.labels), "streams": index.streams, diff --git a/tools/bary_fallback_gs.py b/tools/bary_fallback_gs.py index a3c6ad6fb..2c8e709ba 100644 --- a/tools/bary_fallback_gs.py +++ b/tools/bary_fallback_gs.py @@ -125,6 +125,9 @@ def _helpers_for_index(spirv_dir: str | os.PathLike[str], pair: tuple[str, str] vertex, pixel = pair producer = index.get(vertex, {}) consumer = index.get(pixel, {}) + for name, entry in ((vertex, producer), (pixel, consumer)): + if not isinstance(entry, dict): + raise ValueError(f"{index_path}: index entry {name!r} must be a JSON object") if producer.get("stage") != "vs" or consumer.get("stage") != "ps" or not consumer.get("bary_fallback_input"): raise ValueError("--pair requires a translated VS and a barycentric-fallback PS from the index") caps = set(producer.get("capabilities", [])) @@ -189,6 +192,8 @@ def main(argv): parser.add_argument("spirv_dir") parser.add_argument("--pair", nargs=2, metavar=("VS", "PS"), help="build for these index entries") args = parser.parse_args(argv[1:]) + if not os.path.exists(args.spirv_dir): + parser.exit(2, f"ERROR: {args.spirv_dir}: does not exist\n") if not os.path.isdir(args.spirv_dir): parser.exit(1, f"{args.spirv_dir}: not a directory\n") try: diff --git a/tools/batch_glb.py b/tools/batch_glb.py index 9eca6722f..8564961e1 100644 --- a/tools/batch_glb.py +++ b/tools/batch_glb.py @@ -2,7 +2,11 @@ Uses tools/glb_writer.py to process entire directories of OBJ models with multi-core parallelism and progress reporting. Can optionally link -and embed textures (.png or .dds) directly into glTF materials. +and embed textures (.png or .dds) directly into glTF materials. A texture +that cannot be read or decoded is left out of that model and reported (one +line each, counted in the summary), never dropped silently; a model that +fails to convert is named with its error. Exit status is 1 only when a +model failed. Usage: python -I tools/batch_glb.py [--jobs N] [--up z|y] [--textures ] @@ -13,6 +17,7 @@ import argparse import concurrent.futures import os import sys +import threading import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -37,24 +42,51 @@ def _build_texture_index(texture_dir: str | None) -> dict[str, str]: return index -def _load_png_bytes(tex_path: str, max_size: int = 0) -> bytes | None: - """Load PNG bytes from file or decode DDS directly to PNG bytes.""" +def _load_png_bytes(tex_path: str, max_size: int = 0) -> tuple[bytes | None, str]: + """(PNG bytes from file or DDS decode, or None and why it cannot be embedded: a texture the model + can live without is skipped and reported, never a silent hole in the output).""" lower = tex_path.lower() if lower.endswith(".png"): - with open(tex_path, "rb") as f: - return f.read() + try: + with open(tex_path, "rb") as f: + data = f.read() + except OSError as exc: + return None, str(exc) + if not data: + return None, "the PNG file is empty" + return data, "" elif lower.endswith(".dds"): try: - return dds_png.dds_file_to_png_bytes(tex_path, max_size=max_size) - except Exception: - return None - return None + data = dds_png.dds_file_to_png_bytes(tex_path, max_size=max_size) + except Exception as exc: + return None, f"DDS decode: {exc}" + if not data: + return None, "DDS decode produced no bytes" + return data, "" + return None, "not a .png or .dds" + + +class TextureCache: + """Thread-safe (bytes, reason) per texture path, so the batch decodes a broken DDS once even when two + worker threads reach the same file at the same time (the pool runs one model per thread).""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._entries: dict[str, tuple[bytes | None, str]] = {} + + def get_or_load(self, path: str, max_size: int = 0) -> tuple[bytes | None, str]: + with self._lock: + if path not in self._entries: + self._entries[path] = _load_png_bytes(path, max_size=max_size) + return self._entries[path] def convert_single( - args_tuple: tuple[str, str, str, dict[str, str], int, dict[str, bytes]], -) -> tuple[bool, str, str]: + args_tuple: tuple[str, str, str, dict[str, str], int, TextureCache], +) -> tuple[bool, str, str, list[tuple[str, str]]]: in_path, out_path, up_axis, tex_index, max_tex_size, tex_cache = args_tuple + dropped: list[tuple[str, str]] = [] + dropped_seen: set[str] = set() try: primitives = glb_writer.parse_obj(in_path, is_path=True, up_axis=up_axis) materials: dict[str, dict] = {} @@ -87,11 +119,10 @@ def convert_single( break if found_path: - png_bytes = tex_cache.get(found_path) - if png_bytes is None: - png_bytes = _load_png_bytes(found_path, max_size=max_tex_size) - if png_bytes: - tex_cache[found_path] = png_bytes + png_bytes, why_not = tex_cache.get_or_load(found_path, max_size=max_tex_size) + if why_not and found_path not in dropped_seen: + dropped_seen.add(found_path) # one line per texture per model, not per primitive + dropped.append((found_path, why_not)) if png_bytes: materials[mat_name] = { "name": mat_name or clean_stem, @@ -99,9 +130,9 @@ def convert_single( } glb_writer.write_glb(out_path, primitives, materials=materials if materials else None) - return True, in_path, "" + return True, in_path, "", dropped except Exception as exc: - return False, in_path, str(exc) + return False, in_path, str(exc), dropped def batch_convert( @@ -121,7 +152,7 @@ def batch_convert( ] tex_index = _build_texture_index(texture_dir) - tex_cache: dict[str, bytes] = {} + tex_cache = TextureCache() tasks = [ ( @@ -138,17 +169,27 @@ def batch_convert( total = len(tasks) succeeded = 0 failed = 0 + failures: list[tuple[str, str]] = [] # (model, error): counted and named + dropped_textures: list[tuple[str, str, str]] = [] max_workers = jobs if jobs and jobs > 0 else (os.cpu_count() or 4) with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: - for ok, path, err in executor.map(convert_single, tasks): + for ok, path, err, dropped in executor.map(convert_single, tasks): if ok: succeeded += 1 else: failed += 1 + failures.append((path, err)) + dropped_textures.extend((path, tex, why) for tex, why in dropped) - return {"total": total, "succeeded": succeeded, "failed": failed} + return { + "total": total, + "succeeded": succeeded, + "failed": failed, + "failures": failures, + "dropped_textures": dropped_textures, + } def main(argv: list[str] | None = None) -> int: @@ -198,9 +239,15 @@ def main(argv: list[str] | None = None) -> int: return 1 elapsed = time.monotonic() - t0 + for path, err in stats["failures"]: + print(f"batch_glb: {path}: {err}") + for model, tex, why in stats["dropped_textures"]: + print(f"batch_glb: {os.path.basename(model)}: texture {tex} not embedded: {why}") + dropped = len(stats["dropped_textures"]) + note = f", {dropped} unembedded texture" + ("" if dropped == 1 else "s") if dropped else "" print( f"batch_glb: converted {stats['succeeded']}/{stats['total']} models " - f"({stats['failed']} failed) in {elapsed:.2f}s" + f"({stats['failed']} failed{note}) in {elapsed:.2f}s" ) return 0 if stats["failed"] == 0 else 1 diff --git a/tools/buffer_bounds_probe.py b/tools/buffer_bounds_probe.py new file mode 100644 index 000000000..b79af4a92 --- /dev/null +++ b/tools/buffer_bounds_probe.py @@ -0,0 +1,244 @@ +r"""SHADER-341: native GFX10 MUBUF `OOB_SELECT` bounds probe. + +Runs hand-written one-lane raw kernels through `tools/hw_oracle` and compares a +4-byte `buffer_load_dword` against the two published bounds columns: + + * Mesa's GFX10 column (`.ac_descriptors.c`), which checks `offset >= stride` + in structured-with-offset mode and `offset >= NUM_RECORDS` in raw mode; + * the RDNA2 measurement in docs/buffer_bounds.md (Mesa's GFX11 column), which + checks the *end* of the dword and includes `soffset` in raw mode. + +No game data is involved: every V#, buffer and pattern is built by this file. + +Usage: + python -I tools/buffer_bounds_probe.py --self-test + python -I tools/buffer_bounds_probe.py [--waves 32,64] [--json report.json] + +Exit codes: + 0 every case matches the measured RDNA2/GFX11 column + 1 at least one case disagrees (or a wave32/wave64 result differs) + 2 bad arguments or harness error + 77 hardware oracle unavailable or not a GFX10 device +""" +import argparse +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +if HERE not in sys.path: + sys.path.insert(0, HERE) + +# Raw output V# in s[0:3]; the probed data starts 0x100 bytes into the buffer. +OUT_V_W3 = 0x31016FAC +V_W3_BASE = 0x01000FAC +DATA_OFF = 0x100 +DATA_DWORDS = 64 +SEED_BASE = 0xA0000000 + +# name, mode, stride, num_records, index, offset, soffset, idxen, offen. +# The first four cases are the ones where the two columns disagree. +CASES = [ + ("mode0_stride16_off13", 0, 16, 18, 0, 13, 0, False, True), + ("mode0_stride16_off12", 0, 16, 18, 0, 12, 0, False, True), + ("mode0_index_at_nr", 0, 16, 2, 2, 0, 0, True, False), + ("mode1_index_at_nr", 1, 16, 2, 2, 0, 0, True, False), + ("mode1_index_off48", 1, 16, 18, 1, 48, 0, True, True), + ("mode2_nr0", 2, 16, 0, 0, 0, 0, False, False), + ("mode2_nr18", 2, 16, 18, 0, 0, 0, False, False), + ("mode3_nr18_off16", 3, 0, 18, 0, 16, 0, False, True), + ("mode3_nr18_off13", 3, 0, 18, 0, 13, 0, False, True), + ("mode3_nr3_off0", 3, 0, 3, 0, 0, 0, False, True), + ("mode3_soff8_off8_nr18", 3, 0, 18, 0, 8, 8, False, True), + ("mode3_stride16_index4", 3, 16, 18, 4, 0, 0, True, False), +] + + +def oob_gfx10(case): + """Out-of-range according to Mesa's GFX10 column (docs/buffer_bounds.md).""" + _name, mode, stride, nr, idx, off, _soff, _idxen, _offen = case + if mode == 0: + return idx >= nr or off >= stride + if mode == 1: + return idx >= nr + if mode == 2: + return nr == 0 + if mode == 3: + return off >= nr + raise ValueError(f"bad OOB_SELECT mode {mode}") + + +def oob_gfx11(case): + """Out-of-range according to the measured RDNA2 / Mesa GFX11 column.""" + _name, mode, stride, nr, idx, off, soff, _idxen, _offen = case + if mode == 0: + return idx >= nr or off + 4 > stride + if mode == 1: + return idx >= nr + if mode == 2: + return nr == 0 + if mode == 3: + return off + soff + 4 > nr + raise ValueError(f"bad OOB_SELECT mode {mode}") + + +def kernel_lines(case, wave): + """One self-contained raw kernel: seed the data, load once, store the word.""" + name, mode, stride, nr, idx, off, soff, idxen, offen = case + lbl, done = f".Lseed_{name}", f".Ldone_{name}" + if wave == 32: + save = ["s_mov_b32 s28, exec_lo", "v_cmpx_eq_u32_e32 0, v0"] + restore = ["s_mov_b32 exec_lo, s28"] + else: + save = ["s_mov_b64 s[28:29], exec", "v_cmpx_eq_u32_e32 0, v0"] + restore = ["s_mov_b64 exec, s[28:29]"] + return [ + "s_mov_b32 s0, s2", + "s_and_b32 s1, s3, 0xffff", + "s_mov_b32 s2, 0xffffffff", + f"s_mov_b32 s3, {OUT_V_W3:#x}", + f"s_add_u32 s16, s0, {DATA_OFF:#x}", + "s_addc_u32 s17, s1, 0", + "s_and_b32 s17, s17, 0xffff", + *save, + "s_mov_b32 s20, 0", + f"{lbl}:", + f"s_cmp_ge_u32 s20, {DATA_DWORDS * 4:#x}", + f"s_cbranch_scc1 {done}", + f"s_add_u32 s21, s20, {SEED_BASE:#x}", + "v_mov_b32 v30, s21", + f"s_add_u32 s22, s20, {DATA_OFF:#x}", + "buffer_store_dword v30, off, s[0:3], s22", + "s_add_u32 s20, s20, 4", + f"s_branch {lbl}", + f"{done}:", + "s_waitcnt vmcnt(0)", + *restore, + "s_mov_b32 s4, s16", + f"s_or_b32 s5, s17, {stride << 16:#x}", + f"s_mov_b32 s6, {nr:#x}", + f"s_mov_b32 s7, {V_W3_BASE | (22 << 12) | (mode << 28):#x}", + f"s_mov_b32 s10, {soff:#x}", + f"v_mov_b32 v1, {idx:#x}", + f"v_mov_b32 v2, {off:#x}", + f"buffer_load_dword v8, {_addr(case)}, s[4:7], {_soff(case)}{_mods(case)}", + "s_waitcnt vmcnt(0)", + "buffer_store_dword v8, off, s[0:3], 0", + "s_endpgm", + ] + + +def _addr(case): + _n, _m, _s, _nr, _i, _o, _so, idxen, offen = case + if idxen and offen: + return "v[1:2]" + if idxen: + return "v1" + if offen: + return "v2" + return "off" + + +def _soff(case): + return "s10" if case[6] else "0" + + +def _mods(case): + idxen, offen = case[7], case[8] + if idxen and offen: + return " idxen offen" + if idxen: + return " idxen" + if offen: + return " offen" + return "" + + +def self_test(): + assert len({c[0] for c in CASES}) == len(CASES), "duplicate case names" + for c in CASES: + assert 0 <= c[1] <= 3 and c[2] >= 0 and c[3] >= 0, c + oob_gfx10(c) + oob_gfx11(c) + for wave in (32, 64): + lines = kernel_lines(c, wave) + assert any("buffer_load_dword v8," in ln for ln in lines), c + assert lines[-1] == "s_endpgm", c + # The four witness cases must separate the two columns. + witnesses = [c for c in CASES if oob_gfx10(c) != oob_gfx11(c)] + assert len(witnesses) >= 4, len(witnesses) + assert oob_gfx10(CASES[10]) is False and oob_gfx11(CASES[10]) is True # soffset in raw mode + print("self-test OK") + + +def probe(oracle, asm, waves): + out = {"arch": oracle.arch, "device": str(oracle.device), "waves": {}} + for wave in waves: + kernels = [asm.Kernel(kernel_lines(c, wave), wave=wave, threads=1, + words=4, raw=True) for c in CASES] + results = oracle.run(kernels, words=4) + rows = [] + for case, result in zip(CASES, results): + word = result[0] if isinstance(result, list) else result + oob = word == 0 + rows.append({"name": case[0], "got": word & 0xFFFFFFFF, "oob": oob, + "gfx10_oob": oob_gfx10(case), "gfx11_oob": oob_gfx11(case)}) + out["waves"][str(wave)] = rows + return out + + +def main(): + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)") + ap.add_argument("--json", dest="json_out", help="write the full report to this path") + ap.add_argument("--self-test", action="store_true", help="check the models without a GPU") + args = ap.parse_args() + if args.self_test: + self_test() + return 0 + waves = [int(w) for w in args.waves.split(",") if w.strip()] + if not waves or any(w not in (32, 64) for w in waves): + print("--waves must be a non-empty list of 32 and/or 64", file=sys.stderr) + return 2 + from hw_oracle import asm, runner + try: + oracle = runner.open_oracle() + except runner.Unavailable as exc: + print(f"SKIP: {exc}", file=sys.stderr) + return 77 + try: + if asm.family(oracle.arch) != "gfx10": + print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr) + return 77 + report = probe(oracle, asm, waves) + finally: + oracle.close() + gfx10_diff = gfx11_diff = wave_diff = 0 + for wave, rows in report["waves"].items(): + for row in rows: + gfx10_diff += row["oob"] != row["gfx10_oob"] + gfx11_diff += row["oob"] != row["gfx11_oob"] + print(f"wave{wave} {row['name']:24s} got={'OOB' if row['oob'] else 'data'} " + f"gfx10={'OOB' if row['gfx10_oob'] else 'data'} " + f"gfx11={'OOB' if row['gfx11_oob'] else 'data'} 0x{row['got']:08x}") + if "32" in report["waves"] and "64" in report["waves"]: + a = {r["name"]: r["oob"] for r in report["waves"]["32"]} + b = {r["name"]: r["oob"] for r in report["waves"]["64"]} + wave_diff = sum(a[k] != b.get(k) for k in a) + print(f"{oracle.arch}: {sum(len(v) for v in report['waves'].values())} cases, " + f"{gfx11_diff} disagree with the measured RDNA2/GFX11 column, " + f"{gfx10_diff} disagree with Mesa's GFX10 column, " + f"{wave_diff} wave32/wave64 differences") + if args.json_out: + with open(args.json_out, "w", encoding="utf-8", newline="\n") as f: + json.dump(report, f, indent=2) + return 1 if gfx11_diff or wave_diff else 0 + + +if __name__ == "__main__": + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(errors="replace") + raise SystemExit(main()) diff --git a/tools/bvh_gpu_smoke.py b/tools/bvh_gpu_smoke.py new file mode 100644 index 000000000..9d9fbf11f --- /dev/null +++ b/tools/bvh_gpu_smoke.py @@ -0,0 +1,316 @@ +"""Run XboxBvhBuilder.dll's translated compute programs on the GPU with synthetic inputs (TEST-594). + +docs/embedded_shaders.md: the DLL carries 52 console compute programs, and the translator takes all but one; none had +been run on a GPU. This translates them from your own package and runs each one through vk_compute_test: + + python -I tools/bvh_gpu_smoke.py --game-dir [--work DIR] [--build runtime/build] + [--max-shared-memory 32768] [--table-qword 0x2000] [--include-rehydration] + [--json report.json] + +Each program reads its root arguments from a table at s[0:1], which in vk_compute_test is the heap base (Xbox VA 0). +The heap starts as that table, 64-bit words that all hold --table-qword, then zeros up to --heap-bytes (seeded with +VKC_HEAP_INIT). So every root descriptor points at a zeroed region past the table and every root constant reads +--table-qword or 0. That is enough to run each program, not to give it meaningful work: most leave early, and the +report says how many words each one changed. A run passes when it exits 0, the Khronos validation layer (when +installed) reports no error, and a second run writes the same heap bytes. + +--checked also runs the programs whose effect reads straight off their code with inputs chosen for them, and compares +every byte they write (CHECKED below). Five take a count and write that many 16- or 8-byte entries from thread index 0 +up; 32 threads per group, so one group with a count of 20 also shows that entries past the count are left alone. +PrefixSum64 scans 64 words in place into their exclusive prefix sum and stores the total. + +The three rehydration programs (Box16Rehydration, Box32Rehydration, LeafRehydration) belong to TEST-376, which checks +them against tools/bvh_rehydrate.py; --include-rehydration runs them too. + +--max-shared-memory is passed to rdna2spirv.py: set it to the device's maxComputeSharedMemorySize (32768 on AMD's +Windows driver; the translator's default is 65536). Over it, a program's LDS array shrinks to what the program uses, +which the wave64 bitonic sorts need on a 32 KiB device. + +Nothing from the package is written outside --work. The report holds module names, statuses and counts only. +""" +import argparse +import json +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REHYDRATION = ("Box16Rehydration", "Box32Rehydration", "LeafRehydration") +TABLE_QWORDS = 512 # a 4 KiB root table + + +def heap_image(table_qword, heap_bytes): + """The initial heap: TABLE_QWORDS words of table_qword, then zeros up to heap_bytes.""" + table = struct.pack(f"<{TABLE_QWORDS}Q", *([table_qword] * TABLE_QWORDS)) + if heap_bytes < len(table): + raise ValueError(f"--heap-bytes must be at least {len(table)}") + return table + bytes(heap_bytes - len(table)) + + +def changed_words(initial, after): + """How many 32-bit words of the heap differ from the initial image.""" + n = min(len(initial), len(after)) // 4 + a = struct.unpack_from(f"<{n}I", initial) + b = struct.unpack_from(f"<{n}I", after) + return sum(1 for x, y in zip(a, b) if x != y) + + +def run_program(vkc, spv, init, dump, heap_words, validation, timeout): + """One dispatch of one workgroup. Returns (status, last line of output): ok, 'exit N', validation, timeout.""" + env = dict(os.environ, VKC_OUT_WORDS=str(heap_words), VKC_HEAP_INIT=str(init), VKC_DUMP=str(dump)) + if validation: + env["VK_INSTANCE_LAYERS"] = "VK_LAYER_KHRONOS_validation" + try: + p = subprocess.run([str(vkc), str(spv), "1", "dump"], capture_output=True, text=True, env=env, + timeout=timeout) + except subprocess.TimeoutExpired: + return "timeout", "" + out = (p.stdout or "") + (p.stderr or "") + last = (out.strip().splitlines() or [""])[-1][:160] + if p.returncode != 0: + return f"exit {p.returncode}", last + if "Validation Error" in out: + return "validation", next((line for line in out.splitlines() if "VUID" in line), last)[:160] + return "ok", last + + +def smoke(spirv_dir, vkc, *, table_qword, heap_bytes, validation, timeout, include_rehydration, runner=run_program): + """Run every program in spirv_dir twice. Returns [{name, status, words_changed, detail}] in name order.""" + image = heap_image(table_qword, heap_bytes) + results = [] + with tempfile.TemporaryDirectory(prefix="bvh_gpu_smoke_") as tmp: + tmp = Path(tmp) + init = tmp / "heap.bin" + init.write_bytes(image) + for spv in sorted(Path(spirv_dir).glob("*.spv")): + name = spv.stem + if name in REHYDRATION and not include_rehydration: + continue + first, second = tmp / (name + ".1.bin"), tmp / (name + ".2.bin") + status, detail = runner(vkc, spv, init, first, heap_bytes // 4, validation, timeout) + changed = None + if status == "ok": + again, detail2 = runner(vkc, spv, init, second, heap_bytes // 4, validation, timeout) + a = first.read_bytes() if first.is_file() else b"" + b = second.read_bytes() if second.is_file() else b"" + if again != "ok": + status, detail = again, detail2 + elif not a or a != b: + status, detail = "nondeterministic", "the two runs wrote different heap bytes" + else: + status = "pass" + changed = changed_words(image, a) if a else None + results.append({"name": name, "status": status, "words_changed": changed, "detail": detail}) + return results + + +# ---- checked runs ---- +# +# Root-table fields as each program reads them (offsets in the table at s[0:1]; addresses are 64-bit, counts and +# values 32-bit), and what it writes. FILL marks the bytes a program must leave alone. +DST, SRC, SUMS = 0x2000, 0x6000, 0x4000 # regions past the 4 KiB table +FILL = 0xAA +COUNT = 20 # within one 32-thread group + + +def _u32(heap, at): + return struct.unpack_from("8} {r['detail'] if r['status'] != 'pass' else ''}") + counts = {} + for r in results: + counts[r["status"]] = counts.get(r["status"], 0) + 1 + working = sum(1 for r in results if r["status"] == "pass" and r["words_changed"] and + r["words_changed"] > 0) + print(f"{counts.get('pass', 0)} of {len(results)} pass; {working} changed heap words beyond running; " + + ", ".join(f"{k} {v}" for k, v in sorted(counts.items()) if k != "pass")) + checked = [] + if a.checked: + checked = run_checked(spirv, vkc, heap_bytes=a.heap_bytes, validation=not a.no_validation, timeout=a.timeout) + for r in checked: + print(f"checked {r['name']:20} {r['status']:10} {r['detail']}") + print(f"checked: {sum(r['status'] == 'pass' for r in checked)} of {len(checked)} write exactly what they should") + if a.json: + Path(a.json).write_text(json.dumps({"max_shared_memory": a.max_shared_memory, "table_qword": a.table_qword, + "heap_bytes": a.heap_bytes, "results": results, "checked": checked}, + indent=1), encoding="utf-8", newline="\n") + ok = counts.get("pass", 0) == len(results) and all(r["status"] == "pass" for r in checked) + return 0 if ok else 1 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/bvh_match.py b/tools/bvh_match.py index 242b09e14..f6f807729 100644 --- a/tools/bvh_match.py +++ b/tools/bvh_match.py @@ -255,6 +255,8 @@ def main(argv=None): src = f.read() with open(a.manifest, encoding="utf-8") as f: manifest = json.load(f) + if not isinstance(manifest, dict): + raise ValueError("%s is not a JSON object (got %s)" % (a.manifest, type(manifest).__name__)) items = manifest.get("Items") or [] if not items: raise ValueError("%s has no Items: the export found no model in its window, so there is nothing to match " diff --git a/tools/cf_diff.py b/tools/cf_diff.py index 5f1ce303a..16e1539e6 100644 --- a/tools/cf_diff.py +++ b/tools/cf_diff.py @@ -613,6 +613,10 @@ def main(argv=None): ap.add_argument("--spirv-val", action="store_true", help="also run spirv-as and spirv-val on every translation (a failure counts as a mismatch)") ap.add_argument("--self-test", action="store_true") + if argv is None: + argv = sys.argv[1:] + if not argv: + ap.error("no arguments given; pass --help for the available options") a = ap.parse_args(argv) if a.programs < 1: ap.error("--programs must be at least 1") diff --git a/tools/character_textures.py b/tools/character_textures.py index ca141a446..0c244baf9 100644 --- a/tools/character_textures.py +++ b/tools/character_textures.py @@ -39,11 +39,10 @@ import csv import json import os import sys -import unicodedata # -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 +from report_paths import path_key, same_report_path # noqa: E402 SLOT_ROLES = { "C8E8C282": "diffusetex", @@ -246,7 +245,7 @@ def model_files(targets: list) -> list[str]: unique = [] seen = set() for path in found: - key = _path_key(path) + key = path_key(path) if key not in seen: seen.add(key) unique.append(path) @@ -340,31 +339,6 @@ def write_json(path: str, report: dict, rows: list) -> None: f.write("\n") -_PC_CASE_SENSITIVE = 11 # on macOS; os.pathconf_names doesn't list it - - -def _case_insensitive_volume(path): - """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does.""" - if sys.platform != "darwin": - return False - while not os.path.exists(path): - parent = os.path.dirname(path) - if parent == path: - break - path = parent - try: - return os.pathconf(path, _PC_CASE_SENSITIVE) == 0 - except (OSError, ValueError): - return True - - -def _path_key(path): - path = os.path.normcase(os.path.realpath(path)) - if _case_insensitive_volume(path): - path = unicodedata.normalize("NFD", path.casefold()) - return path - - def check_report_path(parser: argparse.ArgumentParser, flag: str, path: str, sources: list) -> None: if os.path.isdir(path): parser.error(f"{flag} is a directory: {path}") diff --git a/tools/classify_carve.py b/tools/classify_carve.py index 819de999f..0cc6598de 100644 --- a/tools/classify_carve.py +++ b/tools/classify_carve.py @@ -78,6 +78,10 @@ def main(): what = "is not a folder" if os.path.exists(root) else "does not exist" print(f"{root}: {what}; give the carve folder (the one with an index.json per archive)", file=sys.stderr) return 2 + report = os.path.join(root, "types.json") + if os.path.isdir(report): + print(f"{report}: is a directory; remove or rename that directory before rerun", file=sys.stderr) + return 2 per = {} total = defaultdict(lambda: [0, 0, []]) for name in sorted(os.listdir(root)): @@ -106,8 +110,8 @@ def main(): json.dump(out, f, indent=1) f.flush() os.fsync(f.fileno()) - os.chmod(temp, published_mode(os.path.join(root, "types.json"))) # mkstemp creates 0600 - os.replace(temp, os.path.join(root, "types.json")) + os.chmod(temp, published_mode(report)) # mkstemp creates 0600 + os.replace(temp, report) except BaseException: try: os.unlink(temp) diff --git a/tools/conformance/COMPARE.md b/tools/conformance/COMPARE.md new file mode 100644 index 000000000..dda439994 --- /dev/null +++ b/tools/conformance/COMPARE.md @@ -0,0 +1,404 @@ +# compare.py - pixel conformance checker and renderer diff + +`compare.py` verifies rendered PNGs against the pixel checks a renderer's +`manifest.json` declares, and measures how far one renderer's scenes are from +another's. It reads PNG and JSON only: it never parses C++ or `scenes.h`. Every +expectation comes from the manifest, so the same tool works for the native +D3D12 renderer, the Vulkan-backed shim and any future scene. + +Standard library only. Tested with Python 3.12.10 on Windows (the conformance +box). Python 3.8 or newer is needed for the language features used. + +``` +D:\conform\tools\ + compare.py the tool + README.md this file +``` + +On the conformance box: + +```powershell +& "$env:LOCALAPPDATA\Programs\Python\Python312\python.exe" D:\conform\tools\compare.py --help +``` + +Elsewhere, `python compare.py --help` is enough. + +## Manifest contract + +The tool consumes exactly the shape the renderers write: + +```json +{ + "renderer": "native", + "adapter": "NVIDIA GeForce RTX ...", + "scenes": [ + { + "name": "clear", + "png": "clear.png", + "checks": [ + {"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, + "why": "top-left is the clear colour"} + ] + } + ] +} +``` + +The manifest must be UTF-8; a UTF-8 BOM (which PowerShell may add) is accepted. + +Validation rules, all reported with the manifest path and the exact scene/check +position: + +- `renderer` and `adapter` are required strings (`adapter` may be empty). +- `scenes` is a non-empty list. Each scene needs a unique `name`, a unique `png` + file name beside the manifest (no directories), and a non-empty `checks` list. + A scene with no checks is rejected: it would prove nothing. +- A check needs integer `x`, `y` (0 or more) and `r`, `g`, `b`, `a` (0-255). + `why` is optional; when present it is quoted in a failure line. +- The number of checks is not assumed. The current scene contract uses 2 to 5 + per scene; `expect` evaluates however many are declared. +- Unknown extra keys are ignored so a newer renderer can add metadata without + breaking this tool. + +The scene `name` is also used for the heatmap file `.diff.png`, so names +that are Windows-illegal or contain a path separator are rejected at load with +an explanation rather than failing later during a write. + +## Orientation and channel order + +These are contract conventions and the reader follows them literally: + +- Image row 0 is the **top** of the image and corresponds to NDC y = +1. The + reader does not flip rows, and the writer does not flip them either. +- Channels are stored and interpreted in **R, G, B, A** order, 8 bits each. The + reader does not reorder channels. +- **A vertical flip is the single most common reason a GPU diff looks like a + total mismatch.** `inspect` always prints labelled top-left and bottom-right + values so a flip is obvious at a glance, and `selftest` includes an image whose + top and bottom halves differ so the tool's own orientation is proven. + +## expect - verify declared pixels + +```powershell +python compare.py expect --manifest D:\conform\native\manifest.json +python compare.py expect --manifest D:\conform\shim\manifest.json --dir D:\conform\shim\renders +``` + +`--dir` is optional; without it, PNGs are read from the manifest's directory. + +Output is one line per declared check, then a summary. This is an excerpt from a +shim run against an 18-check manifest: + +``` +PASS fullscreen (128,128) expected 200,30,60,255 got 200,30,60 +FAIL fullscreen (8,8) expected 200,30,60,255 got 10,20,30 (top-left corner is covered) +FAIL blend (128,128) expected 105,25,45,255 got 200,30,60 (0.5*(200,30,60) + 0.5*(10,20,30) = (105,25,45)) + +6 scenes, 18 checks: 8 passed, 10 failed +``` + +- `got` prints the channels actually stored: three for an RGB file, four for + RGBA. An RGB file has no alpha channel, so it is compared as if alpha were 255. + A check that declares any other alpha against an RGB file fails and says why. +- A pixel outside the image is a failure that names the coordinate and the + image's size. The scene's other checks still run. +- A missing, truncated or corrupt image is one scene-level FAIL carrying the + reader's message (path, byte offset or CRC), and the scene's declared checks + are counted as failed in the summary. +- Exit code is 0 only when every check passed. + +`expect` does not verify that the manifest's checks are the right expectations. +That is the scene contract's job; this tool checks the pixels against whatever +the manifest declares. + +## diff - compare two renderers + +```powershell +python compare.py diff --reference D:\conform\native\manifest.json --candidate D:\conform\shim\manifest.json +``` + +Both manifests must declare the same scene names; each manifest's own `png` +field is used to find its image, so the two renderers may name files +differently. Images must have equal dimensions. + +Per scene the row reports: + +- **differing**: number of pixels where any R, G, B or A channel differs, and + that count as a percentage of width x height. +- **mean**: mean absolute channel delta over every channel of every pixel. The + denominator is `width * height * 4`, so an RGB image contributes zero alpha + deltas and a small area failing hard is distinguishable from a large area + failing softly. +- **max**: largest single-channel delta in the scene. +- **first**: first differing pixel in row-major order (top row first, left to + right within a row), or `-` when identical. + +Thresholds are strict `>` comparisons and both default to `0.0`, so any +difference fails: + +``` +--max-differing-percent FLOAT fail above this percent of differing pixels +--max-mean-delta FLOAT fail above this mean absolute channel delta +``` + +NaN, infinity and negative values are rejected by the argument parser rather +than silently passing everything. + +Example (the native and shim fixture run, shortened): + +``` +PASS clear differing 0/65536 (0.000%) mean 0.0000 max 0 first - +FAIL fullscreen differing 256/65536 (0.391%) mean 0.2246 max 190 first (8,8) (differing pixels 0.391% exceed --max-differing-percent 0.000%) +FAIL depth_order differing 34648/65536 (52.869%) mean 46.2601 max 180 first (6,6) (differing pixels 52.869% exceed --max-differing-percent 0.000%) +FAIL scissor differing 57344/65536 (87.500%) mean 78.7500 max 180 first (0,0) (differing pixels 87.500% exceed --max-differing-percent 0.000%) +FAIL blend differing 65536/65536 (100.000%) mean 28.7500 max 95 first (0,0) (differing pixels 100.000% exceed --max-differing-percent 0.000%) + scene 'blend': every pixel differs - usually the scene's tint (constant buffer b0) or clear colour, before chasing rasterisation +FAIL indexed differing 10230/65536 (15.610%) mean 18.7317 max 200 first (51,51) (differing pixels 15.610% exceed --max-differing-percent 0.000%) + +6 scenes compared, 5 exceed the thresholds. Heatmaps written beside the candidate images as .diff.png +``` + +When **every** pixel differs, the tool prints a second, indented line naming the +scene and pointing at the most likely cause: + +``` + scene 'fullscreen': every pixel differs - usually the scene's tint (constant buffer b0) or clear colour, before chasing rasterisation +``` + +Each scene's tint is distinct in the current contract, so a whole frame of the +wrong colour is usually a constant-buffer value, not rasterisation. The scene +name is already at the start of the row; the extra line makes that diagnosis +impossible to miss. + +### Heatmap + +For every scene, `diff` writes `.diff.png` beside the candidate image, +same size as the candidate: + +- unchanged pixels: dark grey `(48, 48, 48)`, not black, so a black render pixel + cannot hide in the background; +- differing pixels: `delta` is the largest absolute channel difference at that + pixel. Red is `round(255 * (delta - 1) / 254)`, green is 0, blue is + `255 - red`. Delta 1 is pure blue `(0, 0, 255)`, delta 255 is pure red + `(255, 0, 0)`, and the ramp passes through purple. Alpha differences count. + +Heatmaps are written for passing scenes too, so a clean run leaves a complete +visual record. Existing files are overwritten. The tool is deterministic: the +same inputs produce byte-identical heatmaps (verified with SHA-256 over two +runs). + +### diff failures that are not pixel differences + +- Missing or extra scene names in the candidate manifest: error names them and + exits 2. There is nothing meaningful to compare. +- Different image sizes: error names both paths and their sizes and exits 2. +- Unreadable or unsupported image: error names the file and exits 2. + +A pixel comparison that ran and exceeded a threshold exits 1. + +## inspect - look at one image + +```powershell +python compare.py inspect --image D:\conform\shim\clear.png +python compare.py inspect --image D:\conform\shim\clear.png --pixel 0,0 --pixel 128,128 +``` + +Top-left and bottom-right are always printed with explicit coordinates. Without +`--pixel`, top-right, bottom-left and the centre are printed too. With +`--pixel X,Y` (repeatable), the requested pixels follow the two labelled corners. + +``` +fixtures/native/clear.png + 256 x 256, RGB, 8 bits per channel, non-interlaced + top-left (0,0) = 10,20,30 + bottom-right (255,255) = 10,20,30 + no --pixel given; also showing top-right, bottom-left and centre + top-right (255,0) = 10,20,30 + bottom-left (0,255) = 10,20,30 + centre (128,128) = 10,20,30 +``` + +RGB prints three values, RGBA four. A pixel outside the image is an error naming +the coordinate and the image size; exit code 2. + +## selftest - prove the tool without external files + +```powershell +python compare.py selftest +``` + +It creates a temporary directory, writes fixture PNGs, asserts the behaviours +below, removes the directory, and exits 1 on the first mismatch (naming the +assertion, expected value and actual value). + +``` +selftest: fixtures in C:\Users\Hussain\AppData\Local\Temp\compare-selftest-wf7w_kkg +ok PNG round-trip: RGB pixels and alpha-free pixel reads +ok PNG round-trip: RGBA rectangle at (2,1)-(5,4), alpha 200 preserved +ok PNG writer is deterministic: two writes of one raster match byte for byte +ok failure path: unwritable output directory names the path +ok failure path: corrupt IDAT reports the CRC and byte offset +ok failure path: truncated file reports the byte offset +ok PNG filters 0-4 decode: hand-computed streams for a 3x2 RGB fixture +ok failure path: short filter data and undefined filter type are rejected +ok arguments: thresholds reject negative, NaN, inf and text; pixels need x,y +ok orientation: top and bottom halves survive; inspect labels both corners +ok expect: a five-check manifest exits 0 and prints five PASS rows +ok manifest reader accepts a UTF-8 BOM, as PowerShell writes +ok expect: wrong pixel and out-of-range coordinate fail with explanations +ok expect: a missing image fails once for the scene and names the path +ok failure path: a scene with no checks is rejected, not silently passed +ok diff metrics: 2 known pixels give exact count, percent, mean, max and first +ok heatmap: grey unchanged, red at delta 255, blue at delta 1 +ok diff edge cases: row-major first difference, alpha-only delta, tint hint +ok failure path: mismatched image sizes refuse to compare and say so +ok diff: changed scene exits 1 and writes clear.diff.png beside the candidate +ok diff: generous thresholds pass the same scene without hiding its delta +selftest passed +``` + +### What selftest proves + +- **PNG writer and reader**: an 8x6 RGB image round-trips byte for byte; an 8x6 + RGBA image round-trips with a known rectangle at x 2..5, y 1..4 and alpha 200 + preserved at its corners and clear outside it. A second write of the same + raster is byte-identical. +- **PNG filters**: all five filter types decode a 3x2 RGB fixture whose filtered + streams were computed independently from the filter definitions; filter 0, 1, + 2, 3 and 4 each reconstruct the same pixels. Short filtered data and a filter + type of 5 are rejected with the reason (and the row for an undefined type). +- **PNG failure paths**: writing into a missing directory fails with the path; + a flipped byte inside IDAT fails with a CRC mismatch and byte offset; a + truncated file fails naming the truncation. None of these crash or write a + zero-byte file. +- **Arguments**: thresholds accept 0 and 1.5 and reject negative, NaN, infinity + and text; `--pixel` requires x,y and rejects malformed values. +- **Orientation and channel order**: a 4x4 image with a red top half and a blue + bottom half round-trips with row 0 still red and row 3 still blue, channels + still R,G,B, and `inspect` labels both corners with those values. A row flip + or a BGR swap would fail this step. +- **expect**: a manifest with five checks (one per corner plus the centre) + passes, prints five PASS rows and exits 0; a wrong expectation and an + out-of-range coordinate both fail with explanations and exit 1; a missing + image produces one scene-level failure naming the path; a scene with an empty + check list is rejected at load. A manifest with a UTF-8 BOM still loads. +- **diff metrics**: a known two-pixel change in a 4x3 image produces exact + differing count, total pixels, percent, mean absolute delta, maximum delta and + first coordinate. Identical images report zero. A 100%-different frame gets + the wrong-tint hint naming the scene; a partial difference gets none. +- **diff edge cases**: first difference follows row-major order (a change at + (3,0) wins over (0,1)); an alpha-only change against an RGB reference is + counted with delta 1; mismatched image sizes refuse to compare with both sizes + in the message. +- **diff command**: a changed scene exits 1, writes `clear.diff.png` beside the + candidate, and the written heatmap marks a delta-255 pixel pure red. The same + scene passes with generous thresholds while still printing its pixel count. +- **heatmap colours**: unchanged is dark grey, delta 255 is red, delta 1 is blue + in the built raster before it is written. + +### What selftest does not prove + +- **Independent PNG encoders.** Selftest's PNGs come from the tool's own writer, + and the filter fixtures are hand-built byte streams. Separately, during + development, the reader was cross-checked on macOS against Pillow 13.0.0: 16 + images (RGB and RGBA; 1x1, 2x3, 17x9, 256x256; `optimize` on and off) decoded + byte for byte, and their IDAT streams were observed to use filter types 0, 1, + 2, 3 and 4. Pillow is not installed on the conformance box and is not a + dependency of this tool, so that check is not part of `selftest`. +- **The full command-line parser.** Selftest calls the command functions and the + two argument type functions directly. The transcripts in this README exercise + the real `argparse` wiring on Windows. +- **Unsupported PNG variants.** 16-bit, palette, grayscale and interlaced files + are rejected by the reader with specific messages, but selftest does not + construct each one. +- **Huge or hostile inputs.** There is no decompressed-size cap beyond the + expected length check; a deliberately enormous or adversarial PNG is not + tested. +- **Performance.** 256x256 is fast; a multi-megapixel image is not benchmarked. +- **That the manifest's checks are correct.** It proves the tool, not the scene + contract. + +## Exit codes + +| Code | Meaning | +| --- | --- | +| 0 | Everything the mode checked passed. | +| 1 | The mode ran and found a mismatch: a failed check, a threshold exceeded, or a selftest assertion failed. | +| 2 | The mode could not run: bad arguments, missing/unreadable/invalid manifest, unreadable image, mismatched sizes, or an unwritable heatmap path. | + +`argparse` also exits 2 for malformed command lines, which matches the table. + +## Known limits and deliberate omissions + +- **No enforced 256x256.** The manifest has no size field, so `expect` only + fails when a declared coordinate falls outside the image. A wrong-size image + whose checks all happen to be in range passes. `diff` does refuse to compare + images of different sizes. If a size gate is wanted, add width/height to the + manifest rather than hard-coding 256 in the tool. +- **PNG support is exactly the contract**: 8-bit RGB (type 2) or RGBA (type 6), + non-interlaced, filter types 0-4. Everything else is rejected with a message. +- **No colour management.** Ancillary chunks such as gAMA, sRGB and iCCP are + ignored; pixels are compared exactly as stored. This matches the scene + contract's "no sRGB conversion". +- **APNG** is read as its default image; animation chunks are ancillary and + ignored. +- **Exact matching in expect.** No per-channel tolerance. Use `diff` thresholds + when measuring drift. +- **A global diff threshold**, not per-scene or per-channel limits. +- **Mean is always over four channels.** For RGB files the alpha term is zero, + which is deliberate and consistent. +- **Heatmap is RGB** and encodes the per-pixel maximum channel delta, not the + sum, and not a perceptual metric (no SSIM or Delta-E). +- **Manifest names are file-name constrained** because they become + `.diff.png`; `png` must be a base name beside the manifest. Unknown + extra JSON keys are ignored. +- **No batch/report output**: no recursive directory scan, no JSON or JUnit + output, no parallelism. Run it once per manifest pair. +- **Stale heatmaps are not removed.** Scenes deleted from a manifest leave their + old `.diff.png` beside the candidate until deleted by hand. +- **The writer always uses filter 0.** The reader handles all five, which is the + part that matters for reading other encoders. +- **Python speed.** Plain nested loops are used for clarity; 256x256 is + immediate, very large images will be slower than a vectorised decoder. + +## What changed in review + +The review standard asks for findings, fixes, evidence. These are the real +changes made after the first working version. + +| Finding | Fix | Evidence | +| --- | --- | --- | +| `build_argument_parser` grew to 92 lines, past the one-screen rule. | Split into `add_expect_command`, `add_diff_command`, `add_inspect_command`, `add_selftest_command`; the builder is now 29 lines. | AST check reports no function over 60 lines. | +| 57 functions had no summary of what they do. | Added one-line docstrings to every function, plus fuller docstrings where a decision needs explanation. | AST check reports no function without a docstring. | +| `step_png_error_paths` read `solid.png` created by an earlier selftest step, an invisible ordering dependency. | The step now writes its own `error-fixture.png`. | Selftest passes; no step reads a file another step was assumed to have left. | +| Two paeth fixture bytes were wrong, so selftest failed on its own fixture rather than on the decoder. | Recomputed all five filtered streams with a separate throwaway encoder and corrected the fixture bytes (251 -> 30, 85 -> 30). | Filter step passes; reader cross-checked against Pillow on adaptive-filter PNGs using all five filters. | +| The heatmap endpoint test asserted pure red at deltas of 245 and 190, so the red end of the ramp was never tested. | Fixtures changed to reference red 0, candidate red 255, giving delta 255. | "heatmap delta 255 pixel is red" and the written-file check both pass. | +| Manifests written by PowerShell with a UTF-8 BOM failed to parse. | Decode with `utf-8-sig`; selftest writes and loads a BOM manifest. | Selftest line "manifest reader accepts a UTF-8 BOM". | +| `Raster.colour_name` would have called any unknown colour type "RGBA". | It now asks `channels_for_colour_type`, which validates. | Code path is shared with the reader; invalid types are rejected before a Raster exists. | +| `diff` used the reference manifest's PNG file name to locate the candidate image, so different file names in the two manifests were ignored. | `diff` now looks up the candidate scene by name and uses the candidate manifest's own `png` field. | Selftest's candidate file is `shim-clear.png` while the reference is `clear.png`, and diff passes. | +| `--max-mean-delta nan` parsed as a float; every `>` comparison against NaN is false, so all scenes would pass. | Threshold parser rejects non-finite values; selftest rejects NaN and infinity. | Selftest line "arguments: thresholds reject negative, NaN, inf and text". | +| The revised scene contract allows 2-5 checks and makes `expect` handle any count. | No code assumption existed; selftest now uses five checks and asserts five PASS rows. | Selftest line "expect: a five-check manifest exits 0". | +| The revised contract makes row order and channel order explicit. | Added an orientation selftest and labelled corner output in `inspect`; README states the flip failure mode. | Selftest line "orientation: top and bottom halves survive". | +| The revised contract wants whole-frame colour failures blamed on the tint. | `diff` prints a scene-named hint whenever every pixel differs. | Selftest asserts the hint names the scene and mentions the tint; manual wrong-tint transcript shows one line per scene. | +| A diff that failed after printing its header showed the stderr error above the header when output was captured. | `diff` and `inspect` flush stdout after the header, before a later read can fail. | The Windows wrong-size transcript now shows the header and then the error. | + +## Review pass 2 — corrections + +The legibility review found three claims in this README that the code did not support. They are corrected +here rather than silently rewritten above: + +- **Exit codes are not identical in every mode.** `expect` treats an unreadable or missing image as a failed + scene and exits **1**; `diff` exits **2** when it cannot compare (missing manifest, size mismatch). Both + mean "the run did not complete", but only `diff` returns 2 for them. A crash that the tool did not + anticipate now exits **2** with a traceback, never 1, so a calling script can tell "the pixels differ" + from "this program failed". +- **The whole-frame mean does not separate "small area failing hard" from "large area failing softly".** + One pixel off by 255 and 255 pixels off by 1 give the same mean. Read the mean together with + `differing` and `max`. +- **The whole-frame hint names pixel values now.** It previously blamed the tint. An unblended draw of the + correct colour also differs everywhere, and so does a scene that was never drawn; the first differing + pixel's reference and candidate RGBA values are printed so a reader can tell those apart. + +Also fixed: a failing `selftest` keeps its fixture directory and prints the path instead of deleting the +evidence, and a `ToolError` raised inside selftest is reported as a selftest failure (exit 1) rather than a +usage error. diff --git a/tools/conformance/README.md b/tools/conformance/README.md new file mode 100644 index 000000000..d39104bbe --- /dev/null +++ b/tools/conformance/README.md @@ -0,0 +1,107 @@ +# Conformance harness: does the Vulkan-backed D3D12 device render what D3D12 renders? + +The shim in `runtime/` reimplements D3D12 on Vulkan. Its device, resource, view, sampler, +copy, clear and barrier paths are covered by `runtime/test/`, but nothing today checks the +thing that matters most: **that a draw produces the same pixels as the host's D3D12.** + +This harness defines a small set of deterministic scenes, renders them with native D3D12 on +the same machine, and checks every pixel that the scene claims. When the shim's draw path +lands, the same scenes go through it and the two image sets are diffed. + +## Layout + +``` +tools/conformance/ + spec/scenes.h the contract: scene kinds, geometry, state, expected pixels + spec/shaders/*.hlsl the two shader pairs, compiled by dxc + native/ native D3D12 reference renderer (Windows, D3D12 + WIC) + compare.py check a render against the contract, diff two renders + COMPARE.md compare.py's modes, exit codes and limits +``` + +## The scenes + +Seven scenes, each chosen to make one failure visible at an exact coordinate: + +| scene | proves | +|---|---| +| `clear` | render target creation, clear value, readback | +| `fullscreen` | vertex shader runs, pipeline binds, one triangle covers the target | +| `depth_order` | depth test rejects a later draw that is behind (green survives over red only because of it) | +| `scissor` | scissor clips at `{48,32,176,96}`, right/bottom exclusive | +| `blend` | 50% source over the clear colour, `SRC_ALPHA`/`INV_SRC_ALPHA` | +| `indexed` | the index buffer is read; vertices are stored out of draw order | + +The contract states the baseline pipeline state every scene inherits (cull NONE, +`TRIANGLELIST`, sample mask, viewport, clip-space z in 0..1 with `w = 1`, row 0 is the top). +Anything an implementer would otherwise have to guess is written down, because two guesses +that disagree produce two different images and neither is wrong on its own terms. + +## Run it + +```powershell +# 1. build and render the reference images +powershell -NoProfile -ExecutionPolicy Bypass -File tools\conformance\native\scripts\build.ps1 +powershell -NoProfile -ExecutionPolicy Bypass -File tools\conformance\native\scripts\run.ps1 + +# 2. check every declared pixel +python tools\conformance\compare.py expect --manifest tools\conformance\native\out\run1\manifest.json + +# 3. prove the scenes are not vacuous: corrupt three pieces of state and require three failures +powershell -NoProfile -ExecutionPolicy Bypass -File tools\conformance\native\scripts\negative-control.ps1 +``` + +Requirements: Windows with the D3D12 runtime, Visual Studio 2022 (C++ x64), Windows SDK +10.0.26100 (`dxc.exe`), Python 3.10+ for `compare.py` (standard library only; no pip +installs). The renderer needs a D3D12 device with feature level 11_0 — it runs on the +Microsoft Basic Render Driver as well as on hardware. + +## Status today + +Against the shim as of `2e5c0f2`, the driver in the pull request reports: + +``` +clear OK 3/3 pixel checks matched (row pitch 1024, readback 262144 bytes) +fullscreen BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) +depth_order BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) +scissor BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) +blend BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) +indexed BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) +``` + +`clear` already proves the whole resource → clear → barrier → copy → readback chain through +the Vulkan device. The five drawn scenes stop at the first call the shim genuinely lacks, so +each one becomes a progress marker as the draw path lands: `CreateRootSignature` → +`CreateGraphicsPipelineState` → the `SetPipelineState` / root-binding group → viewport and +scissor → vertex/index buffers → `OMSetRenderTargets` → `DrawInstanced` / +`DrawIndexedInstanced`. + +## The shader format question + +The reference renderer compiles HLSL to **DXIL** because native D3D12 requires it. The +shim's documented contract is **SPIR-V**, because the game's shaders reach it from the RDNA2 +translator. A PSO implementation that understands only one of them cannot serve both. + +The cheapest resolution, when the draw path lands: compile each conformance shader twice +(`dxc -T vs_6_6` and `dxc -spirv -T vs_6_6`) and let each renderer take the blob it wants. +One workload, one set of expected pixels, no DXIL translator in the shim. + +## Why the scenes are trustworthy + +Three independent checks, all reproducible: + +1. **The renderer verifies itself.** It reads every declared pixel back from the GPU *and* + from the PNG decoded off disk, prints one line per check, and exits non-zero on any + mismatch. 18 checks, 18 passes, on both the NVIDIA and AMD adapters. +2. **The negative control asserts its own result.** It disables the depth test, the blend + state and the scissor rect in a throwaway copy, then requires exactly `depth_order`, + `blend` and `scissor` to fail — each at the pixel that names the state. If a + `String.Replace` silently stops matching, the script throws instead of reporting success. +3. **Determinism is measured**, not assumed: two runs produce byte-identical PNGs. + +## Extending it + +Add a `Scene` to `spec/scenes.h` with its expected pixels. The renderer picks it up through +`SceneKind`; `/we4062` makes an unhandled enumerator a build error, so a new kind cannot +silently render as a clear-only scene. Add a matching row to the shim driver's switch when +the draw path exists. diff --git a/tools/conformance/compare.py b/tools/conformance/compare.py new file mode 100644 index 000000000..d910e9e5a --- /dev/null +++ b/tools/conformance/compare.py @@ -0,0 +1,1846 @@ +#!/usr/bin/env python3 +"""Verify rendered PNGs against declared pixel checks, and diff two renderers. + +Every expectation comes from a manifest.json written by a renderer. This tool +never reads C++ or scene definitions: the images and the manifest are the whole +contract. PNG support is deliberately small and complete for that contract: +8-bit RGB or RGBA, non-interlaced, with all five filter types (0-4), because any +encoder that writes those formats may use any of them. + +Exit codes, identical in every mode: + 0 everything the mode checked passed + 1 the mode ran and found a mismatch (pixels, thresholds or selftest) + 2 the mode could not run (bad arguments, unreadable or invalid input) +""" + +import argparse +import contextlib +import io +import json +import math +import os +import shutil +import sys +import tempfile +import zlib +from dataclasses import dataclass + +EXIT_PASSED = 0 +EXIT_FAILED = 1 +EXIT_ERROR = 2 + +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" +PNG_COLOUR_TYPE_RGB = 2 +PNG_COLOUR_TYPE_RGBA = 6 +PNG_BIT_DEPTH_8 = 8 +PNG_COMPRESSION_DEFLATE = 0 +PNG_FILTER_ADAPTIVE = 0 +PNG_INTERLACE_NONE = 0 +OPAQUE_ALPHA = 255 +MAX_CHANNEL_VALUE = 255 + +# Diff arithmetic always works on RGBA so an RGB reference and an RGBA candidate +# are comparable; RGB images supply an implicit alpha of 255. +RGBA_CHANNEL_COUNT = 4 + +FILTER_NONE = 0 +FILTER_SUB = 1 +FILTER_UP = 2 +FILTER_AVERAGE = 3 +FILTER_PAETH = 4 + +# Dark grey rather than black so that a black pixel in a near-black render does +# not vanish into the "unchanged" background of a heatmap. +HEATMAP_UNCHANGED = (48, 48, 48) + +# Coordinates beyond this are certainly a manifest bug, not a big render. +MAX_SANE_COORDINATE = 1_000_000 + +# Heatmaps are written as ".diff.png", so a scene name must be usable as +# a file name. These are Windows' forbidden characters; the tool runs on Windows. +UNSAFE_FILE_NAME_CHARACTERS = '<>:"/\\|?*' + + +class ToolError(Exception): + """A problem the operator can act on: bad input, or a comparison that cannot run.""" + + +class SelftestMismatch(Exception): + """A selftest expectation did not hold; the message names the expectation.""" + + +# --------------------------------------------------------------------------- +# PNG reading and writing +# --------------------------------------------------------------------------- + + +@dataclass +class Raster: + """Decoded pixels plus the metadata a caller needs to interpret them.""" + + width: int + height: int + colour_type: int + pixels: bytearray + source_path: str + + def channels(self): + """Return 3 or 4, matching the stored PNG colour type.""" + return channels_for_colour_type(self.colour_type, self.source_path) + + def colour_name(self): + """Return the PNG colour type as a short display name.""" + return "RGB" if self.channels() == 3 else "RGBA" + + def stored_pixel(self, x, y): + """Return the channels actually stored at (x, y), three or four values.""" + if x < 0 or y < 0 or x >= self.width or y >= self.height: + raise ToolError( + f"pixel ({x},{y}) is outside the {self.width}x{self.height} image " + f"'{self.source_path}'; check the requested coordinate or the render size" + ) + channels = self.channels() + offset = (y * self.width + x) * channels + return tuple(self.pixels[offset:offset + channels]) + + def pixel_rgba(self, x, y): + """Return (r, g, b, a); RGB images are opaque, because they store no alpha.""" + stored = self.stored_pixel(x, y) + if self.colour_type == PNG_COLOUR_TYPE_RGB: + return stored + (OPAQUE_ALPHA,) + return stored + + +def channels_for_colour_type(colour_type, source_path): + """Return 3 channels for RGB and 4 for RGBA; reject every other PNG colour type.""" + if colour_type == PNG_COLOUR_TYPE_RGB: + return 3 + if colour_type == PNG_COLOUR_TYPE_RGBA: + return 4 + raise ToolError( + f"'{source_path}': PNG colour type {colour_type} is not supported; " + f"only 2 (RGB) and 6 (RGBA) are. Re-export without a palette or grayscale mode" + ) + + +def read_file_bytes(path, description): + """Read a file whole, naming the path and the OS error when it cannot.""" + try: + with open(path, "rb") as file_handle: + return file_handle.read() + except OSError as error: + raise ToolError( + f"cannot read {description} '{path}': {error.strerror or error}. " + f"Check that the file exists and is readable" + ) + + +def read_text_file(path, description): + """Read UTF-8 text, accepting an optional BOM, naming the bad byte on failure.""" + raw_bytes = read_file_bytes(path, description) + try: + # utf-8-sig accepts a BOM, which PowerShell-written manifests may carry. + return raw_bytes.decode("utf-8-sig") + except UnicodeDecodeError as error: + raise ToolError( + f"'{path}' is not valid UTF-8 text: byte {error.start} is invalid. " + f"Check that the file was not saved in a legacy code page" + ) + + +def write_file_bytes(path, data, description): + """Write bytes into an existing directory; never creates one.""" + try: + with open(path, "wb") as file_handle: + file_handle.write(data) + except OSError as error: + raise ToolError( + f"cannot write {description} '{path}': {error.strerror or error}. " + f"Check that the directory exists and is writable" + ) + + +def split_png_chunks(file_bytes, source_path): + """Split a PNG into (type, data) chunks, verifying every length and CRC. + + IEND ends the chunk list; bytes after it are rejected rather than ignored so a + concatenated or padded file is reported instead of silently half-read. + """ + if not file_bytes.startswith(PNG_SIGNATURE): + raise ToolError( + f"'{source_path}' is not a PNG: the 8-byte signature is missing. " + f"Check that the renderer wrote a PNG and not a raw or JPEG dump" + ) + + chunks = [] + offset = len(PNG_SIGNATURE) + while True: + header_end = offset + 8 + if header_end > len(file_bytes): + raise ToolError( + f"'{source_path}': truncated chunk header at byte offset {offset}; " + f"the file ends before the chunk length and type. Check for a partial write" + ) + chunk_length = int.from_bytes(file_bytes[offset:offset + 4], "big") + chunk_type = file_bytes[offset + 4:header_end] + data_end = header_end + chunk_length + crc_end = data_end + 4 + if crc_end > len(file_bytes): + raise ToolError( + f"'{source_path}': truncated {chunk_type.decode('ascii', 'replace')} chunk " + f"at byte offset {offset}: declared length {chunk_length} runs past the end " + f"of the file. Check for a partial write" + ) + chunk_data = file_bytes[header_end:data_end] + stored_crc = int.from_bytes(file_bytes[data_end:crc_end], "big") + computed_crc = png_chunk_crc(chunk_type, chunk_data) + if stored_crc != computed_crc: + raise ToolError( + f"'{source_path}': CRC mismatch in {chunk_type.decode('ascii', 'replace')} " + f"chunk at byte offset {offset}: stored {stored_crc:08x}, computed " + f"{computed_crc:08x}. The file is corrupt; re-render it" + ) + chunks.append((chunk_type, chunk_data)) + offset = crc_end + if chunk_type == b"IEND": + break + + if offset != len(file_bytes): + raise ToolError( + f"'{source_path}': {len(file_bytes) - offset} byte(s) follow IEND at offset " + f"{offset}. Check that two files were not concatenated" + ) + return chunks + + +def parse_image_header(chunks, source_path): + """Validate IHDR and return (width, height, colour_type).""" + first_type, first_data = chunks[0] + if first_type != b"IHDR": + raise ToolError( + f"'{source_path}': first chunk is " + f"{first_type.decode('ascii', 'replace')}, not IHDR; the file is not a valid PNG" + ) + if len(first_data) != 13: + raise ToolError( + f"'{source_path}': IHDR is {len(first_data)} bytes, expected 13. " + f"The file is corrupt; re-render it" + ) + + width = int.from_bytes(first_data[0:4], "big") + height = int.from_bytes(first_data[4:8], "big") + bit_depth = first_data[8] + colour_type = first_data[9] + compression_method = first_data[10] + filter_method = first_data[11] + interlace_method = first_data[12] + + if width == 0 or height == 0: + raise ToolError( + f"'{source_path}': IHDR declares {width}x{height}; a PNG must have at " + f"least one pixel in each direction" + ) + if bit_depth != PNG_BIT_DEPTH_8: + raise ToolError( + f"'{source_path}': bit depth {bit_depth} is not supported; only 8 is. " + f"Re-export from the renderer without 16-bit or packed formats" + ) + if colour_type not in (PNG_COLOUR_TYPE_RGB, PNG_COLOUR_TYPE_RGBA): + raise ToolError( + f"'{source_path}': colour type {colour_type} is not supported; only 2 (RGB) " + f"and 6 (RGBA) are. Re-export without palette or grayscale mode" + ) + if compression_method != PNG_COMPRESSION_DEFLATE: + raise ToolError( + f"'{source_path}': compression method {compression_method} is not deflate(0); " + f"the file is not a PNG this tool can read" + ) + if filter_method != PNG_FILTER_ADAPTIVE: + raise ToolError( + f"'{source_path}': filter method {filter_method} is not adaptive(0); " + f"the file is not a PNG this tool can read" + ) + if interlace_method != PNG_INTERLACE_NONE: + raise ToolError( + f"'{source_path}': interlace method {interlace_method}; only non-interlaced(0) " + f"is supported. Re-export as non-interlaced" + ) + return width, height, colour_type + + +def png_chunk_crc(chunk_type, chunk_data): + """CRC-32 over a PNG chunk's type and data, as the format defines it.""" + return zlib.crc32(chunk_type + chunk_data) & 0xFFFFFFFF + + +def read_png(path): + """Read a supported PNG from disk. Raises ToolError naming the file on any defect.""" + file_bytes = read_file_bytes(path, "PNG image") + chunks = split_png_chunks(file_bytes, path) + width, height, colour_type = parse_image_header(chunks, path) + + compressed_data = b"".join( + chunk_data for chunk_type, chunk_data in chunks if chunk_type == b"IDAT" + ) + if not compressed_data: + raise ToolError( + f"'{path}': no IDAT chunk, so there are no pixels. The file is incomplete; " + f"re-render it" + ) + try: + decompressed_data = zlib.decompress(compressed_data) + except zlib.error as error: + raise ToolError( + f"'{path}': IDAT does not decompress as zlib: {error}. " + f"Check that the file is complete and not a partial write" + ) + + channels = channels_for_colour_type(colour_type, path) + pixels = unfilter_image(decompressed_data, width, height, channels, path) + return Raster(width, height, colour_type, pixels, path) + + +def unfilter_image(filtered_bytes, width, height, channels, source_path): + """Turn filtered scanlines into packed pixels, one filter type per row. + + PNG filters each row against the row above, so decoding must proceed top to + bottom, feeding each reconstructed row into the next row's predictor. + """ + row_byte_count = width * channels + row_stride = row_byte_count + 1 # filter-type byte plus the row + expected_length = row_stride * height + if len(filtered_bytes) != expected_length: + raise ToolError( + f"'{source_path}': decompressed pixel data is {len(filtered_bytes)} bytes, " + f"expected {expected_length} for {width}x{height} with {channels} channels " + f"(rows include one filter-type byte). Check the render size and bit depth" + ) + + pixels = bytearray(row_byte_count * height) + # The specification defines the row above the first row as zeroes, so the + # first row's Up, Average and Paeth predictors have a defined input. + previous_row = bytes(row_byte_count) + for row_index in range(height): + row_start = row_index * row_stride + filter_type = filtered_bytes[row_start] + filtered_row = filtered_bytes[row_start + 1:row_start + row_stride] + reconstructed_row = unfilter_row( + filter_type, filtered_row, previous_row, channels, row_index, source_path + ) + row_offset = row_index * row_byte_count + pixels[row_offset:row_offset + row_byte_count] = reconstructed_row + previous_row = reconstructed_row + return pixels + + +def unfilter_row(filter_type, filtered_row, previous_row, bytes_per_pixel, + row_index, source_path): + """Dispatch one scanline to its filter decoder; reject undefined filter types.""" + if filter_type == FILTER_NONE: + return unfilter_none(filtered_row) + if filter_type == FILTER_SUB: + return unfilter_sub(filtered_row, bytes_per_pixel) + if filter_type == FILTER_UP: + return unfilter_up(filtered_row, previous_row) + if filter_type == FILTER_AVERAGE: + return unfilter_average(filtered_row, previous_row, bytes_per_pixel) + if filter_type == FILTER_PAETH: + return unfilter_paeth(filtered_row, previous_row, bytes_per_pixel) + raise ToolError( + f"'{source_path}': row {row_index} uses PNG filter type {filter_type}; " + f"only 0-4 are defined. The file is corrupt; re-render it" + ) + + +def unfilter_none(filtered_row): + """Return the scanline unchanged (filter 0).""" + return bytes(filtered_row) + + +def unfilter_sub(filtered_row, bytes_per_pixel): + """Add the byte one pixel to the left in the same row (filter 1).""" + reconstructed = bytearray(len(filtered_row)) + for index in range(len(filtered_row)): + left = reconstructed[index - bytes_per_pixel] if index >= bytes_per_pixel else 0 + # PNG filter arithmetic is modulo 256; masking keeps the byte in range. + reconstructed[index] = (filtered_row[index] + left) & 0xFF + return bytes(reconstructed) + + +def unfilter_up(filtered_row, previous_row): + """Add the byte directly above in the previous row (filter 2).""" + reconstructed = bytearray(len(filtered_row)) + for index in range(len(filtered_row)): + reconstructed[index] = (filtered_row[index] + previous_row[index]) & 0xFF + return bytes(reconstructed) + + +def unfilter_average(filtered_row, previous_row, bytes_per_pixel): + """Add the floor of the left and above average (filter 3).""" + reconstructed = bytearray(len(filtered_row)) + for index in range(len(filtered_row)): + left = reconstructed[index - bytes_per_pixel] if index >= bytes_per_pixel else 0 + above = previous_row[index] + reconstructed[index] = (filtered_row[index] + ((left + above) // 2)) & 0xFF + return bytes(reconstructed) + + +def unfilter_paeth(filtered_row, previous_row, bytes_per_pixel): + """Add the Paeth predictor of left, above and upper-left (filter 4).""" + reconstructed = bytearray(len(filtered_row)) + for index in range(len(filtered_row)): + left = reconstructed[index - bytes_per_pixel] if index >= bytes_per_pixel else 0 + above = previous_row[index] + upper_left = previous_row[index - bytes_per_pixel] if index >= bytes_per_pixel else 0 + predictor = paeth_predictor(left, above, upper_left) + reconstructed[index] = (filtered_row[index] + predictor) & 0xFF + return bytes(reconstructed) + + +def paeth_predictor(left, above, upper_left): + """Return PNG's Paeth predictor for one byte. + + The predictor is whichever neighbour is closest to left + above - upper_left. + Ties go left, then above, then upper-left; that order is part of the PNG + specification and swapping it silently corrupts smooth gradients. + """ + estimate = left + above - upper_left + distance_left = abs(estimate - left) + distance_above = abs(estimate - above) + distance_upper_left = abs(estimate - upper_left) + if distance_left <= distance_above and distance_left <= distance_upper_left: + return left + if distance_above <= distance_upper_left: + return above + return upper_left + + +def make_chunk(chunk_type, chunk_data): + """Wrap chunk data as length, type, data and CRC, as PNG requires.""" + length_prefix = len(chunk_data).to_bytes(4, "big") + crc = png_chunk_crc(chunk_type, chunk_data) + return length_prefix + chunk_type + chunk_data + crc.to_bytes(4, "big") + + +def write_png(path, raster): + """Write an 8-bit RGB or RGBA PNG, filter type 0 on every row.""" + channels = channels_for_colour_type(raster.colour_type, path) + row_byte_count = raster.width * channels + if len(raster.pixels) != row_byte_count * raster.height: + raise ToolError( + f"cannot write '{path}': raster holds {len(raster.pixels)} bytes, expected " + f"{row_byte_count * raster.height} for {raster.width}x{raster.height} " + f"{raster.colour_name()}" + ) + + filtered_rows = bytearray() + for row_index in range(raster.height): + filtered_rows.append(FILTER_NONE) + row_offset = row_index * row_byte_count + filtered_rows.extend(raster.pixels[row_offset:row_offset + row_byte_count]) + + header = ( + raster.width.to_bytes(4, "big") + + raster.height.to_bytes(4, "big") + + bytes((PNG_BIT_DEPTH_8, raster.colour_type, PNG_COMPRESSION_DEFLATE, + PNG_FILTER_ADAPTIVE, PNG_INTERLACE_NONE)) + ) + file_bytes = ( + PNG_SIGNATURE + + make_chunk(b"IHDR", header) + + make_chunk(b"IDAT", zlib.compress(bytes(filtered_rows), 9)) + + make_chunk(b"IEND", b"") + ) + write_file_bytes(path, file_bytes, "PNG image") + + +# --------------------------------------------------------------------------- +# Manifest loading +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class ManifestCheck: + x: int + y: int + expected_red: int + expected_green: int + expected_blue: int + expected_alpha: int + reason: str + + +@dataclass(frozen=True) +class ManifestScene: + name: str + png_name: str + checks: tuple + + +@dataclass(frozen=True) +class Manifest: + manifest_path: str + renderer: str + adapter: str + scenes: tuple + + +def require_key(mapping, key, context): + """Return a required mapping key, or fail naming the context and key.""" + if key not in mapping: + raise ToolError(f'{context}: required key "{key}" is missing') + return mapping[key] + + +def require_string(mapping, key, context): + """Return a required string value and reject other JSON types.""" + value = require_key(mapping, key, context) + if not isinstance(value, str): + raise ToolError(f'{context}: "{key}" must be a string, got {value!r}') + return value + + +def require_list(mapping, key, context): + """Return a required JSON list and reject other JSON types.""" + value = require_key(mapping, key, context) + if not isinstance(value, list): + raise ToolError(f'{context}: "{key}" must be a list, got {value!r}') + return value + + +def require_int(mapping, key, minimum, maximum, context): + """Return a required integer in range, rejecting booleans and floats.""" + value = require_key(mapping, key, context) + # bool is an int subclass; true would otherwise pass as coordinate 1. + if isinstance(value, bool) or not isinstance(value, int): + raise ToolError(f'{context}: "{key}" must be an integer, got {value!r}') + if value < minimum or value > maximum: + raise ToolError( + f'{context}: "{key}" must be between {minimum} and {maximum}, got {value}' + ) + return value + + +def parse_manifest_check(raw_check, check_index, scene_context): + """Validate one declared pixel into a ManifestCheck.""" + context = f"{scene_context}, check {check_index + 1}" + if not isinstance(raw_check, dict): + raise ToolError(f"{context}: must be an object, got {raw_check!r}") + reason = raw_check.get("why", "") + if not isinstance(reason, str): + raise ToolError(f'{context}: "why" must be a string when present, got {reason!r}') + return ManifestCheck( + x=require_int(raw_check, "x", 0, MAX_SANE_COORDINATE, context), + y=require_int(raw_check, "y", 0, MAX_SANE_COORDINATE, context), + expected_red=require_int(raw_check, "r", 0, MAX_CHANNEL_VALUE, context), + expected_green=require_int(raw_check, "g", 0, MAX_CHANNEL_VALUE, context), + expected_blue=require_int(raw_check, "b", 0, MAX_CHANNEL_VALUE, context), + expected_alpha=require_int(raw_check, "a", 0, MAX_CHANNEL_VALUE, context), + reason=reason, + ) + + +def require_safe_file_name(value, key, context, reason): + """Reject a manifest string that would escape its directory or break a path.""" + has_control_character = any(ord(character) < 32 for character in value) + has_unsafe_character = any( + character in UNSAFE_FILE_NAME_CHARACTERS for character in value + ) + if (os.path.basename(value) != value or value in (".", "..") + or has_control_character or has_unsafe_character): + raise ToolError( + f'{context}: "{key}" must be a plain file name; got {value!r}. {reason}' + ) + return value + + +def parse_manifest_scene(raw_scene, scene_index, manifest_path): + """Validate one scene entry, including a non-empty check list.""" + context = f"manifest '{manifest_path}': scene {scene_index + 1}" + if not isinstance(raw_scene, dict): + raise ToolError(f"{context}: must be an object, got {raw_scene!r}") + name = require_string(raw_scene, "name", context) + if not name.strip(): + raise ToolError(f"{context}: \"name\" is empty; it identifies the scene and the diff row") + name = require_safe_file_name( + name, "name", context, "It is also used as the .diff.png file name" + ) + context = f"manifest '{manifest_path}': scene {scene_index + 1} ('{name}')" + + png_name = require_string(raw_scene, "png", context) + png_name = require_safe_file_name( + png_name, "png", context, "It must name an image beside the manifest" + ) + raw_checks = require_list(raw_scene, "checks", context) + if not raw_checks: + raise ToolError( + f"{context}: \"checks\" is empty; a scene with no pixel checks proves " + f"nothing. Add at least one check or remove the scene" + ) + checks = tuple( + parse_manifest_check(raw_check, check_index, context) + for check_index, raw_check in enumerate(raw_checks) + ) + return ManifestScene(name=name, png_name=png_name, checks=checks) + + +def parse_manifest_scenes(raw_scenes, manifest_path): + """Validate all scenes and reject duplicate scene or PNG names.""" + scenes = [] + scene_number_by_name = {} + png_number_by_name = {} + for scene_index, raw_scene in enumerate(raw_scenes): + scene = parse_manifest_scene(raw_scene, scene_index, manifest_path) + if scene.name in scene_number_by_name: + raise ToolError( + f"manifest '{manifest_path}': scene {scene_index + 1} repeats name " + f"'{scene.name}' from scene {scene_number_by_name[scene.name] + 1}; " + f"diff matches scenes by name, so duplicates are ambiguous" + ) + if scene.png_name in png_number_by_name: + raise ToolError( + f"manifest '{manifest_path}': scene {scene_index + 1} repeats png " + f"'{scene.png_name}' from scene {png_number_by_name[scene.png_name] + 1}; " + f"diff would write the same .diff.png twice" + ) + scene_number_by_name[scene.name] = scene_index + png_number_by_name[scene.png_name] = scene_index + scenes.append(scene) + return tuple(scenes) + + +def load_manifest(path): + """Load and validate a renderer manifest. Unknown extra keys are ignored.""" + manifest_path = os.path.abspath(path) + text = read_text_file(manifest_path, "scene manifest") + try: + document = json.loads(text) + except json.JSONDecodeError as error: + raise ToolError( + f"manifest '{manifest_path}' is not valid JSON: {error.msg} at line " + f"{error.lineno} column {error.colno}. Check for a missing comma or " + f"trailing text" + ) + if not isinstance(document, dict): + raise ToolError( + f"manifest '{manifest_path}': top level must be an object, got " + f"{type(document).__name__}" + ) + + context = f"manifest '{manifest_path}'" + renderer = require_string(document, "renderer", context) + adapter = require_string(document, "adapter", context) + raw_scenes = require_list(document, "scenes", context) + if not raw_scenes: + raise ToolError( + f"manifest '{manifest_path}': \"scenes\" is empty; there is nothing to " + f"check. Point --manifest at the renderer's manifest.json" + ) + return Manifest( + manifest_path=manifest_path, + renderer=renderer, + adapter=adapter, + scenes=parse_manifest_scenes(raw_scenes, manifest_path), + ) + + +def resolve_image_directory(manifest, override): + """Return the absolute image directory, checking that an explicit --dir exists.""" + if override: + if not os.path.isdir(override): + raise ToolError( + f"image directory '{override}' does not exist or is not a directory. " + f"Check the --dir argument" + ) + return os.path.abspath(override) + return os.path.dirname(manifest.manifest_path) + + +def scene_image_path(image_directory, png_name): + """Join an image directory with a manifest's PNG file name.""" + return os.path.join(image_directory, png_name) + + +# --------------------------------------------------------------------------- +# expect +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class CheckOutcome: + scene_name: str + check: ManifestCheck + actual: tuple + failure_note: str + # Decided from the comparison itself. Deriving it from failure_note made the verdict + # depend on whether a "why" string happened to be present. + passed_check: bool + + @property + def passed(self): + """True when the pixel matched; failure_note is display text only.""" + return self.passed_check + + +@dataclass(frozen=True) +class SceneOutcome: + scene: ManifestScene + checks: tuple + image_problem: str = "" + + +def evaluate_check(scene_name, image, check): + """Compare one declared pixel; bounds and absent alpha are explained, not raised.""" + if check.x >= image.width or check.y >= image.height: + note = ( + f"coordinate is outside the {image.width}x{image.height} image " + f"'{image.source_path}'; check the manifest coordinate and the render size" + ) + return CheckOutcome(scene_name, check, (), note, False) + + stored = image.stored_pixel(check.x, check.y) + declared = (check.expected_red, check.expected_green, check.expected_blue, + check.expected_alpha) + if image.pixel_rgba(check.x, check.y) == declared: + return CheckOutcome(scene_name, check, stored, "", True) + + if image.colour_type == PNG_COLOUR_TYPE_RGB and check.expected_alpha != OPAQUE_ALPHA: + note = ( + f"image stores no alpha channel, so declared alpha {check.expected_alpha} " + f"cannot match; {check.reason or 'fix the check or render RGBA'}" + ) + else: + note = check.reason or "pixel does not match the declared value" + return CheckOutcome(scene_name, check, stored, note, False) + + +def verify_scene(scene, image_directory): + """Read one scene's image and evaluate every check; image errors stay scene-local.""" + image_path = scene_image_path(image_directory, scene.png_name) + try: + image = read_png(image_path) + except ToolError as error: + return SceneOutcome(scene, (), str(error)) + checks = tuple( + evaluate_check(scene.name, image, check) for check in scene.checks + ) + return SceneOutcome(scene, checks) + + +def format_channel_values(values): + """Render channel values as comma-separated decimals for the report.""" + return ",".join(str(value) for value in values) + + +def plural(count, singular): + """Return the singular or plural noun for a count, for readable summaries.""" + return singular if count == 1 else singular + "s" + + +def format_check_line(outcome, scene_column_width): + """Format one PASS or FAIL row with expected, actual and failure reason.""" + status = "PASS" if outcome.passed else "FAIL" + coordinate = f"({outcome.check.x},{outcome.check.y})" + expected = format_channel_values(( + outcome.check.expected_red, + outcome.check.expected_green, + outcome.check.expected_blue, + outcome.check.expected_alpha, + )) + got = format_channel_values(outcome.actual) if outcome.actual else "not read" + line = ( + f"{status} {outcome.scene_name:<{scene_column_width}} {coordinate:<12} " + f"expected {expected:<17} got {got}" + ) + if not outcome.passed: + line += f" ({outcome.failure_note})" + return line + + +def print_expect_report(scene_outcomes): + """Print every check row and the summary; return True when all passed.""" + scene_column_width = max(len(outcome.scene.name) for outcome in scene_outcomes) + passed_count = 0 + failed_count = 0 + unreadable_count = 0 + for scene_outcome in scene_outcomes: + if scene_outcome.image_problem: + unreadable_count += 1 + failed_count += len(scene_outcome.scene.checks) + print( + f"FAIL {scene_outcome.scene.name:<{scene_column_width}} " + f"image problem: {scene_outcome.image_problem}" + ) + continue + for check_outcome in scene_outcome.checks: + print(format_check_line(check_outcome, scene_column_width)) + if check_outcome.passed: + passed_count += 1 + else: + failed_count += 1 + + check_count = passed_count + failed_count + summary = ( + f"{len(scene_outcomes)} {plural(len(scene_outcomes), 'scene')}, " + f"{check_count} {plural(check_count, 'check')}: " + f"{passed_count} passed, {failed_count} failed" + ) + if unreadable_count: + summary += ( + f", {unreadable_count} {plural(unreadable_count, 'image')} " + f"could not be read" + ) + print() + print(summary) + return failed_count == 0 + + +def command_expect(arguments): + """Run the expect mode and return its exit code.""" + manifest = load_manifest(arguments.manifest) + image_directory = resolve_image_directory(manifest, arguments.dir) + scene_outcomes = [ + verify_scene(scene, image_directory) for scene in manifest.scenes + ] + return EXIT_PASSED if print_expect_report(scene_outcomes) else EXIT_FAILED + + +# --------------------------------------------------------------------------- +# diff +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class DiffStats: + differing_pixels: int + total_pixels: int + differing_percent: float + mean_absolute_delta: float + max_channel_delta: int + first_difference: tuple + # The RGBA values at first_difference, so a failure line can show what actually + # differed instead of only how much. + first_reference_pixel: tuple + first_candidate_pixel: tuple + + +def compare_rasters(reference, candidate): + """Compare two same-size images using RGBA; RGB images count as opaque.""" + if (reference.width, reference.height) != (candidate.width, candidate.height): + raise ToolError( + f"cannot compare '{reference.source_path}' " + f"({reference.width}x{reference.height}) with '{candidate.source_path}' " + f"({candidate.width}x{candidate.height}); re-render at the same size" + ) + + total_pixels = reference.width * reference.height + # Every RGBA sample compared, so this is 4x the pixel count, not the pixel count. + channel_sample_count = total_pixels * RGBA_CHANNEL_COUNT + differing_pixels = 0 + total_absolute_delta = 0 + max_channel_delta = 0 + first_difference = None + first_reference_pixel = () + first_candidate_pixel = () + + for y in range(reference.height): + for x in range(reference.width): + reference_pixel = reference.pixel_rgba(x, y) + candidate_pixel = candidate.pixel_rgba(x, y) + pixel_delta = 0 + for channel_index in range(RGBA_CHANNEL_COUNT): + channel_delta = abs(reference_pixel[channel_index] + - candidate_pixel[channel_index]) + total_absolute_delta += channel_delta + pixel_delta = max(pixel_delta, channel_delta) + if pixel_delta == 0: + continue + differing_pixels += 1 + max_channel_delta = max(max_channel_delta, pixel_delta) + if first_difference is None: + first_difference = (x, y) + first_reference_pixel = reference_pixel + first_candidate_pixel = candidate_pixel + + return DiffStats( + differing_pixels=differing_pixels, + total_pixels=total_pixels, + differing_percent=100.0 * differing_pixels / total_pixels, + # Mean over every channel sample of every pixel. Read it together with + # differing_pixels and max_channel_delta: on its own, one pixel off by 255 and 255 + # pixels off by 1 give the same mean, so the mean alone cannot rank a failure. + mean_absolute_delta=total_absolute_delta / channel_sample_count, + max_channel_delta=max_channel_delta, + first_difference=first_difference, + first_reference_pixel=first_reference_pixel, + first_candidate_pixel=first_candidate_pixel, + ) + + +def heatmap_colour(channel_delta): + """Map delta 1 to pure blue and delta 255 to pure red, on a linear ramp.""" + if channel_delta <= 0: + return HEATMAP_UNCHANGED + red = round(MAX_CHANNEL_VALUE * (channel_delta - 1) / (MAX_CHANNEL_VALUE - 1)) + return (red, 0, MAX_CHANNEL_VALUE - red) + + +def build_heatmap(reference, candidate): + """Build an RGB image: unchanged grey, differences ramped blue to red.""" + if (reference.width, reference.height) != (candidate.width, candidate.height): + raise ToolError( + f"cannot build a heatmap from {reference.width}x{reference.height} and " + f"{candidate.width}x{candidate.height} images; sizes must match" + ) + pixels = bytearray(reference.width * reference.height * 3) + for y in range(reference.height): + for x in range(reference.width): + reference_pixel = reference.pixel_rgba(x, y) + candidate_pixel = candidate.pixel_rgba(x, y) + pixel_delta = max( + abs(reference_pixel[channel] - candidate_pixel[channel]) + for channel in range(RGBA_CHANNEL_COUNT) + ) + offset = (y * reference.width + x) * 3 + pixels[offset:offset + 3] = bytes(heatmap_colour(pixel_delta)) + return Raster( + width=reference.width, + height=reference.height, + colour_type=PNG_COLOUR_TYPE_RGB, + pixels=pixels, + source_path=os.path.join( + os.path.dirname(candidate.source_path), + "difference heatmap for " + os.path.basename(candidate.source_path), + ), + ) + + +def format_rgba(pixel): + """Format an RGBA tuple for a failure line; empty reads as a dash.""" + if not pixel: + return "-" + return ",".join(str(channel) for channel in pixel) + + +def threshold_violation(stats, max_differing_percent, max_mean_delta): + """Return why the scene fails the thresholds, or "" when it passes.""" + if stats.differing_percent > max_differing_percent: + return ( + f"differing pixels {stats.differing_percent:.3f}% exceed " + f"--max-differing-percent {max_differing_percent:.3f}%" + ) + if stats.mean_absolute_delta > max_mean_delta: + return ( + f"mean absolute channel delta {stats.mean_absolute_delta:.4f} exceeds " + f"--max-mean-delta {max_mean_delta:.4f}" + ) + return "" + + +def whole_frame_difference_note(scene_name, stats): + """Explain a whole-frame difference, with the values that identify the cause. + + A whole-frame difference is not automatically the tint: an unblended draw of the + correct colour also differs everywhere, and so does a scene that was never drawn. + The pixel values are what tell those apart, so they are printed. + """ + if stats.total_pixels == 0 or stats.differing_pixels != stats.total_pixels: + return "" + reference_text = format_rgba(stats.first_reference_pixel) + candidate_text = format_rgba(stats.first_candidate_pixel) + return ( + f"scene '{scene_name}': every pixel differs - at the first difference the " + f"reference is {reference_text} and the candidate is {candidate_text}. " + f"Suspects, in order: the constant buffer tint, the clear colour, blend state, " + f"or a draw that never happened" + ) + + +def format_diff_line(scene_name, stats, scene_column_width, violation): + """Format one scene's diff metrics as a single table row.""" + status = "FAIL" if violation else "PASS" + if stats.first_difference: + first = f"({stats.first_difference[0]},{stats.first_difference[1]})" + else: + first = "-" + line = ( + f"{status} {scene_name:<{scene_column_width}} " + f"differing {stats.differing_pixels}/{stats.total_pixels} " + f"({stats.differing_percent:.3f}%) mean {stats.mean_absolute_delta:.4f} " + f"max {stats.max_channel_delta} first {first}" + ) + if violation: + line += f" ({violation})" + return line + + +def match_manifest_scenes(reference, candidate): + """Require both manifests to declare exactly the same scene names.""" + reference_names = {scene.name for scene in reference.scenes} + candidate_names = {scene.name for scene in candidate.scenes} + missing_names = sorted(reference_names - candidate_names) + extra_names = sorted(candidate_names - reference_names) + if missing_names: + raise ToolError( + f"candidate manifest '{candidate.manifest_path}' is missing scene(s) the " + f"reference declares: {', '.join(missing_names)}. Re-render them" + ) + if extra_names: + raise ToolError( + f"candidate manifest '{candidate.manifest_path}' has scenes the reference " + f"does not declare: {', '.join(extra_names)}. Remove them or update the reference" + ) + + +def command_diff(arguments): + """Run the diff mode: metrics, heatmaps, thresholds and exit code.""" + reference = load_manifest(arguments.reference) + candidate = load_manifest(arguments.candidate) + reference_directory = resolve_image_directory(reference, arguments.reference_dir) + candidate_directory = resolve_image_directory(candidate, arguments.candidate_dir) + match_manifest_scenes(reference, candidate) + + print(f"reference: {reference.manifest_path}") + print(f" renderer '{reference.renderer}', adapter '{reference.adapter}'") + print(f"candidate: {candidate.manifest_path}") + print(f" renderer '{candidate.renderer}', adapter '{candidate.adapter}'") + print() + # Flush before a later read can fail onto stderr, so the error is not + # printed above the header it belongs to when output is redirected. + sys.stdout.flush() + + # Each manifest names its own files, so look up the candidate scene itself + # rather than assuming both renderers wrote the same PNG file name. + candidate_scenes_by_name = {scene.name: scene for scene in candidate.scenes} + scene_column_width = max(len(scene.name) for scene in reference.scenes) + failing_scenes = [] + for scene in reference.scenes: + candidate_scene = candidate_scenes_by_name[scene.name] + reference_image = read_png(scene_image_path(reference_directory, scene.png_name)) + candidate_image = read_png( + scene_image_path(candidate_directory, candidate_scene.png_name) + ) + stats = compare_rasters(reference_image, candidate_image) + heatmap = build_heatmap(reference_image, candidate_image) + heatmap_path = os.path.join(candidate_directory, f"{scene.name}.diff.png") + write_png(heatmap_path, heatmap) + + violation = threshold_violation( + stats, arguments.max_differing_percent, arguments.max_mean_delta + ) + print(format_diff_line(scene.name, stats, scene_column_width, violation)) + whole_frame_note = whole_frame_difference_note(scene.name, stats) + if whole_frame_note: + print(f" {whole_frame_note}") + if violation: + failing_scenes.append(scene.name) + + print() + scene_count = len(reference.scenes) + print( + f"{scene_count} {plural(scene_count, 'scene')} compared, " + f"{len(failing_scenes)} exceed the thresholds. Heatmaps written beside the " + f"candidate images as .diff.png" + ) + return EXIT_FAILED if failing_scenes else EXIT_PASSED + + +# --------------------------------------------------------------------------- +# inspect +# --------------------------------------------------------------------------- + + +def pixel_coordinate_argument(text): + """Parse an argparse X,Y pixel argument into an (x, y) tuple.""" + parts = text.split(",") + if len(parts) != 2: + raise argparse.ArgumentTypeError( + f"'{text}' is not x,y; use for example --pixel 12,34" + ) + try: + x = int(parts[0]) + y = int(parts[1]) + except ValueError: + raise argparse.ArgumentTypeError( + f"'{text}' has a non-integer part; use for example --pixel 12,34" + ) + return (x, y) + + +def format_inspection_line(label, x, y, channel_values): + """Format one labelled pixel row for inspect output.""" + coordinate = f"({x},{y})" + return ( + f" {label:<12} {coordinate:<11}= " + f"{format_channel_values(channel_values)}" + ) + + +def command_inspect(arguments): + """Run the inspect mode and return its exit code. + + Top-left and bottom-right are always printed so a vertical flip is visible: + the corners are labelled and their coordinates are explicit. + """ + image = read_png(arguments.image) + print(arguments.image) + print( + f" {image.width} x {image.height}, {image.colour_name()}, 8 bits per channel, " + f"non-interlaced" + ) + sys.stdout.flush() + bottom_right_x = image.width - 1 + bottom_right_y = image.height - 1 + print(format_inspection_line("top-left", 0, 0, image.stored_pixel(0, 0))) + print( + format_inspection_line( + "bottom-right", bottom_right_x, bottom_right_y, + image.stored_pixel(bottom_right_x, bottom_right_y), + ) + ) + if arguments.pixel: + for x, y in arguments.pixel: + print(format_inspection_line("pixel", x, y, image.stored_pixel(x, y))) + else: + print(" no --pixel given; also showing top-right, bottom-left and centre") + for label, x, y in ( + ("top-right", bottom_right_x, 0), + ("bottom-left", 0, bottom_right_y), + ("centre", image.width // 2, image.height // 2), + ): + print(format_inspection_line(label, x, y, image.stored_pixel(x, y))) + return EXIT_PASSED + + +# --------------------------------------------------------------------------- +# selftest +# --------------------------------------------------------------------------- + + +def require_equal(description, actual, expected): + """Fail the selftest unless actual equals expected.""" + if actual != expected: + raise SelftestMismatch( + f"{description}: expected {expected!r}, got {actual!r}" + ) + + +def require_true(description, condition): + """Fail the selftest unless the condition holds.""" + if not condition: + raise SelftestMismatch(description) + + +def assert_tool_error(action, expected_fragment, description): + """Require the action to raise ToolError containing an expected fragment.""" + try: + action() + except ToolError as error: + require_true( + f"{description}: message should contain {expected_fragment!r}, got '{error}'", + expected_fragment in str(error), + ) + return + raise SelftestMismatch(f"{description}: expected a ToolError, but the call succeeded") + + +def assert_argument_error(action, description): + """Require the action to raise argparse.ArgumentTypeError.""" + try: + action() + except argparse.ArgumentTypeError: + return + raise SelftestMismatch( + f"{description}: expected an ArgumentTypeError, but the call succeeded" + ) + + +def make_solid_raster(width, height, colour_type, colour, source_path): + """Build an in-memory raster filled with one colour.""" + return Raster( + width=width, + height=height, + colour_type=colour_type, + pixels=bytearray(bytes(colour) * (width * height)), + source_path=source_path, + ) + + +def write_selftest_manifest(path, renderer, adapter, scenes): + """Write a manifest in the renderer's shape for selftest fixtures.""" + document = {"renderer": renderer, "adapter": adapter, "scenes": scenes} + write_file_bytes( + path, json.dumps(document, indent=2).encode("utf-8"), "selftest manifest" + ) + + +def run_and_capture(command, arguments): + """Run a command with stdout captured; return its exit code and text.""" + output_buffer = io.StringIO() + with contextlib.redirect_stdout(output_buffer): + exit_code = command(arguments) + return exit_code, output_buffer.getvalue() + + +def make_selftest_directory(path): + """Create one selftest fixture directory, reporting failure as a mismatch.""" + try: + os.makedirs(path) + except OSError as error: + raise SelftestMismatch( + f"cannot create selftest fixture directory '{path}': {error}" + ) + + +def step_png_roundtrip(directory): + """Assert RGB and RGBA round-trip, rectangle pixels and write determinism.""" + solid = make_solid_raster(8, 6, PNG_COLOUR_TYPE_RGB, (10, 20, 30), "selftest solid") + solid_path = os.path.join(directory, "solid.png") + write_png(solid_path, solid) + decoded = read_png(solid_path) + require_equal("solid PNG width", decoded.width, 8) + require_equal("solid PNG height", decoded.height, 6) + require_equal("solid PNG colour type", decoded.colour_type, PNG_COLOUR_TYPE_RGB) + require_equal("solid PNG pixels", bytes(decoded.pixels), bytes(solid.pixels)) + require_equal("solid PNG pixel (0,0)", decoded.stored_pixel(0, 0), (10, 20, 30)) + print("ok PNG round-trip: RGB pixels and alpha-free pixel reads") + + rectangle = make_solid_raster( + 8, 6, PNG_COLOUR_TYPE_RGBA, (10, 20, 30, 255), "selftest rectangle" + ) + for y in range(1, 5): + for x in range(2, 6): + offset = (y * 8 + x) * 4 + rectangle.pixels[offset:offset + 4] = bytes((200, 30, 60, 200)) + rectangle_path = os.path.join(directory, "rectangle.png") + write_png(rectangle_path, rectangle) + decoded_rectangle = read_png(rectangle_path) + require_equal( + "rectangle PNG pixel inside the rectangle", + decoded_rectangle.stored_pixel(2, 1), + (200, 30, 60, 200), + ) + require_equal( + "rectangle PNG pixel at its bottom-right corner", + decoded_rectangle.stored_pixel(5, 4), + (200, 30, 60, 200), + ) + require_equal( + "rectangle PNG pixel left of the rectangle", + decoded_rectangle.pixel_rgba(1, 1), + (10, 20, 30, 255), + ) + require_equal( + "rectangle PNG pixel right of the rectangle", + decoded_rectangle.stored_pixel(6, 1), + (10, 20, 30, 255), + ) + print("ok PNG round-trip: RGBA rectangle at (2,1)-(5,4), alpha 200 preserved") + + second_path = os.path.join(directory, "solid-again.png") + write_png(second_path, solid) + require_equal( + "two writes of the same raster are byte-identical", + read_file_bytes(second_path, "selftest PNG"), + read_file_bytes(solid_path, "selftest PNG"), + ) + print("ok PNG writer is deterministic: two writes of one raster match byte for byte") + + +def step_png_error_paths(directory): + """Assert unwritable directory, corrupt CRC and truncation are reported.""" + solid = make_solid_raster(8, 6, PNG_COLOUR_TYPE_RGB, (10, 20, 30), "selftest solid") + solid_path = os.path.join(directory, "error-fixture.png") + write_png(solid_path, solid) + + missing_directory_path = os.path.join(directory, "missing-subdirectory", "image.png") + assert_tool_error( + lambda: write_png(missing_directory_path, solid), + "cannot write", + "writing into a missing directory", + ) + print("ok failure path: unwritable output directory names the path") + + crc_path = os.path.join(directory, "bad-crc.png") + write_png(crc_path, solid) + corrupt_bytes = bytearray(read_file_bytes(crc_path, "selftest PNG")) + corrupt_bytes[45] ^= 0xFF # inside IDAT data: offset 33 starts IDAT, 8 bytes of header + write_file_bytes(crc_path, bytes(corrupt_bytes), "selftest PNG") + assert_tool_error( + lambda: read_png(crc_path), + "CRC mismatch", + "reading a PNG with a corrupted IDAT", + ) + print("ok failure path: corrupt IDAT reports the CRC and byte offset") + + truncated_path = os.path.join(directory, "truncated.png") + truncated_bytes = read_file_bytes(solid_path, "selftest PNG")[:60] + write_file_bytes(truncated_path, truncated_bytes, "selftest PNG") + assert_tool_error( + lambda: read_png(truncated_path), + "truncated", + "reading a truncated PNG", + ) + print("ok failure path: truncated file reports the byte offset") + + +def step_filter_decoders(): + """Assert filters 0-4 decode hand-computed streams and bad streams fail.""" + # 3x2 RGB fixture: row 0 is (10,20,30) (200,30,60) (105,25,45); + # row 1 is (40,50,60) (70,80,90) (100,110,120). The five filtered streams + # were computed by hand from the PNG filter definitions, independently of + # the decoder, so a mirrored encoder bug cannot hide here. + expected_pixels = bytes(( + 10, 20, 30, 200, 30, 60, 105, 25, 45, + 40, 50, 60, 70, 80, 90, 100, 110, 120, + )) + filtered_streams = { + FILTER_NONE: bytes(( + FILTER_NONE, 10, 20, 30, 200, 30, 60, 105, 25, 45, + FILTER_NONE, 40, 50, 60, 70, 80, 90, 100, 110, 120, + )), + FILTER_SUB: bytes(( + FILTER_SUB, 10, 20, 30, 190, 10, 30, 161, 251, 241, + FILTER_SUB, 40, 50, 60, 30, 30, 30, 30, 30, 30, + )), + FILTER_UP: bytes(( + FILTER_UP, 10, 20, 30, 200, 30, 60, 105, 25, 45, + FILTER_UP, 30, 30, 30, 126, 50, 30, 251, 85, 75, + )), + FILTER_AVERAGE: bytes(( + FILTER_AVERAGE, 10, 20, 30, 195, 20, 45, 5, 10, 15, + FILTER_AVERAGE, 35, 40, 45, 206, 40, 30, 13, 58, 53, + )), + FILTER_PAETH: bytes(( + FILTER_PAETH, 10, 20, 30, 190, 10, 30, 161, 251, 241, + FILTER_PAETH, 30, 30, 30, 126, 30, 30, 30, 30, 30, + )), + } + for filter_type in sorted(filtered_streams): + decoded = unfilter_image(filtered_streams[filter_type], 3, 2, 3, + "selftest filter fixture") + require_equal( + f"filter {filter_type} reconstructs the fixture", + bytes(decoded), + expected_pixels, + ) + print("ok PNG filters 0-4 decode: hand-computed streams for a 3x2 RGB fixture") + + truncated_stream = filtered_streams[FILTER_NONE][:-1] + assert_tool_error( + lambda: unfilter_image(truncated_stream, 3, 2, 3, "selftest filter fixture"), + "decompressed pixel data", + "filter data one byte short", + ) + unknown_filter_stream = bytearray(filtered_streams[FILTER_NONE]) + unknown_filter_stream[0] = 5 + assert_tool_error( + lambda: unfilter_image(bytes(unknown_filter_stream), 3, 2, 3, "selftest fixture"), + "filter type 5", + "undefined filter type", + ) + print("ok failure path: short filter data and undefined filter type are rejected") + + +def step_orientation_and_channel_order(directory): + """Assert row 0 is the top, channels stay R,G,B, and inspect labels both corners.""" + top_colour = (200, 30, 60) + bottom_colour = (10, 20, 30) + image = make_solid_raster( + 4, 4, PNG_COLOUR_TYPE_RGB, bottom_colour, "selftest orientation" + ) + for y in range(2): + for x in range(4): + offset = (y * 4 + x) * 3 + image.pixels[offset:offset + 3] = bytes(top_colour) + + image_path = os.path.join(directory, "orientation.png") + write_png(image_path, image) + decoded = read_png(image_path) + require_equal("row 0 keeps the top colour", decoded.stored_pixel(0, 0), top_colour) + require_equal("last row keeps the bottom colour", decoded.stored_pixel(3, 3), + bottom_colour) + require_equal("channels stay in R,G,B order", decoded.stored_pixel(0, 0), + (200, 30, 60)) + + exit_code, output = run_and_capture( + command_inspect, argparse.Namespace(image=image_path, pixel=None) + ) + require_equal("inspect exit code", exit_code, EXIT_PASSED) + require_true("inspect labels top-left with its value", + "top-left" in output and "(0,0)" in output and "200,30,60" in output) + require_true("inspect labels bottom-right with its value", + "bottom-right" in output and "(3,3)" in output and "10,20,30" in output) + print("ok orientation: top and bottom halves survive; inspect labels both corners") + + +def step_expect_matching(directory): + """Assert expect passes checks that match the fixture image.""" + image_path = os.path.join(directory, "clear.png") + write_png( + image_path, + make_solid_raster(8, 6, PNG_COLOUR_TYPE_RGB, (10, 20, 30), "selftest clear"), + ) + manifest_path = os.path.join(directory, "manifest-good.json") + write_selftest_manifest(manifest_path, "selftest", "fixture", [{ + "name": "clear", + "png": "clear.png", + "checks": [ + {"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, + "why": "top-left is the clear colour"}, + {"x": 7, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, + "why": "top-right is the clear colour"}, + {"x": 0, "y": 5, "r": 10, "g": 20, "b": 30, "a": 255, + "why": "bottom-left is the clear colour"}, + {"x": 7, "y": 5, "r": 10, "g": 20, "b": 30, "a": 255, + "why": "bottom-right is the clear colour"}, + {"x": 4, "y": 3, "r": 10, "g": 20, "b": 30, "a": 255, + "why": "centre-ish pixel is the clear colour"}, + ], + }]) + exit_code, output = run_and_capture( + command_expect, argparse.Namespace(manifest=manifest_path, dir=None) + ) + require_equal("expect exit code for matching pixels", exit_code, EXIT_PASSED) + require_true("expect reports all five checks", output.count("PASS clear") == 5) + require_true("expect output has no FAIL row", "FAIL" not in output) + require_equal("expect evaluates checks in any count", len( + load_manifest(manifest_path).scenes[0].checks + ), 5) + print("ok expect: a five-check manifest exits 0 and prints five PASS rows") + + bom_path = os.path.join(directory, "manifest-bom.json") + bom_bytes = b"\xef\xbb\xbf" + read_file_bytes(manifest_path, "selftest manifest") + write_file_bytes(bom_path, bom_bytes, "selftest manifest") + require_equal("manifest with a UTF-8 BOM still loads", + len(load_manifest(bom_path).scenes), 1) + print("ok manifest reader accepts a UTF-8 BOM, as PowerShell writes") + + +def step_expect_failures(directory): + """Assert a wrong pixel and an out-of-range coordinate both fail.""" + image_path = os.path.join(directory, "clear.png") + write_png( + image_path, + make_solid_raster(8, 6, PNG_COLOUR_TYPE_RGB, (10, 20, 30), "selftest clear"), + ) + bad_manifest_path = os.path.join(directory, "manifest-bad.json") + write_selftest_manifest(bad_manifest_path, "selftest", "fixture", [{ + "name": "clear", + "png": "clear.png", + "checks": [ + {"x": 0, "y": 0, "r": 1, "g": 2, "b": 3, "a": 255, + "why": "deliberate wrong expectation"}, + {"x": 8, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, + "why": "coordinate one past the right edge"}, + ], + }]) + exit_code, output = run_and_capture( + command_expect, argparse.Namespace(manifest=bad_manifest_path, dir=None) + ) + require_equal("expect exit code for a wrong pixel", exit_code, EXIT_FAILED) + require_true("wrong pixel failure quotes its why", "deliberate wrong expectation" in output) + require_true("out-of-range pixel names the image size", "outside the 8x6 image" in output) + print("ok expect: wrong pixel and out-of-range coordinate fail with explanations") + + manifest = load_manifest(bad_manifest_path) + scene_outcome = verify_scene(manifest.scenes[0], directory) + require_equal("declared checks are all evaluated", len(scene_outcome.checks), 2) + require_true("first check fails", not scene_outcome.checks[0].passed) + require_equal("failed check records the stored pixel", scene_outcome.checks[0].actual, + (10, 20, 30)) + require_true("second check fails on bounds", not scene_outcome.checks[1].passed) + + +def step_expect_missing_and_invalid(directory): + """Assert a missing image fails the scene and an empty check list is rejected.""" + missing_manifest_path = os.path.join(directory, "manifest-missing.json") + write_selftest_manifest(missing_manifest_path, "selftest", "fixture", [{ + "name": "clear", + "png": "absent.png", + "checks": [{"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255}], + }]) + exit_code, output = run_and_capture( + command_expect, argparse.Namespace(manifest=missing_manifest_path, dir=None) + ) + require_equal("expect exit code for a missing image", exit_code, EXIT_FAILED) + require_true("missing image message names the file", "absent.png" in output) + require_true( + "missing image message says what to check", + "Check that the file exists" in output, + ) + print("ok expect: a missing image fails once for the scene and names the path") + + empty_checks_manifest_path = os.path.join(directory, "manifest-empty.json") + write_selftest_manifest(empty_checks_manifest_path, "selftest", "fixture", [{ + "name": "clear", "png": "clear.png", "checks": [], + }]) + assert_tool_error( + lambda: load_manifest(empty_checks_manifest_path), + "proves nothing", + "manifest scene with no checks", + ) + print("ok failure path: a scene with no checks is rejected, not silently passed") + + +def step_diff_metrics(): + """Assert diff metrics and heatmap colours for one known two-pixel change.""" + reference = make_solid_raster(4, 3, PNG_COLOUR_TYPE_RGB, (0, 20, 30), "selftest reference") + candidate = Raster( + width=4, height=3, colour_type=PNG_COLOUR_TYPE_RGB, + pixels=bytearray(reference.pixels), source_path="selftest candidate", + ) + candidate.pixels[(1 * 4 + 1) * 3:(1 * 4 + 1) * 3 + 3] = bytes((255, 20, 30)) + candidate.pixels[(2 * 4 + 2) * 3:(2 * 4 + 2) * 3 + 3] = bytes((0, 20, 31)) + + stats = compare_rasters(reference, candidate) + require_equal("differing pixel count", stats.differing_pixels, 2) + require_equal("total pixel count", stats.total_pixels, 12) + require_equal("first differing coordinate", stats.first_difference, (1, 1)) + require_equal("max channel delta", stats.max_channel_delta, 255) + require_equal("differing percent", round(stats.differing_percent, 6), + round(100.0 * 2 / 12, 6)) + require_equal("mean absolute channel delta", round(stats.mean_absolute_delta, 6), + round(256 / 48, 6)) + require_equal("identical rasters report no difference", + compare_rasters(reference, reference).differing_pixels, 0) + + heatmap = build_heatmap(reference, candidate) + require_equal("heatmap unchanged pixel is dark grey", heatmap.stored_pixel(0, 0), + HEATMAP_UNCHANGED) + require_equal("heatmap delta 255 pixel is red", heatmap.stored_pixel(1, 1), (255, 0, 0)) + require_equal("heatmap delta 1 pixel is blue", heatmap.stored_pixel(2, 2), (0, 0, 255)) + print("ok diff metrics: 2 known pixels give exact count, percent, mean, max and first") + print("ok heatmap: grey unchanged, red at delta 255, blue at delta 1") + + +def step_diff_edge_cases(): + """Assert scan order, alpha-only differences and size-mismatch refusal.""" + reference = make_solid_raster( + 4, 3, PNG_COLOUR_TYPE_RGB, (0, 20, 30), "selftest reference" + ) + row_order_candidate = Raster( + width=4, height=3, colour_type=PNG_COLOUR_TYPE_RGB, + pixels=bytearray(reference.pixels), source_path="selftest row order", + ) + row_order_candidate.pixels[3 * 3:3 * 3 + 3] = bytes((1, 20, 30)) + row_order_candidate.pixels[(1 * 4) * 3:(1 * 4) * 3 + 3] = bytes((2, 20, 30)) + require_equal( + "first difference follows row-major order, not column order", + compare_rasters(reference, row_order_candidate).first_difference, + (3, 0), + ) + + alpha_pixels = bytearray() + for offset in range(0, len(reference.pixels), 3): + alpha_pixels.extend(reference.pixels[offset:offset + 3]) + alpha_pixels.append(OPAQUE_ALPHA) + alpha_candidate = Raster( + width=4, height=3, colour_type=PNG_COLOUR_TYPE_RGBA, + pixels=alpha_pixels, source_path="selftest alpha", + ) + alpha_candidate.pixels[3] = OPAQUE_ALPHA - 1 + alpha_stats = compare_rasters(reference, alpha_candidate) + require_equal("alpha-only difference is counted", alpha_stats.differing_pixels, 1) + require_equal("alpha-only difference has delta 1", alpha_stats.max_channel_delta, 1) + require_equal("alpha-only difference coordinate", alpha_stats.first_difference, (0, 0)) + + wrong_tint = make_solid_raster( + 4, 3, PNG_COLOUR_TYPE_RGB, (200, 30, 60), "selftest wrong tint" + ) + wrong_tint_stats = compare_rasters(reference, wrong_tint) + whole_frame_note = whole_frame_difference_note("fullscreen", wrong_tint_stats) + require_true("whole-frame hint names the scene", "'fullscreen'" in whole_frame_note) + require_true("whole-frame hint points at the tint", "tint" in whole_frame_note) + require_equal("partial difference gets no whole-frame hint", + whole_frame_difference_note("clear", alpha_stats), "") + print("ok diff edge cases: row-major first difference, alpha-only delta, tint hint") + + larger = make_solid_raster(5, 3, PNG_COLOUR_TYPE_RGB, (0, 20, 30), "selftest wider") + assert_tool_error( + lambda: compare_rasters(reference, larger), + "re-render at the same size", + "comparing images of different sizes", + ) + print("ok failure path: mismatched image sizes refuse to compare and say so") + + +def step_diff_command(directory): + """Assert diff exit codes and the heatmap file it writes.""" + reference_directory = os.path.join(directory, "reference-images") + candidate_directory = os.path.join(directory, "candidate-images") + make_selftest_directory(reference_directory) + make_selftest_directory(candidate_directory) + + reference_image = make_solid_raster( + 4, 3, PNG_COLOUR_TYPE_RGB, (0, 20, 30), "selftest reference image" + ) + candidate_image = Raster( + width=4, height=3, colour_type=PNG_COLOUR_TYPE_RGB, + pixels=bytearray(reference_image.pixels), source_path="selftest candidate image", + ) + candidate_image.pixels[(0 * 4 + 3) * 3:(0 * 4 + 3) * 3 + 3] = bytes((255, 20, 30)) + write_png(os.path.join(reference_directory, "clear.png"), reference_image) + # Different file names prove diff reads each manifest's own png field. + write_png(os.path.join(candidate_directory, "shim-clear.png"), candidate_image) + + reference_manifest_path = os.path.join(reference_directory, "manifest.json") + candidate_manifest_path = os.path.join(candidate_directory, "manifest.json") + common = { + "name": "clear", + "checks": [{"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255}], + } + write_selftest_manifest( + reference_manifest_path, "native", "fixture", + [dict(common, png="clear.png")], + ) + write_selftest_manifest( + candidate_manifest_path, "shim", "fixture", + [dict(common, png="shim-clear.png")], + ) + + arguments = argparse.Namespace( + reference=reference_manifest_path, + candidate=candidate_manifest_path, + reference_dir=None, + candidate_dir=None, + max_differing_percent=0.0, + max_mean_delta=0.0, + ) + exit_code, output = run_and_capture(command_diff, arguments) + require_equal("diff exit code for a changed pixel", exit_code, EXIT_FAILED) + require_true("diff row names the scene", "FAIL clear" in output) + diff_path = os.path.join(candidate_directory, "clear.diff.png") + require_true("diff wrote the heatmap beside the candidate", os.path.isfile(diff_path)) + require_equal("written heatmap marks the changed pixel red", + read_png(diff_path).stored_pixel(3, 0), (255, 0, 0)) + print("ok diff: changed scene exits 1 and writes clear.diff.png beside the candidate") + + arguments.max_differing_percent = 100.0 + arguments.max_mean_delta = 1000.0 + exit_code, output = run_and_capture(command_diff, arguments) + require_equal("diff exit code inside generous thresholds", exit_code, EXIT_PASSED) + require_true("relaxed thresholds still report the pixel count", + "differing 1/12" in output) + print("ok diff: generous thresholds pass the same scene without hiding its delta") + + +def step_argument_parsing(): + """Assert threshold and pixel arguments accept good text and reject the rest.""" + require_equal("zero threshold", non_negative_float("0"), 0.0) + require_equal("fractional threshold", non_negative_float("1.5"), 1.5) + require_equal("pixel coordinate", pixel_coordinate_argument("12,34"), (12, 34)) + for bad_threshold in ("-1", "nan", "inf", "abc"): + assert_argument_error( + lambda text=bad_threshold: non_negative_float(text), + f"threshold {bad_threshold!r}", + ) + for bad_pixel in ("12", "1,2,3", "a,b"): + assert_argument_error( + lambda text=bad_pixel: pixel_coordinate_argument(text), + f"pixel {bad_pixel!r}", + ) + print("ok arguments: thresholds reject negative, NaN, inf and text; pixels need x,y") + + +def run_selftest_steps(directory): + """Run every selftest step in order; each step prints its own ok line.""" + step_png_roundtrip(directory) + step_png_error_paths(directory) + step_filter_decoders() + step_argument_parsing() + step_orientation_and_channel_order(directory) + step_expect_matching(directory) + step_expect_failures(directory) + step_expect_missing_and_invalid(directory) + step_diff_metrics() + step_diff_edge_cases() + step_diff_command(directory) + + +def command_selftest(arguments): + """Run the selftest in a temporary directory and return its exit code.""" + try: + working_directory = tempfile.mkdtemp(prefix="compare-selftest-") + except OSError as error: + raise ToolError( + f"selftest cannot create a temporary directory: {error}. " + f"Check that %TEMP% is writable" + ) + print(f"selftest: fixtures in {working_directory}") + try: + run_selftest_steps(working_directory) + except SelftestMismatch as mismatch: + print(f"FAIL {mismatch}") + print(f"fixtures kept for inspection: {working_directory}") + return EXIT_FAILED + except ToolError as error: + # A broken fixture is a failed selftest, not a usage error: the tool ran. + print(f"FAIL selftest could not complete: {error}") + print(f"fixtures kept for inspection: {working_directory}") + return EXIT_FAILED + shutil.rmtree(working_directory, ignore_errors=True) + print("selftest passed") + return EXIT_PASSED + + +# --------------------------------------------------------------------------- +# Command line +# --------------------------------------------------------------------------- + + +def non_negative_float(text): + """argparse type for a finite threshold that may be zero but never negative.""" + try: + value = float(text) + except ValueError: + raise argparse.ArgumentTypeError(f"'{text}' is not a number") + # NaN would compare false against every threshold and silently pass all scenes. + if not math.isfinite(value): + raise argparse.ArgumentTypeError(f"'{text}' is not a finite number") + if value < 0: + raise argparse.ArgumentTypeError(f"'{text}' is negative; use 0 or more") + return value + + +def add_expect_command(subparsers): + """Register the expect subcommand and its arguments.""" + expect_parser = subparsers.add_parser( + "expect", + help="verify every pixel declared in a manifest", + description=( + "Read each scene's PNG, compare every declared check, and print one PASS " + "or FAIL line per check with expected and actual values. A missing or " + "unreadable image fails its whole scene with the path and what to check." + ), + ) + expect_parser.add_argument("--manifest", required=True, + help="manifest.json written by the renderer") + expect_parser.add_argument( + "--dir", default=None, + help="directory holding the PNGs (default: the manifest's directory)", + ) + expect_parser.set_defaults(handler=command_expect) + + +def add_diff_command(subparsers): + """Register the diff subcommand and its arguments.""" + diff_parser = subparsers.add_parser( + "diff", + help="compare two renderers' images scene by scene", + description=( + "For every scene the reference manifest declares, compare its PNG against " + "the candidate's. Prints differing pixel count, percent, mean absolute " + "channel delta, maximum channel delta and the first differing coordinate. " + "Writes .diff.png beside the candidate image: unchanged pixels are " + "dark grey, differing pixels ramp from blue (delta 1) to red (delta 255)." + ), + ) + diff_parser.add_argument("--reference", required=True, + help="manifest.json for the reference renderer") + diff_parser.add_argument("--candidate", required=True, + help="manifest.json for the renderer under test") + diff_parser.add_argument( + "--reference-dir", default=None, + help="reference image directory (default: that manifest's directory)", + ) + diff_parser.add_argument( + "--candidate-dir", default=None, + help="candidate image directory (default: that manifest's directory)", + ) + diff_parser.add_argument( + "--max-differing-percent", type=non_negative_float, default=0.0, + help="fail a scene above this percent of differing pixels (default 0.0)", + ) + diff_parser.add_argument( + "--max-mean-delta", type=non_negative_float, default=0.0, + help="fail a scene above this mean absolute channel delta (default 0.0)", + ) + diff_parser.set_defaults(handler=command_diff) + + +def add_inspect_command(subparsers): + """Register the inspect subcommand and its arguments.""" + inspect_parser = subparsers.add_parser( + "inspect", + help="print an image's size, colour type and pixel values", + description=( + "Decode one PNG and print its dimensions, colour type and the requested " + "pixels. Without --pixel it prints the four corners and the centre." + ), + ) + inspect_parser.add_argument("--image", required=True, help="PNG file to read") + inspect_parser.add_argument( + "--pixel", type=pixel_coordinate_argument, action="append", default=None, + metavar="X,Y", help="pixel to print, for example --pixel 12,34 (repeatable)", + ) + inspect_parser.set_defaults(handler=command_inspect) + + +def add_selftest_command(subparsers): + """Register the selftest subcommand.""" + selftest_parser = subparsers.add_parser( + "selftest", + help="prove the reader, writer, expect, diff and heatmap on built-in fixtures", + description=( + "Write fixture PNGs into a temporary directory, then assert known pixel " + "reads, all five PNG filters, expectation matching, diff metrics, heatmap " + "colours and the failure paths. Leaves nothing behind; exits 1 on a mismatch." + ), + ) + selftest_parser.set_defaults(handler=command_selftest) + + +def build_argument_parser(): + """Build the full CLI: shared help text plus four subcommands.""" + parser = argparse.ArgumentParser( + prog="compare.py", + description=( + "Check rendered PNGs against the pixel checks a manifest declares, or " + "measure how far two renderers' images differ. The tool reads only " + "manifest.json and PNG files; it never parses C++." + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=( + "examples:\n" + " python compare.py expect --manifest D:\\conform\\native\\manifest.json\n" + " python compare.py diff --reference native\\manifest.json " + "--candidate shim\\manifest.json\n" + " python compare.py inspect --image shim\\clear.png --pixel 0,0\n" + " python compare.py selftest\n" + "\n" + "exit codes: 0 passed, 1 mismatch found, 2 could not run (bad input).\n" + ), + ) + subparsers = parser.add_subparsers( + dest="mode", required=True, metavar="{expect,diff,inspect,selftest}" + ) + add_expect_command(subparsers) + add_diff_command(subparsers) + add_inspect_command(subparsers) + add_selftest_command(subparsers) + return parser + + +def main(argv=None): + """Parse arguments, run one mode and translate failures into exit codes. + + 0 passed, 1 the run completed and found a mismatch, 2 the tool could not run. + An exception the tool did not anticipate is a 2, never a 1: a calling script must be + able to tell "the pixels differ" from "this program crashed". + """ + arguments = build_argument_parser().parse_args(argv) + try: + return arguments.handler(arguments) + except ToolError as error: + print(f"error: {error}", file=sys.stderr) + return EXIT_ERROR + except Exception: # noqa: BLE001 - deliberate: report and exit 2, never mask as a mismatch + traceback.print_exc() + print("error: unexpected failure; this is a bug in compare.py, not a pixel mismatch", + file=sys.stderr) + return EXIT_ERROR + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/conformance/native/CMakeLists.txt b/tools/conformance/native/CMakeLists.txt new file mode 100644 index 000000000..599080cca --- /dev/null +++ b/tools/conformance/native/CMakeLists.txt @@ -0,0 +1,108 @@ +cmake_minimum_required(VERSION 3.21) +project(conform_native LANGUAGES CXX) + +# The scene contract and the HLSL are the shared spec; this project only reads them. +set(CONFORM_SPEC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../spec" CACHE PATH + "Directory holding scenes.h and shaders/") +set(DXC_EXECUTABLE + "C:/Program Files (x86)/Windows Kits/10/bin/10.0.26100.0/x64/dxc.exe" + CACHE FILEPATH "DirectX Shader Compiler") + +if(NOT EXISTS "${CONFORM_SPEC_DIR}/scenes.h") + message(FATAL_ERROR + "scenes.h not found at ${CONFORM_SPEC_DIR}/scenes.h. Point -DCONFORM_SPEC_DIR at the " + "directory that holds scenes.h and shaders/.") +endif() +if(NOT EXISTS "${DXC_EXECUTABLE}") + message(FATAL_ERROR + "dxc.exe not found at ${DXC_EXECUTABLE}. Install the Windows SDK or pass " + "-DDXC_EXECUTABLE=.") +endif() + +if(NOT MSVC) + message(FATAL_ERROR "This project targets the Visual Studio toolchain; use -G \"Visual Studio 17 2022\" -A x64.") +endif() +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +set(SHADER_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders") +file(MAKE_DIRECTORY "${SHADER_OUTPUT_DIR}") + +set(FULLSCREEN_HLSL "${CONFORM_SPEC_DIR}/shaders/fullscreen_color.hlsl") +set(VERTEX_COLOR_HLSL "${CONFORM_SPEC_DIR}/shaders/vertex_color.hlsl") + +set(FULLSCREEN_VS_CSO "${SHADER_OUTPUT_DIR}/fullscreen_color.vs.cso") +set(FULLSCREEN_PS_CSO "${SHADER_OUTPUT_DIR}/fullscreen_color.ps.cso") +set(VERTEX_COLOR_VS_CSO "${SHADER_OUTPUT_DIR}/vertex_color.vs.cso") +set(VERTEX_COLOR_PS_CSO "${SHADER_OUTPUT_DIR}/vertex_color.ps.cso") + +# -Qstrip_debug and -Qstrip_reflect keep the .cso small and deterministic: nothing in the +# file depends on the build directory or the machine. -WX makes a shader warning a build +# failure rather than a silent behaviour change in the reference images. +set(DXC_COMMON_ARGS -nologo -O3 -WX -Qstrip_debug -Qstrip_reflect) + +add_custom_command( + OUTPUT "${FULLSCREEN_VS_CSO}" + COMMAND "${DXC_EXECUTABLE}" -T vs_6_6 -E VSMain ${DXC_COMMON_ARGS} + "-Fo${FULLSCREEN_VS_CSO}" "${FULLSCREEN_HLSL}" + DEPENDS "${FULLSCREEN_HLSL}" "${DXC_EXECUTABLE}" + COMMENT "Compiling fullscreen_color.hlsl VSMain as vs_6_6" + VERBATIM) + +add_custom_command( + OUTPUT "${FULLSCREEN_PS_CSO}" + COMMAND "${DXC_EXECUTABLE}" -T ps_6_6 -E PSMain ${DXC_COMMON_ARGS} + "-Fo${FULLSCREEN_PS_CSO}" "${FULLSCREEN_HLSL}" + DEPENDS "${FULLSCREEN_HLSL}" "${DXC_EXECUTABLE}" + COMMENT "Compiling fullscreen_color.hlsl PSMain as ps_6_6" + VERBATIM) + +add_custom_command( + OUTPUT "${VERTEX_COLOR_VS_CSO}" + COMMAND "${DXC_EXECUTABLE}" -T vs_6_6 -E VSMain ${DXC_COMMON_ARGS} + "-Fo${VERTEX_COLOR_VS_CSO}" "${VERTEX_COLOR_HLSL}" + DEPENDS "${VERTEX_COLOR_HLSL}" "${DXC_EXECUTABLE}" + COMMENT "Compiling vertex_color.hlsl VSMain as vs_6_6" + VERBATIM) + +add_custom_command( + OUTPUT "${VERTEX_COLOR_PS_CSO}" + COMMAND "${DXC_EXECUTABLE}" -T ps_6_6 -E PSMain ${DXC_COMMON_ARGS} + "-Fo${VERTEX_COLOR_PS_CSO}" "${VERTEX_COLOR_HLSL}" + DEPENDS "${VERTEX_COLOR_HLSL}" "${DXC_EXECUTABLE}" + COMMENT "Compiling vertex_color.hlsl PSMain as ps_6_6" + VERBATIM) + +add_custom_target(conform_shaders DEPENDS + "${FULLSCREEN_VS_CSO}" "${FULLSCREEN_PS_CSO}" + "${VERTEX_COLOR_VS_CSO}" "${VERTEX_COLOR_PS_CSO}") + +add_executable(conform_native + src/main.cpp + src/diagnostics.cpp + src/gpu.cpp + src/renderer.cpp + src/scene_plan.cpp + src/png_io.cpp + src/verify.cpp + src/manifest.cpp) + +target_include_directories(conform_native PRIVATE "${CONFORM_SPEC_DIR}") +target_compile_definitions(conform_native PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN) +# /we4062 is separate from /W4 because C4062 (enumerator not handled in a switch that has +# no default) is off by default, so /W4 /WX would let a new SceneKind render as a clear. +target_compile_options(conform_native PRIVATE /W4 /WX /we4062 /permissive- /utf-8 /EHsc) +target_link_libraries(conform_native PRIVATE d3d12 dxgi windowscodecs ole32) +add_dependencies(conform_native conform_shaders) + +add_custom_command(TARGET conform_native POST_BUILD + COMMAND "${CMAKE_COMMAND}" -E make_directory "$/shaders" + COMMAND "${CMAKE_COMMAND}" -E copy_if_different + "${FULLSCREEN_VS_CSO}" "${FULLSCREEN_PS_CSO}" + "${VERTEX_COLOR_VS_CSO}" "${VERTEX_COLOR_PS_CSO}" + "$/shaders/" + COMMENT "Copying compiled shaders next to conform_native.exe" + VERBATIM) + +set_property(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" PROPERTY VS_STARTUP_PROJECT conform_native) diff --git a/tools/conformance/native/README.md b/tools/conformance/native/README.md new file mode 100644 index 000000000..a6f57e38c --- /dev/null +++ b/tools/conformance/native/README.md @@ -0,0 +1,362 @@ +# conform_native + +Native D3D12 golden-image renderer for the conformance suite. It renders every scene in +`../spec/scenes.h` into an offscreen 256x256 `R8G8B8A8_UNORM` colour target, reads the +colour back through a readback heap, checks every `conform::PixelCheck` against the +pixels, and writes `.png` plus `manifest.json`. + +No swapchain, no window, no present. One process run produces one complete set of images. + +The contract lives in `../spec` and is read, never modified: + +| Input | Used for | +| --- | --- | +| `../spec/scenes.h` | scene list, per-scene tint, clear values, scissor rect, geometry, PixelChecks | +| `../spec/shaders/fullscreen_color.hlsl` | `vs_6_6`/`ps_6_6`, entries `VSMain`/`PSMain` | +| `../spec/shaders/vertex_color.hlsl` | `vs_6_6`/`ps_6_6`, entries `VSMain`/`PSMain` | + +## Build + +```bat +cd tools/conformance/native +"C:\Program Files\CMake\bin\cmake.exe" -S . -B build -G "Visual Studio 17 2022" -A x64 +"C:\Program Files\CMake\bin\cmake.exe" --build build --config Release --parallel +``` + +Equivalently: `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build.ps1`. + +Requirements, all already present on this machine: + +* Visual Studio 2022 x64 toolset (`C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools`). +* Windows SDK 10.0.26100 (`d3d12`, `dxgi`, `windowscodecs`; no d3dx12 helpers, no third-party code). +* `dxc.exe` at `C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\dxc.exe`. + Override with `-DDXC_EXECUTABLE=` if the SDK moves. + +The build compiles the four shader entry points into `build/shaders/*.cso` +(`-T vs_6_6` / `-T ps_6_6`, `-O3 -WX -Qstrip_debug -Qstrip_reflect`) and copies them next +to the executable. The program loads those `.cso` files at startup; if they are missing it +stops with the filename and the target that produces them rather than falling back to +anything. + +## Run + +```bat +tools/conformance/native\build\Release\conform_native.exe tools/conformance/native\out\run1 +``` + +``` +usage: conform_native [options] + --shaders where the .cso files live (default: \shaders) + --adapter adapter from the printed list (default: most dedicated + memory, non-software) + --debug-layer enable D3D12 validation and fail on validation errors + --help print this text +``` + +Exit codes: `0` every check passed, `1` a check failed or the run could not complete, +`2` bad command line. The output directory is created if absent. + +Each run prints one line per check: + +``` +PASS readback scene=blend (128,128) expected 105,25,45,255 actual 105,25,45,255 0.5*(200,30,60) + 0.5*(10,20,30) = (105,25,45) +``` + +`readback` verifies the pixels copied out of the render target. `png` re-decodes the PNG +that was just written with WIC and runs the same checks against it, so a channel swap or a +truncated file in the encoder path fails the run instead of silently shipping. + +## Baseline state conformance + +The header's baseline table is not documentation in this renderer; it is the state that is +set. Where each row lives: + +| Baseline row | Set in | +| --- | --- | +| topology `TRIANGLELIST` | `BindPipelineAndDraw` — `IASetPrimitiveTopology` | +| cull `NONE`, fill `SOLID`, `FrontCounterClockwise FALSE` | `MakeBasePipelineDescription` | +| sample count 1, sample mask `0xFFFFFFFF`, no MSAA | `MakeBasePipelineDescription` | +| `RenderTargetWriteMask = ALL` | `MakeBasePipelineDescription` | +| viewport `(0,0,256,256)`, depth 0..1 | `Renderer::Initialize` | +| scissor full target unless the scene says otherwise | `MakeDrawPlan` | +| root signature: one root CBV at b0, visibility ALL, space 0, `ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT` | `CreateSceneRootSignature` | +| constant buffer: one float4 at offset 0, `tint/255.0f` | `CreateTintConstants` (one 256-byte slot per scene), bound in `BindPipelineAndDraw` | +| depth only for `depth_order`: `D32_FLOAT`, clear 1.0, LESS, write ALL, stencil off | `ClearAndDrawScene` (DSV bound only there) + `CreateVertexColorPipeline` | +| vertex format `ClipVertex`, stride 16 | `kVertexColorInputLayout` plus two `static_assert`s on size and offset | +| index format `R16_UINT` | `CreateGeometryBuffers` | + +The vertex-colour shaders do not read b0; the constant buffer is bound for those draws +anyway so all three pipelines share the single signature the header names. + +## Output + +Six PNGs, 8-bit RGBA (`colour type 6`), 256x256, top-left origin, plus `manifest.json`: + +```json +{ + "renderer": "native", + "adapter": "NVIDIA GeForce RTX 5070 Ti", + "scenes": [ + { + "name": "clear", + "png": "clear.png", + "checks": [ + {"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, "why": "top-left is the clear colour"} + ] + } + ] +} +``` + +Every check is copied from `scenes.h` (`checkCount`, up to the header's five); the diff +tool never parses C++. The manifest carries no timestamp, run counter or build path, so it +is byte-comparable between runs. + +## Verified + +Transcripts from this machine: RTX 5070 Ti (default pick) and AMD Radeon iGPU +(`--adapter 0`), one Windows install. + +**All checks pass, both adapters.** `scripts\verify.ps1` prints `VERIFY: PASS` and exits 0: + +``` +ok run A exits 0 (all PixelChecks pass) +ok run A wrote 7 files (6 PNGs + manifest.json), found 7 +ok identical bytes: blend.png 75AD77065361FAF4951974525D00B1AB92154E04EB375FD87DB883BC10E2217F +ok identical bytes: clear.png 28DDD65A36CF858D64E12F07D3BD910AC06B7EA9C45C20E8EB8C6F22FF5857DC +ok identical bytes: depth_order.png B01EA5355093A8AEDF4B625422A46EE3647214C51371E4B04D6ECC4630C97C5F +ok identical bytes: fullscreen.png 7AFB53BFBBF7FE54D59B9BFA12D46F118E81D25C1DD951596CA466D8B2A5FFEC +ok identical bytes: indexed.png 52043F2B0F9C79DCFF1A85873642FE6DA11E3357B17D2471E8F726AAD85DFD04 +ok identical bytes: manifest.json 8029372FD2147D99F965F1C0AE31E8E051ADA1C897F7ED0D3E6C90310AC51420 +ok identical bytes: scissor.png 394DAD5B4BF2D8AF0B79132A79750A8AE40305DBA443BFACA5D84DF332028E48 +ok render on adapter 0 exits 0 +ok adapter 0 passes all 18 readback checks +ok adapter 0 passes all 18 PNG checks +... +VERIFY: PASS +``` + +| Scene | Checks | Readback | PNG | +| --- | --- | --- | --- | +| clear | 3 | pass | pass | +| fullscreen | 3 | pass | pass | +| depth_order | 2 | pass | pass | +| scissor | 5 | pass | pass | +| blend | 2 | pass | pass | +| indexed | 3 | pass | pass | +| **total** | **18** | **18/18** | **18/18** | + +Rendered identically on `NVIDIA GeForce RTX 5070 Ti` (default) and `AMD Radeon(TM) +Graphics` (`--adapter 0`). Same PNG hashes on the NVIDIA adapter across two runs. + +**The scenes are not vacuous.** A throwaway copy with three pieces of state disabled +(`scripts/negative-control.ps1`, build discarded afterwards) produced exactly the failures +each scene claims to catch, and nothing else: + +``` +FAIL readback scene=depth_order (128,128) expected 40,160,90,255 actual 220,40,40,255 +FAIL readback scene=scissor (40,64) expected 10,20,30,255 actual 70,140,210,255 +FAIL readback scene=scissor (180,64) expected 10,20,30,255 actual 70,140,210,255 +FAIL readback scene=scissor (112,24) expected 10,20,30,255 actual 70,140,210,255 +FAIL readback scene=scissor (112,104) expected 10,20,30,255 actual 70,140,210,255 +FAIL readback scene=blend (128,128) expected 105,25,45,255 actual 200,30,60,128 +FAIL readback scene=blend (8,8) expected 105,25,45,255 actual 200,30,60,128 +readback checks: 11 passed, 7 failed +``` + +That is: with `DepthEnable = FALSE` the far red quad drawn second wins (proving the depth +test is what keeps green); with the scissor widened to the full target the four outside +checks see the tint; with `BlendEnable = FALSE` the source colour lands unchanged, alpha +128 included. Clear, fullscreen and indexed still passed, so the failures are attributable. + +**The images are the expected shapes.** Read the PNGs back and looked at them: +`depth_order.png` is a full-height red rectangle with a green rectangle over its left two +thirds and a clear border where the quads stop at ±0.95; `scissor.png` is a filled blue +rectangle inset from every edge (the 48..176 × 32..96 rect); `indexed.png` is two right +triangles, yellow and blue, with clear space between and below them. + +**PNG structure.** IHDR of all six files: `width 256 height 256 bitdepth 8 colortype 6`. + +**Shader bytecode.** `dxc -dumpbin` on the four `.cso` files reports +`EntryFunctionName: VSMain` / `PSMain`, `Vertex Shader` / `Pixel Shader`, and the input +signatures the code assumes: `SV_VertexID` for the fullscreen VS, `POSITION`/`COLOR` for +the vertex-colour VS, `SV_Position`/`COLOR` for its PS, and a `cbuffer` in the fullscreen +PS. + +**Failure paths exercised** (`scripts/failure-log.cmd`, merged stdout+stderr, all exit +non-zero, all naming the file and the next thing to check): + +``` +=== output path is an existing file +FAIL tools/conformance/native\src\main.cpp:154 std::filesystem::create_directories -> could not create tools/conformance/native\out\failures\blocked: Cannot create a file when that file already exists. Check: the path is a directory the process can write to, not an existing file and not a read-only volume +EXITCODE 1 + +=== shader directory with no .cso files +FAIL tools/conformance/native\src\renderer.cpp:420 std::ifstream::open -> could not open tools/conformance/native\out\failures\no-shaders\fullscreen_color.vs.cso. Check: the build ran the conform_shaders target and the shaders directory sits next to conform_native.exe; use --shaders to point elsewhere +EXITCODE 1 + +=== PNG path occupied by a directory +PASS readback scene=clear (0,0) expected 10,20,30,255 actual 10,20,30,255 top-left is the clear colour +FAIL tools/conformance/native\src\png_io.cpp:61 IWICStream::InitializeFromFilename -> HRESULT 0x80070005. Check: the output directory is writable and nothing else holds tools/conformance/native\out\failures\png-blocked\clear.png open +readback checks: 3 passed, 0 failed +png checks: 0 passed, 0 failed +RESULT: FAIL (run did not complete) +EXITCODE 1 +``` + +The third case is an unwritable output path (a directory occupies `clear.png`): rendering +and readback verification still ran and passed for that scene; the run exits non-zero +because no PNG was written. Command-line errors exit 2 and print usage (no arguments, +unknown flag, missing option value, bad `--adapter` value, two positional directories). + +## Decisions a reviewer should agree with, or overrule + +1. **Three pipeline states, not two.** D3D12 bakes blend state into a PSO and has no + `OMSetBlendState`, so the blend scene needs its own. Fullscreen and blend share the root + signature and shaders and differ only in `D3D12_BLEND_DESC`, so the split isolates blend + rather than duplicating anything. +2. **Scissor is per-scene state, not pipeline state.** `D3D12_RASTERIZER_DESC` has no + `ScissorEnable` (that is D3D11). D3D12 applies the scissor rect whenever one is set, so + the scissor scene is the fullscreen pipeline plus `RSSetScissorRects(48,32,176,96)`. + The negative control above shows the rect is load-bearing: widen it and four checks fail. +3. **One DSV binding, for `depth_order` only.** The header's baseline says every other + scene binds no DSV, so `OMSetRenderTargets` passes `nullptr` for them. The indexed scene + uses the depth-enabled vertex-colour PSO with no DSV bound, which leaves depth testing + inert; that is the same PSO the contract asks for, not a fourth state. +4. **One 256-byte constant-buffer slot per scene.** A root CBV must be 256-byte aligned and + each scene now carries its own tint. Each slot's float4 sits at byte offset 0 of its + slot, so the shader sees exactly "a single float4 at offset 0". Slots are filled once + before any draw and never rewritten, so no CPU write can race a GPU read. +5. **No sRGB anywhere.** Target format is `R8G8B8A8_UNORM` (not `_SRGB`), clears are + `byte/255.0f`, and WIC writes the bytes it is given. Nothing converts. + +## Not covered + +* **D3D12 validation was not available on this machine.** `--debug-layer` reports + `the D3D12 debug layer is not installed (HRESULT 0x887A002D)` and continues without it. + The plumbing (`ID3D12InfoQueue` drain, failure on validation errors) is implemented but + has never validated anything here. Install the Graphics Tools optional feature to + exercise it. This is the largest gap in the verification. +* Only two adapters were tried, both on one Windows install. The software adapter + `Microsoft Basic Render Driver` (index 2) was listed but not rendered on. +* Device-removed and GPU-hang paths (`GetDeviceRemovedReason`, 60 s fence timeout) are + coded but never triggered; forcing a TDR needs a debugger or a fault-injection build. +* PNG determinism is verified on this WIC build only. WIC's zlib output is stable here, but + that is an observation about this machine, not a documented Windows guarantee. The + pixels are deterministic; the compressed bytes are a WIC implementation detail. +* The depth buffer is never read back, so depth correctness is inferred from colour. The + negative control closes that gap for this scene (colour changes when depth is disabled), + but there is no direct depth-value check. +* 16-bit indices are configured (`DXGI_FORMAT_R16_UINT`) and the shuffled index buffer + draws the expected triangles, but no scene has more than 8 vertices, so nothing proves + behaviour past 65 535 indices. +* `scenes.h` allows at most 5 checks per scene (`PixelCheck checks[5]`); the manifest and + verifier iterate `checkCount` and would read past the array if the contract raised it + without changing the struct. +* No swapchain, present, resize or multi-frame path is implemented or tested; out of scope + for a golden-image tool. +* Nothing here validates the Vulkan shim's output. That comparison needs the diff tool. + +## Contract revision (05:07) + +The shared header was replaced mid-work. Changes and how they landed: + +| Header change | What the renderer does now | +| --- | --- | +| baseline pipeline table | one root signature (CBV b0, visibility ALL, `ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT`); see the conformance table above | +| `depth_order` draw order reversed | unchanged code path: indices are drawn in header order, so the near green quad is now first and depth rejects the later red one | +| `indexed` vertices/indices shuffled, third check | unchanged code path: the vertex and index arrays are uploaded as declared | +| scissor rect `{48,32,176,96}`, five checks | `MakeDrawPlan` reads `kScissor*`; checks at all four outside edges now run | +| per-scene tint (`tintR/G/B/A`) | one CB slot per scene, filled from each `Scene` | +| `checks[5]`, 2..5 per scene | verifier and manifest already iterate `checkCount` | +| blend alpha `ONE/INV_SRC_ALPHA` | PSO updated from the previous `ZERO/ONE`; `SrcBlendAlpha = ONE`, `DestBlendAlpha = INV_SRC_ALPHA` | + +After the revision: 18/18 readback and 18/18 PNG on both adapters, and determinism holds +(`verify.ps1`: `VERIFY: PASS`). Only `scissor.png` and `manifest.json` changed bytes +relative to the pre-revision run; the other five PNGs are byte-identical, which is what the +contract predicts — the reversed depth order and shuffled indices produce the same image +when implemented correctly, and 128/255 with `ONE/INV_SRC_ALPHA` resolves to the same +8-bit blend result the header says it should. + +## What changed in review + +Three passes in the order `REVIEW.md` asks for. Every fix was re-verified by the build and +`scripts\verify.ps1` after the change. + +**Pass 1 — functional.** + +* Finding: first build failed with `C2065: 'D3D12_COMMAND_QUEUE_TYPE_DIRECT'` and + `C2039: 'ScissorEnable' is not a member of 'D3D12_RASTERIZER_DESC'`. + Fix: queue type is `D3D12_COMMAND_LIST_TYPE_DIRECT`; the scissor PSO was deleted because + D3D12 has no scissor enable bit, and the scissor rect became per-scene state. + Evidence: `BUILD EXIT 0`; scissor checks pass and fail correctly in the negative control. +* Finding: the first run passed everything, which is not evidence by itself. + Checked the blend arithmetic by hand and changed the alpha channel to the header's + `ONE/INV_SRC_ALPHA`; then built the negative control to prove the passing scenes react to + their state. Evidence: negative-control transcript above. +* Finding: a stray closing brace after `CreatePipelines` (bad edit) broke the build with + `C2059`. + Fix: removed. Evidence: `BUILD EXIT 0`. + +**Pass 2 — legibility.** + +* Finding: FAIL diagnostics appeared above the program banner because stdout was buffered + and stderr was not. Fix: `setvbuf(stdout, nullptr, _IONBF, 0)` in `main`. Evidence: the + merged failure transcript now reads banner → `FAIL …` → `RESULT: FAIL`. +* Finding: `Check: could not create ` read as a broken sentence under the + `FAIL file:line call -> detail. Check:` shape. Fix: the hint is now a testable claim + ("the output directory is writable and nothing else holds `` open"). +* Finding: a doubled period from concatenating a Win32 message that already ends in `.` + with the `. Check:` separator. Fix: `TrimTrailingPeriod`. Evidence: `… already exists. + Check: …`. +* Finding: `Renderer::full_frame_scissor` and `GpuContext::adapter_index` were written and + never read. Fix: both removed. Evidence: clean rebuild under `/W4 /WX`. +* Finding: `#include ` in `gpu.cpp` with no use. Fix: removed. +* Finding: the marker `TintKind` and two hard-coded tint addresses became dead state when + the header moved to per-scene tints. Fix: replaced by the scene's tint slot; `grep` for + `TintKind`/`kTint*` now returns nothing. + +**Pass 3 — verify and fix.** Clean rebuild from an empty `build\`, then +`scripts\verify.ps1`: 30 claims, `VERIFY: PASS`, exit 0, plus the negative control and the +failure-path log above. + +## Layout + +``` +CMakeLists.txt build, shader compilation, shader copy +scripts/build.ps1 configure + build +scripts/run.ps1 run one output directory with extra arguments +scripts/verify.ps1 re-checks every claim in this README, exits 0 only if all hold +scripts/failure-log.cmd exercises the three failure paths and prints one merged log +scripts/negative-control.ps1 throwaway build with depth/blend/scissor disabled, then deleted +src/main.cpp arguments, COM, run loop, tally, exit code +src/gpu.h/.cpp adapter choice, device, queue, fence, validation drain +src/renderer.h/.cpp targets, buffers, root signature, PSOs, recording, readback +src/scene_plan.h/.cpp Scene -> pipeline/geometry/tint slot/depth binding/scissor +src/png_io.h/.cpp WIC encode and decode +src/verify.h/.cpp PixelCheck comparison and PASS/FAIL output +src/manifest.h/.cpp manifest.json with JSON escaping +src/pixel_surface.h R8G8B8A8 pixel buffer shared by readback and decode +src/diagnostics.h/.cpp failure lines: file, call, HRESULT/error in hex, what to check +``` + +## Review pass 2 — legibility fixes applied + +A second review pass read every file against the review notes in the pull request. These were fixed and re-verified; +each line names the failure it prevents. + +| fix | file | the failure it prevents | +|---|---|---| +| Severity comparisons inverted | `gpu.cpp` `ReportValidationMessages` | `D3D12_MESSAGE_SEVERITY` counts **down** as severity rises (CORRUPTION 0 … MESSAGE 4), so `>= WARNING` printed only INFO/MESSAGE and `>= ERROR` counted everything except corruption. Real errors were printed as nothing and corruption was ignored. | +| `--debug-layer` now fails when the layer is absent | `main.cpp`, `gpu.cpp`, `gpu.h` | It printed `validation errors: 0` and could end `RESULT: PASS` on a machine where validation never ran. It now prints `validation: NOT RUN` and exits 1. | +| Enum switches can no longer fall through | `CMakeLists.txt` (`/we4062`), `scene_plan.cpp` | `DrawPlan` defaults to `{Fullscreen, None}`, so a new `SceneKind` would have rendered as a clear-only scene with no message. C4062 is off under `/W4`, so `/WX` never caught it. | +| Renderer released before the device | `gpu.h`, `gpu.cpp`, `main.cpp` | `DestroyGpuContext` ran while `Renderer` still held resources, PSOs and command lists. A `GpuContext` destructor now runs after the renderer's, and the manual teardown calls are gone. | +| Readback pitch derived, padding stripped | `renderer.cpp` | `kReadbackRowPitch` was hard-coded to `width*4` and the copy used the pitch as the row length, so any width whose pitch is padded would have produced sheared rows. | +| Index type pinned at compile time | `renderer.cpp` | The format (`R16_UINT`) and `sizeof/sizeof` counts were independent of the array types; a switch to `uint32_t` would have doubled every count with no build error. | +| Check counts validated at compile time | `verify.cpp` | A scene with `checkCount == 0` passed with nothing checked; a count above 5 read past `checks[5]`. Now a `static_assert`. | +| Validation messages that cannot be read are counted | `gpu.cpp` | `GetMessage` failures were skipped silently, hiding queue entries. | +| Negative control asserts its own result | `scripts/negative-control.ps1` | The script printed and hoped. `Replace` calls that silently did nothing produced no evidence, and the README quoted output that did not match what the current code prints. It now throws when a replacement does not match exactly once, and fails unless exactly `blend`, `depth_order` and `scissor` fail. | + +Deferred, and why: `HrSucceeded` still carries the `__FILE__`/`__LINE__` pairs instead of taking a +`std::source_location`, because renaming it touches 69 call sites and the functional pass would have to be +re-run entirely; the name is misleading but the behaviour is correct. diff --git a/tools/conformance/native/scripts/build.ps1 b/tools/conformance/native/scripts/build.ps1 new file mode 100644 index 000000000..f665d93e8 --- /dev/null +++ b/tools/conformance/native/scripts/build.ps1 @@ -0,0 +1,16 @@ +# Builds conform_native. Run from anywhere: +# powershell -NoProfile -ExecutionPolicy Bypass -File tools\conformance\native\scripts\build.ps1 +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $PSScriptRoot +$cmake = (Get-Command cmake -ErrorAction SilentlyContinue) +if ($cmake) { $cmake = $cmake.Path } else { $cmake = 'C:\Program Files\CMake\bin\cmake.exe' } +$source = $root +$build = Join-Path $root 'build' + +& $cmake -S $source -B $build -G 'Visual Studio 17 2022' -A x64 +if ($LASTEXITCODE -ne 0) { Write-Output "CONFIGURE EXIT $LASTEXITCODE"; exit $LASTEXITCODE } + +& $cmake --build $build --config Release --parallel +$buildExit = $LASTEXITCODE +Write-Output "BUILD EXIT $buildExit" +exit $buildExit diff --git a/tools/conformance/native/scripts/failure-log.cmd b/tools/conformance/native/scripts/failure-log.cmd new file mode 100755 index 000000000..fde2c21cf --- /dev/null +++ b/tools/conformance/native/scripts/failure-log.cmd @@ -0,0 +1,28 @@ +@echo off +setlocal +set EXE=%~dp0..\build\Release\conform_native.exe +set ROOT=%~dp0..\out\failures +set LOG=%~dp0..\out\failures.log +if exist "%ROOT%" rmdir /s /q "%ROOT%" +mkdir "%ROOT%" + +> "%LOG%" echo === output path is an existing file +echo not a directory> "%ROOT%\blocked" +"%EXE%" "%ROOT%\blocked">> "%LOG%" 2>&1 +>> "%LOG%" echo EXITCODE %errorlevel% +del "%ROOT%\blocked" + +>> "%LOG%" echo. +>> "%LOG%" echo === shader directory with no .cso files +mkdir "%ROOT%\no-shaders" +"%EXE%" "%ROOT%\shader-failure" --shaders "%ROOT%\no-shaders">> "%LOG%" 2>&1 +>> "%LOG%" echo EXITCODE %errorlevel% + +>> "%LOG%" echo. +>> "%LOG%" echo === PNG path occupied by a directory +mkdir "%ROOT%\png-blocked" +mkdir "%ROOT%\png-blocked\clear.png" +"%EXE%" "%ROOT%\png-blocked">> "%LOG%" 2>&1 +>> "%LOG%" echo EXITCODE %errorlevel% + +type "%LOG%" diff --git a/tools/conformance/native/scripts/negative-control.ps1 b/tools/conformance/native/scripts/negative-control.ps1 new file mode 100644 index 000000000..712efe2a1 --- /dev/null +++ b/tools/conformance/native/scripts/negative-control.ps1 @@ -0,0 +1,65 @@ +$ErrorActionPreference = 'Stop' +$source = Split-Path -Parent $PSScriptRoot +$scratch = Join-Path $source 'negative-control' +$cmake = (Get-Command cmake -ErrorAction SilentlyContinue) +if ($cmake) { $cmake = $cmake.Path } else { $cmake = 'C:\Program Files\CMake\bin\cmake.exe' } + +# This script exists to prove the scenes are not vacuous: it disables three pieces of +# pipeline state and requires the suite to notice exactly those three scenes. It asserts +# its own result, so a silent no-op edit cannot be mistaken for evidence. + +function Replace-ExactlyOnce { + param([string] $Text, [string] $Search, [string] $Replacement, [string] $What) + $count = ([regex]::Matches($Text, [regex]::Escape($Search))).Count + if ($count -ne 1) { + throw "expected exactly one occurrence of '$Search' while disabling $What, found $count. The source moved; update negative-control.ps1 before trusting this test." + } + return $Text.Replace($Search, $Replacement) +} + +Write-Output '=== building a throwaway copy with depth, blend and scissor state disabled ===' +if (Test-Path $scratch) { Remove-Item $scratch -Recurse -Force } +New-Item -ItemType Directory "$scratch\src" | Out-Null +Copy-Item "$source\CMakeLists.txt" $scratch +Copy-Item "$source\src\*" "$scratch\src" + +# 1. depth test off in the vertex-colour pipeline +$renderer = Get-Content "$scratch\src\renderer.cpp" -Raw +$renderer = Replace-ExactlyOnce $renderer 'description.DepthStencilState.DepthEnable = TRUE;' 'description.DepthStencilState.DepthEnable = FALSE;' 'the depth test' +# 2. blending off +$renderer = Replace-ExactlyOnce $renderer 'description.BlendState.RenderTarget[0].BlendEnable = TRUE;' 'description.BlendState.RenderTarget[0].BlendEnable = FALSE;' 'blending' +Set-Content -Path "$scratch\src\renderer.cpp" -Value $renderer -NoNewline + +# 3. scissor rect widened to the whole target +$plan = Get-Content "$scratch\src\scene_plan.cpp" -Raw +$plan = Replace-ExactlyOnce $plan 'plan.scissor = {conform::kScissorLeft, conform::kScissorTop, conform::kScissorRight,' 'plan.scissor = {0, 0, conform::kSceneWidth,' 'the scissor rectangle' +$plan = Replace-ExactlyOnce $plan 'conform::kScissorBottom};' 'conform::kSceneHeight};' 'the scissor rectangle bottom edge' +Set-Content -Path "$scratch\src\scene_plan.cpp" -Value $plan -NoNewline + +& $cmake -S $scratch -B "$scratch\build" -G 'Visual Studio 17 2022' -A x64 | Out-Null +& $cmake --build "$scratch\build" --config Release --parallel | Select-Object -Last 2 +if ($LASTEXITCODE -ne 0) { Write-Output "BUILD FAILED $LASTEXITCODE"; exit 1 } + +Write-Output '=== run: which scenes notice? ===' +$output = & "$scratch\build\Release\conform_native.exe" (Join-Path $source 'out/negative-control') 2>&1 +$exit = $LASTEXITCODE +$output | Select-String -Pattern '^FAIL|^readback checks|^RESULT' +Write-Output "EXITCODE $exit" + +# Assert, rather than print and hope. +$failedScenes = $output | + Select-String -Pattern '^FAIL (?:readback|png) scene=(\w+)' | + ForEach-Object { $_.Matches[0].Groups[1].Value } | + Sort-Object -Unique +$expected = @('blend', 'depth_order', 'scissor') +if (Compare-Object $failedScenes $expected) { + Write-Output "NEGATIVE CONTROL FAILED: scenes that noticed = $($failedScenes -join ', '); expected $($expected -join ', ')" + exit 1 +} +if ($exit -eq 0) { + Write-Output 'NEGATIVE CONTROL FAILED: the corrupted build still exited 0' + exit 1 +} +Write-Output "NEGATIVE CONTROL PASSED: exactly $($expected -join ', ') failed" +Remove-Item $scratch -Recurse -Force +exit 0 diff --git a/tools/conformance/native/scripts/run.ps1 b/tools/conformance/native/scripts/run.ps1 new file mode 100644 index 000000000..42ab1e2f8 --- /dev/null +++ b/tools/conformance/native/scripts/run.ps1 @@ -0,0 +1,12 @@ +param( + [string]$Output = '', + [string[]]$Extra = @() +) +# Renders every scene into $Output (default: /tools/conformance/native/out/run1). +$ErrorActionPreference = 'Continue' +$root = Split-Path -Parent $PSScriptRoot +if ([string]::IsNullOrEmpty($Output)) { $Output = Join-Path $root 'out/run1' } +$exe = Join-Path $root 'build/Release/conform_native.exe' +if (Test-Path $Output) { Remove-Item $Output -Recurse -Force } +& $exe $Output @Extra +Write-Output "EXITCODE $LASTEXITCODE" diff --git a/tools/conformance/native/scripts/verify.ps1 b/tools/conformance/native/scripts/verify.ps1 new file mode 100644 index 000000000..26a4af6f2 --- /dev/null +++ b/tools/conformance/native/scripts/verify.ps1 @@ -0,0 +1,88 @@ +# Re-checks every claim the README makes about the native renderer. +# Run: powershell -NoProfile -ExecutionPolicy Bypass -File verify.ps1 +# Exit code 0 means every claim held. + +$ErrorActionPreference = 'Continue' +$root_dir = Split-Path -Parent $PSScriptRoot +$exe = Join-Path $root_dir 'build/Release/conform_native.exe' +$root = Join-Path $root_dir 'out' +$script:broken = 0 + +function Check([bool]$condition, [string]$label) { + if ($condition) { + Write-Output "ok $label" + } else { + Write-Output "BROKEN $label" + $script:broken += 1 + } +} + +if (-not (Test-Path $exe)) { Write-Output "BROKEN $exe does not exist; build first"; exit 1 } +if (Test-Path $root) { Remove-Item $root -Recurse -Force } + +Write-Output '--- contract checks on the primary adapter ---' +& $exe "$root\a" | Out-Null +Check ($LASTEXITCODE -eq 0) 'run A exits 0 (all PixelChecks pass)' + +Write-Output '--- determinism: two runs, byte compare ---' +& $exe "$root\b" | Out-Null +Check ($LASTEXITCODE -eq 0) 'run B exits 0' +$names = Get-ChildItem "$root\a" | Select-Object -ExpandProperty Name | Sort-Object +Check ($names.Count -eq 7) "run A wrote 7 files (6 PNGs + manifest.json), found $($names.Count)" +foreach ($name in $names) { + $hashA = (Get-FileHash "$root\a\$name" -Algorithm SHA256).Hash + $hashB = (Get-FileHash "$root\b\$name" -Algorithm SHA256).Hash + Check ($hashA -eq $hashB) "identical bytes: $name $hashA" +} + +Write-Output '--- second adapter (index 0 = AMD Radeon iGPU on this machine) ---' +$amdText = (& $exe "$root\amd" --adapter 0 2>&1 | Out-String) +Check ($LASTEXITCODE -eq 0) 'render on adapter 0 exits 0' +Check ($amdText -match 'adapter: AMD Radeon') 'adapter 0 is reported as the AMD Radeon' +Check ($amdText -match 'readback checks: 18 passed, 0 failed') 'adapter 0 passes all 18 readback checks' +Check ($amdText -match 'png checks: 18 passed, 0 failed') 'adapter 0 passes all 18 PNG checks' + +Write-Output '--- failure paths ---' +Set-Content -Path "$root\blocked-by-file" -Value 'not a directory' +$fileText = (& $exe "$root\blocked-by-file" 2>&1 | Out-String) +Check ($LASTEXITCODE -eq 1) 'output path that is a file exits 1' +Check ($fileText -match 'create_directories') 'that failure names create_directories' +Check ($fileText -match 'blocked-by-file') 'that failure names the path' +Remove-Item "$root\blocked-by-file" -Force + +New-Item -ItemType Directory "$root\no-shaders" | Out-Null +$shaderText = (& $exe "$root\shader-failure" --shaders "$root\no-shaders" 2>&1 | Out-String) +Check ($LASTEXITCODE -eq 1) 'missing .cso files exit 1' +Check ($shaderText -match 'fullscreen_color.vs.cso') 'that failure names the missing file' +Check ($shaderText -match 'conform_shaders') 'that failure says which build target produces it' + +New-Item -ItemType Directory "$root\png-blocked" | Out-Null +New-Item -ItemType Directory "$root\png-blocked\clear.png" | Out-Null +$pngText = (& $exe "$root\png-blocked" 2>&1 | Out-String) +Check ($LASTEXITCODE -eq 1) 'unwritable PNG path exits 1' +Check ($pngText -match 'clear\.png') 'that failure names the PNG' +Check ($pngText -match 'RESULT: FAIL \(run did not complete\)') 'that run reports it did not complete' + +$noArgText = (& $exe 2>&1 | Out-String) +Check ($LASTEXITCODE -eq 2) 'no arguments exits 2' +Check ($noArgText -match 'usage: conform_native') 'no arguments prints usage' + +$badFlagText = (& $exe "$root\x" --nonsense 2>&1 | Out-String) +Check ($LASTEXITCODE -eq 2) 'unknown flag exits 2' + +Write-Output '--- manifest ---' +$manifest = Get-Content "$root\a\manifest.json" -Raw | ConvertFrom-Json +Check ($manifest.renderer -eq 'native') 'manifest renderer is native' +Check ($manifest.adapter -match 'RTX 5070 Ti') 'manifest records the chosen adapter' +Check ($manifest.scenes.Count -eq 6) 'manifest lists 6 scenes' +$checkCount = 0 +foreach ($scene in $manifest.scenes) { $checkCount += $scene.checks.Count } +Check ($checkCount -eq 18) 'manifest lists all 18 checks from scenes.h' + +Write-Output '' +if ($script:broken -eq 0) { + Write-Output 'VERIFY: PASS' + exit 0 +} +Write-Output "VERIFY: FAIL ($script:broken broken claim(s))" +exit 1 diff --git a/tools/conformance/native/src/diagnostics.cpp b/tools/conformance/native/src/diagnostics.cpp new file mode 100644 index 000000000..36798f34e --- /dev/null +++ b/tools/conformance/native/src/diagnostics.cpp @@ -0,0 +1,50 @@ +#include "diagnostics.h" + +#include +#include + +namespace { + +// One line shape for every failure so a log grep for "FAIL " finds all of them. +void PrintDiagnostic(const char* file, int line, const char* call, const std::string& detail, + const char* what_to_check) { + std::fprintf(stderr, "FAIL %s:%d %s -> %s. Check: %s\n", file, line, call, detail.c_str(), + what_to_check); + std::fflush(stderr); +} + +// Hex is how HRESULTs are looked up in the SDK headers and in Event Viewer. +std::string FormatHex32(unsigned long value, const char* prefix) { + char text[32]; + std::snprintf(text, sizeof text, "%s0x%08lX", prefix, value); + return std::string(text); +} + +} // namespace + +bool HrSucceeded(HRESULT result, const char* file, int line, const char* call, + const char* what_to_check) { + if (SUCCEEDED(result)) { + return true; + } + PrintDiagnostic(file, line, call, FormatHex32(static_cast(result), "HRESULT "), + what_to_check); + return false; +} + +bool Win32Succeeded(BOOL result, const char* file, int line, const char* call, + const char* what_to_check) { + if (result != FALSE) { + return true; + } + const unsigned long last_error = static_cast(GetLastError()); + char detail[64]; + std::snprintf(detail, sizeof detail, "Win32 error %lu (0x%08lX)", last_error, last_error); + PrintDiagnostic(file, line, call, detail, what_to_check); + return false; +} + +void ReportFailure(const char* file, int line, const char* call, const std::string& message, + const char* what_to_check) { + PrintDiagnostic(file, line, call, message, what_to_check); +} diff --git a/tools/conformance/native/src/diagnostics.h b/tools/conformance/native/src/diagnostics.h new file mode 100644 index 000000000..9990e2174 --- /dev/null +++ b/tools/conformance/native/src/diagnostics.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include + +// Failure reporting for this tool. Every fallible call goes through one of these so a +// failed run always names the file, the call, the numeric error and the next thing to +// check. Each function returns true only when the call succeeded, so call sites branch +// on a single boolean and never need a nested if. + +// Reports a failed HRESULT. Use for anything that returns HRESULT, including +// GetDeviceRemovedReason, where the value is the reason rather than a call failure. +bool HrSucceeded(HRESULT result, const char* file, int line, const char* call, + const char* what_to_check); + +// Reports a failed Win32 call using GetLastError. Use for CreateEventW and friends. +bool Win32Succeeded(BOOL result, const char* file, int line, const char* call, + const char* what_to_check); + +// Reports a failure that carries no error code (missing file, bad argument, a check the +// tool itself does not implement). message states what went wrong and may name a path. +void ReportFailure(const char* file, int line, const char* call, const std::string& message, + const char* what_to_check); diff --git a/tools/conformance/native/src/gpu.cpp b/tools/conformance/native/src/gpu.cpp new file mode 100644 index 000000000..d607a340a --- /dev/null +++ b/tools/conformance/native/src/gpu.cpp @@ -0,0 +1,299 @@ +#include "gpu.h" + +#include +#include + +#include "diagnostics.h" + +namespace { + +// One enumerated adapter. The index is kept so `--adapter N` matches the printed list +// even after software adapters are filtered out of automatic selection. +struct AdapterCandidate { + int index = -1; + bool software = false; + SIZE_T dedicated_video_memory = 0; + std::string description; + ComPtr adapter; +}; + +// Converts a driver-supplied UTF-16 name to UTF-8. Returns false rather than storing a +// truncated name, so a broken name shows up as a reported failure, not a blank field. +bool Utf8FromWide(const wchar_t* wide, std::string& text_out) { + const int byte_count = WideCharToMultiByte(CP_UTF8, 0, wide, -1, nullptr, 0, nullptr, nullptr); + if (byte_count <= 1) { + return false; + } + std::vector buffer(static_cast(byte_count)); + const int written = + WideCharToMultiByte(CP_UTF8, 0, wide, -1, buffer.data(), byte_count, nullptr, nullptr); + if (written != byte_count) { + return false; + } + text_out.assign(buffer.data()); + return true; +} + +// Enumerates every DXGI adapter. DXGI_ERROR_NOT_FOUND ends the list; any other failure +// on a later index would silently truncate the list, so it is reported. +bool EnumerateAdapters(IDXGIFactory4& factory, std::vector& candidates) { + for (int index = 0;; ++index) { + ComPtr adapter; + const HRESULT result = factory.EnumAdapters1(static_cast(index), adapter.GetAddressOf()); + if (result == DXGI_ERROR_NOT_FOUND) { + return true; + } + if (!HrSucceeded(result, __FILE__, __LINE__, "IDXGIFactory4::EnumAdapters1", + "a broken display driver; try another adapter with --adapter")) { + return false; + } + + DXGI_ADAPTER_DESC1 description{}; + if (!HrSucceeded(adapter->GetDesc1(&description), __FILE__, __LINE__, + "IDXGIAdapter1::GetDesc1", "a display driver that does not expose a " + "description; try another adapter with --adapter")) { + return false; + } + + AdapterCandidate candidate; + candidate.index = index; + candidate.software = (description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0; + candidate.dedicated_video_memory = description.DedicatedVideoMemory; + if (!Utf8FromWide(description.Description, candidate.description)) { + ReportFailure(__FILE__, __LINE__, "WideCharToMultiByte", + "the adapter description could not be converted to UTF-8", + "the driver reports an empty adapter name"); + return false; + } + candidate.adapter = adapter; + candidates.push_back(candidate); + } +} + +// Prints the candidate list so a surprising choice can be diagnosed from the log alone. +void PrintAdapterCandidates(const std::vector& candidates) { + for (const AdapterCandidate& candidate : candidates) { + std::printf("adapter[%d] %s (%llu MB dedicated)%s\n", candidate.index, + candidate.description.c_str(), + static_cast(candidate.dedicated_video_memory / + (1024ull * 1024ull)), + candidate.software ? " [software]" : ""); + } +} + +// Chooses the adapter: an explicit index wins verbatim, otherwise the non-software +// adapter with the most dedicated memory (the discrete GPU on a hybrid machine). +bool SelectAdapter(const std::vector& candidates, int requested_index, + const AdapterCandidate*& selected_out) { + if (candidates.empty()) { + ReportFailure(__FILE__, __LINE__, "SelectAdapter", "DXGI enumerated no adapters", + "the GPU driver is installed and the machine has a display adapter"); + return false; + } + if (requested_index >= 0) { + for (const AdapterCandidate& candidate : candidates) { + if (candidate.index == requested_index) { + selected_out = &candidate; + return true; + } + } + ReportFailure(__FILE__, __LINE__, "SelectAdapter", "--adapter names an adapter that does " + "not exist", "pick an index from the adapter list printed above"); + return false; + } + + const AdapterCandidate* best = nullptr; + for (const AdapterCandidate& candidate : candidates) { + if (candidate.software) { + continue; + } + if (best == nullptr || candidate.dedicated_video_memory > best->dedicated_video_memory) { + best = &candidate; + } + } + if (best == nullptr) { + ReportFailure(__FILE__, __LINE__, "SelectAdapter", + "every enumerated adapter is software-only", + "install a GPU driver, or pass --adapter with the WARP index if WARP is " + "acceptable for a reference image"); + return false; + } + selected_out = best; + return true; +} + +// Turns on the D3D12 debug layer. Reports success only when the layer was actually +// enabled: the caller must not claim validation ran when this returns false. +bool EnableDebugLayer() { + ComPtr debug_controller; + const HRESULT result = D3D12GetDebugInterface(IID_PPV_ARGS(debug_controller.GetAddressOf())); + if (FAILED(result)) { + std::fprintf(stderr, + "note: --debug-layer requested but the D3D12 debug layer is not installed " + "(HRESULT 0x%08lX); continuing without validation\n", + static_cast(result)); + return false; + } + debug_controller->EnableDebugLayer(); + // GPU-based validation is left at its default (off): it changes nothing about the + // output but makes a 256x256 reference render take minutes on some drivers. Nothing + // else is changed here; the layer is used exactly as Microsoft configured it. + return true; +} + +} // namespace + +GpuContext::~GpuContext() { DestroyGpuContext(*this); } + +bool CreateGpuContext(GpuContext& gpu, int requested_adapter_index, bool enable_debug_layer) { + const bool debug_layer_active = enable_debug_layer ? EnableDebugLayer() : false; + // Recorded on the context so the caller can tell "validation ran and found nothing" + // from "validation was asked for and never ran". + gpu.validation_active = debug_layer_active; + const UINT factory_flags = debug_layer_active ? DXGI_CREATE_FACTORY_DEBUG : 0; + + if (!HrSucceeded(CreateDXGIFactory2(factory_flags, IID_PPV_ARGS(gpu.dxgi_factory.GetAddressOf())), + __FILE__, __LINE__, "CreateDXGIFactory2", + "dxgi.dll is present and, with --debug-layer, the DXGI debug layer is " + "installed")) { + return false; + } + + std::vector candidates; + if (!EnumerateAdapters(*gpu.dxgi_factory.Get(), candidates)) { + return false; + } + PrintAdapterCandidates(candidates); + + const AdapterCandidate* selected = nullptr; + if (!SelectAdapter(candidates, requested_adapter_index, selected)) { + return false; + } + gpu.adapter_description = selected->description; + gpu.adapter_is_software = selected->software; + + // Feature level 11_0 is the floor the scene contract needs; the shaders are SM 6.6, + // which the PSO creation below validates against the actual device. + if (!HrSucceeded(D3D12CreateDevice(selected->adapter.Get(), D3D_FEATURE_LEVEL_11_0, + IID_PPV_ARGS(gpu.device.GetAddressOf())), + __FILE__, __LINE__, "D3D12CreateDevice", + "the adapter supports D3D12; an adapter listed as [software] or an old " + "driver is the usual cause")) { + return false; + } + + D3D12_COMMAND_QUEUE_DESC queue_description{}; + queue_description.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + queue_description.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; + queue_description.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + if (!HrSucceeded(gpu.device->CreateCommandQueue(&queue_description, IID_PPV_ARGS( + gpu.command_queue.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateCommandQueue", + "a direct queue is available; a device lost at creation is the usual cause")) { + return false; + } + + if (!HrSucceeded(gpu.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, + IID_PPV_ARGS(gpu.fence.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateFence", + "the device is still present after queue creation")) { + return false; + } + + gpu.fence_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!Win32Succeeded(gpu.fence_event != nullptr, __FILE__, __LINE__, "CreateEventW", + "the process can create kernel events; a restricted job object is the " + "usual cause")) { + return false; + } + return true; +} + +void DestroyGpuContext(GpuContext& gpu) { + if (gpu.fence_event != nullptr) { + CloseHandle(gpu.fence_event); + gpu.fence_event = nullptr; + } + gpu.fence.Reset(); + gpu.command_queue.Reset(); + gpu.device.Reset(); + gpu.dxgi_factory.Reset(); +} + +bool WaitForFenceValue(GpuContext& gpu, uint64_t fence_value) { + if (gpu.fence->GetCompletedValue() >= fence_value) { + return true; + } + if (!HrSucceeded(gpu.fence->SetEventOnCompletion(fence_value, gpu.fence_event), __FILE__, + __LINE__, "ID3D12Fence::SetEventOnCompletion", + "the fence event handle is valid and the queue has not been destroyed")) { + return false; + } + const DWORD wait_result = WaitForSingleObject(gpu.fence_event, 60000); + if (wait_result != WAIT_OBJECT_0) { + ReportFailure(__FILE__, __LINE__, "WaitForSingleObject", + wait_result == WAIT_TIMEOUT ? "the GPU did not finish within 60 s" + : "waiting for the fence failed", + "Event Viewer for a display driver reset (TDR) on the adapter named above; " + "a hung draw or an unbound resource is the usual cause"); + return false; + } + return true; +} + +bool SignalAndWaitForGpu(GpuContext& gpu) { + const uint64_t fence_value = gpu.next_fence_value; + gpu.next_fence_value += 1; + if (!HrSucceeded(gpu.command_queue->Signal(gpu.fence.Get(), fence_value), __FILE__, __LINE__, + "ID3D12CommandQueue::Signal", "the queue is still open and the fence valid")) { + return false; + } + return WaitForFenceValue(gpu, fence_value); +} + +bool DeviceStillPresent(GpuContext& gpu) { + const HRESULT reason = gpu.device->GetDeviceRemovedReason(); + if (SUCCEEDED(reason)) { + return true; + } + return HrSucceeded(reason, __FILE__, __LINE__, "ID3D12Device::GetDeviceRemovedReason", + "Event Viewer for a TDR on the adapter named above; the HRESULT names " + "the removal reason (DEVICE_HUNG, DEVICE_RESET, OUT_OF_MEMORY)"); +} + +int ReportValidationMessages(ID3D12Device& device) { + ComPtr info_queue; + if (FAILED(device.QueryInterface(IID_PPV_ARGS(info_queue.GetAddressOf())))) { + return 0; + } + const UINT64 message_count = info_queue->GetNumStoredMessages(); + int error_count = 0; + int unreadable_count = 0; + for (UINT64 index = 0; index < message_count; ++index) { + SIZE_T message_size = 0; + if (FAILED(info_queue->GetMessage(index, nullptr, &message_size)) || message_size == 0) { + ++unreadable_count; + continue; + } + std::vector storage(message_size); + D3D12_MESSAGE* message = reinterpret_cast(storage.data()); + if (FAILED(info_queue->GetMessage(index, message, &message_size))) { + ++unreadable_count; + continue; + } + // Severity counts down as severity rises (CORRUPTION 0 ... MESSAGE 4). + if (message->Severity <= D3D12_MESSAGE_SEVERITY_WARNING) { + std::fprintf(stderr, "validation: %.*s\n", static_cast(message->DescriptionByteLength), + message->pDescription); + } + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + ++error_count; + } + } + if (unreadable_count > 0) { + std::fprintf(stderr, "validation: %d message(s) could not be retrieved from the info queue\n", + unreadable_count); + } + std::fflush(stderr); + return error_count; +} diff --git a/tools/conformance/native/src/gpu.h b/tools/conformance/native/src/gpu.h new file mode 100644 index 000000000..9caf17828 --- /dev/null +++ b/tools/conformance/native/src/gpu.h @@ -0,0 +1,60 @@ +#pragma once + +#include +#include +#include + +#include +#include + +using Microsoft::WRL::ComPtr; + +// Everything the renderer needs from the GPU: a device, a direct queue, and the fence +// used to know when readback is safe. Adapter selection happens here and the chosen +// adapter's description is kept for the manifest. +struct GpuContext { + ComPtr dxgi_factory; + ComPtr device; + ComPtr command_queue; + ComPtr fence; + HANDLE fence_event = nullptr; + uint64_t next_fence_value = 1; + std::string adapter_description; // UTF-8 copy of DXGI_ADAPTER_DESC1::Description + bool adapter_is_software = false; + // True only when --debug-layer was requested AND the layer actually came up. A run + // that asked for validation but did not get it must never report "0 errors". + bool validation_active = false; + + // Releases the COM objects in the right order when the context goes out of scope, so + // a caller cannot forget DestroyGpuContext on an early return. + ~GpuContext(); +}; + +// Creates the DXGI factory, picks an adapter, creates the device, queue and fence. +// Does not create any command lists or resources; that is the renderer's job. +// adapter_index < 0 selects the non-software adapter with the most dedicated memory. +bool CreateGpuContext(GpuContext& gpu, int requested_adapter_index, bool enable_debug_layer); + +// Releases the COM objects and closes the fence event. Safe on a partially built +// context, which is why failure paths call it before returning. +void DestroyGpuContext(GpuContext& gpu); + +// Blocks until the GPU has finished the given fence value, or 60 s pass. A timeout is +// reported as a failure rather than waited out forever. +bool WaitForFenceValue(GpuContext& gpu, uint64_t fence_value); + +// Signals the queue's fence and waits for it. Call after ExecuteCommandLists whenever +// the next step touches the result on the CPU. +bool SignalAndWaitForGpu(GpuContext& gpu); + +// True when the device has not been removed. A removed device silently produces zeroed +// or stale readback, so this is checked after every wait. +bool DeviceStillPresent(GpuContext& gpu); + +// Prints validation-layer messages of WARNING severity or worse and returns the number +// of ERROR or CORRUPTION messages. Zero when the debug layer was not enabled. +// +// D3D12_MESSAGE_SEVERITY counts DOWN as severity goes up: CORRUPTION is 0, ERROR 1, +// WARNING 2, INFO 3, MESSAGE 4. So "severity <= WARNING" means "warning or worse", and +// "severity <= ERROR" means "error or corruption". +int ReportValidationMessages(ID3D12Device& device); diff --git a/tools/conformance/native/src/main.cpp b/tools/conformance/native/src/main.cpp new file mode 100644 index 000000000..5dbe7c3e0 --- /dev/null +++ b/tools/conformance/native/src/main.cpp @@ -0,0 +1,315 @@ +#include + +#include +#include +#include +#include + +#include "diagnostics.h" +#include "gpu.h" +#include "manifest.h" +#include "png_io.h" +#include "renderer.h" +#include "scene_plan.h" +#include "scenes.h" +#include "verify.h" + +namespace { + +// Balances CoInitializeEx for the lifetime of main. One owner, no copy: a second +// initialisation would change the apartment model under WIC. +struct ComScope { + HRESULT result = E_FAIL; + + ComScope() { result = CoInitializeEx(nullptr, COINIT_MULTITHREADED); } + ~ComScope() { + if (SUCCEEDED(result)) { + CoUninitialize(); + } + } + ComScope(const ComScope&) = delete; + ComScope& operator=(const ComScope&) = delete; +}; + +struct CommandLineOptions { + std::filesystem::path output_directory; + std::filesystem::path shader_directory; // empty: \shaders + int adapter_index = -1; // -1: the non-software adapter with most memory + bool enable_debug_layer = false; + bool show_help = false; +}; + +// Totals for the run. Readback and PNG are counted separately so a failure says which +// path broke: rendering, or the file the diff tool will read. +struct RunTally { + int readback_passed = 0; + int readback_failed = 0; + int png_passed = 0; + int png_failed = 0; +}; + +void PrintUsage() { + std::printf( + "usage: conform_native [options]\n" + " --shaders where the .cso files live (default: \\shaders)\n" + " --adapter adapter from the printed list (default: most dedicated\n" + " memory, non-software)\n" + " --debug-layer enable D3D12 validation and fail on validation errors\n" + " --help print this text\n"); +} + +// Parses argv into options. Returns false on any malformed argument; the caller prints +// usage, so this function prints only the reason. +bool ParseCommandLine(int argument_count, char** arguments, CommandLineOptions& options) { + for (int index = 1; index < argument_count; ++index) { + const std::string argument = arguments[index]; + if (argument == "--help" || argument == "-h") { + options.show_help = true; + continue; + } + if (argument == "--debug-layer") { + options.enable_debug_layer = true; + continue; + } + if (argument == "--adapter" || argument == "--shaders") { + if (index + 1 >= argument_count) { + ReportFailure(__FILE__, __LINE__, "ParseCommandLine", + argument + " needs a value", "see --help for the argument list"); + return false; + } + const std::string value = arguments[++index]; + if (argument == "--shaders") { + options.shader_directory = std::filesystem::path(value); + continue; + } + char* end_of_number = nullptr; + const long parsed = std::strtol(value.c_str(), &end_of_number, 10); + if (end_of_number == value.c_str() || *end_of_number != '\0' || parsed < 0) { + ReportFailure(__FILE__, __LINE__, "ParseCommandLine", + "--adapter expects a non-negative index, got \"" + value + "\"", + "the adapter list printed at startup numbers the adapters"); + return false; + } + options.adapter_index = static_cast(parsed); + continue; + } + if (!argument.empty() && argument[0] == '-') { + ReportFailure(__FILE__, __LINE__, "ParseCommandLine", "unknown option " + argument, + "see --help for the argument list"); + return false; + } + if (!options.output_directory.empty()) { + ReportFailure(__FILE__, __LINE__, "ParseCommandLine", + "more than one output directory: " + argument, + "pass exactly one output directory"); + return false; + } + options.output_directory = std::filesystem::path(argument); + } + + if (options.show_help) { + return true; + } + if (options.output_directory.empty()) { + ReportFailure(__FILE__, __LINE__, "ParseCommandLine", "no output directory given", + "pass the directory the PNGs and manifest.json should be written to"); + return false; + } + return true; +} + +// The directory holding the running executable. Shaders are copied next to the exe at +// build time, so this keeps the tool runnable from any working directory. +bool ExecutableDirectory(std::filesystem::path& directory_out) { + std::wstring buffer(32768, L'\0'); + const DWORD length = + GetModuleFileNameW(nullptr, buffer.data(), static_cast(buffer.size())); + if (length == 0 || length >= buffer.size()) { + ReportFailure(__FILE__, __LINE__, "GetModuleFileNameW", + "could not read the executable path", + "the process image is still on disk and the path is shorter than 32768 " + "characters"); + return false; + } + buffer.resize(length); + directory_out = std::filesystem::path(buffer).parent_path(); + return true; +} + +// Trims the trailing period Windows appends to system messages so the "Check:" clause +// that follows does not produce "...exists.. Check:". +std::string TrimTrailingPeriod(std::string text) { + while (!text.empty() && text.back() == '.') { + text.pop_back(); + } + return text; +} + +// Creates the output directory if needed. Reports the filesystem's own message, which +// distinguishes "it is a file" from "access denied" from "the drive is gone". +bool EnsureOutputDirectory(const std::filesystem::path& directory) { + std::error_code error; + std::filesystem::create_directories(directory, error); + if (error) { + ReportFailure(__FILE__, __LINE__, "std::filesystem::create_directories", + TrimTrailingPeriod("could not create " + directory.string() + ": " + + error.message()), + "the path is a directory the process can write to, not an existing file and " + "not a read-only volume"); + return false; + } + return true; +} + +// Renders, verifies and writes one scene. Returns false only when the pipeline itself +// broke; a wrong pixel is recorded in the tally and the run keeps going so one log +// shows every failing scene. +bool RunOneScene(GpuContext& gpu, Renderer& renderer, + const std::filesystem::path& output_directory, int scene_index, + const conform::Scene& scene, RunTally& tally) { + const DrawPlan plan = MakeDrawPlan(scene, scene_index); + PixelSurface rendered; + if (!renderer.RenderScene(gpu, plan, rendered)) { + ReportFailure(__FILE__, __LINE__, "Renderer::RenderScene", + std::string("scene ") + scene.name + " did not render", + "the failure printed above this line names the call that broke"); + return false; + } + if (rendered.width != conform::kSceneWidth || rendered.height != conform::kSceneHeight) { + ReportFailure(__FILE__, __LINE__, "Renderer::RenderScene", + std::string("scene ") + scene.name + " produced a " + + std::to_string(rendered.width) + "x" + std::to_string(rendered.height) + + " image", + "the readback footprint matches the contract's 256x256 target"); + return false; + } + + std::printf("\nscene %s: %d checks -- %s\n", scene.name, scene.checkCount, scene.proves); + const CheckTally readback_tally = VerifyChecks(scene, rendered, "readback"); + tally.readback_passed += readback_tally.passed; + tally.readback_failed += readback_tally.failed; + + const std::filesystem::path png_path = + output_directory / (std::string(scene.name) + ".png"); + if (!WritePngFile(png_path, rendered)) { + return false; + } + + // Decode what landed on disk. A WIC channel swap or a truncated file passes the + // readback checks and fails here, which is the point of the second comparison. + PixelSurface decoded; + if (!ReadPngFile(png_path, decoded)) { + return false; + } + if (decoded.width != rendered.width || decoded.height != rendered.height) { + ReportFailure(__FILE__, __LINE__, "ReadPngFile", + png_path.string() + " decoded to " + std::to_string(decoded.width) + "x" + + std::to_string(decoded.height), + "the encoder wrote a full 256x256 image"); + return false; + } + const CheckTally png_tally = VerifyChecks(scene, decoded, "png"); + tally.png_passed += png_tally.passed; + tally.png_failed += png_tally.failed; + return true; +} + +// Every scene in the contract, in declaration order, then the manifest. Scene order is +// fixed so two runs do the same GPU work in the same order. +bool RunAllScenes(GpuContext& gpu, Renderer& renderer, + const std::filesystem::path& output_directory, RunTally& tally) { + for (int index = 0; index < conform::kSceneCount; ++index) { + if (!RunOneScene(gpu, renderer, output_directory, index, conform::kScenes[index], tally)) { + return false; + } + } + // After the images: a manifest must never describe PNGs that do not exist. + return WriteManifest(output_directory / "manifest.json", gpu.adapter_description, + conform::kScenes, conform::kSceneCount); +} + +} // namespace + +int main(int argument_count, char** arguments) { + // stdout unbuffered so PASS/FAIL lines stay in order with FAIL diagnostics, which + // stderr prints immediately. A reordered transcript invites a wrong conclusion. + std::setvbuf(stdout, nullptr, _IONBF, 0); + + CommandLineOptions options; + if (!ParseCommandLine(argument_count, arguments, options)) { + PrintUsage(); + return 2; + } + if (options.show_help) { + PrintUsage(); + return 0; + } + + std::printf("conform native renderer (D3D12, 256x256 R8G8B8A8_UNORM, offscreen)\n"); + ComScope com; + if (FAILED(com.result)) { + HrSucceeded(com.result, __FILE__, __LINE__, "CoInitializeEx", + "COM can be initialised on this thread; RPC_E_CHANGED_MODE means another " + "part of the process already picked a different apartment"); + return 1; + } + + std::filesystem::path shader_directory = options.shader_directory; + if (shader_directory.empty()) { + std::filesystem::path executable_directory; + if (!ExecutableDirectory(executable_directory)) { + return 1; + } + shader_directory = executable_directory / "shaders"; + } + if (!EnsureOutputDirectory(options.output_directory)) { + return 1; + } + std::printf("output: %s\n", options.output_directory.string().c_str()); + std::printf("shaders: %s\n", shader_directory.string().c_str()); + + GpuContext gpu; + if (!CreateGpuContext(gpu, options.adapter_index, options.enable_debug_layer)) { + return 1; + } + std::printf("adapter: %s%s\n\n", gpu.adapter_description.c_str(), + gpu.adapter_is_software ? " (software)" : ""); + + // A run that asked for validation and did not get it must stop here. Reporting + // "0 validation errors" after the layer failed to load is an invented result. + if (options.enable_debug_layer && !gpu.validation_active) { + std::fprintf(stderr, + "validation: NOT RUN - --debug-layer was requested but the D3D12 debug " + "layer is not installed on this machine. Install the Graphics Tools " + "optional feature, or drop --debug-layer to run unvalidated.\n"); + return 1; + } + + Renderer renderer; + if (!renderer.Initialize(gpu, shader_directory)) { + return 1; + } + + RunTally tally; + const bool run_completed = RunAllScenes(gpu, renderer, options.output_directory, tally); + + bool validation_errors_present = false; + if (options.enable_debug_layer) { + const int validation_error_count = ReportValidationMessages(*gpu.device.Get()); + validation_errors_present = validation_error_count > 0; + std::printf("\nvalidation errors: %d\n", validation_error_count); + } + + std::printf("\nreadback checks: %d passed, %d failed\n", tally.readback_passed, + tally.readback_failed); + std::printf("png checks: %d passed, %d failed\n", tally.png_passed, tally.png_failed); + + if (!run_completed) { + std::printf("RESULT: FAIL (run did not complete)\n"); + return 1; + } + const bool all_checks_passed = + tally.readback_failed == 0 && tally.png_failed == 0 && !validation_errors_present; + std::printf("RESULT: %s\n", all_checks_passed ? "PASS" : "FAIL"); + return all_checks_passed ? 0 : 1; +} diff --git a/tools/conformance/native/src/manifest.cpp b/tools/conformance/native/src/manifest.cpp new file mode 100644 index 000000000..5f59c1b6c --- /dev/null +++ b/tools/conformance/native/src/manifest.cpp @@ -0,0 +1,96 @@ +#include "manifest.h" + +#include +#include +#include + +#include "diagnostics.h" + +namespace { + +// Escapes the bytes JSON requires escaped. UTF-8 passes through unchanged, which JSON +// allows and keeps the adapter name readable. +void WriteJsonString(std::ostream& output, const char* text) { + output << '"'; + for (const char* cursor = text; *cursor != '\0'; ++cursor) { + const unsigned char byte = static_cast(*cursor); + switch (byte) { + case '"': + output << "\\\""; + break; + case '\\': + output << "\\\\"; + break; + case '\n': + output << "\\n"; + break; + case '\r': + output << "\\r"; + break; + case '\t': + output << "\\t"; + break; + default: + if (byte < 0x20) { + char escape[8]; + std::snprintf(escape, sizeof escape, "\\u%04X", byte); + output << escape; + } else { + output << static_cast(byte); + } + break; + } + } + output << '"'; +} + +void WriteCheck(std::ostream& output, const conform::PixelCheck& check) { + output << "{\"x\": " << check.x << ", \"y\": " << check.y + << ", \"r\": " << static_cast(check.r) << ", \"g\": " << static_cast(check.g) + << ", \"b\": " << static_cast(check.b) << ", \"a\": " << static_cast(check.a) + << ", \"why\": "; + WriteJsonString(output, check.why); + output << '}'; +} + +void WriteScene(std::ostream& output, const conform::Scene& scene, bool is_last_scene) { + const std::string png_name = std::string(scene.name) + ".png"; + output << " {\n \"name\": "; + WriteJsonString(output, scene.name); + output << ",\n \"png\": "; + WriteJsonString(output, png_name.c_str()); + output << ",\n \"checks\": [\n"; + for (int index = 0; index < scene.checkCount; ++index) { + output << " "; + WriteCheck(output, scene.checks[index]); + output << (index + 1 < scene.checkCount ? ",\n" : "\n"); + } + output << " ]\n }" << (is_last_scene ? "\n" : ",\n"); +} + +} // namespace + +bool WriteManifest(const std::filesystem::path& path, const std::string& adapter_description, + const conform::Scene* scenes, int scene_count) { + std::ofstream output(path, std::ios::binary | std::ios::trunc); + if (!output.is_open()) { + ReportFailure(__FILE__, __LINE__, "std::ofstream::open", "could not create " + path.string(), + "the output directory is writable and not on a read-only volume"); + return false; + } + + output << "{\n \"renderer\": \"native\",\n \"adapter\": "; + WriteJsonString(output, adapter_description.c_str()); + output << ",\n \"scenes\": [\n"; + for (int index = 0; index < scene_count; ++index) { + WriteScene(output, scenes[index], index + 1 == scene_count); + } + output << " ]\n}\n"; + output.close(); + if (output.fail()) { + ReportFailure(__FILE__, __LINE__, "std::ofstream::close", "could not write " + path.string(), + "the disk has free space; a full volume fails on close, not on open"); + return false; + } + return true; +} diff --git a/tools/conformance/native/src/manifest.h b/tools/conformance/native/src/manifest.h new file mode 100644 index 000000000..28f1e42bf --- /dev/null +++ b/tools/conformance/native/src/manifest.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +#include "scenes.h" + +// Writes manifest.json in the schema the diff tool consumes. Every check comes from +// scenes.h so the tool never parses C++. Holds no timestamps or run counts: two runs +// against the same adapter must produce identical bytes. +bool WriteManifest(const std::filesystem::path& path, const std::string& adapter_description, + const conform::Scene* scenes, int scene_count); diff --git a/tools/conformance/native/src/pixel_surface.h b/tools/conformance/native/src/pixel_surface.h new file mode 100644 index 000000000..87b40afbd --- /dev/null +++ b/tools/conformance/native/src/pixel_surface.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +// Pixels in the form both the readback path and the PNG decode path produce: four +// bytes per pixel in R,G,B,A order, top-left origin, tightly packed. Keeping one shape +// for both means a single comparison function covers rendering and file output. +struct PixelSurface { + int width = 0; + int height = 0; + std::vector rgba; + + // Points at the RGBA bytes of one pixel. The caller owns the bounds check; sizing + // is validated once when the surface is filled. + const uint8_t* At(int x, int y) const { + return rgba.data() + (static_cast(y) * static_cast(width) + + static_cast(x)) * 4; + } +}; diff --git a/tools/conformance/native/src/png_io.cpp b/tools/conformance/native/src/png_io.cpp new file mode 100644 index 000000000..95ef92796 --- /dev/null +++ b/tools/conformance/native/src/png_io.cpp @@ -0,0 +1,177 @@ +#include "png_io.h" + +#include +#include + +#include +#include + +#include "diagnostics.h" + +using Microsoft::WRL::ComPtr; + +namespace { + +// One WIC factory per call. It is a few thousand bytes of COM state, and keeping it +// local means no object outlives the function that needed it. +bool CreateWicFactory(ComPtr& factory_out) { + return HrSucceeded( + CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(factory_out.GetAddressOf())), + __FILE__, __LINE__, "CoCreateInstance(CLSID_WICImagingFactory)", + "the Windows Imaging Component is registered; a stripped Windows image without " + "the WIC feature is the usual cause"); +} + +// WIC's PNG encoder takes 32bppBGRA. Swapping here, once, keeps the channel order +// correct on disk without a format converter. +std::vector ConvertRgbaToBgra(const PixelSurface& surface) { + std::vector bgra(surface.rgba.size()); + for (size_t offset = 0; offset + 3 < surface.rgba.size(); offset += 4) { + bgra[offset + 0] = surface.rgba[offset + 2]; + bgra[offset + 1] = surface.rgba[offset + 1]; + bgra[offset + 2] = surface.rgba[offset + 0]; + bgra[offset + 3] = surface.rgba[offset + 3]; + } + return bgra; +} + +} // namespace + +bool WritePngFile(const std::filesystem::path& path, const PixelSurface& surface) { + ComPtr factory; + if (!CreateWicFactory(factory)) { + return false; + } + if (surface.width <= 0 || surface.height <= 0 || + surface.rgba.size() != static_cast(surface.width) * surface.height * 4) { + ReportFailure(__FILE__, __LINE__, "WritePngFile", + "the pixel surface is empty or its size does not match its dimensions", + "the readback path produced a full 256x256 image before this ran"); + return false; + } + + ComPtr stream; + if (!HrSucceeded(factory->CreateStream(stream.GetAddressOf()), __FILE__, __LINE__, + "IWICImagingFactory::CreateStream", "WIC is initialised on this thread")) { + return false; + } + const std::string write_hint = + "the output directory is writable and nothing else holds " + path.string() + " open"; + if (!HrSucceeded(stream->InitializeFromFilename(path.c_str(), GENERIC_WRITE), __FILE__, __LINE__, + "IWICStream::InitializeFromFilename", write_hint.c_str())) { + return false; + } + + ComPtr encoder; + if (!HrSucceeded(factory->CreateEncoder(GUID_ContainerFormatPng, nullptr, + encoder.GetAddressOf()), + __FILE__, __LINE__, "IWICImagingFactory::CreateEncoder(PNG)", + "the PNG codec is installed with Windows")) { + return false; + } + if (!HrSucceeded(encoder->Initialize(stream.Get(), WICBitmapEncoderNoCache), __FILE__, __LINE__, + "IWICBitmapEncoder::Initialize", "the output stream is writable")) { + return false; + } + + ComPtr frame; + ComPtr frame_properties; + if (!HrSucceeded(encoder->CreateNewFrame(frame.GetAddressOf(), frame_properties.GetAddressOf()), + __FILE__, __LINE__, "IWICBitmapEncoder::CreateNewFrame", + "the encoder was initialised")) { + return false; + } + if (!HrSucceeded(frame->Initialize(frame_properties.Get()), __FILE__, __LINE__, + "IWICBitmapFrameEncode::Initialize", "the frame property bag is valid")) { + return false; + } + if (!HrSucceeded(frame->SetSize(static_cast(surface.width), + static_cast(surface.height)), + __FILE__, __LINE__, "IWICBitmapFrameEncode::SetSize", + "the dimensions are non-zero and fit in UINT")) { + return false; + } + + WICPixelFormatGUID pixel_format = GUID_WICPixelFormat32bppBGRA; + if (!HrSucceeded(frame->SetPixelFormat(&pixel_format), __FILE__, __LINE__, + "IWICBitmapFrameEncode::SetPixelFormat", "the PNG codec accepts 32bppBGRA")) { + return false; + } + if (!IsEqualGUID(pixel_format, GUID_WICPixelFormat32bppBGRA)) { + ReportFailure(__FILE__, __LINE__, "IWICBitmapFrameEncode::SetPixelFormat", + "the PNG codec silently changed the requested pixel format", + "a channel order assumption in this tool no longer holds; the written " + "file would not be comparable"); + return false; + } + + std::vector bgra = ConvertRgbaToBgra(surface); + const UINT stride = static_cast(surface.width) * 4; + if (!HrSucceeded(frame->WritePixels(static_cast(surface.height), stride, + static_cast(bgra.size()), bgra.data()), + __FILE__, __LINE__, "IWICBitmapFrameEncode::WritePixels", + "the disk has space and the surface buffer is as large as its dimensions")) { + return false; + } + if (!HrSucceeded(frame->Commit(), __FILE__, __LINE__, "IWICBitmapFrameEncode::Commit", + "the frame was fully written before commit")) { + return false; + } + // Commit is where the PNG chunks are flushed; the stream closes when the local COM + // pointers are released as this function returns. + return HrSucceeded(encoder->Commit(), __FILE__, __LINE__, "IWICBitmapEncoder::Commit", + "the stream accepted every byte; a full disk shows up here"); +} + +bool ReadPngFile(const std::filesystem::path& path, PixelSurface& surface_out) { + ComPtr factory; + if (!CreateWicFactory(factory)) { + return false; + } + + ComPtr decoder; + const std::string read_hint = path.string() + + " exists and is not locked by another process"; + if (!HrSucceeded(factory->CreateDecoderFromFilename(path.c_str(), nullptr, GENERIC_READ, + WICDecodeMetadataCacheOnDemand, + decoder.GetAddressOf()), + __FILE__, __LINE__, "IWICImagingFactory::CreateDecoderFromFilename", + read_hint.c_str())) { + return false; + } + + ComPtr frame; + if (!HrSucceeded(decoder->GetFrame(0, frame.GetAddressOf()), __FILE__, __LINE__, + "IWICBitmapDecoder::GetFrame(0)", "the PNG has at least one frame")) { + return false; + } + + ComPtr converter; + if (!HrSucceeded(factory->CreateFormatConverter(converter.GetAddressOf()), __FILE__, __LINE__, + "IWICImagingFactory::CreateFormatConverter", "WIC is initialised")) { + return false; + } + if (!HrSucceeded(converter->Initialize(frame.Get(), GUID_WICPixelFormat32bppRGBA, + WICBitmapDitherTypeNone, nullptr, 0.0, + WICBitmapPaletteTypeCustom), + __FILE__, __LINE__, "IWICFormatConverter::Initialize", + "the decoded frame can be converted to 32bppRGBA without a palette")) { + return false; + } + + UINT width = 0; + UINT height = 0; + if (!HrSucceeded(converter->GetSize(&width, &height), __FILE__, __LINE__, + "IWICFormatConverter::GetSize", "the frame header is intact")) { + return false; + } + surface_out.width = static_cast(width); + surface_out.height = static_cast(height); + surface_out.rgba.resize(static_cast(width) * height * 4); + return HrSucceeded(converter->CopyPixels(nullptr, width * 4, + static_cast(surface_out.rgba.size()), + surface_out.rgba.data()), + __FILE__, __LINE__, "IWICFormatConverter::CopyPixels", + "the file holds a complete image; a truncated PNG fails here"); +} diff --git a/tools/conformance/native/src/png_io.h b/tools/conformance/native/src/png_io.h new file mode 100644 index 000000000..674ab34d4 --- /dev/null +++ b/tools/conformance/native/src/png_io.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#include "pixel_surface.h" + +// Writes the surface as an 8-bit RGBA PNG. The WIC encoder is handed BGRA, the byte +// order it stores natively, so the file's R, G and B channels match the surface exactly. +bool WritePngFile(const std::filesystem::path& path, const PixelSurface& surface); + +// Decodes the first frame of a PNG back into R,G,B,A bytes. Used to prove the file on +// disk, not just the readback buffer, matches the contract. +bool ReadPngFile(const std::filesystem::path& path, PixelSurface& surface_out); diff --git a/tools/conformance/native/src/renderer.cpp b/tools/conformance/native/src/renderer.cpp new file mode 100644 index 000000000..f71ac2c4a --- /dev/null +++ b/tools/conformance/native/src/renderer.cpp @@ -0,0 +1,712 @@ +#include "renderer.h" + +#include + +#include +#include +#include +#include +#include +#include + +#include "diagnostics.h" + +namespace { + +constexpr UINT kTintConstantStride = 256; // D3D12 requires 256-byte alignment for a root CBV +// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT is 256 bytes: the readback buffer's rows are padded +// to that boundary, which happens to equal width*4 at 256 pixels wide. Deriving it keeps +// the copy loop honest if the scene size ever changes. +constexpr UINT kReadbackRowPitch = + (conform::kSceneWidth * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) / + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT * D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; +constexpr UINT kReadbackRowBytes = conform::kSceneWidth * 4; +constexpr SIZE_T kUploadAlignment = 256; +constexpr UINT kFullscreenTriangleVertices = 3; + +// The index buffers are declared uint16_t in the contract and bound as R16_UINT. If the +// contract ever switches to 32-bit indices these fail at compile time instead of every +// index being read as two. +static_assert(std::is_same_v>, uint16_t>); +static_assert(std::is_same_v>, uint16_t>); + +// A .cso held in ordinary memory. D3D12_SHADER_BYTECODE copies nothing, so the vector +// must stay alive until the pipeline state is created. +struct ShaderFile { + std::vector bytes; + + D3D12_SHADER_BYTECODE Bytecode() const { + return D3D12_SHADER_BYTECODE{bytes.data(), bytes.size()}; + } +}; + +// The input layout for conform::ClipVertex. The offsets mirror scenes.h: three floats, +// then four UNORM bytes, so the colour arrives in the shader as straight 0..1 RGBA. +// The asserts make a future edit to the struct a build failure instead of a scene that +// renders the wrong shade. +static_assert(sizeof(conform::ClipVertex) == 16, + "ClipVertex must stay 3 floats + 4 bytes; the input layout assumes 16"); +static_assert(offsetof(conform::ClipVertex, r) == 12, + "COLOR must start at byte 12; the input layout hard-codes that offset"); + +const D3D12_INPUT_ELEMENT_DESC kVertexColorInputLayout[] = { + {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + 0}, + {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, +}; + +SIZE_T AlignToUploadBoundary(SIZE_T size) { + return (size + (kUploadAlignment - 1)) & ~(kUploadAlignment - 1); +} + +// Creates one committed resource and names it for the debug layer. Reports its own +// failure because every resource in this file is created the same way. +bool CreateCommittedResourceAt(ID3D12Device& device, D3D12_HEAP_TYPE heap_type, + D3D12_RESOURCE_STATES initial_state, + const D3D12_RESOURCE_DESC& description, const wchar_t* debug_name, + ComPtr& resource_out) { + D3D12_HEAP_PROPERTIES heap_properties{}; + heap_properties.Type = heap_type; + heap_properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + heap_properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + heap_properties.CreationNodeMask = 0; + heap_properties.VisibleNodeMask = 0; + + const HRESULT result = device.CreateCommittedResource( + &heap_properties, D3D12_HEAP_FLAG_NONE, &description, initial_state, nullptr, + IID_PPV_ARGS(resource_out.GetAddressOf())); + if (!HrSucceeded(result, __FILE__, __LINE__, "ID3D12Device::CreateCommittedResource", + "GPU memory is available and the heap type matches the resource; " + "OUT_OF_MEMORY means the adapter is full or the limit is set too low")) { + return false; + } + resource_out->SetName(debug_name); + return true; +} + +// Upload-heap buffer holding a CPU-side copy of geometry or constants. The size is +// rounded up because D3D12 wants buffer widths aligned and the slack costs nothing. +bool CreateUploadBuffer(ID3D12Device& device, const void* data, SIZE_T data_size, + const wchar_t* debug_name, ComPtr& resource_out) { + D3D12_RESOURCE_DESC description{}; + description.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + description.Width = AlignToUploadBoundary(data_size); + description.Height = 1; + description.DepthOrArraySize = 1; + description.MipLevels = 1; + description.Format = DXGI_FORMAT_UNKNOWN; + description.SampleDesc.Count = 1; + description.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + description.Flags = D3D12_RESOURCE_FLAG_NONE; + + if (!CreateCommittedResourceAt(device, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, + description, debug_name, resource_out)) { + return false; + } + + void* mapped = nullptr; + if (!HrSucceeded(resource_out->Map(0, nullptr, &mapped), __FILE__, __LINE__, + "ID3D12Resource::Map(upload)", "the upload heap is not exhausted")) { + return false; + } + std::memcpy(mapped, data, data_size); + resource_out->Unmap(0, nullptr); + return true; +} + +D3D12_RESOURCE_DESC MakeTextureDescription(DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC description{}; + description.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + description.Width = static_cast(conform::kSceneWidth); + description.Height = static_cast(conform::kSceneHeight); + description.DepthOrArraySize = 1; + description.MipLevels = 1; + description.Format = format; + description.SampleDesc.Count = 1; + description.SampleDesc.Quality = 0; + description.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + description.Flags = flags; + return description; +} + +bool CreateDescriptorHeaps(Renderer& renderer, ID3D12Device& device) { + D3D12_DESCRIPTOR_HEAP_DESC render_target_heap{}; + render_target_heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + render_target_heap.NumDescriptors = 1; + if (!HrSucceeded(device.CreateDescriptorHeap(&render_target_heap, IID_PPV_ARGS( + renderer.render_target_view_heap.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateDescriptorHeap(RTV)", + "the RTV heap limit is not exhausted and the heap type is supported")) { + return false; + } + renderer.color_render_target_view = + renderer.render_target_view_heap->GetCPUDescriptorHandleForHeapStart(); + + D3D12_DESCRIPTOR_HEAP_DESC depth_stencil_heap{}; + depth_stencil_heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; + depth_stencil_heap.NumDescriptors = 1; + if (!HrSucceeded(device.CreateDescriptorHeap(&depth_stencil_heap, IID_PPV_ARGS( + renderer.depth_stencil_view_heap.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateDescriptorHeap(DSV)", + "the DSV heap limit is not exhausted and the heap type is supported")) { + return false; + } + renderer.depth_stencil_view = + renderer.depth_stencil_view_heap->GetCPUDescriptorHandleForHeapStart(); + return true; +} + +bool CreateTargets(Renderer& renderer, ID3D12Device& device) { + if (!CreateCommittedResourceAt(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, + MakeTextureDescription(DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + L"color_target", renderer.color_target)) { + return false; + } + if (!CreateCommittedResourceAt(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_DEPTH_WRITE, + MakeTextureDescription(DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + L"depth_target", renderer.depth_target)) { + return false; + } + + D3D12_RESOURCE_DESC readback_description{}; + readback_description.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + readback_description.Width = static_cast(kReadbackRowPitch) * conform::kSceneHeight; + readback_description.Height = 1; + readback_description.DepthOrArraySize = 1; + readback_description.MipLevels = 1; + readback_description.Format = DXGI_FORMAT_UNKNOWN; + readback_description.SampleDesc.Count = 1; + readback_description.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (!CreateCommittedResourceAt(device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, + readback_description, L"readback_buffer", + renderer.readback_buffer)) { + return false; + } + + // Null descriptions inherit the resource format, which is what the pipelines expect. + device.CreateRenderTargetView(renderer.color_target.Get(), nullptr, + renderer.color_render_target_view); + device.CreateDepthStencilView(renderer.depth_target.Get(), nullptr, + renderer.depth_stencil_view); + return true; +} + +bool CreateGeometryBuffers(Renderer& renderer, ID3D12Device& device) { + if (!CreateUploadBuffer(device, conform::kDepthOrderVertices, + sizeof(conform::kDepthOrderVertices), L"depth_order_vertex_buffer", + renderer.depth_order_vertex_buffer)) { + return false; + } + if (!CreateUploadBuffer(device, conform::kDepthOrderIndices, + sizeof(conform::kDepthOrderIndices), L"depth_order_index_buffer", + renderer.depth_order_index_buffer)) { + return false; + } + if (!CreateUploadBuffer(device, conform::kIndexedVertices, sizeof(conform::kIndexedVertices), + L"indexed_vertex_buffer", renderer.indexed_vertex_buffer)) { + return false; + } + if (!CreateUploadBuffer(device, conform::kIndexedIndices, sizeof(conform::kIndexedIndices), + L"indexed_index_buffer", renderer.indexed_index_buffer)) { + return false; + } + + renderer.depth_order_vertex_view.BufferLocation = + renderer.depth_order_vertex_buffer->GetGPUVirtualAddress(); + renderer.depth_order_vertex_view.SizeInBytes = + static_cast(sizeof(conform::kDepthOrderVertices)); + renderer.depth_order_vertex_view.StrideInBytes = + static_cast(sizeof(conform::ClipVertex)); + + renderer.depth_order_index_view.BufferLocation = + renderer.depth_order_index_buffer->GetGPUVirtualAddress(); + renderer.depth_order_index_view.SizeInBytes = + static_cast(sizeof(conform::kDepthOrderIndices)); + renderer.depth_order_index_view.Format = DXGI_FORMAT_R16_UINT; + + renderer.indexed_vertex_view.BufferLocation = + renderer.indexed_vertex_buffer->GetGPUVirtualAddress(); + renderer.indexed_vertex_view.SizeInBytes = static_cast(sizeof(conform::kIndexedVertices)); + renderer.indexed_vertex_view.StrideInBytes = static_cast(sizeof(conform::ClipVertex)); + + renderer.indexed_index_view.BufferLocation = + renderer.indexed_index_buffer->GetGPUVirtualAddress(); + renderer.indexed_index_view.SizeInBytes = static_cast(sizeof(conform::kIndexedIndices)); + renderer.indexed_index_view.Format = DXGI_FORMAT_R16_UINT; + return true; +} + +bool CreateTintConstants(Renderer& renderer, ID3D12Device& device) { + // One 256-byte slot per scene. Each slot holds exactly the single float4 the contract + // specifies at byte offset 0, already divided by 255 so the UNORM bytes come back + // exact. Slots are filled before any draw and never rewritten. + std::vector slot_bytes( + static_cast(conform::kSceneCount) * kTintConstantStride, 0); + for (int index = 0; index < conform::kSceneCount; ++index) { + const conform::Scene& scene = conform::kScenes[index]; + const float tint[4] = {scene.tintR / 255.0f, scene.tintG / 255.0f, + scene.tintB / 255.0f, scene.tintA / 255.0f}; + std::memcpy(slot_bytes.data() + static_cast(index) * kTintConstantStride, tint, + sizeof tint); + } + return CreateUploadBuffer(device, slot_bytes.data(), slot_bytes.size(), L"tint_constants", + renderer.tint_constants); +} + +// Address of one scene's float4. Callers validate the slot; this only converts. +D3D12_GPU_VIRTUAL_ADDRESS TintAddress(const Renderer& renderer, int tint_slot) { + return renderer.tint_constants->GetGPUVirtualAddress() + + static_cast(tint_slot) * kTintConstantStride; +} + +// Serialises and creates a root signature. On a serialisation failure the compiler's +// own message is printed, because that text names the offending parameter. +bool CreateRootSignatureFromDescription(ID3D12Device& device, + const D3D12_ROOT_SIGNATURE_DESC& description, + const wchar_t* debug_name, + ComPtr& signature_out) { + ComPtr serialized; + ComPtr error_text; + const HRESULT serialize_result = D3D12SerializeRootSignature( + &description, D3D_ROOT_SIGNATURE_VERSION_1, serialized.GetAddressOf(), + error_text.GetAddressOf()); + if (FAILED(serialize_result)) { + if (error_text != nullptr) { + std::fprintf(stderr, "root signature error: %.*s\n", + static_cast(error_text->GetBufferSize()), + static_cast(error_text->GetBufferPointer())); + } + HrSucceeded(serialize_result, __FILE__, __LINE__, "D3D12SerializeRootSignature", + "the root signature description is valid; the printed text names the " + "offending field"); + return false; + } + if (!HrSucceeded(device.CreateRootSignature(0, serialized->GetBufferPointer(), + serialized->GetBufferSize(), + IID_PPV_ARGS(signature_out.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateRootSignature", + "the device is still present and the serialised blob is intact")) { + return false; + } + signature_out->SetName(debug_name); + return true; +} + +bool CreateSceneRootSignature(Renderer& renderer, ID3D12Device& device) { + // The contract's baseline: one root CBV at b0, shader visibility ALL, space 0, and + // ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT so the vertex-colour pipeline can declare an + // input layout. The vertex-colour shaders never read b0; every draw binds it anyway so + // all three pipelines share one signature, exactly as the header specifies. + D3D12_ROOT_PARAMETER tint_parameter{}; + tint_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + tint_parameter.Descriptor.ShaderRegister = 0; + tint_parameter.Descriptor.RegisterSpace = 0; + tint_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + + D3D12_ROOT_SIGNATURE_DESC description{}; + description.NumParameters = 1; + description.pParameters = &tint_parameter; + description.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + return CreateRootSignatureFromDescription(device, description, L"scene_root_signature", + renderer.root_signature); +} + +// The state every pipeline shares. Callers override blend and depth; the three pipelines +// share everything else. Scissor is not pipeline state in D3D12: it is per-draw state set +// in ClearAndDrawScene, which is why no pipeline mentions it. +D3D12_GRAPHICS_PIPELINE_STATE_DESC MakeBasePipelineDescription( + ID3D12RootSignature& root_signature, const D3D12_SHADER_BYTECODE& vertex_shader, + const D3D12_SHADER_BYTECODE& pixel_shader, const D3D12_INPUT_LAYOUT_DESC& input_layout) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC description{}; + description.pRootSignature = &root_signature; + description.VS = vertex_shader; + description.PS = pixel_shader; + description.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; + description.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + description.NumRenderTargets = 1; + description.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + description.DSVFormat = DXGI_FORMAT_D32_FLOAT; + description.SampleDesc.Count = 1; + description.SampleMask = UINT_MAX; + description.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; + description.InputLayout = input_layout; + + // Winding is irrelevant for these axis-aligned quads and a fullscreen triangle, so + // culling is off; a cull setting must never be what makes a scene pass or fail. + description.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + description.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + description.RasterizerState.FrontCounterClockwise = FALSE; + description.RasterizerState.DepthBias = 0; + description.RasterizerState.DepthBiasClamp = 0.0f; + description.RasterizerState.SlopeScaledDepthBias = 0.0f; + description.RasterizerState.DepthClipEnable = TRUE; + description.RasterizerState.MultisampleEnable = FALSE; + description.RasterizerState.AntialiasedLineEnable = FALSE; + description.RasterizerState.ForcedSampleCount = 0; + description.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + + description.BlendState.AlphaToCoverageEnable = FALSE; + description.BlendState.IndependentBlendEnable = FALSE; + description.BlendState.RenderTarget[0].BlendEnable = FALSE; + description.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + + description.DepthStencilState.DepthEnable = FALSE; + description.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + description.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + description.DepthStencilState.StencilEnable = FALSE; + return description; +} + +bool CreateFullscreenPipeline(Renderer& renderer, ID3D12Device& device, + const ShaderFile& vertex_shader, const ShaderFile& pixel_shader) { + const D3D12_INPUT_LAYOUT_DESC no_input_layout{nullptr, 0}; + D3D12_GRAPHICS_PIPELINE_STATE_DESC description = MakeBasePipelineDescription( + *renderer.root_signature.Get(), vertex_shader.Bytecode(), + pixel_shader.Bytecode(), no_input_layout); + if (!HrSucceeded(device.CreateGraphicsPipelineState(&description, IID_PPV_ARGS( + renderer.fullscreen_pipeline.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateGraphicsPipelineState(fullscreen)", + "the shader bytecode matches the declared formats and the shader model is " + "supported by this adapter")) { + return false; + } + renderer.fullscreen_pipeline->SetName(L"fullscreen_pipeline"); + return true; +} + +bool CreateBlendPipeline(Renderer& renderer, ID3D12Device& device, + const ShaderFile& vertex_shader, const ShaderFile& pixel_shader) { + const D3D12_INPUT_LAYOUT_DESC no_input_layout{nullptr, 0}; + D3D12_GRAPHICS_PIPELINE_STATE_DESC description = MakeBasePipelineDescription( + *renderer.root_signature.Get(), vertex_shader.Bytecode(), + pixel_shader.Bytecode(), no_input_layout); + description.BlendState.RenderTarget[0].BlendEnable = TRUE; + description.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; + description.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + description.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; + // The contract states the alpha channel explicitly: ONE, INV_SRC_ALPHA, ADD, which + // evaluates to 1.0*0.5 + 0.5*1.0 = 1.0 and stores 255. SRC_ALPHA here would store + // 191 and fail the scene's checks. + description.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; + description.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + description.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; + if (!HrSucceeded(device.CreateGraphicsPipelineState(&description, IID_PPV_ARGS( + renderer.blend_pipeline.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateGraphicsPipelineState(blend)", + "the render target format supports blending; R8G8B8A8_UNORM always does")) { + return false; + } + renderer.blend_pipeline->SetName(L"blend_pipeline"); + return true; +} + +bool CreateVertexColorPipeline(Renderer& renderer, ID3D12Device& device, + const ShaderFile& vertex_shader, const ShaderFile& pixel_shader) { + D3D12_INPUT_LAYOUT_DESC input_layout{}; + input_layout.pInputElementDescs = kVertexColorInputLayout; + input_layout.NumElements = static_cast( + sizeof(kVertexColorInputLayout) / sizeof(kVertexColorInputLayout[0])); + D3D12_GRAPHICS_PIPELINE_STATE_DESC description = MakeBasePipelineDescription( + *renderer.root_signature.Get(), vertex_shader.Bytecode(), pixel_shader.Bytecode(), + input_layout); + // The only pipeline with depth: the contract asks for LESS with writes enabled so the + // nearer green quad wins regardless of draw order. + description.DepthStencilState.DepthEnable = TRUE; + description.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + description.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + if (!HrSucceeded(device.CreateGraphicsPipelineState(&description, IID_PPV_ARGS( + renderer.vertex_color_pipeline.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateGraphicsPipelineState(vertex_color)", + "the input layout matches the shader's semantics and the depth format is " + "supported")) { + return false; + } + renderer.vertex_color_pipeline->SetName(L"vertex_color_pipeline"); + return true; +} + +bool LoadShaderFile(const std::filesystem::path& path, ShaderFile& shader_out) { + std::ifstream input(path, std::ios::binary | std::ios::ate); + if (!input.is_open()) { + ReportFailure(__FILE__, __LINE__, "std::ifstream::open", "could not open " + path.string(), + "the build ran the conform_shaders target and the shaders directory sits " + "next to conform_native.exe; use --shaders to point elsewhere"); + return false; + } + const std::streamoff size = input.tellg(); + if (size <= 0) { + ReportFailure(__FILE__, __LINE__, "std::ifstream::tellg", + path.string() + " is empty", + "rebuild with the conform_shaders target so dxc writes a real .cso"); + return false; + } + shader_out.bytes.resize(static_cast(size)); + input.seekg(0, std::ios::beg); + input.read(reinterpret_cast(shader_out.bytes.data()), size); + if (!input) { + ReportFailure(__FILE__, __LINE__, "std::ifstream::read", + "could not read all of " + path.string(), + "the file is not locked by another process and the disk is readable"); + return false; + } + return true; +} + +bool CreatePipelines(Renderer& renderer, ID3D12Device& device, + const std::filesystem::path& shader_directory) { + ShaderFile fullscreen_vertex_shader; + ShaderFile fullscreen_pixel_shader; + ShaderFile vertex_color_vertex_shader; + ShaderFile vertex_color_pixel_shader; + if (!LoadShaderFile(shader_directory / "fullscreen_color.vs.cso", fullscreen_vertex_shader) || + !LoadShaderFile(shader_directory / "fullscreen_color.ps.cso", fullscreen_pixel_shader) || + !LoadShaderFile(shader_directory / "vertex_color.vs.cso", vertex_color_vertex_shader) || + !LoadShaderFile(shader_directory / "vertex_color.ps.cso", vertex_color_pixel_shader)) { + return false; + } + + if (!CreateSceneRootSignature(renderer, device) || + !CreateFullscreenPipeline(renderer, device, fullscreen_vertex_shader, + fullscreen_pixel_shader) || + !CreateBlendPipeline(renderer, device, fullscreen_vertex_shader, + fullscreen_pixel_shader) || + !CreateVertexColorPipeline(renderer, device, vertex_color_vertex_shader, + vertex_color_pixel_shader)) { + return false; + } + return true; +} + +bool CreateCommandObjects(Renderer& renderer, ID3D12Device& device) { + if (!HrSucceeded(device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS( + renderer.command_allocator.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateCommandAllocator", + "the direct queue was created successfully")) { + return false; + } + if (!HrSucceeded(device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, + renderer.command_allocator.Get(), nullptr, + IID_PPV_ARGS(renderer.command_list.GetAddressOf())), + __FILE__, __LINE__, "ID3D12Device::CreateCommandList", + "the allocator is valid and no list of this type is already recording")) { + return false; + } + // A newly created list is open; close it so the first scene starts from a clean reset. + return HrSucceeded(renderer.command_list->Close(), __FILE__, __LINE__, + "ID3D12GraphicsCommandList::Close", + "the list was created in a recordable state"); +} + +// Inserts one transition for every subresource. All barriers in this file go through it +// so the before-state is always the state the previous barrier left behind. +bool TransitionColorTarget(Renderer& renderer, D3D12_RESOURCE_STATES state_before, + D3D12_RESOURCE_STATES state_after) { + if (state_before == state_after) { + ReportFailure(__FILE__, __LINE__, "TransitionColorTarget", + "the barrier would have identical before and after states", + "this is a renderer bug in the scene state machine, not a driver issue"); + return false; + } + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.Transition.pResource = renderer.color_target.Get(); + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = state_before; + barrier.Transition.StateAfter = state_after; + renderer.command_list->ResourceBarrier(1, &barrier); + return true; +} + +// Binds the pipeline named by the plan and issues exactly one draw. Split from the +// recording function so that function stays short and the draw geometry is in one place. +void BindPipelineAndDraw(Renderer& renderer, const DrawPlan& plan) { + ID3D12PipelineState* pipeline = nullptr; + switch (plan.pipeline) { + case PipelineKind::Fullscreen: + pipeline = renderer.fullscreen_pipeline.Get(); + break; + case PipelineKind::Blend: + pipeline = renderer.blend_pipeline.Get(); + break; + case PipelineKind::VertexColor: + pipeline = renderer.vertex_color_pipeline.Get(); + break; + } + ID3D12GraphicsCommandList* list = renderer.command_list.Get(); + list->SetPipelineState(pipeline); + // Bound for every draw, including vertex-colour draws whose shaders ignore it: the + // contract's baseline names one root CBV at b0 for every scene. + list->SetGraphicsRootSignature(renderer.root_signature.Get()); + list->SetGraphicsRootConstantBufferView(0, TintAddress(renderer, plan.tint_slot)); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + switch (plan.geometry) { + case GeometryKind::None: + return; + case GeometryKind::FullscreenTriangle: + list->DrawInstanced(kFullscreenTriangleVertices, 1, 0, 0); + return; + case GeometryKind::DepthOrderQuads: + list->IASetVertexBuffers(0, 1, &renderer.depth_order_vertex_view); + list->IASetIndexBuffer(&renderer.depth_order_index_view); + // The index buffer carries the contract's draw order: near green first, far + // red second. A renderer that ignores depth paints red over green. + list->DrawIndexedInstanced( + static_cast(sizeof(conform::kDepthOrderIndices) / sizeof(uint16_t)), 1, 0, 0, 0); + return; + case GeometryKind::IndexedTriangles: + list->IASetVertexBuffers(0, 1, &renderer.indexed_vertex_view); + list->IASetIndexBuffer(&renderer.indexed_index_view); + list->DrawIndexedInstanced( + static_cast(sizeof(conform::kIndexedIndices) / sizeof(uint16_t)), 1, 0, 0, 0); + return; + } +} + +// Clears the colour target (and the depth target for depth_order only), then draws when +// the plan asks for geometry. The clear always happens, which is what the clear scene +// alone tests. +void ClearAndDrawScene(Renderer& renderer, const DrawPlan& plan) { + ID3D12GraphicsCommandList* list = renderer.command_list.Get(); + // The contract's baseline binds a DSV only for depth_order; every other scene passes + // a null DSV, which leaves depth testing inert. + const D3D12_CPU_DESCRIPTOR_HANDLE* depth_view = + plan.binds_depth_target ? &renderer.depth_stencil_view : nullptr; + list->OMSetRenderTargets(1, &renderer.color_render_target_view, FALSE, depth_view); + + const float clear_color[4] = {conform::kClearR / 255.0f, conform::kClearG / 255.0f, + conform::kClearB / 255.0f, conform::kClearA / 255.0f}; + list->ClearRenderTargetView(renderer.color_render_target_view, clear_color, 0, nullptr); + if (plan.binds_depth_target) { + list->ClearDepthStencilView(renderer.depth_stencil_view, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, + nullptr); + } + list->RSSetViewports(1, &renderer.viewport); + list->RSSetScissorRects(1, &plan.scissor); + if (plan.geometry != GeometryKind::None) { + BindPipelineAndDraw(renderer, plan); + } +} + +// Copies the rendered target into the readback buffer at the contract's row pitch. +void CopyColorTargetToReadback(Renderer& renderer) { + D3D12_TEXTURE_COPY_LOCATION destination{}; + destination.pResource = renderer.readback_buffer.Get(); + destination.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + destination.PlacedFootprint.Offset = 0; // 512-byte aligned, as placed footprints require + destination.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + destination.PlacedFootprint.Footprint.Width = static_cast(conform::kSceneWidth); + destination.PlacedFootprint.Footprint.Height = static_cast(conform::kSceneHeight); + destination.PlacedFootprint.Footprint.Depth = 1; + destination.PlacedFootprint.Footprint.RowPitch = kReadbackRowPitch; + + D3D12_TEXTURE_COPY_LOCATION source{}; + source.pResource = renderer.color_target.Get(); + source.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + source.SubresourceIndex = 0; + + const D3D12_BOX source_box{0, 0, 0, static_cast(conform::kSceneWidth), + static_cast(conform::kSceneHeight), 1}; + renderer.command_list->CopyTextureRegion(&destination, 0, 0, 0, &source, &source_box); +} + +// Records one scene's whole pass: reset, clear, optional draw, copy out, back to COMMON +// so the next scene always starts from the same state. +bool RecordSceneCommands(Renderer& renderer, const DrawPlan& plan) { + if (!HrSucceeded(renderer.command_allocator->Reset(), __FILE__, __LINE__, + "ID3D12CommandAllocator::Reset", + "the GPU finished the previous scene; RenderScene waits on a fence before " + "the next reset")) { + return false; + } + if (!HrSucceeded(renderer.command_list->Reset(renderer.command_allocator.Get(), nullptr), + __FILE__, __LINE__, "ID3D12GraphicsCommandList::Reset", + "the list is closed and its allocator was just reset")) { + return false; + } + + if (!TransitionColorTarget(renderer, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_RENDER_TARGET)) { + return false; + } + ClearAndDrawScene(renderer, plan); + if (!TransitionColorTarget(renderer, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE)) { + return false; + } + CopyColorTargetToReadback(renderer); + if (!TransitionColorTarget(renderer, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON)) { + return false; + } + return HrSucceeded(renderer.command_list->Close(), __FILE__, __LINE__, + "ID3D12GraphicsCommandList::Close", + "every recording call above succeeded on a list that was open"); +} + +// Maps the readback buffer and copies it row by row; the row pitch is explicit because +// a buffer's mapped layout follows the placed footprint, not the image width alone. +bool CopyReadbackToSurface(Renderer& renderer, PixelSurface& surface_out) { + void* mapped = nullptr; + if (!HrSucceeded(renderer.readback_buffer->Map(0, nullptr, &mapped), __FILE__, __LINE__, + "ID3D12Resource::Map(readback)", + "the GPU finished the copy and the resource is a readback heap buffer")) { + return false; + } + surface_out.width = conform::kSceneWidth; + surface_out.height = conform::kSceneHeight; + // The surface is tightly packed; the mapped buffer is not. Copy row bytes, not pitch. + const SIZE_T image_size = static_cast(kReadbackRowBytes) * conform::kSceneHeight; + surface_out.rgba.resize(image_size); + for (int row = 0; row < conform::kSceneHeight; ++row) { + std::memcpy(surface_out.rgba.data() + static_cast(row) * kReadbackRowBytes, + static_cast(mapped) + static_cast(row) * kReadbackRowPitch, + kReadbackRowBytes); + } + renderer.readback_buffer->Unmap(0, nullptr); + return true; +} + +} // namespace + +bool Renderer::Initialize(GpuContext& gpu, const std::filesystem::path& shader_directory) { + if (!CreateDescriptorHeaps(*this, *gpu.device.Get()) || !CreateTargets(*this, *gpu.device.Get()) || + !CreateGeometryBuffers(*this, *gpu.device.Get()) || + !CreateTintConstants(*this, *gpu.device.Get()) || !CreatePipelines(*this, *gpu.device.Get(), + shader_directory) || + !CreateCommandObjects(*this, *gpu.device.Get())) { + return false; + } + + viewport.TopLeftX = 0.0f; + viewport.TopLeftY = 0.0f; + viewport.Width = static_cast(conform::kSceneWidth); + viewport.Height = static_cast(conform::kSceneHeight); + viewport.MinDepth = 0.0f; // the clip-space z values in scenes.h map straight to 0..1 + viewport.MaxDepth = 1.0f; + return true; +} + +bool Renderer::RenderScene(GpuContext& gpu, const DrawPlan& plan, PixelSurface& surface_out) { + if (plan.tint_slot < 0 || plan.tint_slot >= conform::kSceneCount) { + ReportFailure(__FILE__, __LINE__, "Renderer::RenderScene", + "tint slot " + std::to_string(plan.tint_slot) + + " is outside the constant buffer", + "MakeDrawPlan is given an index inside conform::kScenes"); + return false; + } + if (!RecordSceneCommands(*this, plan)) { + return false; + } + ID3D12CommandList* command_lists[] = {command_list.Get()}; + gpu.command_queue->ExecuteCommandLists(1, command_lists); + if (!SignalAndWaitForGpu(gpu) || !DeviceStillPresent(gpu)) { + return false; + } + return CopyReadbackToSurface(*this, surface_out); +} diff --git a/tools/conformance/native/src/renderer.h b/tools/conformance/native/src/renderer.h new file mode 100644 index 000000000..198f252c0 --- /dev/null +++ b/tools/conformance/native/src/renderer.h @@ -0,0 +1,65 @@ +#pragma once + +#include + +#include + +#include "gpu.h" +#include "pixel_surface.h" +#include "scene_plan.h" + +// A D3D12 renderer fixed to the contract's 256x256 R8G8B8A8_UNORM target with a +// D32_FLOAT depth buffer, no swapchain. Owns every GPU object it needs; the only state +// that lives outside is the device and queue in GpuContext. +// +// It does not create a window, pump messages, present, or touch D:\conform\spec; the +// shaders are loaded from disk as compiled by the build. +struct Renderer { + // Descriptor heaps. One RTV and one DSV is all the contract needs. + ComPtr render_target_view_heap; + ComPtr depth_stencil_view_heap; + D3D12_CPU_DESCRIPTOR_HANDLE color_render_target_view{}; + D3D12_CPU_DESCRIPTOR_HANDLE depth_stencil_view{}; + + // Render and readback targets. + ComPtr color_target; + ComPtr depth_target; + ComPtr readback_buffer; + + // Geometry, one upload buffer per array in scenes.h. + ComPtr depth_order_vertex_buffer; + ComPtr depth_order_index_buffer; + ComPtr indexed_vertex_buffer; + ComPtr indexed_index_buffer; + D3D12_VERTEX_BUFFER_VIEW depth_order_vertex_view{}; + D3D12_INDEX_BUFFER_VIEW depth_order_index_view{}; + D3D12_VERTEX_BUFFER_VIEW indexed_vertex_view{}; + D3D12_INDEX_BUFFER_VIEW indexed_index_view{}; + + // One constant-buffer slot per scene: the contract now gives each scene its own + // tint, and a root CBV must sit on a 256-byte boundary. Filled once before any draw, + // so no CPU write can race a GPU read. + ComPtr tint_constants; + + // Pipelines and the one root signature they share. + ComPtr root_signature; + ComPtr fullscreen_pipeline; + ComPtr blend_pipeline; + ComPtr vertex_color_pipeline; + + // Command recording objects. One list is enough because every scene waits for the + // GPU before the next reset. + ComPtr command_allocator; + ComPtr command_list; + + // Fixed state shared by every scene. + D3D12_VIEWPORT viewport{}; + + // Creates every resource, pipeline and command object. Does not render anything and + // does not verify output; RenderScene does both of those. + bool Initialize(GpuContext& gpu, const std::filesystem::path& shader_directory); + + // Renders one scene, waits for the GPU, and fills surface_out with the readback + // pixels. Does not compare them against the contract; VerifyChecks does that. + bool RenderScene(GpuContext& gpu, const DrawPlan& plan, PixelSurface& surface_out); +}; diff --git a/tools/conformance/native/src/scene_plan.cpp b/tools/conformance/native/src/scene_plan.cpp new file mode 100644 index 000000000..6effaeac8 --- /dev/null +++ b/tools/conformance/native/src/scene_plan.cpp @@ -0,0 +1,52 @@ +#include "scene_plan.h" + +#include +#include + +DrawPlan MakeDrawPlan(const conform::Scene& scene, int scene_index) { + DrawPlan plan{}; + plan.tint_slot = scene_index; + // The baseline scissor is the full target; only the scissor scene narrows it. + plan.scissor = {0, 0, conform::kSceneWidth, conform::kSceneHeight}; + + switch (scene.kind) { + case conform::SceneKind::Clear: + // No draw at all: the contract tests the clear and the readback path. + plan.geometry = GeometryKind::None; + break; + case conform::SceneKind::Fullscreen: + plan.geometry = GeometryKind::FullscreenTriangle; + break; + case conform::SceneKind::DepthOrder: + plan.pipeline = PipelineKind::VertexColor; + plan.geometry = GeometryKind::DepthOrderQuads; + // The only scene that binds a depth target; every other scene passes a null + // DSV, which is what the contract's baseline table says. + plan.binds_depth_target = true; + break; + case conform::SceneKind::Scissor: + // Same pipeline as fullscreen. D3D12 applies the scissor test whenever a rect + // is set, with no enable flag in the pipeline state, so this scene proves + // RSSetScissorRects. Right and bottom are exclusive. + plan.geometry = GeometryKind::FullscreenTriangle; + plan.scissor = {conform::kScissorLeft, conform::kScissorTop, conform::kScissorRight, + conform::kScissorBottom}; + break; + case conform::SceneKind::Blend: + plan.pipeline = PipelineKind::Blend; + plan.geometry = GeometryKind::FullscreenTriangle; + break; + case conform::SceneKind::Indexed: + plan.pipeline = PipelineKind::VertexColor; + plan.geometry = GeometryKind::IndexedTriangles; + break; + default: + // Unreachable while every SceneKind has a case above. If scenes.h gains a kind + // and this switch is forgotten, /we4062 turns the missing case into a build + // error; this line is the belt for a compiler that does not implement it. + std::fprintf(stderr, "internal: scene kind %d has no draw plan\n", + static_cast(scene.kind)); + std::abort(); + } + return plan; +} diff --git a/tools/conformance/native/src/scene_plan.h b/tools/conformance/native/src/scene_plan.h new file mode 100644 index 000000000..4328b44df --- /dev/null +++ b/tools/conformance/native/src/scene_plan.h @@ -0,0 +1,36 @@ +#pragma once + +#include + +#include "scenes.h" + +// Which of the three pipeline states the draw needs. The PSO carries blend and depth +// state, so this choice fixes both at once; the scissor rect and the depth-target binding +// are per-scene state, because D3D12 always applies the scissor and allows a null DSV. +enum class PipelineKind { + Fullscreen, // oversized triangle, no depth, no blend + Blend, // identical but with the contract's blend state + VertexColor, // vertex buffer + 16-bit indices, depth LESS with write +}; + +enum class GeometryKind { + None, // clear only + FullscreenTriangle, // SV_VertexID, three vertices, no buffers + DepthOrderQuads, // conform::kDepthOrderVertices / kDepthOrderIndices + IndexedTriangles, // conform::kIndexedVertices / kIndexedIndices +}; + +// Everything one scene needs bound, resolved from the contract before any GPU call so +// the render loop contains no per-scene branching. +struct DrawPlan { + PipelineKind pipeline = PipelineKind::Fullscreen; + GeometryKind geometry = GeometryKind::None; + int tint_slot = 0; // which 256-byte slot holds this scene's float4 + bool binds_depth_target = false; // true only for depth_order, per the baseline state + D3D12_RECT scissor{}; +}; + +// Maps a contract scene to pipeline, geometry, constant-buffer slot, depth binding and +// scissor. scene_index is the scene's position in conform::kScenes and selects its tint. +// Pure function: reads only scenes.h values and touches no device state. +DrawPlan MakeDrawPlan(const conform::Scene& scene, int scene_index); diff --git a/tools/conformance/native/src/verify.cpp b/tools/conformance/native/src/verify.cpp new file mode 100644 index 000000000..3c37f2d68 --- /dev/null +++ b/tools/conformance/native/src/verify.cpp @@ -0,0 +1,50 @@ +#include "verify.h" + +#include +#include + +namespace { + +// A scene with zero checks proves nothing, and a count above the array size reads past +// the end. Both are contract errors, so they are build errors rather than runtime ones. +constexpr bool CheckCountsAreSane() { + for (const conform::Scene& scene : conform::kScenes) { + if (scene.checkCount < 1 || scene.checkCount > static_cast(std::size(scene.checks))) { + return false; + } + } + return true; +} +static_assert(CheckCountsAreSane(), "every scene needs 1..N pixel checks; see conform::Scene"); + +} // namespace + +CheckTally VerifyChecks(const conform::Scene& scene, const PixelSurface& surface, + const char* source_label) { + CheckTally tally; + for (int index = 0; index < scene.checkCount; ++index) { + const conform::PixelCheck& check = scene.checks[index]; + if (check.x < 0 || check.y < 0 || check.x >= surface.width || check.y >= surface.height) { + std::printf("FAIL %s scene=%s (%d,%d) lies outside the %dx%d image %s\n", source_label, + scene.name, check.x, check.y, surface.width, surface.height, check.why); + ++tally.failed; + continue; + } + + const uint8_t* actual = surface.At(check.x, check.y); + const bool matches = actual[0] == check.r && actual[1] == check.g && + actual[2] == check.b && actual[3] == check.a; + std::printf("%s %s scene=%s (%d,%d) expected %u,%u,%u,%u actual %u,%u,%u,%u %s\n", + matches ? "PASS" : "FAIL", source_label, scene.name, check.x, check.y, + static_cast(check.r), static_cast(check.g), + static_cast(check.b), static_cast(check.a), + static_cast(actual[0]), static_cast(actual[1]), + static_cast(actual[2]), static_cast(actual[3]), check.why); + if (matches) { + ++tally.passed; + } else { + ++tally.failed; + } + } + return tally; +} diff --git a/tools/conformance/native/src/verify.h b/tools/conformance/native/src/verify.h new file mode 100644 index 000000000..7fa8e9e18 --- /dev/null +++ b/tools/conformance/native/src/verify.h @@ -0,0 +1,17 @@ +#pragma once + +#include "pixel_surface.h" +#include "scenes.h" + +// How many of a scene's contract checks matched one pixel surface. Kept per source so +// the summary can say which path failed: rendering or PNG encoding. +struct CheckTally { + int passed = 0; + int failed = 0; +}; + +// Compares every conform::PixelCheck of one scene against the surface and prints one +// PASS/FAIL line per check with the scene, coordinate, expected and actual pixel. Does +// not stop at the first failure, and does not modify the surface. +CheckTally VerifyChecks(const conform::Scene& scene, const PixelSurface& surface, + const char* source_label); diff --git a/tools/conformance/spec/scenes.h b/tools/conformance/spec/scenes.h new file mode 100644 index 000000000..c392b1fcd --- /dev/null +++ b/tools/conformance/spec/scenes.h @@ -0,0 +1,245 @@ +// Conformance scene contract — the single source of truth shared by the native D3D12 +// reference renderer, the Vulkan-shim renderer, and the image diff tool. +// +// Every scene is deterministic and analytically checkable: it names the exact pixels +// that must come out, so a mismatch is a bug with a coordinate, not a vague "the +// picture looks off". Where a value could be read two ways, this header states the +// reading; if an implementer has to guess, that is a defect in this header. +// +// Conventions, stated once and assumed everywhere below: +// * clip space is D3D style: x and y in -1..1, z in 0..1, w = 1.0. Depth == z. +// There is no GL-style (z+1)/2 remap anywhere in this suite. +// * image row 0 is the TOP of the image and corresponds to NDC y = +1. +// Byte order in memory is R, G, B, A. +// * the render target is R8G8B8A8_UNORM, so writing v in 0..1 stores round(v * 255) +// and reading gives the same 8-bit value back. No sRGB conversion, no dithering. +#pragma once + +#include + +namespace conform { + +constexpr int kSceneWidth = 256; +constexpr int kSceneHeight = 256; + +// Clear colour, in 8-bit UNORM, shared by every scene. +constexpr uint8_t kClearR = 10; +constexpr uint8_t kClearG = 20; +constexpr uint8_t kClearB = 30; +constexpr uint8_t kClearA = 255; + +// Pixel value that the clear colour writes, restated for checks and comments. +inline constexpr uint8_t kClearBytes[4] = {kClearR, kClearG, kClearB, kClearA}; + +// --------------------------------------------------------------------------------- +// Baseline pipeline state. Every scene starts from this and only the listed scene +// differences change. A zero-initialised D3D12_RASTERIZER_DESC is invalid, and a zero +// sample mask draws nothing, so this table is not optional documentation: it is the +// state an implementer must set. +// --------------------------------------------------------------------------------- +// +// topology D3D12_PRIMITIVE_TOPOLOGY_TRIANGLELIST (never a strip: a strip +// would bridge the depth-order quads with phantom triangles) +// cull mode D3D12_CULL_MODE_NONE, fill SOLID, FrontCounterClockwise FALSE +// sample count 1, sample mask 0xFFFFFFFF, no MSAA +// render target R8G8B8A8_UNORM, RenderTargetWriteMask = ALL (0x0F) +// viewport (0, 0, 256, 256), depth 0..1 +// scissor the full 256x256 target unless the scene says otherwise; +// scissor is always enabled in D3D12, so it must be set explicitly +// root signature one root CBV at b0, shader visibility ALL, space 0, +// flags = ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT (vertex-colour scenes +// also bind a vertex buffer and use the same signature unused) +// constant buffer a single float4 at byte offset 0, set to tint/255.0f +// depth only the depth_order scene binds a depth target, and it binds +// D32_FLOAT, clears to 1.0, DepthFunc LESS, DepthWriteMask ALL, +// stencil disabled. Every other scene binds no DSV. +// vertex format ClipVertex as declared below, stride sizeof(ClipVertex) +// index format R16_UINT for every indexed draw +// +// Each scene clears the render target to the clear colour before it draws, so state +// left behind by a previous scene can never explain a pass. + +// A vertex in clip space with a straight (non-premultiplied) colour. +// w is 1.0 everywhere, so z is the depth value written to SV_Position. +struct ClipVertex { + float x; + float y; + float z; + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; +}; + +// depth_order: the NEAR green quad is drawn FIRST, the FAR red quad SECOND. +// +// This order is deliberate and load-bearing. At the overlap, the red quad is drawn +// after the green one, so the only reason green survives is that the depth test rejects +// red (0.75 vs 0.25, LESS). A shim that ignores the depth target paints red over green +// and fails the check at (128,128). +// +// Green spans x -0.95..0.15, red spans x -0.95..0.95, so the right-hand side of the +// image shows red with nothing over it. +inline constexpr ClipVertex kDepthOrderVertices[] = { + // near quad: green, z = 0.25, drawn first + {-0.95f, -0.95f, 0.25f, 40, 160, 90, 255}, + {-0.95f, 0.95f, 0.25f, 40, 160, 90, 255}, + { 0.15f, 0.95f, 0.25f, 40, 160, 90, 255}, + { 0.15f, -0.95f, 0.25f, 40, 160, 90, 255}, + // far quad: red, z = 0.75, drawn second + {-0.95f, -0.95f, 0.75f, 220, 40, 40, 255}, + {-0.95f, 0.95f, 0.75f, 220, 40, 40, 255}, + { 0.95f, 0.95f, 0.75f, 220, 40, 40, 255}, + { 0.95f, -0.95f, 0.75f, 220, 40, 40, 255}, +}; +// Two triangles per quad, both wound counter-clockwise in NDC, which is irrelevant +// while culling is NONE but stated so the geometry has one meaning. +inline constexpr uint16_t kDepthOrderIndices[] = { + 0, 1, 2, 0, 2, 3, // near green quad + 4, 5, 6, 4, 6, 7, // far red quad +}; + +// indexed: six vertices stored in an order that is NOT the draw order, addressed by a +// non-identity index list. A program that ignores the index buffer and draws the vertex +// buffer in order produces the wrong triangles, which is the failure this scene exists +// to catch. +// +// Vertex layout in memory (deliberately shuffled): +// slot 0 = left-bottom, slot 1 = right-top, slot 2 = left-top, +// slot 3 = right-bottom, slot 4 = right-top, slot 5 = left-bottom +inline constexpr ClipVertex kIndexedVertices[] = { + {-0.60f, -0.60f, 0.50f, 240, 200, 40, 255}, // slot 0: left triangle, bottom left + { 0.60f, -0.60f, 0.50f, 40, 120, 240, 255}, // slot 1: right triangle, bottom right + {-0.60f, 0.60f, 0.50f, 240, 200, 40, 255}, // slot 2: left triangle, top left + { 0.10f, 0.60f, 0.50f, 40, 120, 240, 255}, // slot 3: right triangle, top left + { 0.10f, -0.60f, 0.50f, 40, 120, 240, 255}, // slot 4: right triangle, bottom left + {-0.10f, -0.60f, 0.50f, 240, 200, 40, 255}, // slot 5: left triangle, bottom right +}; +inline constexpr uint16_t kIndexedIndices[] = { + 0, 2, 5, // left triangle (slots 0, 2, 5) + 1, 3, 4, // right triangle (slots 1, 3, 4) +}; + +// Scissor rectangle for the scissor scene: D3D12_RECT{left, top, right, bottom} with +// right and bottom EXCLUSIVE. Deliberately asymmetric in both axes so that reading the +// rectangle as (x, y, width, height) - the usual mistake - fails the checks. +constexpr int kScissorLeft = 48; +constexpr int kScissorTop = 32; +constexpr int kScissorRight = 176; +constexpr int kScissorBottom = 96; + +struct PixelCheck { + int x; + int y; + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; + const char* why; // what this pixel proves, phrased as a claim +}; + +enum class SceneKind { + Clear, // clear only, no draw + Fullscreen, // one oversized triangle, colour from the constant buffer at b0 + DepthOrder, // kDepthOrderVertices / kDepthOrderIndices, depth target bound + Scissor, // oversized triangle restricted to the scissor rectangle + Blend, // oversized triangle, source alpha 0.5, SRC_ALPHA / INV_SRC_ALPHA + Indexed, // kIndexedVertices / kIndexedIndices +}; + +struct Scene { + const char* name; // also the PNG name, without extension + SceneKind kind; + const char* proves; // one sentence: the failure this scene would catch + + // Constant-buffer value for the scenes that read it, in 8-bit UNORM. + // Each scene uses a distinct colour so that state leaking from a previous scene + // changes the image instead of hiding behind an identical tint. + uint8_t tintR; + uint8_t tintG; + uint8_t tintB; + uint8_t tintA; + + int checkCount; + PixelCheck checks[5]; +}; + +// Blend arithmetic, stated so there is nothing to guess: +// source colour (200, 30, 60) with source alpha 0.5, over the clear colour: +// colour: SRC_ALPHA, INV_SRC_ALPHA, ADD +// alpha: ONE, INV_SRC_ALPHA, ADD -> 1.0*0.5 + 0.5*1.0 = 1.0 -> 255 +// 0.5*200 + 0.5*10 = 105, 0.5*30 + 0.5*20 = 25, 0.5*60 + 0.5*30 = 45 +// With the source alpha quantised to either 127 or 128 the result is still 105/25/45, +// so no tolerance is needed. +inline constexpr Scene kScenes[] = { + { + "clear", SceneKind::Clear, + "render target creation, the clear value and the readback path are wired up", + 10, 20, 30, 255, // tint unused + 3, + { + {0, 0, kClearR, kClearG, kClearB, kClearA, "top-left is the clear colour"}, + {128, 128, kClearR, kClearG, kClearB, kClearA, "centre is the clear colour"}, + {255, 255, kClearR, kClearG, kClearB, kClearA, "bottom-right is the clear colour"}, + }, + }, + { + "fullscreen", SceneKind::Fullscreen, + "vertex shader runs, a pipeline binds, and one triangle covers every pixel", + 200, 30, 60, 255, + 3, + { + {128, 128, 200, 30, 60, 255, "centre is the constant-buffer colour"}, + {8, 8, 200, 30, 60, 255, "top-left corner is covered: the triangle is oversized"}, + {247, 247, 200, 30, 60, 255, "bottom-right corner is covered too"}, + }, + }, + { + "depth_order", SceneKind::DepthOrder, + "the depth test rejects a later draw that is behind: without it this scene is red", + 0, 0, 0, 255, // tint unused + 2, + { + {128, 128, 40, 160, 90, 255, "overlap keeps the near quad drawn first (green, z=0.25) although red (z=0.75) was drawn after it"}, + {224, 128, 220, 40, 40, 255, "uncovered right side shows the far quad (red)"}, + }, + }, + { + "scissor", SceneKind::Scissor, + "scissor state is honoured: draws are clipped at the rectangle, not merely darkened", + 70, 140, 210, 255, + 5, + { + {112, 64, 70, 140, 210, 255, "inside the rectangle the draw lands"}, + {40, 64, kClearR, kClearG, kClearB, kClearA, "left of the rectangle stays clear"}, + {180, 64, kClearR, kClearG, kClearB, kClearA, "right of the rectangle stays clear"}, + {112, 24, kClearR, kClearG, kClearB, kClearA, "above the rectangle stays clear"}, + {112, 104, kClearR, kClearG, kClearB, kClearA, "below the rectangle stays clear"}, + }, + }, + { + "blend", SceneKind::Blend, + "blend state is applied: 50% source over the clear colour, not a replacement", + 200, 30, 60, 128, // 128/255 ~= 0.5, which rounds to the same result as 127 + 2, + { + {128, 128, 105, 25, 45, 255, "0.5*(200,30,60) + 0.5*(10,20,30) = (105,25,45)"}, + {8, 8, 105, 25, 45, 255, "blending applies everywhere the triangle covers"}, + }, + }, + { + "indexed", SceneKind::Indexed, + "the index buffer is read: a program that ignores it draws different triangles", + 0, 0, 0, 255, // tint unused + 3, + { + {80, 200, 240, 200, 40, 255, "left triangle, from index triple 0,2,5"}, + {176, 200, 40, 120, 240, 255, "right triangle, from index triple 1,3,4"}, + {128, 240, kClearR, kClearG, kClearB, kClearA, "the gap between the two triangles stays clear"}, + }, + }, +}; + +inline constexpr int kSceneCount = static_cast(sizeof(kScenes) / sizeof(kScenes[0])); + +} // namespace conform diff --git a/tools/conformance/spec/shaders/fullscreen_color.hlsl b/tools/conformance/spec/shaders/fullscreen_color.hlsl new file mode 100644 index 000000000..ff6a1381e --- /dev/null +++ b/tools/conformance/spec/shaders/fullscreen_color.hlsl @@ -0,0 +1,35 @@ +// Fullscreen triangle, one colour from a constant buffer. +// Used by the clear, fullscreen, scissor, blend and constant-buffer scenes: they +// differ only in pipeline state and the value in the CB, so one shader pair covers +// them and a failure points at state, not at shader compilation. + +cbuffer SceneConstants : register(b0) +{ + float4 tint; // straight (non-premultiplied) RGBA in 0..1 +}; + +struct VsOut +{ + float4 position : SV_Position; +}; + +VsOut VSMain(uint vertexId : SV_VertexID) +{ + // One oversized triangle covering clip space; no vertex buffer needed. + // id 0 -> (-1,-1) id 1 -> (-1, 3) id 2 -> (3,-1) + float2 corners[3] = + { + float2(-1.0, -1.0), + float2(-1.0, 3.0), + float2( 3.0, -1.0), + }; + + VsOut output; + output.position = float4(corners[vertexId], 0.0, 1.0); + return output; +} + +float4 PSMain(VsOut input) : SV_Target +{ + return tint; +} diff --git a/tools/conformance/spec/shaders/vertex_color.hlsl b/tools/conformance/spec/shaders/vertex_color.hlsl new file mode 100644 index 000000000..64be2a6af --- /dev/null +++ b/tools/conformance/spec/shaders/vertex_color.hlsl @@ -0,0 +1,29 @@ +// Clip-space position with a per-vertex colour. +// Used by the depth-order and indexed scenes: the two quads/triangles differ in +// depth or index order, and the colour comes from the vertex data so a wrong draw +// is visible as the wrong colour rather than the wrong shade. + +struct VsIn +{ + float3 position : POSITION; // already in clip space: xy in -1..1, z in 0..1 + float4 color : COLOR; +}; + +struct VsOut +{ + float4 position : SV_Position; + float4 color : COLOR; +}; + +VsOut VSMain(VsIn input) +{ + VsOut output; + output.position = float4(input.position, 1.0); + output.color = input.color; + return output; +} + +float4 PSMain(VsOut input) : SV_Target +{ + return input.color; +} diff --git a/tools/content_definitions.py b/tools/content_definitions.py index 21c0f5105..e8205fa13 100644 --- a/tools/content_definitions.py +++ b/tools/content_definitions.py @@ -204,7 +204,13 @@ def main() -> int: counts["included_sets"] += len(doc.included_sets) counts["groups"] += len(doc.change_set_groups) + status = 0 for path in args.inputs: + if not os.path.exists(path): + print(f"ERROR: {path}: does not exist", file=sys.stderr) + counts["failed_inputs"] += 1 + status = 2 + continue try: if os.path.isdir(path): for _, _, doc in carve_documents(path): @@ -214,8 +220,9 @@ def main() -> int: add(parse_content(file_chunks(stream))) except (OSError, ContentError, ValueError, KeyError, TypeError): counts["failed_inputs"] += 1 + status = max(status, 1) print(json.dumps(counts, sort_keys=True)) - return int(bool(counts["failed_inputs"])) + return status if __name__ == "__main__": diff --git a/tools/cpu_ref.py b/tools/cpu_ref.py index 694782f52..84c5e8b65 100644 --- a/tools/cpu_ref.py +++ b/tools/cpu_ref.py @@ -90,12 +90,39 @@ SUPPORTED_OPS = { "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32", "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_alignbit_b32", "v_alignbyte_b32", "v_perm_b32", "v_med3_i32", "v_med3_u32", + "v_not_b32", "v_bfrev_b32", "v_ffbl_b32", "v_ffbh_u32", "v_ffbh_i32", + "v_xnor_b32", "v_bcnt_u32_b32", + "v_add3_u32", "v_lshl_add_u32", "v_add_lshl_u32", "v_lshl_or_b32", "v_and_or_b32", "v_or3_b32", "v_xad_u32", "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", "s_endpgm", } SPECIAL_WRITE = {"vcc", "vcc_lo", "vcc_hi", "exec", "exec_lo", "exec_hi", "scc", "null"} +def _ffbh_i32(a): + if a in (0, MASK32): + return MASK32 + return 32 - (~a & MASK32).bit_length() if a & SIGN32 else 32 - a.bit_length() + + +_INT_VOP = { + "v_not_b32": (1, lambda a: ~a), + "v_bfrev_b32": (1, lambda a: int(f"{a:032b}"[::-1], 2)), + "v_ffbl_b32": (1, lambda a: MASK32 if a == 0 else (a & -a).bit_length() - 1), + "v_ffbh_u32": (1, lambda a: MASK32 if a == 0 else 32 - a.bit_length()), + "v_ffbh_i32": (1, _ffbh_i32), + "v_xnor_b32": (2, lambda a, b: ~(a ^ b)), + "v_bcnt_u32_b32": (2, lambda a, b: a.bit_count() + b), + "v_add3_u32": (3, lambda a, b, c: a + b + c), + "v_lshl_add_u32": (3, lambda a, b, c: (a << (b & 31)) + c), + "v_add_lshl_u32": (3, lambda a, b, c: ((a + b) & MASK32) << (c & 31)), + "v_lshl_or_b32": (3, lambda a, b, c: (a << (b & 31)) | c), + "v_and_or_b32": (3, lambda a, b, c: (a & b) | c), + "v_or3_b32": (3, lambda a, b, c: a | b | c), + "v_xad_u32": (3, lambda a, b, c: (a ^ b) + c), +} + + class CpuRefError(Exception): """Base class for a program the model cannot execute as written.""" @@ -661,6 +688,12 @@ class Machine: vals = [v - (1 << 32) if v & SIGN32 else v for v in vals] x, y, z = vals self._write_vgpr(args[0], lane, max(min(x, y), min(max(x, y), z)) & MASK32) + elif base in _INT_VOP: + arity, fn = _INT_VOP[base] + self._expect(ins, 1 + arity) + for lane in self._active_lanes(): + vals = [self._int_src(args[i], lane) for i in range(1, 1 + arity)] + self._write_vgpr(args[0], lane, fn(*vals) & MASK32) elif base == "s_mov_b32": self._expect(ins, 2) self._write_scalar_dst(args[0], self._int_src(args[1], 0, scalar=True)) @@ -775,6 +808,9 @@ def main(argv=None): ap.add_argument("--parse-only", action="store_true", help="report parsed and modelled instructions only") ap.add_argument("--json", action="store_true", help="print the result as JSON") args = ap.parse_args(argv) + if not os.path.exists(args.listing): + print(f"ERROR: {args.listing}: does not exist", file=sys.stderr) + return 2 inputs = {"lanes": args.lanes, "vcc": args.vcc} if args.lanes == 1: diff --git a/tools/crosslane_fuzz.py b/tools/crosslane_fuzz.py index fe39baa17..b653c9fba 100644 --- a/tools/crosslane_fuzz.py +++ b/tools/crosslane_fuzz.py @@ -11,6 +11,7 @@ local GPU: llvm-mc assembles it, tools/rdna2spirv.py translates it (wave32 nativ VKC_DUMP, and every word every thread stores is compared. docs/shader_validation.md has the details. python -I tools/crosslane_fuzz.py --programs 200 --seed 1 [--wave 32|64|both] [--modes native,emulate] + python -I tools/crosslane_fuzz.py --ext --wave 64 # more wave64 ops (below); wave32 programs are unchanged python -I tools/crosslane_fuzz.py --self-test # the model against hand-computed values, no GPU python -I tools/crosslane_fuzz.py --oracle hw # model vs the AMD GPU natively (wave32 and wave64); exit 77 # when tools/hw_oracle's tools are missing. --oracle translator,hw @@ -45,6 +46,23 @@ Reference semantics (AMD "RDNA 2" ISA reference guide; Mesa ACO and LLVM where t lane keeps its old vD. That was measured on RDNA2 and RDNA3.5 (docs/shader_validation.md, #374), but the translator models it only with #580, so programs that reach it are still reported apart. * VALU results are written only in active lanes; SALU is wave-uniform. + +--ext adds these to wave64 programs (the model of each was checked against an RDNA2 GPU, gfx1036, with --oracle hw): + * v_add_co / v_sub_co / v_subrev_co_u32 and the _ci forms, carries in SGPR pairs or VCC: the carry-out mask has + the lane's carry (borrow) for an active lane and 0 for an inactive one. + * ds_bpermute_b32: lane l reads vData of lane ((vAddr + offset) >> 2) & 31 of its own 32-lane half; a source + lane that is off in EXEC reads 0. ds_permute_b32: every active lane sends vData to that lane; a lane nobody + sends to gets 0, and with several senders the highest lane wins. ds_swizzle_b32 (QUAD_PERM, BITMASK_PERM, SWAP, + REVERSE, BROADCAST) works inside each group of 32 lanes; an EXEC-off source lane reads 0, which the + translator models only with #2780, so programs that reach it are reported apart like the permlane case. + On hardware the three need `s_waitcnt lgkmcnt(0)` before the result is used; the generator emits it. + * v_readlane / v_writelane with an SGPR lane select of 64 or more (S1[5:0]). + * s_bcnt0/1 and s_ff0/1 of a mask, s_and/or/xor/andn2_b64 of masks, the ten s_*_saveexec_b64 forms and + s_andn1/andn2_wrexec_b64, s_wqm_b64, s_cmp_eq/lg_u64 and s_bitcmp0/1_b64 of masks, each followed by an + s_cselect_b32 so its SCC reaches a stored SGPR; s_cselect_b64 between masks; s_mov_b64 exec, mask; + s_bfm_b64 (D = ((1 << S0[5:0]) - 1) << S1[5:0]) into a mask or EXEC. + * A loop in LLVM's SI_LOOP shape: per-lane trip counts, a break mask, s_andn2_b64 exec and s_cbranch_execnz + back to the head, so lanes of both halves leave on different iterations while the rest keep running. """ import argparse import os @@ -69,6 +87,10 @@ OUT_REGS = [("v", r) for r in DATA_V] + [("s", r) for r in DATA_S] SAVE = (22, 24, 26) # saveexec destinations (pairs in wave64) ENTRY = 30 # entry EXEC (pair in wave64) SEL = 28 # scratch SGPRs for lane selects / permlane selectors (28, 29) +PERM_V = 23 # --ext: scratch VGPR for ds_permute addresses +LOOP_V = (24, 25) # --ext: a loop's per-lane trip limit and counter +LOOP_S = (32, 34) # --ext: a loop's break mask and "done this iteration" mask (pairs) +DS_WAIT = "\n\ts_waitcnt lgkmcnt(0)" # after ds_bpermute / ds_permute / ds_swizzle: the result comes back late PERMLANE_FETCH_INACTIVE = False TRANSLATOR = [os.path.join(HERE, "rdna2spirv.py")] # --translator # --permlane-fetch-inactive: model FI = 1 (read inactive sources) @@ -308,7 +330,7 @@ def dpp_sweep_programs(wave): class Gen: - def __init__(self, rng, wave, group, allow_maskdata=True, wave32_hi_lanes=True, dpp=False): + def __init__(self, rng, wave, group, allow_maskdata=True, wave32_hi_lanes=True, dpp=False, ext=False): self.rng, self.W, self.L = rng, wave, group self.nwaves = (group + wave - 1) // wave last = group - (self.nwaves - 1) * wave @@ -316,6 +338,7 @@ class Gen: self.full = last == wave self.allow_maskdata, self.hi_lanes = allow_maskdata, wave32_hi_lanes self.dpp = dpp + self.ext = ext and wave == 64 # --ext: the wave64 extension ops self.masks = [] # mask registers written so far self.depth = 0 self.in_branch, self.branch_id = False, 0 @@ -703,6 +726,387 @@ class Gen: op.tags = {"branch"} | {t for o in body for t in getattr(o, "tags", {o.tag})} return op + # ---- --ext: more wave64 ops (all return None in a wave32 program) ----------------------------------- + def scc_probe(self): + """(text, fn) of an s_cselect_b32 right after an op, so the op's SCC reaches a stored SGPR.""" + d, a, b = self.r(DATA_S), self.r(DATA_S), self.r(DATA_S) + + def fn(w, scc): + w.s[d] = w.sr(a) if scc else w.sr(b) + return f"\n\ts_cselect_b32 s{d}, s{a}, s{b}", fn + + def ext_mask(self): + """A mask that has been written, or EXEC.""" + return self.r(self.masks + ["exec"]) + + def op_scan64(self): + """s_bcnt1 / s_bcnt0 / s_ff1 / s_ff0 of a 64-bit mask; the counts also show their SCC (result != 0).""" + if self.W != 64: + return None + m, d = self.ext_mask(), self.r(DATA_S) + kind = self.r(("bcnt1", "bcnt0", "ff1", "ff0")) + ptext, pfn = self.scc_probe() + probe = kind.startswith("bcnt") + text = f"s_{kind}_i32_b64 s{d}, {mreg(64, m)}" + (ptext if probe else "") + + def fn(w): + x = w.mask(m) + if kind == "bcnt1": + r = popcount(x) + elif kind == "bcnt0": + r = 64 - popcount(x) + else: + y = x if kind == "ff1" else ~x & M64 + r = ((y & -y).bit_length() - 1) & M32 if y else M32 + w.s[d] = r + if probe: + pfn(w, r != 0) + return Op(text, fn, "scan64") + + def op_mask_scc(self): + """s_and/or/xor/andn2_b64 of two masks into a mask or VCC, and its SCC (result != 0).""" + if self.W != 64 or not self.masks: + return None + a, b = self.r(self.masks), self.r(self.masks) + d = self.r([16, 18, 20, "vcc"]) + kind = self.r(("and", "or", "xor", "andn2")) + ptext, pfn = self.scc_probe() + text = f"s_{kind}_b64 {mreg(64, d)}, {mreg(64, a)}, {mreg(64, b)}" + ptext + if d not in self.masks: + self.masks.append(d) + + def fn(w): + x, y = w.mask(a), w.mask(b) + r = {"and": x & y, "or": x | y, "xor": x ^ y, "andn2": x & ~y}[kind] & M64 + w.set_mask(d, r) + pfn(w, r != 0) + return Op(text, fn, "mask_scc") + + def op_exec_logic(self): + """The saveexec / wrexec family (RDNA2 ISA SOP1): saveexec D = EXEC, EXEC = f(S0, EXEC); wrexec + EXEC = f(S0, EXEC), D = EXEC; SCC = (EXEC != 0). D is one of the mask registers, not the saveexec stack of + op_saveexec. The forms that complement a whole mask stay out of a partial wave: they would turn on lanes + that do not exist.""" + if self.W != 64 or not self.masks: + return None + m, d = self.r(self.masks), self.r([16, 18, 20]) + kinds = ["and", "or", "xor", "andn1", "andn2"] + if self.full: + kinds += ["orn1", "orn2", "nand", "nor", "xnor"] + kind = self.r(kinds) + wr = kind in ("andn1", "andn2") and self.rng.random() < 0.4 + ptext, pfn = self.scc_probe() + text = f"s_{kind}_{'wrexec' if wr else 'saveexec'}_b64 {mreg(64, d)}, {mreg(64, m)}" + ptext + if d not in self.masks: + self.masks.append(d) + + def fn(w): + s, e = w.mask(m), w.exec + r = {"and": s & e, "or": s | e, "xor": s ^ e, "andn1": ~s & e, "andn2": s & ~e, "orn1": ~s | e, + "orn2": s | ~e, "nand": ~(s & e), "nor": ~(s | e), "xnor": ~(s ^ e)}[kind] & M64 + w.exec = r + w.set_mask(d, r if wr else e) + pfn(w, r != 0) + return Op(text, fn, "exec") + + def op_exec_mask(self): + """EXEC = a mask (s_mov_b64), not only the restore of a saved EXEC.""" + if self.W != 64 or not self.masks: + return None + m = self.r(self.masks) + + def fn(w): + w.exec = w.mask(m) + return Op(f"s_mov_b64 exec, {mreg(64, m)}", fn, "exec") + + def op_cselect64(self): + """s_cselect_b64 between two masks on the SCC of a scalar compare.""" + if self.W != 64 or not self.masks: + return None + a, b = self.ext_mask(), self.r(self.masks) + d = self.r([16, 18, 20, "vcc"]) + sa, sb = self.r(DATA_S), self.r(DATA_S) + text = f"s_cmp_lt_u32 s{sa}, s{sb}\n\ts_cselect_b64 {mreg(64, d)}, {mreg(64, a)}, {mreg(64, b)}" + if d not in self.masks: + self.masks.append(d) + + def fn(w): + w.set_mask(d, w.mask(a) if w.sr(sa) < w.sr(sb) else w.mask(b)) + return Op(text, fn, "cselect64") + + def op_mask_test(self): + """s_cmp_eq_u64 / s_cmp_lg_u64 of two masks, or s_bitcmp0/1_b64 of one lane's bit, seen through SCC.""" + if self.W != 64 or not self.masks: + return None + ptext, pfn = self.scc_probe() + if self.rng.random() < 0.5: + a, b = self.ext_mask(), self.ext_mask() + kind = self.r(("eq", "lg")) + text = f"s_cmp_{kind}_u64 {mreg(64, a)}, {mreg(64, b)}" + ptext + + def fn(w): + pfn(w, (w.mask(a) == w.mask(b)) == (kind == "eq")) + else: + m, one, lane = self.ext_mask(), self.rng.randrange(2), self.rng.randrange(64) + text = f"s_bitcmp{one}_b64 {mreg(64, m)}, {lane}" + ptext + + def fn(w): + pfn(w, (w.mask(m) >> lane & 1) == one) + return Op(text, fn, "mask_test") + + def op_bfm(self): + """s_bfm_b64 D, S0, S1: D = ((1 << S0[5:0]) - 1) << S1[5:0], into a mask, VCC or EXEC (full waves only).""" + if self.W != 64 or not self.full: + return None + d = self.r([16, 18, 20, "vcc", "exec"]) + form = self.r(("cc", "sc", "cs", "ss")) + sa, sb = self.r(DATA_S), self.r(DATA_S) + ka, kb = self.rng.randrange(65), self.rng.randrange(65) + text = (f"s_bfm_b64 {mreg(64, d)}, " + (f"s{sa}" if form[0] == "s" else str(ka)) + ", " + + (f"s{sb}" if form[1] == "s" else str(kb))) + if d not in self.masks and d != "exec": + self.masks.append(d) + + def fn(w): + size = (w.sr(sa) if form[0] == "s" else ka) & 63 + off = (w.sr(sb) if form[1] == "s" else kb) & 63 + w.set_mask(d, (((1 << size) - 1) << off) & M64) + return Op(text, fn, "exec" if d == "exec" else "bfm") + + def op_wqm(self): + """s_wqm_b64: every group of four bits with a bit set becomes 1111; SCC = (D != 0). Full waves only.""" + if self.W != 64 or not self.full or not self.masks: + return None + m, d = self.ext_mask(), self.r([16, 18, 20, "vcc"]) + ptext, pfn = self.scc_probe() + text = f"s_wqm_b64 {mreg(64, d)}, {mreg(64, m)}" + ptext + if d not in self.masks: + self.masks.append(d) + + def fn(w): + x, r = w.mask(m), 0 + for q in range(16): + if x >> (4 * q) & 15: + r |= 15 << (4 * q) + w.set_mask(d, r) + pfn(w, r != 0) + return Op(text, fn, "wqm") + + def op_carry(self): + """v_add_co / v_sub_co / v_subrev_co (and the _ci forms) with the carry in and out in SGPR pairs or VCC. + Carry out: bit l for an active lane, 0 for an inactive one; the carry in is read before it is written.""" + if self.W != 64: + return None + d, a, b = self.r(DATA_V), self.vsrc(), self.vsrc() + kind = self.r(("add_co", "sub_co", "subrev_co", "add_co_ci", "sub_co_ci", "subrev_co_ci")) + ci = kind.endswith("_ci") + if ci and not self.masks: + return None + mo = self.mask_name(write=True) + mi = self.r(self.masks) if ci else None + sfx = "e32" if mo == "vcc" and mi == "vcc" and self.rng.random() < 0.5 else "e64" # VOP2 only has VCC + text = f"v_{kind}_u32_{sfx} v{d}, {mreg(64, mo)}, v{a}, v{b}" + (f", {mreg(64, mi)}" if ci else "") + if mo not in self.masks: + self.masks.append(mo) + + def fn(w): + cin = w.mask(mi) if ci else 0 + vals, m = [], 0 + for l in range(w.size): + x, y, c = w.vr(a)[l], w.vr(b)[l], cin >> l & 1 + if kind.startswith("add"): + t = x + y + c + co = t >> 32 + else: + t = (y - x - c) if kind.startswith("subrev") else (x - y - c) + co = int(t < 0) + vals.append(t & M32) + if w.active(l) and co: + m |= 1 << l + w.vwrite(d, vals) + w.set_mask(mo, m) + return Op(text, fn, "carry") + + def op_bpermute(self): + """ds_bpermute_b32 vD, vAddr, vData: lane l reads vData of lane ((vAddr + offset) >> 2) & 31 of its own + 32-lane half; a source lane that is off in EXEC (or missing from a partial wave) reads 0.""" + if self.W != 64: + return None + d, ad, dat = self.r(DATA_V), self.vsrc(), self.vsrc() + off = self.r((0, 0, 4, 60, 128, 252, 65532)) + text = f"ds_bpermute_b32 v{d}, v{ad}, v{dat}" + (f" offset:{off}" if off else "") + DS_WAIT + + def fn(w): + vals = [] + for l in range(w.size): + sl = (l & 32) | (((w.vr(ad)[l] + off) >> 2) & 31) + vals.append(w.vr(dat)[sl] if w.active(sl) else 0) + w.vwrite(d, vals) + return Op(text, fn, "bpermute") + + def op_permute(self): + """ds_permute_b32 vD, vAddr, vData: every lane on in EXEC sends vData to lane ((vAddr + offset) >> 2) & 31 + of its own half; a lane nobody sends to gets 0; several senders: the highest lane wins (measured). Half of + the time the addresses are a permutation (lane * odd + c), else any data VGPR.""" + if self.W != 64: + return None + d, dat = self.r(DATA_V), self.vsrc() + if self.rng.random() < 0.5: + k, c = self.r((1, 3, 5, 7, 9, 11, 13, 15, 17, 31)), self.rng.randrange(64) + ad, off = PERM_V, self.r((0, 0, 4, 124)) + pre = f"v_mad_u32_u24 v{ad}, v1, {k}, {c}\n\tv_lshlrev_b32_e32 v{ad}, 2, v{ad}\n\t" + else: + k = c = None + ad, off, pre = self.vsrc(), 0, "" + text = pre + f"ds_permute_b32 v{d}, v{ad}, v{dat}" + (f" offset:{off}" if off else "") + DS_WAIT + + def fn(w): + if k is not None: + w.vwrite(ad, [((l * k + c) << 2) & M32 for l in range(w.size)]) + vals = [0] * w.size + for l in range(w.size): + if w.active(l): + vals[(l & 32) | (((w.vr(ad)[l] + off) >> 2) & 31)] = w.vr(dat)[l] + w.vwrite(d, vals) + return Op(text, fn, "permute") + + def op_swizzle(self): + """ds_swizzle_b32 vD, vS offset:swizzle(...): QUAD_PERM inside each group of four lanes; the other modes + are source lane = ((lane & and) | or) ^ xor inside each group of 32. A source lane that is off in EXEC + reads 0 (measured; the translator does that with #2780, so a program that reaches it is reported apart).""" + if self.W != 64: + return None + d, v = self.r(DATA_V), self.vsrc() + mode = self.r(("quad", "bits", "bits", "swap", "reverse", "broadcast")) + and_m, or_m, xor_m = 31, 0, 0 + if mode == "quad": + q = [self.rng.randrange(4) for _ in range(4)] + sw = f"swizzle(QUAD_PERM, {', '.join(map(str, q))})" + elif mode == "bits": + chars = [self.r("01pi") for _ in range(5)] + and_m = 0 + for i, ch in enumerate(chars): # bit 4 first: p = keep, i = invert, 0 / 1 = force + bit = 1 << (4 - i) + and_m |= bit if ch in "pi" else 0 + xor_m |= bit if ch == "i" else 0 + or_m |= bit if ch == "1" else 0 + sw = f'swizzle(BITMASK_PERM, "{"".join(chars)}")' + elif mode == "swap": + xor_m = self.r((1, 2, 4, 8, 16)) + sw = f"swizzle(SWAP,{xor_m})" + elif mode == "reverse": + n = self.r((2, 4, 8, 16, 32)) + xor_m = n - 1 + sw = f"swizzle(REVERSE,{n})" + else: + n = self.r((2, 4, 8, 16, 32)) + or_m = self.rng.randrange(n) + and_m = ~(n - 1) & 31 + sw = f"swizzle(BROADCAST,{n},{or_m})" + text = f"ds_swizzle_b32 v{d}, v{v} offset:{sw}" + DS_WAIT + + def fn(w): + vals, hyp = [], False + for l in range(w.size): + sl = (l & ~3) | q[l & 3] if mode == "quad" else (l & ~31) | (((l & 31 & and_m) | or_m) ^ xor_m) + if w.active(sl): + vals.append(w.vr(v)[sl]) + else: + vals.append(0) + hyp |= bool(w.active(l)) + w.vwrite(d, vals) + return hyp + return Op(text, fn, "swizzle") + + def op_lane_wrap(self): + """v_readlane / v_writelane with an SGPR lane select of 64 or more: wave64 uses S1[5:0].""" + if self.W != 64: + return None + lane = self.lane() + enc = lane + 64 * self.rng.randrange(1, 1 << 20) + if self.rng.random() < 0.5: + d, v = self.r(DATA_S), self.vsrc() + text = f"s_mov_b32 s{SEL}, {enc}\n\tv_readlane_b32 s{d}, v{v}, s{SEL}" + + def fn(w): + w.s[SEL] = enc + w.s[d] = w.vr(v)[lane] + else: + d, s = self.r(DATA_V), self.r(DATA_S) + text = f"s_mov_b32 s{SEL}, {enc}\n\tv_writelane_b32 v{d}, s{s}, s{SEL}" + + def fn(w): + w.s[SEL] = enc + if w.exists >> lane & 1: + w.vr(d)[lane] = w.sr(s) + return Op(text, fn, "lane_wrap") + + LOOP_BODY = ("op_readfirstlane", "op_bcnt", "op_mbcnt", "op_valu", "op_valu", "op_readlane", "op_writelane", + "op_cmp", "op_cndmask", "op_bpermute", "op_permute", "op_carry", "op_salu", "op_mask_salu", + "op_scan64", "op_cselect64", "op_mask_test") + + def op_loop(self): + """A loop in the shape LLVM's SI_LOOP gives: every lane has its own trip count (1 to 8), a lane that is + done joins the break mask, s_andn2_b64 takes it out of EXEC and s_cbranch_execnz closes the loop while a + lane is left; EXEC comes back from the break mask after it. The body is one to four ops that do not write + EXEC, then the count of the lanes still running added to a data VGPR, so every iteration shows.""" + if self.W != 64 or self.in_branch: + return None + src, trips = self.vsrc(), self.r((1, 3, 3, 7)) + self.in_branch = True # no branch and no second loop inside + body, n = [], self.rng.randrange(1, 5) + while len(body) < n: + o = getattr(self, self.r(self.LOOP_BODY))() + if o is not None: + body.append(o) + sd, vx = self.r(DATA_S), self.r(DATA_V) + self.in_branch = False + k = self.branch_id + self.branch_id += 1 + lim, it = LOOP_V + brk, done = LOOP_S + lines = [f"v_and_b32_e32 v{lim}, {trips}, v{src}", f"v_mov_b32_e32 v{it}, 0", + f"s_mov_b64 {mreg(64, brk)}, 0", f";@LOOP{k}"] + lines += [o.text for o in body] + lines += [f"s_bcnt1_i32_b64 s{sd}, exec", f"v_add_nc_u32_e32 v{vx}, s{sd}, v{vx}", + f"v_cmp_ge_u32_e64 {mreg(64, done)}, v{it}, v{lim}", f"v_add_nc_u32_e32 v{it}, 1, v{it}", + f"s_or_b64 {mreg(64, brk)}, {mreg(64, done)}, {mreg(64, brk)}", + f"s_andn2_b64 exec, exec, {mreg(64, brk)}", f"s_cbranch_execnz @-{k}", + f"s_or_b64 exec, exec, {mreg(64, brk)}"] + + def fn(w): + hyp = False + w.vwrite(lim, [x & trips for x in w.vr(src)]) + w.vwrite(it, [0] * w.size) + broke = 0 + for _ in range(trips + 2): + for o in body: + hyp |= bool(o.fn(w)) + w.s[sd] = popcount(w.exec) + w.vwrite(vx, [w.sr(sd) + x for x in w.vr(vx)]) + m = 0 + for l in range(w.size): + if w.active(l) and w.vr(it)[l] >= w.vr(lim)[l]: + m |= 1 << l + w.vwrite(it, [x + 1 for x in w.vr(it)]) + broke |= m + w.exec &= ~broke + if not w.exec: + break + else: + raise AssertionError("loop model did not end") + w.set_mask(brk, broke) + w.set_mask(done, m) + w.exec |= broke + return hyp + op = Op("\n\t".join(lines), fn, "loop") + op.tags = {"loop"} | {t for o in body for t in getattr(o, "tags", {o.tag})} + return op + + EXT_WEIGHTS = (("op_scan64", 3), ("op_mask_scc", 3), ("op_exec_logic", 3), ("op_exec_mask", 1), + ("op_cselect64", 2), ("op_mask_test", 3), ("op_bfm", 2), ("op_wqm", 2), ("op_carry", 4), + ("op_bpermute", 3), ("op_permute", 4), ("op_swizzle", 3), ("op_lane_wrap", 2), ("op_loop", 3)) + WEIGHTS = (("op_branch", 3), ("op_cmp", 5), ("op_cmpx", 2), ("op_exec_const", 2), ("op_saveexec", 2), ("op_restore", 2), ("op_readlane", 4), ("op_writelane", 3), ("op_readfirstlane", 3), ("op_bcnt", 3), ("op_mbcnt", 3), ("op_mbcnt_data", 1), ("op_cndmask", 2), ("op_maskdata", 1), ("op_mask_salu", 2), @@ -710,6 +1114,8 @@ class Gen: def program(self, n): table = [kw for kw in self.WEIGHTS if kw[0] != "op_dpp" or self.dpp] # seeds stay stable without --dpp + if self.ext: # and without --ext + table += self.EXT_WEIGHTS names = [k for k, _ in table] weights = [w for _, w in table] ops = [] @@ -795,11 +1201,12 @@ class Program: out = [] for text in self.pro + [o.text for o in ops] + epilogue(self.wave, hw=True): for ln in (x.strip() for x in text.split("\n")): - m = re.fullmatch(r";@END(\d+)", ln) + m = re.fullmatch(r";@(END|LOOP)(\d+)", ln) if m: - out.append(f".L{self.name}_{m.group(1)}:") + out.append(f".L{self.name}_{'B' if m.group(1) == 'LOOP' else ''}{m.group(2)}:") continue - ln = re.sub(r"^(s_cbranch_\w+) @(\d+)$", lambda b: f"{b.group(1)} .L{self.name}_{b.group(2)}", ln) + ln = re.sub(r"^(s_cbranch_\w+) @(-?)(\d+)$", + lambda b: f"{b.group(1)} .L{self.name}_{'B' if b.group(2) else ''}{b.group(3)}", ln) out.append(ln) if guard and ln != "s_endpgm": out.append("s_nop 7") @@ -862,26 +1269,39 @@ def assemble(mc, prog, src, disasm, fssm): os.remove(asm_path) +def branch_offsets(lines, size_at): + """lines with every `s_cbranch_* @k` replaced by the dword offset to its `;@ENDk` line below it, and every + `@-k` (--ext loops) by the negative offset back to its `;@LOOPk` line above it. size_at: line index -> the + instruction's size in dwords. A branch offset counts from the instruction after the branch.""" + out = list(lines) + for i, ln in enumerate(lines): + m = re.search(r"@(-?)(\d+)$", ln.strip()) + if not m: + continue + if m.group(1): + head = next(j for j in range(i - 1, -1, -1) if lines[j].strip() == f";@LOOP{m.group(2)}") + off = -sum(size_at.get(j, 0) for j in range(head + 1, i + 1)) + else: + end = next(j for j in range(i + 1, len(lines)) if lines[j].strip() == f";@END{m.group(2)}") + off = sum(size_at.get(j, 0) for j in range(i + 1, end)) + out[i] = ln[:ln.rindex("@")] + str(off) + return out + + def resolve_branches(cmd, prog, src): - """Replace each `s_cbranch_* @k` with the dword offset to its `;@ENDk` line: assemble once with offset 0, - take each instruction's size from its encoding, and sum the sizes in between.""" + """Replace each `s_cbranch_* @k` with the dword offset to its `;@ENDk` line (and `@-k` with the offset back + to `;@LOOPk`): assemble once with offset 0, take each instruction's size from its encoding, and sum the + sizes in between (branch_offsets).""" lines = src.splitlines() insns = [i for i, ln in enumerate(lines) if ln.strip() and not ln.strip().startswith(";")] - first = "\n".join(re.sub(r"@\d+$", "0", ln) for ln in lines) + "\n" + first = "\n".join(re.sub(r"@-?\d+$", "0", ln) for ln in lines) + "\n" r = mc_command.run(cmd, input=first, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{first}") sizes = [len(re.findall(r"0x[0-9a-f]{2}", m)) // 4 for m in re.findall(r"encoding: \[([^\]]*)\]", r.stdout)] if len(sizes) != len(insns): raise RuntimeError(f"{prog.name}: {len(sizes)} encodings for {len(insns)} instructions") - size_at = dict(zip(insns, sizes)) - for i, ln in enumerate(lines): - m = re.search(r"@(\d+)$", ln.strip()) - if not m: - continue - end = next(j for j in range(i + 1, len(lines)) if lines[j].strip() == f";@END{m.group(1)}") - lines[i] = ln.replace(f"@{m.group(1)}", str(sum(size_at.get(j, 0) for j in range(i + 1, end)))) - return "\n".join(lines) + "\n" + return "\n".join(branch_offsets(lines, dict(zip(insns, sizes)))) + "\n" def translate(work, emulate): @@ -1044,6 +1464,10 @@ def main(): ap.add_argument("--permlane-fetch-inactive", action="store_true", help="model an inactive permlane source as read (FI = 1) instead of the hypothesis") ap.add_argument("--dpp", action="store_true", help="also generate DPP16 / DPP8 ops") + ap.add_argument("--ext", action="store_true", + help="wave64 programs also get carries, ds_bpermute/ds_permute/ds_swizzle, lane selects of 64 " + "and up, b64 mask SALU with SCC probes, the saveexec/wrexec family, s_bfm_b64, s_wqm_b64 " + "and SI_LOOP-shaped loops (wave32 programs and seeds without the flag are unchanged)") ap.add_argument("--dpp-sweep", action="store_true", help="instead of random programs, one program per DPP case: every DPP16 control x bound_ctrl x " "fi x EXEC pattern, all row_mask / bank_mask pairs, and a set of DPP8 selects " @@ -1103,7 +1527,7 @@ def main(): for i in range(0 if args.dpp_sweep else args.programs): wave = waves[i % len(waves)] progs.append(make_program(args.seed * 100003 + i, wave, args.ops, allow_maskdata=not args.no_maskdata, - wave32_hi_lanes=not args.no_w32_hi_lanes, dpp=args.dpp)) + wave32_hi_lanes=not args.no_w32_hi_lanes, dpp=args.dpp, ext=args.ext)) stats = {} fails = [] try: @@ -1214,7 +1638,7 @@ def run_hw(oracle, progs, stats, fails, guard=True): st["match"] += 1 st["hyp_confirmed"] += bool(hyp) for kind in sorted({t for i in hyp for t in getattr(p.ops[i], "tags", {p.ops[i].tag}) - if t in ("permlane", "dpp")}): + if t in ("permlane", "dpp", "swizzle")}): st["hyp_" + kind] = st.get("hyp_" + kind, 0) + 1 else: # On the hardware a failing hypothesis is a falsified claim, and it could hide a model bug elsewhere in diff --git a/tools/cvt_norm_mods_probe.py b/tools/cvt_norm_mods_probe.py new file mode 100644 index 000000000..b8fdeb6c1 --- /dev/null +++ b/tools/cvt_norm_mods_probe.py @@ -0,0 +1,667 @@ +r"""Measure RDNA2 VOP3/SDWA output modifiers on v_cvt_norm_{i16,u16}_f16 and v_cvt_pknorm_{i16,u16}_f32. + +Standard library only. Uses `tools/hw_oracle` to run native RDNA2 ISA kernels on AMD GFX10 hardware: +- `v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16`: exhaustive 65,536-input f16 sweeps across VOP3 `_e64` + (`plain`, `clamp`, `mul:2`, `mul:4`, `div:2`, `clamp mul:2`, `clamp div:2`) in wave32 and wave64, + plus `HW_REG_MODE` (`RTZ`, `IEEE=1`), `_e64` high-half preservation / `abs` / `neg`, and `_sdwa` `clamp` + (`WORD_0`/`WORD_1`, `UNUSED_PRESERVE`/`UNUSED_SEXT`/`UNUSED_PAD`). +- `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32`: 40 edge, NaN, inf, subnormal, out-of-range, and single-rounding + near-tie pairs across `plain` vs VOP3 `clamp`, 6 `HW_REG_MODE` states, source modifiers, and wave32/wave64. + +Usage: + python -I tools/cvt_norm_mods_probe.py [--waves 32,64] [--ops ...] [--hw-arch gfx1036] [--json out.json] + python -I tools/cvt_norm_mods_probe.py --self-test + +Exit codes: + 0 all hardware outputs match the reference model across requested waves (with wave32 == wave64) + 1 at least one word mismatch or wave32/wave64 difference + 2 bad CLI arguments, unwritable --json path, or harness error + 77 hardware oracle unavailable or GPU is not GFX10 +""" +from __future__ import annotations + +import argparse +from fractions import Fraction +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +if HERE not in sys.path: + sys.path.insert(0, HERE) + +M16 = 0xFFFF +M32 = 0xFFFFFFFF + +NORM_F16_OPS = ("v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16") +PKNORM_F32_OPS = ("v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32") +OPS: tuple[str, ...] = NORM_F16_OPS + PKNORM_F32_OPS + +VOP3_NORM_MODS: tuple[str, ...] = ( + "", + "clamp", + "mul:2", + "mul:4", + "div:2", + "clamp mul:2", + "clamp div:2", +) + +NORM_MODE_VARIANTS: tuple[tuple[str, int], ...] = ( + ("rtz16", 0x000000CC), # round16_64=3 (RTZ), denorm16_64=3 + ("ieee1", 0x000002C0), # IEEE=1, denorm16_64=3 +) + +PKNORM_MODES: tuple[tuple[str, int], ...] = ( + ("game", 0x000001C0), # IEEE=0, DX10_CLAMP=1, denorm32=0, denorm16_64=3, RNE + ("ieee0_dx0", 0x000000C0), # IEEE=0, DX10_CLAMP=0, denorm32=0, denorm16_64=3, RNE + ("ieee1_dx0", 0x000002C0), # IEEE=1, DX10_CLAMP=0, denorm32=0, denorm16_64=3, RNE + ("ieee1_dx1", 0x000003C0), # IEEE=1, DX10_CLAMP=1, denorm32=0, denorm16_64=3, RNE + ("rtz", 0x000001CF), # FP_ROUND32=RTZ, FP_ROUND16_64=RTZ, DX10_CLAMP=1 + ("den32_keep", 0x000001F0), # denorm32=3, denorm16_64=3, DX10_CLAMP=1, RNE +) + +# 40 f32 bit patterns: +-0, subnormals, near-ties from pknorm_probe.py, scale steps, +-0.25/0.5/1/2, huge, +-inf, NaNs. +PKNORM_F32_VALUES: tuple[int, ...] = ( + 0x00000000, 0x80000000, # +0, -0 + 0x00000001, 0x80000001, # min subnormal + 0x007FFFFF, 0x807FFFFF, # max subnormal + 0x37800000, 0xB7800000, # +-2^-16 + 0x37800080, 0xB7800080, # just above 0.5 / 32767 + 0x37000040, 0x37000080, # near 0.5 / 65535 + 0x38400180, 0x38E001C0, # pknorm_probe.py near-ties (i16) + 0x39300160, 0x3C004101, + 0x3C014103, 0x3C024105, + 0x37C000C0, 0x386000E0, # pknorm_probe.py near-ties (u16) + 0x38B000B0, 0x3B008081, + 0x3B028083, 0x3B048085, + 0x3E800000, 0xBE800000, # +-0.25 + 0x3F000000, 0xBF000000, # +-0.5 (exact halfway ties) + 0x3F000100, 0xBF000100, # near +-0.5 + 0x3F7FFFFF, 0xBF7FFFFF, # just below +-1.0 + 0x3F800000, 0xBF800000, # +-1.0 + 0x3FC00000, 0xBFC00000, # +-1.5 + 0x40000000, 0xC0000000, # +-2.0 + 0x60000000, 0xE0000000, # huge finite + 0x7F800000, 0xFF800000, # +inf, -inf + 0x7FC00000, 0xFFC00000, # +qNaN, -qNaN + 0x7F800001, 0xFF800001, # +sNaN, -sNaN + 0x7FC01234, 0xFFC01234, # payload qNaN +) + +PKNORM_PAIRS: tuple[tuple[int, int], ...] = tuple( + (PKNORM_F32_VALUES[i], PKNORM_F32_VALUES[(i * 7 + 3) % len(PKNORM_F32_VALUES)]) + for i in range(40) +) + +# SDWA cases for v_cvt_norm_{i16,u16}_f16. Input register v1 = 0x3800B800 (hi=+0.5, lo=-0.5), v0 seeded with 0xCAFE1234. +SDWA_CASES: tuple[tuple[str, int, int, str, str, str], ...] = ( + # (label, seed_v0, src_v1, mod_prefix, src_expr, tail) + ("w1_preserve", 0xCAFE1234, 0x3800B800, "", "v1", "dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1"), + ("w0_preserve", 0xCAFE1234, 0x3800B800, "", "v1", "dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0"), + ("w0_sext", 0xCAFE1234, 0x3800B800, "", "v1", "dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0"), + ("w0_pad", 0xCAFE1234, 0x3800B800, "", "v1", "dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0"), + ("w1_abs", 0xCAFE1234, 0xB8003800, "", "|v1|", "dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1"), + ("w0_neg", 0xCAFE1234, 0x38003800, "", "-v1", "dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0"), +) + + +def _f16_to_frac(h: int) -> Fraction | str: + h &= M16 + sign = (h >> 15) & 1 + exp = (h >> 10) & 0x1F + mant = h & 0x3FF + if exp == 31: + return "nan" if mant else ("-inf" if sign else "+inf") + if exp == 0: + val = Fraction(mant, 1 << 24) + elif exp <= 25: + val = Fraction(1024 + mant, 1 << (25 - exp)) + else: + val = Fraction((1024 + mant) << (exp - 25), 1) + return -val if sign else val + + +def expected_norm_f16(h: int, snorm: bool) -> int: + """Exact rational result for v_cvt_norm_i16_f16 (snorm=True) or v_cvt_norm_u16_f16 (snorm=False).""" + v = _f16_to_frac(h) + if v == "nan": + return 0 + if v == "-inf": + return (-32767) & M16 if snorm else 0 + if v == "+inf": + return 32767 if snorm else 65535 + lo = Fraction(-1, 1) if snorm else Fraction(0, 1) + if v < lo: + v = lo + elif v > 1: + v = Fraction(1, 1) + return round(v * (32767 if snorm else 65535)) & M16 + + +def _f32_to_frac(u: int) -> Fraction | str: + u &= M32 + sign = (u >> 31) & 1 + exp = (u >> 23) & 0xFF + mant = u & 0x7FFFFF + if exp == 255: + return "nan" if mant else ("-inf" if sign else "+inf") + if exp == 0: + val = Fraction(mant, 1 << 149) + elif exp <= 150: + val = Fraction((1 << 23) + mant, 1 << (150 - exp)) + else: + val = Fraction(((1 << 23) + mant) << (exp - 150), 1) + return -val if sign else val + + +def expected_pknorm_f32_lane(u: int, snorm: bool, *, flush_denorm: bool = True) -> int: + """Exact single-rounded 16-bit result for one lane of v_cvt_pknorm_{i16,u16}_f32.""" + u &= M32 + if flush_denorm and ((u >> 23) & 0xFF) == 0: + return 0 + v = _f32_to_frac(u) + if v == "nan": + return 0 + if v == "-inf": + return (-32767) & M16 if snorm else 0 + if v == "+inf": + return 32767 if snorm else 65535 + lo = Fraction(-1, 1) if snorm else Fraction(0, 1) + if v < lo: + v = lo + elif v > 1: + v = Fraction(1, 1) + return round(v * (32767 if snorm else 65535)) & M16 + + +def expected_pknorm_f32(op: str, s0: int, s1: int, *, flush_denorm: bool = True) -> int: + """Expected packed 32-bit dword for v_cvt_pknorm_i16_f32 or v_cvt_pknorm_u16_f32.""" + if op not in PKNORM_F32_OPS: + raise ValueError(f"unknown pknorm op: {op}") + snorm = op == "v_cvt_pknorm_i16_f32" + lo = expected_pknorm_f32_lane(s0, snorm, flush_denorm=flush_denorm) + hi = expected_pknorm_f32_lane(s1, snorm, flush_denorm=flush_denorm) + return lo | (hi << 16) + + +def _apply_f16_src_mod(h: int, src_expr: str) -> int: + h &= M16 + if "|" in src_expr: + h &= 0x7FFF + if src_expr.startswith("-"): + h ^= 0x8000 + return h + + +def expected_sdwa_words(op: str) -> list[int]: + """Expected 32-bit words for SDWA_CASES on op (plain or clamp).""" + snorm = op == "v_cvt_norm_i16_f16" + out: list[int] = [] + for _, seed_v0, src_v1, _, src_expr, tail in SDWA_CASES: + src_hi = "src0_sel:WORD_1" in tail + h = (src_v1 >> 16) & M16 if src_hi else (src_v1 & M16) + h = _apply_f16_src_mod(h, src_expr) + val16 = expected_norm_f16(h, snorm) + if "dst_sel:WORD_1" in tail: + word = (val16 << 16) | (seed_v0 & M16) + elif "UNUSED_PRESERVE" in tail: + word = (seed_v0 & 0xFFFF0000) | val16 + elif "UNUSED_SEXT" in tail: + word = (0xFFFF0000 | val16) if (val16 & 0x8000) else val16 + else: + word = val16 + out.append(word & M32) + return out + + +def expected_sweep_words(op: str) -> list[int]: + """All 32,768 packed dwords (65,536 f16 inputs) for v_cvt_norm_{i16,u16}_f16.""" + snorm = op == "v_cvt_norm_i16_f16" + return [ + expected_norm_f16(2 * wi, snorm) | (expected_norm_f16(2 * wi + 1, snorm) << 16) + for wi in range(32768) + ] + + +def sweep_kernel_lines(op: str, mod_str: str, base_word: int, label: str, mode_val: int | None = None) -> list[str]: + """GFX10 kernel evaluating 32,768 sequential f16 inputs as 16,384 packed dwords.""" + mod_suf = (" " + mod_str) if mod_str else "" + lines: list[str] = [] + if mode_val is not None: + lines.append(f"s_setreg_imm32_b32 hwreg(HW_REG_MODE), {mode_val:#010x}") + lines += [ + "v_mov_b32_e32 v2, 0", + "v_mov_b32_e32 v3, 0", + "v_lshlrev_b32_e32 v10, 4, v0", + f"v_add_nc_u32_e32 v11, {base_word}, v10", + "v_lshlrev_b32_e32 v12, 1, v11", + "v_lshlrev_b32_e32 v13, 2, v10", + "s_mov_b32 s4, 16", + f"{label}:", + f"{op}_e64 v2, v12{mod_suf}", + "v_add_nc_u32_e32 v14, 1, v12", + f"{op}_e64 v3, v14{mod_suf}", + "v_lshl_or_b32 v4, v3, 16, v2", + "global_store_dword v13, v4, s[2:3]", + "v_add_nc_u32_e32 v12, 2, v12", + "v_add_nc_u32_e32 v13, 4, v13", + "s_sub_u32 s4, s4, 1", + "s_cmp_lg_u32 s4, 0", + f"s_cbranch_scc1 {label}", + "s_waitcnt vmcnt(0)", + "s_endpgm", + ] + return lines + + +def sdwa_kernel_lines(op: str, clamp: bool) -> list[str]: + """GFX10 kernel testing SDWA plain vs clamp, dst_unused forms, and VOP3 preservation.""" + c_mod = " clamp" if clamp else "" + lines: list[str] = [] + for idx, (_, seed_v0, src_v1, _, src_expr, tail) in enumerate(SDWA_CASES): + lines += [ + f"v_mov_b32_e32 v0, {seed_v0:#010x}", + f"v_mov_b32_e32 v1, {src_v1:#010x}", + f"{op}_sdwa v0, {src_expr}{c_mod} {tail}", + f"v_mov_b32_e32 v12, {idx * 4}", + "global_store_dword v12, v0, s[2:3]", + ] + # Also verify VOP3 _e64 preserves the high half of v0 under clamp and omod. + vop3_mods = ("clamp", "mul:2", "mul:4", "div:2") if clamp else ("",) + base_idx = len(SDWA_CASES) + for k, mod in enumerate(vop3_mods): + suf = (" " + mod) if mod else "" + lines += [ + "v_mov_b32_e32 v0, 0xCAFE1234", + "v_mov_b32_e32 v1, 0xB8003800", # lo=+0.5, hi=-0.5 + f"{op}_e64 v0, -|v1|{suf}", + f"v_mov_b32_e32 v12, {(base_idx + k) * 4}", + "global_store_dword v12, v0, s[2:3]", + ] + lines += ["s_waitcnt vmcnt(0)", "s_endpgm"] + return lines + + +def expected_sdwa_and_pres_words(op: str, clamp: bool) -> list[int]: + words = expected_sdwa_words(op) + snorm = op == "v_cvt_norm_i16_f16" + # -|0x3800| = -0.5 -> 0xB800 + val16 = expected_norm_f16(0xB800, snorm) + pres_word = 0xCAFE0000 | val16 + count = 4 if clamp else 1 + return words + [pres_word] * count + + +def pknorm_kernel_lines(op: str, clamp: bool, mode_val: int) -> list[str]: + """GFX10 kernel running PKNORM_PAIRS + source modifier checks under one HW_REG_MODE.""" + suf = " clamp" if clamp else "" + lines: list[str] = [f"s_setreg_imm32_b32 hwreg(HW_REG_MODE), {mode_val:#010x}"] + for idx, (a, b) in enumerate(PKNORM_PAIRS): + lines += [ + f"v_mov_b32_e32 v1, {a:#010x}", + f"v_mov_b32_e32 v2, {b:#010x}", + f"{op} v0, v1, v2{suf}", + f"v_mov_b32_e32 v12, {idx * 4}", + "global_store_dword v12, v0, s[2:3]", + ] + # Also check VOP3 source modifiers (-v1, |v2|, -|v1|) with clamp. + mod_cases = ( + (0x3F000000, 0xBF000000, "-v1, |v2|"), + (0xBF000000, 0x3F000000, "|v1|, -v2"), + (0x3F800000, 0x3F000000, "-|v1|, -|v2|"), + ) + base_idx = len(PKNORM_PAIRS) + for k, (a, b, expr) in enumerate(mod_cases): + lines += [ + f"v_mov_b32_e32 v1, {a:#010x}", + f"v_mov_b32_e32 v2, {b:#010x}", + f"{op} v0, {expr}{suf}", + f"v_mov_b32_e32 v12, {(base_idx + k) * 4}", + "global_store_dword v12, v0, s[2:3]", + ] + lines += ["s_waitcnt vmcnt(0)", "s_endpgm"] + return lines + + +def expected_pknorm_words(op: str) -> list[int]: + words = [expected_pknorm_f32(op, a, b) for a, b in PKNORM_PAIRS] + # (-0.5, |-0.5|), (|-0.5|, -0.5), (-|1.0|, -|0.5|) + mod_inputs = ( + (0xBF000000, 0x3F000000), + (0x3F000000, 0xBF000000), + (0xBF800000, 0xBF000000), + ) + words.extend(expected_pknorm_f32(op, a, b) for a, b in mod_inputs) + return words + + +def build_jobs(ops: list[str], waves: list[int]): + """Build (kernels, metadata) pairs for oracle.run().""" + from hw_oracle import asm + + kernels = [] + meta = [] + label_id = 0 + + for op in ops: + if op in NORM_F16_OPS: + exp_full = expected_sweep_words(op) + for wave in waves: + for mod_str in VOP3_NORM_MODS: + mod_key = mod_str or "plain" + for part, base_word in enumerate((0, 16384)): + lbl = f".L_cvt_loop_{label_id}" + label_id += 1 + lines = sweep_kernel_lines(op, mod_str, base_word, lbl) + kernels.append(asm.Kernel(lines, wave=wave, threads=1024, words=16384, raw=True)) + exp_slice = exp_full[base_word : base_word + 16384] + meta.append(("sweep", op, wave, f"{mod_key}_p{part}", bool(mod_str), exp_slice)) + for clamp in (False, True): + lines = sdwa_kernel_lines(op, clamp) + exp = expected_sdwa_and_pres_words(op, clamp) + kernels.append(asm.Kernel(lines, wave=wave, threads=1, words=len(exp), raw=True)) + meta.append(("sdwa", op, wave, "clamp" if clamp else "plain", clamp, exp)) + # MODE tests (RTZ and IEEE=1) on the first requested wave. + mode_wave = waves[0] + for mode_name, mode_val in NORM_MODE_VARIANTS: + for part, base_word in enumerate((0, 16384)): + lbl = f".L_cvt_loop_{label_id}" + label_id += 1 + lines = sweep_kernel_lines(op, "", base_word, lbl, mode_val=mode_val) + kernels.append(asm.Kernel(lines, wave=mode_wave, threads=1024, words=16384, raw=True)) + exp_slice = exp_full[base_word : base_word + 16384] + meta.append(("mode", op, mode_wave, f"{mode_name}_p{part}", False, exp_slice)) + elif op in PKNORM_F32_OPS: + exp_pk = expected_pknorm_words(op) + for wave in waves: + for mode_name, mode_val in PKNORM_MODES: + for clamp in (False, True): + lines = pknorm_kernel_lines(op, clamp, mode_val) + kernels.append(asm.Kernel(lines, wave=wave, threads=1, words=len(exp_pk), raw=True)) + meta.append(("pknorm", op, wave, mode_name, clamp, exp_pk)) + else: + raise ValueError(f"unknown op: {op}") + + return kernels, meta + + +def evaluate_results(waves: list[int], meta, raw_results) -> dict: + """Compare hardware outputs against expected words and check wave32 == wave64.""" + by_key: dict[tuple[str, str, int, str, bool], list[int]] = {} + harness_errors: list[dict] = [] + total_words = 0 + + for (kind, op, wave, variant, clamp, expected), res in zip(meta, raw_results): + total_words += len(expected) + if isinstance(res, str): + harness_errors.append({"kind": kind, "op": op, "wave": wave, "variant": variant, "error": res}) + continue + if len(res) != len(expected): + harness_errors.append({ + "kind": kind, + "op": op, + "wave": wave, + "variant": variant, + "error": f"expected {len(expected)} words, got {len(res)}", + }) + continue + by_key[(kind, op, wave, variant, clamp)] = [w & M32 for w in res] + + if harness_errors: + return { + "total_words": total_words, + "mismatches": 0, + "wave_diffs": 0, + "harness_errors": harness_errors, + "mismatch_details": [], + "wave_diff_details": [], + } + + mismatches = 0 + mismatch_details: list[dict] = [] + for (kind, op, wave, variant, clamp, expected), res in zip(meta, raw_results): + words = [w & M32 for w in res] + for idx, (got_w, exp_w) in enumerate(zip(words, expected)): + if got_w != exp_w: + mismatches += 1 + if len(mismatch_details) < 32: + mismatch_details.append({ + "kind": kind, + "op": op, + "wave": wave, + "variant": variant, + "clamp": clamp, + "word_idx": idx, + "expected": f"0x{exp_w:08x}", + "actual": f"0x{got_w:08x}", + }) + + wave_diffs = 0 + wave_diff_details: list[dict] = [] + if 32 in waves and 64 in waves: + seen_pairs: set[tuple[str, str, str, bool]] = set() + for kind, op, wave, variant, clamp, _ in meta: + if kind == "mode": + continue + pkey = (kind, op, variant, clamp) + if pkey in seen_pairs: + continue + seen_pairs.add(pkey) + k32 = (kind, op, 32, variant, clamp) + k64 = (kind, op, 64, variant, clamp) + if k32 not in by_key or k64 not in by_key: + continue + for idx, (w32, w64) in enumerate(zip(by_key[k32], by_key[k64])): + if w32 != w64: + wave_diffs += 1 + if len(wave_diff_details) < 32: + wave_diff_details.append({ + "kind": kind, + "op": op, + "variant": variant, + "clamp": clamp, + "word_idx": idx, + "wave32": f"0x{w32:08x}", + "wave64": f"0x{w64:08x}", + }) + + return { + "total_words": total_words, + "mismatches": mismatches, + "wave_diffs": wave_diffs, + "harness_errors": [], + "mismatch_details": mismatch_details, + "wave_diff_details": wave_diff_details, + } + + +def self_test() -> int: + """Verify reference model, kernel construction, and evaluation logic without a GPU.""" + # 1. Exact v_cvt_norm_{i16,u16}_f16 edges & single-rounding ties near +-0.5. + assert expected_norm_f16(0x0000, True) == 0 + assert expected_norm_f16(0x8000, True) == 0 + assert expected_norm_f16(0x3C00, True) == 0x7FFF + assert expected_norm_f16(0xBC00, True) == 0x8001 + assert expected_norm_f16(0xFC00, True) == 0x8001 + assert expected_norm_f16(0x7E00, True) == 0 + assert expected_norm_f16(0x7C01, False) == 0 + assert expected_norm_f16(0x3800, True) == 16384 # 0.5 * 32767 = 16383.5 -> 16384 (even) + assert expected_norm_f16(0x3801, True) == 16399 # single rounding near +0.5 (double-rounding gives 16400) + assert expected_norm_f16(0x37FF, True) == 16376 # single rounding near +0.5 (double-rounding gives 16375) + assert expected_norm_f16(0x3800, False) == 32768 # 0.5 * 65535 = 32767.5 -> 32768 (even) + assert expected_norm_f16(0x3801, False) == 32799 + assert expected_norm_f16(0x37FF, False) == 32752 + + # 2. Exact v_cvt_pknorm_{i16,u16}_f32 near-ties & saturation. + assert expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x38400180, 0x00000000) == 0x00000001 + assert expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x3C004101, 0xBF800000) == 0x80010101 + assert expected_pknorm_f32("v_cvt_pknorm_u16_f32", 0x37C000C0, 0x40000000) == 0xFFFF0001 + assert expected_pknorm_f32("v_cvt_pknorm_u16_f32", 0x7FC00000, 0xFF800000) == 0x00000000 + + # 3. Exhaustive sweep builders produce 32,768 packed dwords, valid labels, and proper endpgm. + for op in NORM_F16_OPS: + assert len(expected_sweep_words(op)) == 32768 + l0 = sweep_kernel_lines(op, "clamp mul:2", 0, ".L_test_0") + l1 = sdwa_kernel_lines(op, True) + assert l0[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] + assert l1[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] + assert len(expected_sdwa_and_pres_words(op, True)) == len(SDWA_CASES) + 4 + for op in PKNORM_F32_OPS: + lp = pknorm_kernel_lines(op, True, 0x000001C0) + assert lp[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] + assert len(expected_pknorm_words(op)) == len(PKNORM_PAIRS) + 3 + + # 4. Synthetic evaluation checks pass, mismatch, and wave diff detection. + meta = [ + ("sdwa", "v_cvt_norm_i16_f16", 32, "clamp", True, expected_sdwa_and_pres_words("v_cvt_norm_i16_f16", True)), + ("sdwa", "v_cvt_norm_i16_f16", 64, "clamp", True, expected_sdwa_and_pres_words("v_cvt_norm_i16_f16", True)), + ("pknorm", "v_cvt_pknorm_u16_f32", 32, "game", True, expected_pknorm_words("v_cvt_pknorm_u16_f32")), + ("pknorm", "v_cvt_pknorm_u16_f32", 64, "game", True, expected_pknorm_words("v_cvt_pknorm_u16_f32")), + ] + raw_ok = [list(m[5]) for m in meta] + rep_ok = evaluate_results([32, 64], meta, raw_ok) + assert rep_ok["mismatches"] == 0 and rep_ok["wave_diffs"] == 0 and not rep_ok["harness_errors"], rep_ok + + raw_bad = [list(w) for w in raw_ok] + raw_bad[0][0] ^= 1 + rep_bad = evaluate_results([32, 64], meta, raw_bad) + assert rep_bad["mismatches"] == 1 and rep_bad["wave_diffs"] == 1, rep_bad + + print( + f"self-test ok ({len(OPS)} ops, {len(VOP3_NORM_MODS)} VOP3 norm mods, " + f"{len(SDWA_CASES)} SDWA cases, {len(PKNORM_PAIRS)} pknorm pairs)" + ) + return 0 + + +def _parse_waves(spec: str) -> list[int] | None: + parts = [p.strip() for p in spec.split(",")] + if not parts or any(not p for p in parts): + return None + try: + waves = [int(p) for p in parts] + except ValueError: + return None + if any(w not in (32, 64) for w in waves): + return None + return list(dict.fromkeys(waves)) + + +def _parse_ops(spec: str) -> list[str] | None: + parts = [p.strip() for p in spec.split(",")] + if not parts or any(not p for p in parts): + return None + if any(p not in OPS for p in parts): + return None + return list(dict.fromkeys(parts)) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--waves", default="32,64", help="comma-separated wave sizes (default: 32,64)") + ap.add_argument("--ops", default=",".join(OPS), help="comma-separated conversion opcodes to probe") + ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle") + ap.add_argument("--json", dest="json_out", default=None, help="write JSON report to this path") + ap.add_argument("--self-test", action="store_true", help="verify reference model and kernel generator without GPU") + args = ap.parse_args(argv) + + if args.self_test: + return self_test() + + waves = _parse_waves(args.waves) + if waves is None: + print(f"ERROR: --waves must list 32 and/or 64, got {args.waves!r}", file=sys.stderr) + return 2 + + ops = _parse_ops(args.ops) + if ops is None: + print(f"ERROR: unknown or malformed --ops {args.ops!r} (valid: {', '.join(OPS)})", file=sys.stderr) + return 2 + + if args.json_out is not None: + out_check = os.path.abspath(args.json_out) + if os.path.isdir(out_check): + print(f"ERROR: --json path is a directory: {out_check}", file=sys.stderr) + return 2 + + from hw_oracle import asm, runner + + try: + oracle = runner.open_oracle(arch=args.hw_arch) + except runner.Unavailable as e: + print(f"hardware oracle unavailable: {e}") + return 77 + + try: + try: + fam = asm.family(oracle.arch) + except ValueError: + fam = None + if fam != "gfx10": + print(f"skipping: requires GFX10 RDNA2 hardware, found {oracle.arch}") + return 77 + + kernels, meta = build_jobs(ops, waves) + raw_results = oracle.run(kernels, words=16384) + summary = evaluate_results(waves, meta, raw_results) + device = oracle.device + arch = oracle.arch + finally: + oracle.close() + + total_words = summary["total_words"] + print(f"cvt_norm_mods_probe on {device} ({arch}):") + if summary["harness_errors"]: + for err in summary["harness_errors"][:8]: + print(f" harness error ({err['kind']} wave{err['wave']} {err['op']} {err['variant']}): {err['error']}") + return 2 + + print( + f" {total_words} word evaluations across {len(waves)} wave(s) x {len(ops)} op(s): " + f"mismatches={summary['mismatches']}, wave_diffs={summary['wave_diffs']}" + ) + for d in summary["mismatch_details"]: + print( + f" MISMATCH {d['kind']} wave{d['wave']} {d['op']} {d['variant']} clamp={d['clamp']} " + f"w[{d['word_idx']}]: expected={d['expected']} actual={d['actual']}" + ) + for d in summary["wave_diff_details"]: + print( + f" WAVE DIFF {d['kind']} {d['op']} {d['variant']} clamp={d['clamp']} " + f"w[{d['word_idx']}]: wave32={d['wave32']} wave64={d['wave64']}" + ) + + if args.json_out is not None: + out_path = os.path.abspath(args.json_out) + if os.path.isdir(out_path): + print(f"ERROR: cannot write {out_path}: path is a directory", file=sys.stderr) + return 2 + payload = { + "device": device, + "arch": arch, + "waves": waves, + "ops": ops, + **summary, + } + try: + parent = os.path.dirname(out_path) + if parent: + os.makedirs(parent, exist_ok=True) + with open(out_path, "w", encoding="utf-8", newline="\n") as f: + json.dump(payload, f, indent=2) + f.write("\n") + except OSError as e: + print(f"ERROR: cannot write {out_path}: {e}", file=sys.stderr) + return 2 + + return 1 if (summary["mismatches"] or summary["wave_diffs"]) else 0 + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/d16_format_probe.py b/tools/d16_format_probe.py index ede26e85c..d19754e03 100644 --- a/tools/d16_format_probe.py +++ b/tools/d16_format_probe.py @@ -71,20 +71,22 @@ RULES32 = ("f32_rte", "f32_rtz", "mul_f32") def round_frac(x, prec, emin, rtz=False): """x rounded to a binary float with prec significand bits (implicit bit included) and minimum normal exponent - emin, denormals kept; nearest even, or toward zero. No overflow: every value here is in [-1, 1].""" - if x == 0: + emin, denormals kept; nearest even, or toward zero. No overflow: every value here is in [-1, 1]. + Exact, in integers: x = p/q, 2^e <= p/q < 2^(e+1), ulp = 2^k; the significand is p/q / 2^k rounded. Building + Fractions for 2^e and the quotient instead gave the same bits about 4x slower (minutes for a 16-bit sweep).""" + p, q = x.numerator, x.denominator + if p == 0: return Fraction(0) - sign = -1 if x < 0 else 1 - a = abs(x) - e = a.numerator.bit_length() - a.denominator.bit_length() - if Fraction(2) ** e > a: + sign, p = (-1, -p) if p < 0 else (1, p) + e = p.bit_length() - q.bit_length() # floor(log2(p/q)) is e or e - 1 + if (p << -e if e < 0 else p) < (q << e if e > 0 else q): e -= 1 - if Fraction(2) ** (e + 1) <= a: - e += 1 - ulp = Fraction(2) ** (max(e, emin) - prec + 1) - q = a / ulp - n = q.numerator // q.denominator if rtz else round(q) # round() of a Fraction is half to even - return sign * n * ulp + k = max(e, emin) - prec + 1 + num, den = (p, q << k) if k >= 0 else (p << -k, q) + n, r = divmod(num, den) + if not rtz and (2 * r > den or (2 * r == den and n & 1)): # half to even + n += 1 + return Fraction(sign * n << k) if k >= 0 else Fraction(sign * n, 1 << -k) def f16_bits(v): diff --git a/tools/d3d12_xs_surface.py b/tools/d3d12_xs_surface.py index 5e2e6330f..cac8b4bf9 100644 --- a/tools/d3d12_xs_surface.py +++ b/tools/d3d12_xs_surface.py @@ -10,7 +10,8 @@ Checks that always run: * 116 slots, ordinals 1..116 exactly once, 23 functions + 93 GUID data; * every standard GUID in the table is byte-identical to the Windows SDK, when the SDK is found; * GUIDs are valid RFC 4122 version 4, unique, and the 10 console GUIDs are not in the SDK set; - * the 88 IID ordinals 28..115 are alphabetical, except IID_ID3D12ConsDmaCommandList pinned at 100. + * the 88 IID ordinals 28..115 are alphabetical, except IID_ID3D12ConsDmaCommandList pinned at 100; + * the four unresolved console command-list IIDs are not assigned values or ordinals in the local tables. Optional checks: * ``--scarab PATH`` cross-checks the table against a SCARAB checkout (values, ordinals, catalogue). @@ -262,6 +263,16 @@ CONSOLE_IIDS = { "IID_IGraphicsUnknown": (0xACEEEA63, 0xE0A9, 0x4A1C, 0xBB, 0xEC, 0x71, 0xB2, 0xF4, 0x85, 0xF7, 0x58), } +# The four console command-list interfaces whose IIDs SCARAB reports as not exported and not +# recovered (doc section 4). The local tables must not assign a value; a title trace is one +# possible future source. They must stay out of DATA_EXPORTS and CONSOLE_IIDS. +UNRECOVERED_CONSOLE_IIDS = ( + "ID3D12ConsComputeCommandList", + "ID3D12ConsComputeCommandList6", + "ID3D12ConsComputeCommandList8", + "ID3D12ConsCopyCommandList6", +) + # The 11 catalogue rows labelled "method" that are not interface methods (doc section 5). CATALOGUE_NON_METHODS = { "UINT_MAX", @@ -365,6 +376,20 @@ def check_guid_values(): return errors +def check_unrecovered_console_iids(): + """The four unresolved command-list IIDs are absent from the local export table and CONSOLE_IIDS; the + vendor-runtime observation is SCARAB's.""" + errors = [] + export_names = {name for _n, name, _kind, _ev in DATA_EXPORTS} + for interface in UNRECOVERED_CONSOLE_IIDS: + for name in (interface, "IID_" + interface): + if name in export_names: + errors.append("%s must not be assigned to the 93-GUID export table" % name) + if name in CONSOLE_IIDS: + errors.append("%s must not be assigned a local GUID value" % name) + return errors + + def check_iid_order(): """The 88 IID names at 28..115 are alphabetical, except the DMA IID pinned at 100.""" errors = [] @@ -566,6 +591,7 @@ def main(argv=None): errors += check_data_classes() errors += check_guid_values() errors += check_iid_order() + errors += check_unrecovered_console_iids() sdk_checked = 0 if args.sdk or args.require_sdk: @@ -589,8 +615,9 @@ def main(argv=None): print("FAIL: " + e) return 1 if args.check or args.sdk or args.scarab: - print("PASS: 116 slots (23 functions + 93 GUID data), %d standard + %d console GUIDs" - % (len(STANDARD_GUIDS), len(CONSOLE_IIDS))) + print("PASS: 116 slots (23 functions + 93 GUID data), %d standard + %d console GUIDs, " + "%d command-list IIDs not exported" + % (len(STANDARD_GUIDS), len(CONSOLE_IIDS), len(UNRECOVERED_CONSOLE_IIDS))) return 0 diff --git a/tools/dds_png.py b/tools/dds_png.py index 9e08e7647..376233a3b 100644 --- a/tools/dds_png.py +++ b/tools/dds_png.py @@ -1,8 +1,9 @@ """Pure standard-library DDS to PNG decoder and 2x box-filter downscaler. Supports legacy and DX10 DDS headers across uncompressed 32-bit formats -(BGRA8, RGBA8, BGRX8, RGBX8, R10G10B10A2_UNORM, and arbitrary 32-bit RGB/RGBA bitmasks) and -block-compressed formats (BC1, BC2, BC3, BC4, BC5, BC7). +(BGRA8, RGBA8, BGRX8, RGBX8, R10G10B10A2_UNORM, and arbitrary 32-bit RGB/RGBA bitmasks), the +legacy 24-bit RGB layouts (BGR8/RGB8, e.g. the D3DFMT_R8G8B8 byte order), +and block-compressed formats (BC1, BC2, BC3, BC4, BC5, BC7). BC7 covers all eight modes. DXGI 97/98/99 (typeless, UNORM, UNORM_SRGB) emit the stored RGBA8 values with no sRGB transfer, and the reserved mode (no mode @@ -103,6 +104,13 @@ _CANONICAL_MASKS: dict[tuple[int, int, int, int], str] = { (0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000): "RGBX8", } +# Legacy 24-bit RGB layouts: channel letters in stored byte order (D3DFMT_R8G8B8 +# stores B, G, R; alpha is absent, so decoded pixels are opaque). +_RGB24_LAYOUTS: dict[tuple[int, int, int, int], str] = { + (0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000): "BGR8", + (0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000): "RGB8", +} + _R5_TO_8 = tuple((i << 3) | (i >> 2) for i in range(32)) _G6_TO_8 = tuple((i << 2) | (i >> 4) for i in range(64)) @@ -228,8 +236,10 @@ def _parse_header_internal( if fmt is None: raise DdsError(f"Unsupported DDS FourCC: {fourcc!r}") elif pf_flags & DDPF_RGB: - if rgb_bit_count != 32: - raise DdsError(f"Unsupported uncompressed RGB bit count: {rgb_bit_count} (only 32-bit supported)") + if rgb_bit_count not in (24, 32): + raise DdsError( + f"Unsupported uncompressed RGB bit count: {rgb_bit_count} (only 24- and 32-bit supported)" + ) if not (pf_flags & DDPF_ALPHAPIXELS): a_mask = 0 if (r_mask | g_mask | b_mask) == 0: @@ -237,9 +247,17 @@ def _parse_header_internal( for m in (r_mask, g_mask, b_mask, a_mask): _validate_mask(m) masks = (r_mask, g_mask, b_mask, a_mask) - fmt = _CANONICAL_MASKS.get(masks) - if fmt is None: - fmt = "RGBA8" if a_mask != 0 else "RGBX8" + if rgb_bit_count == 24: + fmt = _RGB24_LAYOUTS.get(masks) + if fmt is None: + raise DdsError( + "Unsupported 24-bit RGB bitmask layout: " + f"0x{r_mask:08X}/0x{g_mask:08X}/0x{b_mask:08X}" + ) + else: + fmt = _CANONICAL_MASKS.get(masks) + if fmt is None: + fmt = "RGBA8" if a_mask != 0 else "RGBX8" else: raise DdsError(f"Unsupported DDS pixel format flags: 0x{pf_flags:08X}") @@ -340,6 +358,41 @@ def _decode_uncompressed_32( return bytes(out) +def _decode_uncompressed_24( + payload: memoryview, + width: int, + height: int, + fmt: str, + masks: tuple[int, int, int, int], + pitch: int, +) -> bytes: + """Decode a legacy 24-bit RGB payload (one byte per channel, no alpha) to RGBA8.""" + pixel_count = width * height + row_bytes = width * 3 + pitch = pitch or row_bytes + if pitch < row_bytes: + raise DdsError(f"Invalid {fmt} row pitch: {pitch} bytes (need at least {row_bytes})") + expected = (height - 1) * pitch + row_bytes + if len(payload) < expected: + raise DdsError(f"Truncated {fmt} payload: {len(payload)} bytes (need {expected})") + + if pitch == row_bytes: + src = bytes(payload[:expected]) + else: + src = b"".join(payload[start : start + row_bytes] for start in range(0, height * pitch, pitch)) + + # The header validation pinned each mask to a byte-aligned 8-bit lane. + r_byte = _validate_mask(masks[0])[0] >> 3 + g_byte = _validate_mask(masks[1])[0] >> 3 + b_byte = _validate_mask(masks[2])[0] >> 3 + out = bytearray(pixel_count * 4) + out[0::4] = src[r_byte::3] + out[1::4] = src[g_byte::3] + out[2::4] = src[b_byte::3] + out[3::4] = b"\xff" * pixel_count + return bytes(out) + + def _bc_interp_lut(v0: int, v1: int) -> tuple[int, int, int, int, int, int, int, int]: """Build the 8-entry BC3-alpha / BC4 / BC5 unsigned interpolation table.""" if v0 > v1: @@ -979,6 +1032,11 @@ def decode_dds(data: bytes) -> tuple[int, int, bytes]: flags = struct.unpack_from(" (sources, kind, model) ---- -# kinds: "f" float source (takes neg/abs), "u" integer source, "k" literal float constant (fmaak/madak). +# kinds: "f" float source (takes neg/abs), "u" integer source, "k" literal float constant (fmaak/fmamk/madak/madmk). def _op(srcs, fn, mods=True, sel="any", hw_only=False): return {"srcs": srcs, "fn": fn, "mods": mods, "sel": sel, "hw_only": hw_only} @@ -1661,6 +1661,10 @@ def main(argv=None): ap.add_argument("--fma", choices=("glsl", "khr"), default="glsl", help="with the translator oracle: emit the fused multiply-adds as GLSL Fma (default) or OpFmaKHR") ap.add_argument("--keep", help="write the kernel body of every hardware mismatch to this folder") + if argv is None: + argv = sys.argv[1:] + if not argv: + ap.error("no arguments given; pass --help for the available options") a = ap.parse_args(argv) rdna2spirv.FMA_KHR = a.fma == "khr" if a.programs < 1: diff --git a/tools/first_light.py b/tools/first_light.py index 4fca31e0d..c0e51cf85 100644 --- a/tools/first_light.py +++ b/tools/first_light.py @@ -32,6 +32,7 @@ from __future__ import annotations import argparse import hashlib import json +import math import os import shutil import struct @@ -60,6 +61,51 @@ def run(argv, **kwargs): subprocess.run(cmd, check=True, **kwargs) +def reset_run_folders(work: str) -> str: + """Remove /first_light/dxbc and spirv as an earlier run left them; return a new, empty dxbc. + + The unpacker, the disassembler and the translator each take every file in the folder they are given, and the + translator merges into an index.json it finds, so a container staged by an earlier run would be translated + again beside this run's pair. Both folders hold only copies from /shaders and files derived from them, + so they are removed whole; first_light/out, another --out and /shaders are not touched. A folder that + is a symlink or a junction, or is reached through one at first_light, is refused: nothing outside the work + folder is removed. shutil.rmtree unlinks a link inside a folder without entering it. + """ + base = os.path.join(work, "first_light") + real_base = os.path.join(os.path.realpath(work), "first_light") + # first_light itself is checked first: when it is a link to a folder with no dxbc or spirv in it, there is + # nothing stale to judge below, and the new dxbc would be created on the far side of the link. + if os.path.lexists(base) and ( + not os.path.isdir(base) or os.path.normcase(os.path.realpath(base)) != os.path.normcase(real_base) + ): + raise SystemExit( + f"{base} is a symlink, a junction or a file: each run removes and creates folders under it and does " + "not follow a link to do it; remove it and run again" + ) + stale = [os.path.join(base, name) for name in ("dxbc", "spirv") if os.path.lexists(os.path.join(base, name))] + for folder in stale: # both are checked before either is removed + real = os.path.join(real_base, os.path.basename(folder)) + if not os.path.isdir(folder) or os.path.normcase(os.path.realpath(folder)) != os.path.normcase(real): + raise SystemExit( + f"{folder} is a symlink, a junction or a file, or first_light above it is a link: each run " + "removes this folder and does not follow a link to do it; remove it and run again" + ) + for folder in stale: + try: + shutil.rmtree(folder) + except OSError as e: + raise SystemExit( + f"cannot remove {e.filename or folder} left by an earlier run ({e.strerror or e}); " + f"close what holds it or delete {folder}, then run again" + ) from e + dxbc = os.path.join(base, "dxbc") + try: + os.makedirs(dxbc) + except OSError as e: + raise SystemExit(f"cannot create {dxbc}: {e.strerror or e}") from e + return dxbc + + def carve_index(work: str) -> str: return os.path.join(work, "shaders", "dxbc", "index.json") @@ -93,8 +139,7 @@ def choose(index_path: str, vs: str, ps: str) -> list[dict]: def translate(work: str, picked: list[dict]) -> dict: """Translate just the two chosen containers, in the layout rdna2spirv.py reads.""" base = os.path.join(work, "first_light") - dxbc = os.path.join(base, "dxbc") - os.makedirs(dxbc, exist_ok=True) + dxbc = reset_run_folders(work) index = [] for entry in picked: shutil.copy( @@ -407,6 +452,70 @@ def find_harness(explicit: str | None) -> str: CLEAR = -1.0 +FALLBACK_RGBA = (1.0, 0.0, 1.0, 1.0) + + +def _close(got: float, want: float, tol: float) -> bool: + return math.isfinite(got) and abs(got - want) <= tol + + +def _distinguishable_from_fallback(rgba: list[float] | tuple[float, ...], tol: float) -> bool: + return any(abs(c - m) > tol for c, m in zip(rgba, FALLBACK_RGBA)) + + +def rgba_probes_for_mesh( + vertices, + indices, + width: int, + height: int, + tw: int, + th: int, + rgba: bytes, + uv_probe_list: list[dict] | None = None, + tol: float = 0.02, + limit: int = 4, +) -> list[dict]: + """Select covered RGBA probes for textured verification. + + Starts from ``uv_probe_list`` when available; if that is empty (e.g. an off-centre mesh with + default (0, 0) UVs), scans covered pixels so textured draws always have at least one covered + RGBA probe. Prefers samples whose expected colour differs from the harness's magenta fallback. + """ + candidates = list(uv_probe_list) if uv_probe_list else [] + if not candidates and vertices: + step = max(1, min(width, height) // 16) + for py in range(step // 2, height, step): + for px in range(step // 2, width, step): + uv = uv_at(vertices, indices, px, py, width, height) + if uv is not None: + candidates.append( + {"pixel": [px, py], "uv": [round(uv[0], 6), round(uv[1], 6)]} + ) + if not candidates: + for py in range(height): + for px in range(width): + uv = uv_at(vertices, indices, px, py, width, height) + if uv is not None: + candidates.append( + {"pixel": [px, py], "uv": [round(uv[0], 6), round(uv[1], 6)]} + ) + if len(candidates) >= limit * 4: + break + if len(candidates) >= limit * 4: + break + sampled = [ + { + "pixel": p["pixel"], + "uv": p["uv"], + "rgba": sample_rgba_bilinear(tw, th, rgba, p["uv"][0], p["uv"][1]), + } + for p in candidates + ] + distinct = [p for p in sampled if _distinguishable_from_fallback(p["rgba"], tol)] + pool = distinct if distinct else sampled + if len(pool) > limit: + pool = [pool[int(i * len(pool) / limit)] for i in range(limit)] + return pool def check_image(data: bytes, manifest: dict) -> dict: @@ -420,7 +529,22 @@ def check_image(data: bytes, manifest: dict) -> dict: f"raw is {len(data)} bytes, expected {width * height * 16}" ) pixels = struct.unpack(f"<{len(data) // 4}f", data) - covered = sum(1 for i in range(3, len(pixels), 4) if pixels[i] > 0.5) + clear_val = manifest.get("clear", CLEAR) + textured = ( + manifest.get("texture") is not None + or manifest.get("centre_rgba") is not None + or manifest.get("rgba_probes") is not None + ) + if textured: + # UNORM texels can have any alpha in [0, 1] (including 0.0), so distinguish covered fragments + # from the harness clear sentinel (-1.0) instead of testing alpha > 0.5. + covered = sum( + 1 + for i in range(0, len(pixels), 4) + if not all(_close(pixels[i + c], clear_val, 1e-5) for c in range(4)) + ) + else: + covered = sum(1 for i in range(3, len(pixels), 4) if pixels[i] > 0.5) ratio = covered / (width * height) if ( not manifest.get("min_coverage", 0.0) @@ -433,17 +557,31 @@ def check_image(data: bytes, manifest: dict) -> dict: ) if (clear := manifest.get("clear_pixel")) is not None: i = (clear[1] * width + clear[0]) * 4 - want = manifest.get("clear", CLEAR) - if any(abs(pixels[i + c] - want) > 1e-5 for c in range(4)): + if any(not _close(pixels[i + c], clear_val, 1e-5) for c in range(4)): raise AssertionError( - f"clear pixel {clear} is {pixels[i : i + 4]}, expected {want}" + f"clear pixel {clear} is {pixels[i : i + 4]}, expected {clear_val}" + ) + if textured: + tol = manifest.get("rgba_tolerance", 0.02) + expected_rgbas = [] + if (rgba := manifest.get("centre_rgba")) is not None: + expected_rgbas.append(rgba) + for probe in manifest.get("rgba_probes") or []: + expected_rgbas.append(probe["rgba"]) + if not expected_rgbas: + raise AssertionError( + "textured manifest has no covered RGBA samples (centre_rgba or rgba_probes)" + ) + if not any(_distinguishable_from_fallback(r, tol) for r in expected_rgbas): + raise AssertionError( + f"textured manifest has no expected colour distinguishable from fallback {FALLBACK_RGBA} (tol {tol})" ) if (rgba := manifest.get("centre_rgba")) is not None: centre = manifest.get("centre_pixel") or [width // 2, height // 2] i = (centre[1] * width + centre[0]) * 4 tol = manifest.get("rgba_tolerance", 0.02) for c, want in enumerate(rgba): - if abs(pixels[i + c] - want) > tol: + if not _close(pixels[i + c], want, tol): raise AssertionError( f"centre {centre} is {pixels[i : i + 4]}, expected {rgba} (tol {tol})" ) @@ -451,7 +589,7 @@ def check_image(data: bytes, manifest: dict) -> dict: centre = manifest.get("centre_pixel") or [width // 2, height // 2] i = (centre[1] * width + centre[0]) * 4 for c, want in enumerate((uv[0], uv[1], 0.0, 1.0)): - if abs(pixels[i + c] - want) > 2e-3: + if not _close(pixels[i + c], want, 2e-3): raise AssertionError( f"centre {centre} is {pixels[i : i + 4]}, expected {want} at {c}" ) @@ -462,7 +600,7 @@ def check_image(data: bytes, manifest: dict) -> dict: i = (py * width + px) * 4 want_rgba = probe["rgba"] for c, want in enumerate(want_rgba): - if abs(pixels[i + c] - want) > tol: + if not _close(pixels[i + c], want, tol): raise AssertionError( f"RGBA probe {probe['pixel']} is {pixels[i : i + 4]}, expected {want_rgba} (tol {tol})" ) @@ -472,7 +610,7 @@ def check_image(data: bytes, manifest: dict) -> dict: i = (py * width + px) * 4 u, v = probe["uv"] for c, want in enumerate((u, v, 0.0, 1.0)): - if abs(pixels[i + c] - want) > 2e-3: + if not _close(pixels[i + c], want, 2e-3): raise AssertionError( f"UV probe {probe['pixel']} is {pixels[i : i + 4]}, expected {want} at {c}" ) @@ -493,6 +631,8 @@ def write_ppm(path: str, pixels, width: int, height: int) -> None: def run_draw(args, manifest: dict, out_dir: str) -> dict: + if manifest.get("vertex_count") == 0 or manifest.get("index_count") == 0: + raise SystemExit("first-light draw requires an OBJ with faces. Prepare this output with --obj before drawing.") harness = find_harness(args.harness) raw = os.path.join(out_dir, "image.raw") if os.path.exists(raw): @@ -682,6 +822,11 @@ def main(argv=None) -> int: if not a.no_fit: vertices = fit(vertices, a.width, a.height, True, not a.keep_z) write_mesh(os.path.join(out_dir, "mesh.bin"), vertices, indices) + else: # a run without a model must not draw the mesh an earlier run left in the folder + try: + os.unlink(os.path.join(out_dir, "mesh.bin")) + except FileNotFoundError: + pass centre_pixel = [a.width // 2, a.height // 2] centre_uv = ( uv_at(vertices, indices, centre_pixel[0], centre_pixel[1], a.width, a.height) @@ -752,15 +897,19 @@ def main(argv=None) -> int: manifest["centre_rgba"] = sample_rgba_bilinear( tw, th, rgba, centre_uv[0], centre_uv[1] ) - if probes: - manifest["rgba_probes"] = [ - { - "pixel": p["pixel"], - "uv": p["uv"], - "rgba": sample_rgba_bilinear(tw, th, rgba, p["uv"][0], p["uv"][1]), - } - for p in probes - ] + tex_probes = rgba_probes_for_mesh( + vertices, + indices, + a.width, + a.height, + tw, + th, + rgba, + uv_probe_list=probes, + tol=manifest["rgba_tolerance"], + ) + if tex_probes: + manifest["rgba_probes"] = tex_probes with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(manifest, f, indent=1) print(f"{len(vertices)} vertices, {len(indices) // 3} triangles -> {out_dir}") diff --git a/tools/fragment_children.py b/tools/fragment_children.py new file mode 100644 index 000000000..a1719e5f0 --- /dev/null +++ b/tools/fragment_children.py @@ -0,0 +1,370 @@ +"""Census the child drawables of the fragments in an RPF9 archive (ASSET-261). + +docs/character_models.md records that every one of the 2,865 `packs.rpf` fragments has a single drawable and +no child arrays. This tool measures the same thing for any archive, `levels.rpf` included, from the raw +system pages: no manifest, no table of contents and no decoder is needed. Only archives whose resources are +plain page-aligned zlib streams are read, the way tools/skin_streams.py reads them. + +A fragment is the resource shape rpf9-explorer's `RageModelDecoder` calls one: not a drawable, not a drawable +dictionary, and a header whose `+0x08`, `+0x18` and `+0xA8` fields are system pointers, whose `+0x10`, `+0x20` +and `+0x28` fields are null or system pointers, and whose u16 fields at `+0x30..+0x36` read (a, b, c, d) with +0 < a <= 4096, b <= 4096 and c <= d <= 4096. `+0x18` points at the fragment's main drawable. + +Layout measured here (counts only; nothing the archive holds is written out): + + drawable array `a` (u16 at `+0x30`) is the number of drawables. They are 0x110-byte records at a fixed + stride starting at the main drawable `+0x18` points at, so record i is at main + 0x110 * i. + Records 1..a-1 are the child drawables; their `+0x00` and `+0x08` fields are zero. + drawable body what the tool accepts as a drawable at an offset: `+0x00` and `+0x08` zero, `+0x10` (shader + group) and `+0xA8` (name) null or system pointers, finite ordered bounds, a finite + radius in [0, 1e6), and a LOD list behind `+0x50` (u16 model count 1..256 at +0x08, + repeated at +0x0A, an array of system pointers to models whose geometry count at + +0x10 equals the copies at +0x12 and +0x36). + child drawable a body at main + 0x110 * i for 1 <= i < a (the declared children). + stray drawable a body at any other 16-byte-aligned offset of the system pages outside the main record, + found by scanning; a count of what the array walk would miss. + child array a fragment whose array holds at least one child drawable. + part element the 0x50-byte records of the array `+0x28` points at (c of them, c = u16 at `+0x34`); + the fragments with more than one are counted too. + +A fragment with no child drawable and no stray drawable has nothing the main-drawable export misses. + +Usage: + python -I tools/fragment_children.py [--jobs N] [--start BYTES] [--end BYTES] + [--records out.jsonl] [--json out.json] + +`--start`/`--end` bound the byte range scanned (resume a long run, or split it); `--jobs` splits the range +over worker processes. `--records` writes one JSON line per fragment with its stream offset and the measured +numbers, for a re-count without a re-scan; it is a local working file, not something to publish. +""" +import argparse +import array as array_module +import json +import mmap +import multiprocessing +import os +import struct +import sys +import time +import zlib + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # -I keeps the script directory off sys.path +import skin_streams as ss # noqa: E402 + +SYSTEM = 0x50000000 +PAGE = 4096 +MAX_SYSTEM_BYTES = 64 * 1024 * 1024 +MAX_PAGES = 32 +MAX_ELEMENTS = 4096 +ELEMENT_STRIDE = 0x50 +RECORD = 0x110 # stride of the drawable records +HEADER = 192 # a fragment header; nothing embedded starts inside it +ZHDR = ss.ZHDR + + +def u16(b, o): + return struct.unpack_from(" len(b) or u64(b, at) != 0: + return False + pages, shader, high, name = u64(b, at + 8), u64(b, at + 16), u64(b, at + 80), u64(b, at + 168) + if (pages != 0) if embedded else (not system_pointer(pages)): + return False + if not (system_pointer(shader) and system_pointer(high)): + return False + if not (system_pointer(name) or (embedded and name == 0)): + return False + radius = struct.unpack_from(" n or u64(b, at) != 0 or u64(b, at + 8) != 0: + return False + shader, name, lod = u64(b, at + 16), u64(b, at + 168), u64(b, at + 80) + if (shader and not system_pointer(shader)) or (name and not system_pointer(name)): + return False + radius = struct.unpack_from(" total or pages < 1: + nxt = ss.next_stream(m, fp, size) + if nxt is None or pages >= MAX_PAGES: + return None + parts.append(nxt[0]) + total += len(nxt[0]) + fp = nxt[1] + nxt[2] + pages += 1 + joined = b"".join(parts) + system_pages = joined[directory + 8] + if not 0 < system_pages <= MAX_PAGES: + return None + while pages < system_pages: + nxt = ss.next_stream(m, fp, size) + if nxt is None: + return None + parts.append(nxt[0]) + fp = nxt[1] + nxt[2] + pages += 1 + joined = b"".join(parts) + return joined, fp + + +def stray_bodies(system, array): + """Offsets of drawable bodies outside the record array: `array` is the (start, end) the records span.""" + n = len(system) + words = array_module.array("Q") + words.frombytes(system[:n // 8 * 8]) + if sys.byteorder != "little": + words.byteswap() + found, low, high = [], SYSTEM, SYSTEM + n + for at in range(HEADER, n - 176, 16): + if array[0] <= at < array[1]: + continue + i = at >> 3 + if words[i] or words[i + 1] or not low <= words[i + 10] < high: # +0x00, +0x08, the LOD pointer + continue + if drawable_body(system, at): + found.append(at) + return found + + +def walk(system): + """Measure one fragment's system pages; returns a dict of counts, or None if the header is unusable.""" + if not fragment_header(system): + return None + main = u64(system, 24) - SYSTEM + a, b, c, d = struct.unpack_from("<4H", system, 48) + rec = {"main": main, "abcd": [a, b, c, d], + "optional_null": sum(1 << i for i, at in enumerate((16, 32, 40)) if u64(system, at) == 0)} + rec["main_ok"] = 0 <= main <= len(system) - 176 and drawable_header(system, main, True) + found = [i for i in range(1, a) if drawable_body(system, main + RECORD * i)] + rec["children"] = len(found) + rec["declared"] = a - 1 + # the main record is excluded from the scan through the array span, so a missing child stays "stray" + rec["stray"] = len(stray_bodies(system, (main, main + RECORD * a))) if main >= HEADER else -1 + elements = 0 + table = u64(system, 40) - SYSTEM + if c and u64(system, 40) and 0 <= table <= len(system) - c * ELEMENT_STRIDE and c <= MAX_ELEMENTS: + elements = c + rec["elements"] = elements + return rec + + +def empty_stats(): + return {"fragments": 0, "unreadable": 0, "main_drawable_invalid": 0, "optional_pointers_null": 0, + "multi_drawable_fragments": 0, "declared_child_drawables": 0, "child_drawables": 0, + "child_arrays": 0, "stray_drawables": 0, "fragments_with_stray": 0, "max_children": 0, + "multi_part_fragments": 0, "part_elements": 0} + + +def count(stats, rec): + stats["fragments"] += 1 + if not rec["main_ok"]: + stats["main_drawable_invalid"] += 1 + if rec["optional_null"]: + stats["optional_pointers_null"] += 1 + if rec["declared"]: + stats["multi_drawable_fragments"] += 1 + stats["declared_child_drawables"] += rec["declared"] + if rec["children"]: + stats["child_arrays"] += 1 + stats["child_drawables"] += rec["children"] + stats["max_children"] = max(stats["max_children"], rec["children"]) + if rec["stray"] > 0: + stats["fragments_with_stray"] += 1 + stats["stray_drawables"] += rec["stray"] + stats["part_elements"] += rec["elements"] + if rec["elements"] > 1: + stats["multi_part_fragments"] += 1 + + +def merge(into, other): + for key, value in other.items(): + into[key] = max(into[key], value) if key == "max_children" else into[key] + value + + +def scan_range(path, start, end, records, log=None): + """Scan [start, end) of one archive; returns the stats. `records` is a writable handle or None.""" + stats = empty_stats() + size = os.path.getsize(path) + end = min(end, size) + if size == 0 or start >= end: + return stats + t0 = time.time() + with open(path, "rb") as fh: + m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) + pos = start + while pos < end: + page = (pos + PAGE - 1) & ~(PAGE - 1) + at = page + 16 + if at + 2 > size or page >= end: + break + pos = page + PAGE + if m[at - 16:at] != b"\0" * 16 or not ZHDR.match(m, at): + continue + try: + prefix = zlib.decompressobj().decompress(m[at:at + 4 * PAGE], 192) + except zlib.error: + continue + if classify(prefix) is None: + continue + got = read_system(m, at, size) + rec = None + if got is not None: + rec = walk(got[0]) + if rec is None: + stats["unreadable"] += 1 + continue + count(stats, rec) + pos = max(pos, got[1]) # resume after the pages this resource consumed + if records is not None: + records.write(json.dumps(dict(rec, at=at), separators=(",", ":")) + "\n") + records.flush() + if log and stats["fragments"] % 5000 == 0: + log(f" {os.path.basename(path)} @{page:#x}: {stats['fragments']} fragments, " + f"{time.time() - t0:.0f}s") + return stats + + +def worker(args): + path, start, end, records_path = args + handle = open(records_path, "w", encoding="utf-8", newline="\n") if records_path else None + try: + return scan_range(path, start, end, handle) + finally: + if handle: + handle.close() + + +def split_ranges(start, end, jobs): + step = max(PAGE, ((end - start) // jobs + PAGE - 1) // PAGE * PAGE) + return [(lo, min(lo + step, end)) for lo in range(start, end, step)] + + +def scan_archive(path, start=0, end=None, jobs=1, records=None, log=None): + size = os.path.getsize(path) + end = size if end is None else min(end, size) + total = empty_stats() + if jobs <= 1 or end - start < 2 * PAGE: + handle = open(records, "w", encoding="utf-8", newline="\n") if records else None + try: + merge(total, scan_range(path, start, end, handle, log)) + finally: + if handle: + handle.close() + return total + ranges = split_ranges(start, end, jobs) + work = [(path, lo, hi, f"{records}.{i}" if records else None) for i, (lo, hi) in enumerate(ranges)] + with multiprocessing.Pool(len(work)) as pool: + for part in pool.imap_unordered(worker, work): + merge(total, part) + if records: # join the per-range files in range order + with open(records, "w", encoding="utf-8", newline="\n") as out: + for i in range(len(work)): + part = f"{records}.{i}" + with open(part, encoding="utf-8") as fh: + out.write(fh.read()) + os.remove(part) + return total + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("archive", help="RPF9 archive to scan") + ap.add_argument("--start", type=int, default=0, help="first byte offset to scan") + ap.add_argument("--end", type=int, help="byte offset to stop at (default: end of file)") + ap.add_argument("--jobs", type=int, default=1, help="worker processes (the range is split evenly)") + ap.add_argument("--records", help="write one JSON line per fragment here (a local working file)") + ap.add_argument("--json", help="write the totals to this file") + a = ap.parse_args(argv) + if a.jobs < 1 or a.start < 0 or (a.end is not None and a.end < a.start): + print("error: bad --jobs, --start or --end", file=sys.stderr) + return 2 + if not os.path.isfile(a.archive): + print(f"error: {a.archive} is not a file", file=sys.stderr) + return 2 + for out in (a.records, a.json): + if out and (os.path.isdir(out) or ss.same_output_path(out, a.archive)): + print(f"error: {out} is a directory or the input", file=sys.stderr) + return 2 + t0 = time.time() + stats = scan_archive(a.archive, a.start, a.end, a.jobs, a.records, lambda text: print(text, flush=True)) + print(f"{os.path.basename(a.archive)}: {time.time() - t0:.0f}s") + for key, value in stats.items(): + print(f" {key:26s} {value:10d}") + if a.json: + with open(a.json, "w", encoding="utf-8", newline="\n") as fh: + json.dump(stats, fh, indent=1) + return 0 + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index a3454861d..fb37925a0 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -171,13 +171,23 @@ def main(argv=None) -> int: help="llvm-mc CPU for --disasm (default gfx1030: the programs use v_dot4 instructions, which " "gfx1010 and gfx1013 do not decode)") a = ap.parse_args(argv) - os.makedirs(os.path.join(a.out, "fspx"), exist_ok=True) + fspx_dir = os.path.join(a.out, "fspx") + try: + os.makedirs(fspx_dir, exist_ok=True) + except OSError as error: + print(f"cannot create output directory {fspx_dir}: {error}", file=sys.stderr) + return 2 disasm = None if a.disasm: sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import shader_disasm # noqa: E402 (resolves LLVM_MC at import) disasm = shader_disasm - os.makedirs(os.path.join(a.out, "disasm"), exist_ok=True) + disasm_dir = os.path.join(a.out, "disasm") + try: + os.makedirs(disasm_dir, exist_ok=True) + except OSError as error: + print(f"cannot create output directory {disasm_dir}: {error}", file=sys.stderr) + return 2 index, bad = [], 0 used_names = set() for path in a.files: @@ -219,6 +229,19 @@ def main(argv=None) -> int: entry["threads"] = meta["threads"] if "wave32" in meta: entry["wave32"] = meta["wave32"] + listing = None + if disasm and meta["code"]["end"]: + start, end = meta["code"]["start"], meta["code"]["end"] + asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu) + if not asm.strip(): + reason = (err.strip().splitlines() or ["no output"])[0] + print(f"{name}: {reason}", file=sys.stderr) + bad += 1 + continue + entry["invalid_words"] = invalid + listing = f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n" + asm + if err.strip(): + listing += "\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n" if container: with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: f.write(container) @@ -228,15 +251,9 @@ def main(argv=None) -> int: f.write(blob[0]) with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8", newline="\n") as f: json.dump(meta, f, indent=1) - if disasm and meta["code"]["end"]: - start, end = meta["code"]["start"], meta["code"]["end"] - asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu) - entry["invalid_words"] = invalid + if listing is not None: with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n") - f.write(asm) - if err.strip(): - f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n") + f.write(listing) index.append(entry) with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(index, f, indent=1) diff --git a/tools/fssm_header.py b/tools/fssm_header.py index 5f4b83488..56570fc6e 100644 --- a/tools/fssm_header.py +++ b/tools/fssm_header.py @@ -223,7 +223,7 @@ def stage_index(path): The index is the one `make_game.py` writes next to the carved `.dxbc` files. Both the `fssm` directory (parent holds index.json) and a directory that contains index.json are accepted. - Prefer the local index when it has rows. + Prefer the local index when it has stage rows. """ base = path if os.path.isdir(path) else (os.path.dirname(path) or ".") for candidate in (os.path.join(base, "index.json"), os.path.join(base, "..", "index.json")): @@ -235,15 +235,25 @@ def stage_index(path): continue if not isinstance(rows, list): continue - stages = { - stem: stage - for row in rows - if isinstance(row, dict) - and isinstance(file := row.get("file"), str) - and (stem := os.path.splitext(os.path.basename(file))[0]) - and isinstance(stage := row.get("stage"), str) - and stage - } + stages = {} + ambiguous = set() + for row in rows: + if not ( + isinstance(row, dict) + and isinstance(file := row.get("file"), str) + and (stem := os.path.splitext(os.path.basename(file.replace("\\", "/")))[0]) + and isinstance(stage := row.get("stage"), str) + and stage + ): + continue + if stem in ambiguous: + continue + prev = stages.get(stem) + if prev is not None and prev != stage: + del stages[stem] + ambiguous.add(stem) + else: + stages[stem] = stage if stages: return stages return {} @@ -377,7 +387,8 @@ def main(argv=None): label = "PS entry counts" if total["entry_counts_scope"] == "ps" else "entry counts" print(label + ": " + ", ".join(f"{k}:{v}" for k, v in total["entry_counts"].items())) if total["stage_source"] == "table-only": - print("(no index.json found: counted every blob with a non-empty table as a PS)") + why = "no inspected blob in index.json" if stages else "no index.json found" + print(f"({why}: counted every blob with a non-empty table as a PS)") if args.bindings: parsed = [row for row in rows if row["bindings"]] records = sum(row["bindings"]["records"] for row in parsed) diff --git a/tools/gamedata_maps.py b/tools/gamedata_maps.py index b8f80ebe9..21f2038b1 100644 --- a/tools/gamedata_maps.py +++ b/tools/gamedata_maps.py @@ -499,6 +499,9 @@ def main() -> int: ap.add_argument("carve_dir", help="rpf9_carve.py output directory") ap.add_argument("--json", help="write the decoded header and grid summary to this JSON") a = ap.parse_args() + if not os.path.exists(a.carve_dir): + print(f"ERROR: {a.carve_dir}: does not exist", file=sys.stderr) + return 2 try: if a.json: diff --git a/tools/gamedata_reader.py b/tools/gamedata_reader.py index 3f37b273b..67ea81cde 100644 --- a/tools/gamedata_reader.py +++ b/tools/gamedata_reader.py @@ -270,7 +270,8 @@ def run(targets, root_filter=None, out_dir=None, reader=None): continue try: tag, _, value = reader.read(doc["data"]) - except ET.ParseError as e: + except (ET.ParseError, LookupError, ValueError) as e: + # Unsupported encodings and malformed content arrays fail outside ET.ParseError too. failed[str(e).split(":")[0]] += 1 continue read += 1 diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py index f769fe0e7..69e964abe 100644 --- a/tools/gamedata_xml.py +++ b/tools/gamedata_xml.py @@ -25,6 +25,7 @@ import io import json import os import re +import stat import statistics import sys import xml.etree.ElementTree as ET @@ -493,6 +494,58 @@ def input_files(targets: list): yield target +def input_name_matches(name: str, target: str) -> bool: + """Whether a report basename could be a name the scan reads from this directory target.""" + name = name.lower() + if os.path.isdir(target): + if os.path.isfile(os.path.join(target, "index.json")): + return name == "index.json" or name.endswith((".bin", ".bk2")) + return name.endswith(".xml") + return False + + +def has_symlinked_input(target: str) -> bool: + """Whether the scan can read a symlink to the report from this target.""" + if os.path.isdir(target): + if os.path.isfile(os.path.join(target, "index.json")): + with os.scandir(target) as entries: + for entry in entries: + if entry.is_symlink(): + leaf = entry.name.lower() + if leaf == "index.json" or leaf.endswith((".bin", ".bk2")): + return True + else: + for base, _, names in os.walk(target): + for name in names: + if name.lower().endswith(".xml") and os.path.islink(os.path.join(base, name)): + return True + return False + + +def report_needs_input_check(path: str, targets: list) -> bool: + """Whether a report path has to be compared with every scanned input. + + A report that already exists as a regular file, is not a symlink and has one link is reachable + only through its own name. When that name cannot be an input read from a directory target, and + no scanned input is a symlink to it, the per-file ``same_report_path`` checks can be skipped. + Missing reports, links, explicit file targets and input-like names are always compared. + """ + try: + st = os.lstat(path) + except OSError: + return True + if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1: + return True + name = os.path.basename(os.path.realpath(path)) + for target in targets: + if os.path.isdir(target): + if input_name_matches(name, target) or has_symlinked_input(target): + return True + elif os.path.isfile(target): + return True # an explicit file target can have any name + return False + + def document_mode(targets: list) -> str: for target in targets: if os.path.isdir(target) and os.path.isfile(os.path.join(target, "index.json")): @@ -628,9 +681,10 @@ def main() -> int: continue if os.path.isdir(path): parser.error(f"{flag} is a directory: {path}") - for source in input_files(args.targets): - if same_report_path(path, source): - parser.error(f"{flag} would overwrite the input {source}") + if report_needs_input_check(path, args.targets): + for source in input_files(args.targets): + if same_report_path(path, source): + parser.error(f"{flag} would overwrite the input {source}") rows = [] mode = document_mode(args.targets) diff --git a/tools/gdk_runtime_calls.py b/tools/gdk_runtime_calls.py new file mode 100644 index 000000000..476d94ddf --- /dev/null +++ b/tools/gdk_runtime_calls.py @@ -0,0 +1,1045 @@ +"""List the GDK runtime classes, interfaces and vtable slots a PE image calls through xgameruntime.lib's thunks. + +Usage: + python -I tools/gdk_runtime_calls.py [ ...] [--json] [--out DIR] + [--table FILE] [--runtime-source FILE] + +A title linked with xgameruntime.lib imports no GDK function. Each function of the library is a thunk that calls a +helper with a class id and an interface id (the helper initializes the runtime once and calls QueryApiImpl), then +calls one slot of the returned object's vtable with the function's own arguments after `this`, then Release (slot 2) +(docs/runtime_imports.md, "Class layouts, measured"). This finds those thunks in the image's code without running +it, and names each slot from tools/gdk_runtime_classes.json (tools/gen_gdk_runtime_classes.py makes it from +xgameruntime-docs). Run on the game executable, the classes and slots it prints are the runtime surface to serve +before the first boot. + +How it finds them (x86-64 images only): +1. Every 16-byte in-memory copy of a class or interface id the table knows, in the data sections (in the code + sections when the data sections have none). +2. Every RIP-relative `lea reg,[id]` in executable sections; the first call after it is a helper candidate. A + candidate is a helper when, after it returns, one or more vtable slots past IUnknown are called (`mov r,[obj]`, + `mov r,[r+disp]` and a call through it, the CFG `call __guard_dispatch_icall` form or `call [r+disp]`, followed + through register copies). +3. Every call to a helper is a thunk, whatever ids it passes: an id the table doesn't know is reported as unknown. + The ids are the RIP-relative addresses loaded into the helper's first two argument registers (followed through + register copies): rcx holds the class id, rdx the interface id (the class id when rdx holds none). A helper call + whose rcx holds no address is listed as not followed, with the calls after which no slot call is found. +4. After the helper call, each slot call up to Release, the next helper call or the end of the function is + recorded. Function bounds come from the exception directory (.pdata), or a byte window without one. +5. Whether anything in the image reaches each thunk function: a call, tail jump, RIP-relative address load or + 8-byte pointer in data, directly or through an incremental-link `jmp` stub, from code that is itself reached + when it is another thunk. An incremental link doesn't remove unreferenced functions, so an image can carry + thunks nothing calls (libHttpClient.GDK.dll calls 15 of its 404). + +The interface's slot table is the methods of its inheritance chain, base first, from slot 3. An id that is a class +id but not an interface id is read as the class's implemented interface. The argument count is an estimate: the +highest of rdx/r8/r9 (xmm1-3) written, or [rsp+20h+8k] stored, between the previous call and the slot call. + +Output: per image and class, the class and interface ids, the slots called with their method names and whether +their thunks are referenced, the thunk count, and whether runtime/shims/xgameruntime.cpp serves the class (a +`constexpr GUID k...Class` with its id; the class only, not each slot); then the known ids present in the image that +no thunk reaches. Text by default, --json for JSON. --out DIR writes both, as .gdk_calls.txt and +.json (x.dll-2.gdk_calls.txt for a second input named x.dll), and prints one summary line per image instead. + +Exit status 1 when an image (or the class table) can't be read, or an image is cut off before the end of its +sections (the report of what is there is still written); 0 otherwise. Reads the files only; never runs them. +Standard library only. +""" +from __future__ import annotations + +import argparse +import bisect +import json +import os +import re +import struct +import sys +import uuid + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from pe_inspect import DIR_EXCEPTION, MACHINES, PeFormatError, PeImage # noqa: E402 + +HERE = os.path.dirname(os.path.abspath(__file__)) +DEFAULT_TABLE = os.path.join(HERE, "gdk_runtime_classes.json") +DEFAULT_RUNTIME_SOURCE = os.path.join(HERE, "..", "runtime", "shims", "xgameruntime.cpp") + +IUNKNOWN_SLOTS = 3 # QueryInterface, AddRef, Release +RELEASE = 2 +NO_PDATA_WINDOW = 256 # bytes scanned after a helper call when no .pdata entry covers it +BACK_WINDOW = 64 # bytes searched before a helper call for the instructions that load its arguments +LEA_TO_CALL = 8 # instructions from an id's lea to the helper call it feeds + +# ---- A small x86-64 instruction decoder: lengths, ModRM operands and branch targets ---- + +RIP = 16 # base register value of a RIP-relative operand +XMM = 32 # register number of xmm0 in writes() +RAX, RCX, RDX, RSP, R8, R9 = 0, 1, 2, 4, 8, 9 +VOLATILE = frozenset((0, 1, 2, 8, 9, 10, 11)) +ARG_INDEX = {RDX: 1, R8: 2, R9: 3, XMM + 1: 1, XMM + 2: 2, XMM + 3: 3} + +_PREFIXES = frozenset((0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3)) +_ALU = [b + i for b in range(0, 0x40, 8) for i in range(4)] +_M1_MODRM = frozenset(_ALU + [0x63, 0x69, 0x6B, *range(0x80, 0x90), 0xC0, 0xC1, 0xC6, 0xC7, *range(0xD0, 0xD4), + *range(0xD8, 0xE0), 0xF6, 0xF7, 0xFE, 0xFF]) +_M1_INVALID = frozenset((0x06, 0x07, 0x0E, 0x16, 0x17, 0x1E, 0x1F, 0x27, 0x2F, 0x37, 0x3F, 0x60, 0x61, 0x82, 0x9A, + 0xCE, 0xD4, 0xD5, 0xD6, 0xEA)) +_M1_IMM8 = frozenset([b + 4 for b in range(0, 0x40, 8)] + [0x6A, 0x6B, 0x80, 0x83, 0xA8, *range(0xB0, 0xB8), 0xC0, + 0xC1, 0xC6, 0xCD, 0xE4, 0xE5, 0xE6, 0xE7]) +_M1_IMMZ = frozenset([b + 5 for b in range(0, 0x40, 8)] + [0x68, 0x69, 0x81, 0xA9, 0xC7]) +_M1_REL8 = frozenset([*range(0x70, 0x80), 0xE0, 0xE1, 0xE2, 0xE3, 0xEB]) +_M2_NO_MODRM = frozenset((0x05, 0x06, 0x07, 0x08, 0x09, 0x0B, 0x0E, *range(0x30, 0x38), 0x77, 0xA0, 0xA1, 0xA2, + 0xA8, 0xA9, 0xAA, *range(0xC8, 0xD0))) +_M2_IMM8 = frozenset((0x0F, 0x70, 0x71, 0x72, 0x73, 0xA4, 0xAC, 0xBA, 0xC2, 0xC4, 0xC5, 0xC6)) +_M2_INVALID = frozenset((0x04, 0x0A, 0x0C, 0x24, 0x25, 0x26, 0x27, 0x36, 0x39, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F)) +_VEX_IMM8 = frozenset((0x70, 0x71, 0x72, 0x73, 0xC2, 0xC4, 0xC5, 0xC6)) + +# Opcodes (0x1xx = 0F xx) that write their ModRM reg operand, or their r/m operand when it is a register. +_WRITE_REG = frozenset((0x02, 0x03, 0x0A, 0x0B, 0x12, 0x13, 0x1A, 0x1B, 0x22, 0x23, 0x2A, 0x2B, 0x32, 0x33, 0x63, + 0x69, 0x6B, 0x86, 0x87, 0x8A, 0x8B, 0x8D, *range(0x140, 0x150), 0x1AF, 0x1B6, 0x1B7, 0x1B8, + 0x1BC, 0x1BD, 0x1BE, 0x1BF, 0x1C0, 0x1C1)) +_WRITE_RM = frozenset((0x00, 0x01, 0x08, 0x09, 0x10, 0x11, 0x18, 0x19, 0x20, 0x21, 0x28, 0x29, 0x30, 0x31, 0x86, + 0x87, 0x88, 0x89, 0x8F, 0xC0, 0xC1, 0xD0, 0xD1, 0xD2, 0xD3, *range(0x190, 0x1A0), 0x1C0, + 0x1C1)) +_WRITE_XMM = frozenset((0x110, 0x112, 0x114, 0x115, 0x116, 0x128, 0x12A, *range(0x151, 0x160), 0x16E, 0x16F)) +_STORE = frozenset((0x88, 0x89, 0xC6, 0xC7, 0x111, 0x129, 0x17F, 0x1D6)) + + +class Insn: + """One decoded instruction. `op` is the opcode byte, 0x100|b for 0F b, 0x200|b / 0x300|b for 0F 38 / 0F 3A + and 0x1000|map<<8|b under VEX/EVEX. `reg`/`rm` carry their REX bits; `base` is RIP for a RIP-relative operand + and None for a register operand; `target` is a branch target or a RIP-relative operand's RVA.""" + __slots__ = ("rva", "size", "op", "rex", "reg", "mod", "rm", "base", "index", "disp", "target") + + def __init__(self, rva, size, op, rex, reg, mod, rm, base, index, disp, target): + self.rva, self.size, self.op, self.rex = rva, size, op, rex + self.reg, self.mod, self.rm, self.base, self.index, self.disp, self.target = ( + reg, mod, rm, base, index, disp, target) + + @property + def end(self) -> int: + return self.rva + self.size + + @property + def wide(self) -> bool: + return bool(self.rex & 8) + + def is_call(self) -> bool: + return self.op == 0xE8 or (self.op == 0xFF and self.mod is not None and self.reg & 7 == 2) + + def ends_flow(self) -> bool: + """ret, or an unconditional jump.""" + return (self.op in (0xC3, 0xC2, 0xE9, 0xEB) + or (self.op == 0xFF and self.mod is not None and self.reg & 7 in (4, 5))) + + def call_key(self): + """What a direct call reaches: ("rel", rva) for call rel32, ("mem", rva) for call [rip+x].""" + if self.op == 0xE8: + return ("rel", self.target) + if self.op == 0xFF and self.base == RIP and self.reg & 7 == 2: + return ("mem", self.target) + return None + + def memory_at(self, base: int) -> bool: + """A memory operand [base+disp] with no index register.""" + return self.mod is not None and self.mod != 3 and self.base == base and self.index is None + + +def decode(buf, off: int, base_rva: int) -> Insn | None: + """Decode the instruction at buf[off] (buf starts at base_rva). None for an invalid or cut-off instruction.""" + n = len(buf) + p = off + p66 = p67 = False + while p < n and buf[p] in _PREFIXES: + p66 |= buf[p] == 0x66 + p67 |= buf[p] == 0x67 + p += 1 + if p >= n or p - off > 14: + return None + rex = 0 + b = buf[p] + if 0x40 <= b <= 0x4F: + rex = b + p += 1 + if p >= n: + return None + b = buf[p] + p += 1 + modrm = False + imm = rel = 0 + if b in (0xC4, 0xC5, 0x62): # VEX / EVEX: always so in 64-bit mode + if b == 0xC5: + if p >= n: + return None + rex, vmap = 0x40 | (0 if buf[p] & 0x80 else 4), 1 + p += 1 + else: + if p + (2 if b == 0x62 else 1) >= n: + return None + b1, b2 = buf[p], buf[p + 1] + vmap = b1 & (0x07 if b == 0x62 else 0x1F) + rex = (0x40 | (0 if b1 & 0x80 else 4) | (0 if b1 & 0x40 else 2) | (0 if b1 & 0x20 else 1) + | (8 if b2 & 0x80 else 0)) + p += 3 if b == 0x62 else 2 + if p >= n: + return None + b = buf[p] + p += 1 + op = 0x1000 | (vmap << 8) | b + modrm = not (vmap == 1 and b == 0x77) + imm = 1 if vmap == 3 or (vmap == 1 and b in _VEX_IMM8) else 0 + elif b == 0x0F: + if p >= n: + return None + b = buf[p] + p += 1 + if b in (0x38, 0x3A): + if p >= n: + return None + op = (0x200 if b == 0x38 else 0x300) | buf[p] + p += 1 + modrm = True + imm = 1 if b == 0x3A else 0 + else: + if b in _M2_INVALID: + return None + op = 0x100 | b + if 0x80 <= b <= 0x8F: + rel = 4 + elif b not in _M2_NO_MODRM: + modrm = True + imm = 1 if b in _M2_IMM8 else 0 + else: + if b in _M1_INVALID: + return None + op = b + modrm = b in _M1_MODRM + if b in _M1_IMM8: + imm = 1 + elif b in _M1_IMMZ: + imm = 2 if p66 else 4 + elif b in _M1_REL8: + rel = 1 + elif b in (0xE8, 0xE9): + rel = 4 + elif 0xB8 <= b <= 0xBF: + imm = 8 if rex & 8 else (2 if p66 else 4) + elif b in (0xC2, 0xCA): + imm = 2 + elif b == 0xC8: + imm = 3 + elif 0xA0 <= b <= 0xA3: + imm = 4 if p67 else 8 + + reg = mod = rm = mbase = index = None + disp = 0 + rip = False + if modrm: + if p >= n: + return None + m = buf[p] + p += 1 + mod, reg, low = m >> 6, ((m >> 3) & 7) | ((rex & 4) << 1), m & 7 + dsize = 1 if mod == 1 else 4 if mod == 2 else 0 + if mod == 3: + rm = low | ((rex & 1) << 3) + elif low == 4: + if p >= n: + return None + s = buf[p] + p += 1 + idx = ((s >> 3) & 7) | ((rex & 2) << 2) + index = None if idx == 4 else idx + if s & 7 == 5 and mod == 0: + dsize = 4 # [index*scale + disp32], no base + else: + mbase = (s & 7) | ((rex & 1) << 3) + elif low == 5 and mod == 0: + mbase, dsize, rip = RIP, 4, True + else: + mbase = low | ((rex & 1) << 3) + if p + dsize > n: + return None + if dsize == 1: + disp = struct.unpack_from(" n: + return None + delta = struct.unpack_from(" n or p - off > 15: + return None + if rip: + target = base_rva + p + disp + return Insn(base_rva + off, p - off, op, rex, reg, mod, rm, mbase, index, disp, target) + + +def writes(i: Insn) -> list[int]: + """Registers the instruction writes (general registers 0-15, xmm n as XMM+n), for the forms that matter here.""" + op = i.op + if i.mod is None: + low = (op & 7) | ((i.rex & 1) << 3) + if 0xB0 <= op <= 0xBF or 0x58 <= op <= 0x5F: + return [low] + if 0x91 <= op <= 0x97: + return [RAX, low] + if op == 0x99: + return [RDX] + if op == 0x98: + return [RAX] + return [] + out = [] + if op in _WRITE_REG: + out.append(i.reg) + elif op in _WRITE_XMM: + out.append(XMM + i.reg) + if i.mod == 3: + sub = i.reg & 7 + if (op in _WRITE_RM or (op in (0x80, 0x81, 0x83) and sub != 7) or (op in (0xC6, 0xC7) and sub == 0) + or (op in (0xF6, 0xF7) and sub in (2, 3)) or (op in (0xFE, 0xFF) and sub in (0, 1))): + out.append(i.rm) + if op in (0xF6, 0xF7) and i.reg & 7 >= 4: # mul/imul/div/idiv + out += [RAX, RDX] + return out + + +def stack_argument(i: Insn) -> int | None: + """The argument number (5th = 4 after `this`) of a store to the outgoing stack area [rsp+20h+8k], else None.""" + if (i.op in _STORE and i.memory_at(RSP) and i.disp >= 0x20 and i.disp % 8 == 0 + and not (i.op in (0xC6, 0xC7) and i.reg & 7)): + return 4 + (i.disp - 0x20) // 8 + return None + + +# ---- The class table and the runtime shim ---- + +def guid_bytes(guid: str) -> bytes: + return uuid.UUID(guid).bytes_le + + +class RuntimeTable: + """tools/gdk_runtime_classes.json: class and interface ids, inheritance and method order.""" + + def __init__(self, doc: dict): + self.source = doc.get("source", "") + self.classes: dict = doc["classes"] + self.interfaces: dict = doc["interfaces"] + self.class_by_id = {c["id"]: name for name, c in self.classes.items()} + self.interface_by_id = {i["id"]: name for name, i in self.interfaces.items()} + + @classmethod + def load(cls, path: str) -> "RuntimeTable": + with open(path, encoding="utf-8") as f: + return cls(json.load(f)) + + def ids(self) -> set[str]: + return set(self.class_by_id) | set(self.interface_by_id) + + def label(self, guid: str) -> str: + """What an id names: 'XUserImpl', 'IXUserImpl5', 'XThreadingImpl/IXThreadingImpl', or 'unknown'.""" + names = [n for n in (self.class_by_id.get(guid), self.interface_by_id.get(guid)) if n] + return "/".join(names) or "unknown" + + def class_of(self, guid: str) -> str | None: + if guid in self.class_by_id: + return self.class_by_id[guid] + iface = self.interface_by_id.get(guid) + return self.interfaces[iface]["class"] if iface else None + + def interface_for(self, guid: str) -> str | None: + """The interface whose slot table names the slots called through this id.""" + if guid in self.interface_by_id: + return self.interface_by_id[guid] + cls = self.class_by_id.get(guid) + if cls and self.classes[cls]["implements"]: + return self.classes[cls]["implements"][0] + return None + + def chain(self, iface: str) -> list[str]: + out, seen = [], set() + while iface and iface in self.interfaces and iface not in seen: + seen.add(iface) + out.append(iface) + iface = self.interfaces[iface]["inherits"] + return out[::-1] + + def slot_table(self, iface: str) -> tuple[list, list[str]]: + """(method names from slot 3 on, None where unknown), and the chain's interfaces without a layout.""" + names, no_layout = [], [] + for name in self.chain(iface): + methods = self.interfaces[name]["methods"] + if methods is None: + no_layout.append(name) + else: + names.extend(methods) + return names, no_layout + + def method(self, iface: str | None, slot: int) -> tuple[str | None, str | None]: + """(method name or None, the interface it was read from when that is not `iface`).""" + if not iface: + return None, None + names, _ = self.slot_table(iface) + k = slot - IUNKNOWN_SLOTS + if 0 <= k < len(names): + return names[k], None + # Past the requested interface: the object is the class's, so its implemented interface may name the slot + # when the requested one is on that interface's chain (an id that is both the class's and its base's). + cls = self.interfaces[iface]["class"] + for impl in self.classes.get(cls, {}).get("implements", []): + if impl != iface and iface in self.chain(impl): + more, _ = self.slot_table(impl) + if 0 <= k < len(more): + return more[k], impl + return None, None + + +GUID_CONSTANT = re.compile( + r"constexpr\s+GUID\s+k(\w*?)Class\s*=\s*\{\s*(0x[0-9a-fA-F]+)\s*,\s*(0x[0-9a-fA-F]+)\s*,\s*(0x[0-9a-fA-F]+)\s*," + r"\s*\{([^}]*)\}\s*\}") + + +def served_classes(source: str) -> dict[str, str]: + """{class id: constant name} for each `constexpr GUID kClass = {...}` in the runtime shim's source.""" + out = {} + for m in GUID_CONSTANT.finditer(source): + try: + tail = [int(x, 16) for x in m.group(5).split(",") if x.strip()] + if len(tail) != 8: + continue + guid = uuid.UUID(fields=(int(m.group(2), 16), int(m.group(3), 16), int(m.group(4), 16), tail[0], + tail[1], int.from_bytes(bytes(tail[2:]), "big"))) + except ValueError: # not a GUID after all (a value out of range, a non-hex byte) + continue + out[str(guid)] = f"k{m.group(1)}Class" + return out + + +# ---- Scanning an image ---- + +class Code: + """The image's executable sections and .pdata function bounds.""" + + def __init__(self, img: PeImage): + self.img = img + self.sections = [] # (rva, bytes): file bytes of each executable section, mapped span only + for s in img.sections: + if s["exec"]: + data = img.section_data(s) + span = s["vsize"] or s["rawsize"] + self.sections.append((s["rva"], data[:span])) + self.begins, self.ends = [], [] + rva, size = img.directory(DIR_EXCEPTION) + at = img.offset(rva) if rva and size >= 12 else None + if at is not None: + count = min(size, len(img.data) - at) // 12 + entries = sorted((b, e) for b, e, _ in struct.iter_unpack(" b) + self.begins = [b for b, _ in entries] + self.ends = [e for _, e in entries] + + def view(self, rva: int): + """(bytes, section rva) of the executable section holding rva, or (None, 0).""" + for base, data in self.sections: + if base <= rva < base + len(data): + return data, base + return None, 0 + + def decode(self, rva: int) -> Insn | None: + data, base = self.view(rva) + return None if data is None else decode(data, rva - base, base) + + def function(self, rva: int) -> tuple[int, int] | None: + k = bisect.bisect_right(self.begins, rva) - 1 + if k >= 0 and self.begins[k] <= rva < self.ends[k]: + return self.begins[k], self.ends[k] + return None + + def run(self, start: int, stop: int) -> list[Insn] | None: + """The instructions from start up to stop, or None when decoding doesn't land on stop exactly.""" + out = [] + rva = start + while rva < stop: + i = self.decode(rva) + if i is None: + return None + out.append(i) + rva = i.end + return out if rva == stop else None + + +def guid_at(img: PeImage, rva: int) -> str | None: + at = img.offset(rva) + if at is None or at + 16 > len(img.data): + return None + return str(uuid.UUID(bytes_le=bytes(img.data[at:at + 16]))) + + +def find_ids(img: PeImage, ids: set[str]) -> dict[int, str]: + """{rva: id} for every in-memory copy of a known id in the data sections, or in the code sections when the data + sections have none (a linker can merge .rdata into .text).""" + found = {} + patterns = {guid_bytes(g): g for g in ids} + for code in (False, True): + for s in img.sections: + if s["exec"] != code: + continue + data = img.section_data(s)[:s["vsize"] or s["rawsize"]] + for pattern, guid in patterns.items(): + at = data.find(pattern) + while at >= 0: + found[s["rva"] + at] = guid + at = data.find(pattern, at + 1) + if found: + break + return found + + +LEA_RIP = re.compile(rb"[\x48\x4c]\x8d[\x05\x0d\x15\x1d\x25\x2d\x35\x3d]") + + +def lea_sites(code: Code, targets: dict[int, str]): + """RVAs of `lea r64,[rip+x]` instructions whose x is one of targets.""" + for base, data in code.sections: + for m in LEA_RIP.finditer(data): + at = m.start() + if at + 7 > len(data): + break + if base + at + 7 + struct.unpack_from(" dict[int, int]: + """{function start: references} for the thunk functions at `starts`: calls, tail jumps, RIP-relative address + loads and 8-byte pointers in data, each also through an incremental-link `jmp` stub (a jmp to the function from + outside every .pdata function). A reference from inside another of these functions counts only when that one + is referenced itself (every thunk calls the XThreadAssertNotTimeSensitive thunk, live or not). 0 means nothing + that is reached reaches it.""" + def source_function(source: int) -> int | None: + func = code.function(source) + return func[0] if func else None + + stubs: dict[int, int] = {} + outside = dict.fromkeys(starts, 0) + inside: dict[int, set[int]] = {s: set() for s in starts} + + def add(func: int, source: int | None) -> None: + if source in inside and source != func: + inside[func].add(source) + elif source not in inside: + outside[func] += 1 + + for source, target in branches(code, b"\xe9"): + if target in outside: + func = source_function(source) + if func is None: + stubs[source] = target # not inside any function: an incremental-link stub + else: + add(target, func) # a tail call + owner = {s: s for s in starts} | stubs + for source, target in branches(code, b"\xe8"): + if target in owner: + add(owner[target], source_function(source)) + for base, data in code.sections: + for m in LEA_RIP.finditer(data): + at = m.start() + if at + 7 <= len(data): + func = owner.get(base + at + 7 + struct.unpack_from(" 0) + if outside[func] + live != count[func]: + count[func] = outside[func] + live + changed = True + return count + + +def call_after(code: Code, lea_rva: int) -> Insn | None: + """The first call within LEA_TO_CALL instructions of an id's lea, unless control flow leaves first.""" + rva = lea_rva + for _ in range(LEA_TO_CALL): + i = code.decode(rva) + if i is None or i.ends_flow(): + return None + if i.is_call(): + return i + rva = i.end + return None + + +def call_arguments(code: Code, call: int) -> list[int | None]: + """The RIP-relative addresses passed in rcx, rdx, r8 and r9 to the call at `call`, in that order (None for a + register that holds none). The instructions before it are decoded from its function's start when .pdata covers + it and the start is near; else (or when that finds none) from each byte in BACK_WINDOW from which decoding lands + on the call, the first run that loads an address into rcx or rdx winning.""" + func = code.function(call) + starts = [func[0]] if func and call - func[0] <= 4096 else [] + starts += range(max(func[0] if func else 0, call - BACK_WINDOW), call) + for start in starts: + run = code.run(start, call) + if run is not None: + found = argument_addresses(run) + if found[0] is not None or found[1] is not None: + return found + return [None] * 4 + + +def argument_addresses(run: list[Insn]) -> list[int | None]: + """The RIP-relative addresses in rcx, rdx, r8 and r9 at the end of `run` (None where there isn't one).""" + state: dict[int, int] = {} + for i in run: + if i.is_call(): + for r in VOLATILE: + state.pop(r, None) + continue + if i.ends_flow(): + state.clear() + continue + if i.op == 0x8D and i.wide and i.base == RIP: + state[i.reg] = i.target + continue + if i.wide and i.mod == 3 and i.op in (0x8B, 0x89): # mov r64, r64 + dst, src = (i.reg, i.rm) if i.op == 0x8B else (i.rm, i.reg) + if src in state: + state[dst] = state[src] + else: + state.pop(dst, None) + continue + for r in writes(i): + state.pop(r, None) + return [state.get(r) for r in (RCX, RDX, R8, R9)] + + +def slot_calls(code: Code, start: int, helpers: set) -> tuple[list[tuple[int, int, int]], set]: + """[(slot, estimated argument count, call rva)] of the vtable calls after a helper call returns at `start`, and + the keys of the direct calls that dispatched them (the CFG dispatch routine).""" + func = code.function(start) + stop = func[1] if func else start + NO_PDATA_WINDOW + vtables: set[int] = set() # registers holding a vtable pointer + methods: dict[int, int] = {} # register -> slot of the method pointer it holds + written: set[int] = set() # argument registers written since the last call + stack: set[int] = set() # stack arguments stored since the last call + found, dispatchers = [], set() + rva = start + while rva < stop: + i = code.decode(rva) + if i is None: + break + rva = i.end + if i.is_call(): + slot = None + if i.op == 0xFF and i.mod != 3 and i.base in vtables and i.index is None and i.disp % 8 == 0: + slot = i.disp // 8 # call [vtable+disp] + elif i.op == 0xFF and i.mod == 3: + slot = methods.get(i.rm) # call reg + elif i.call_key() is not None and RAX in methods: + slot = methods[RAX] # CFG: call __guard_dispatch_icall (target in rax) + dispatchers.add(i.call_key()) + if slot is None and i.call_key() in helpers: + break # the next thunk's helper call + if slot is not None: + args = max([ARG_INDEX[r] for r in written if r in ARG_INDEX] + list(stack) + [0]) + found.append((slot, args, i.rva)) + if slot == RELEASE: + break + for r in VOLATILE: + vtables.discard(r) + methods.pop(r, None) + written.clear() + stack.clear() + continue + if i.ends_flow(): + if not func: + break + vtables.clear() + methods.clear() + continue + k = stack_argument(i) + if k is not None: + stack.add(k) + dests = writes(i) + written.update(dests) + load = (i.op == 0x8B and i.wide and i.mod != 3 and i.index is None + and i.base is not None and i.base not in (RIP, RSP)) + from_vtable = load and i.base in vtables and i.disp >= 0 and i.disp % 8 == 0 + copy = i.wide and i.mod == 3 and i.op in (0x8B, 0x89) # mov r64, r64 carries what its source held + if copy: + src = i.rm if i.op == 0x8B else i.reg + src_vtable, src_method = src in vtables, methods.get(src) + for r in dests: + vtables.discard(r) + methods.pop(r, None) + if copy: + if src_vtable: + vtables.add(dests[0]) + if src_method is not None: + methods[dests[0]] = src_method + elif from_vtable: + methods[i.reg] = i.disp // 8 # mov r, [vtable+disp] + elif load and i.disp == 0: + vtables.add(i.reg) # mov r, [object] + return found, dispatchers + + +def scan(img: PeImage, table: RuntimeTable) -> dict: + """Thunk sites of the image: {"helpers": [...], "sites": [...], "ids_present": {id: [rva, ...]}}.""" + known = find_ids(img, table.ids()) + present: dict[str, list[int]] = {} + for rva, guid in sorted(known.items()): + present.setdefault(guid, []).append(rva) + result = {"helpers": [], "sites": [], "unmatched": [], "ids_present": present, "pdata_functions": 0} + if img.machine != 0x8664: + result["skipped"] = f"{MACHINES.get(img.machine, hex(img.machine))} code is not scanned (x86-64 only)" + return result + code = Code(img) + result["pdata_functions"] = len(code.begins) + + # A helper: a call fed by a known id's lea and followed by a vtable call past IUnknown. + candidates: dict[int, Insn] = {} + for lea in lea_sites(code, known): + call = call_after(code, lea) + key = call.call_key() if call else None + if key is not None: + candidates.setdefault(call.rva, call) + helpers, dispatchers = set(), set() + for call in candidates.values(): + calls, used = slot_calls(code, call.end, set()) + dispatchers |= used + if any(slot >= IUNKNOWN_SLOTS for slot, _, _ in calls): + helpers.add(call.call_key()) + helpers -= dispatchers # a CFG dispatch routine is never the helper + result["helpers"] = sorted(helpers) + + near = {t for kind, t in helpers if kind == "rel"} + helper_calls = {source for source, target in branches(code, b"\xe8") if target in near} if near else set() + far = {t for kind, t in helpers if kind == "mem"} + if far: + helper_calls.update(source for source, target in branches(code, b"\xff\x15") if target in far) + + for call_rva in sorted(helper_calls): + call = code.decode(call_rva) + if call is None or call.call_key() not in helpers: + continue + # The class id is the one in rcx, the interface id the one in rdx (the class id when rdx holds none). + rcx, rdx = (None if a is None else guid_at(img, a) for a in call_arguments(code, call_rva)[:2]) + class_id, interface_id = rcx, rdx or rcx + slots = [c for c in slot_calls(code, call.end, helpers)[0] if c[0] >= IUNKNOWN_SLOTS] if rcx else [] + func = code.function(call_rva) + site = {"call": call_rva, "function": func[0] if func else None, "class_id": class_id, + "interface_id": interface_id, "slots": slots} + result["sites" if slots else "unmatched"].append(site) + + starts = {s["function"] for s in result["sites"] if s["function"] is not None} + refs = references(img, code, starts) if starts else {} + for s in result["sites"]: + s["references"] = refs.get(s["function"]) if s["function"] is not None else None + return result + + +def ranges(numbers) -> str: + """'3-7, 9, 12-14' for [3, 4, 5, 6, 7, 9, 12, 13, 14].""" + out, run = [], [] + for n in sorted(set(numbers)): + if run and n == run[-1] + 1: + run.append(n) + continue + if run: + out.append(f"{run[0]}-{run[-1]}" if len(run) > 1 else str(run[0])) + run = [n] + if run: + out.append(f"{run[0]}-{run[-1]}" if len(run) > 1 else str(run[0])) + return ", ".join(out) + + +def report(path: str, table: RuntimeTable, served: dict[str, str] | None) -> dict: + """The JSON report of one image. Raises PeFormatError or OSError when it can't be read.""" + with open(path, "rb") as f: + data = f.read() + try: + img = PeImage(data) + found = scan(img, table) + except struct.error as e: + raise PeFormatError(f"truncated or corrupt table: {e}") from None + cut = [s["name"] for s in img.sections if s["rawsize"] and s["rawptr"] + s["rawsize"] > len(data)] + + classes: dict[str, dict] = {} + for site in found["sites"]: + cid, iid = site["class_id"], site["interface_id"] + refs = site["references"] + cls = classes.setdefault(cid, { + "class": table.class_of(cid), "class_id": cid, + "served": None if served is None else cid in served, + "thunks": 0, "referenced_thunks": 0, "interfaces": {}}) + cls["thunks"] += 1 + if cls["referenced_thunks"] is not None: + cls["referenced_thunks"] = None if refs is None else cls["referenced_thunks"] + (refs > 0) + names_from = table.interface_for(iid) + iface = cls["interfaces"].setdefault(iid, { + "interface": table.label(iid), "interface_id": iid, "slots_named_from": names_from, + "without_layout": table.slot_table(names_from)[1] if names_from else [], "thunks": 0, "slots": {}}) + iface["thunks"] += 1 + where = f"{site['function'] if site['function'] is not None else site['call']:#x}" + for slot, args, _ in site["slots"]: + method, via = table.method(names_from, slot) + entry = iface["slots"].setdefault(slot, {"slot": slot, "method": method, "named_from": via, + "args_estimate": set(), "thunk_rvas": {}}) + entry["args_estimate"].add(args) + entry["thunk_rvas"][where] = refs + + out_classes = [] + for cid, cls in sorted(classes.items(), key=lambda kv: (kv[1]["class"] or "~", kv[0])): + ifaces = [] + for iface in sorted(cls["interfaces"].values(), key=lambda i: i["interface"]): + slots = [] + for _, s in sorted(iface["slots"].items()): + refs = list(s["thunk_rvas"].values()) + slots.append(dict(s, args_estimate=sorted(s["args_estimate"]), thunk_rvas=sorted(s["thunk_rvas"]), + referenced=None if None in refs else sum(r > 0 for r in refs))) + known = all(s["referenced"] is not None for s in slots) + ifaces.append(dict(iface, slots=slots, slot_list=ranges(s["slot"] for s in slots), + referenced_slot_list=ranges(s["slot"] for s in slots if s["referenced"]) + if known else None)) + out_classes.append(dict(cls, interfaces=ifaces)) + + reached = {table.class_of(c) for c in classes} | set(classes) + unreached = [] + for name, cls in sorted(table.classes.items()): + if name in reached: + continue + ids = [cls["id"]] + [i["id"] for i in table.interfaces.values() if i["class"] == name] + hits = [{"id": g, "names": table.label(g), "copies": len(found["ids_present"][g])} + for g in dict.fromkeys(ids) if g in found["ids_present"]] + if hits: + unreached.append({"class": name, "class_id": cls["id"], "ids": hits}) + + unmatched = [{"call": f"{s['call']:#x}", "class": table.class_of(s["class_id"]) if s["class_id"] else None, + "class_id": s["class_id"], "interface_id": s["interface_id"]} for s in found["unmatched"]] + refs = [s["references"] for s in found["sites"]] + return { + "file": os.path.basename(path), + "size": len(data), + "machine": MACHINES.get(img.machine, hex(img.machine)), + "is_dll": bool(img.characteristics & 0x2000), + "pdata_functions": found["pdata_functions"], + "cut_off_sections": cut, + "skipped": found.get("skipped"), + "helpers": [f"{kind} {rva:#x}" for kind, rva in found["helpers"]], + "thunks": len(found["sites"]), + "referenced_thunks": None if None in refs else sum(r > 0 for r in refs), + "classes": out_classes, + "helper_calls_without_slot_call": unmatched, + "unreached_classes": unreached, + } + + +def served_text(flag) -> str: + return {True: "served by xgameruntime.cpp", False: "NOT served by xgameruntime.cpp", None: "served: unknown"}[flag] + + +def referenced_text(count, total) -> str: + if count is None: + return "references unknown" + if count == total: + return "referenced" + return "unreferenced" if count == 0 else f"{count} referenced" + + +def to_text(r: dict) -> str: + kind = "DLL" if r["is_dll"] else "EXE" + out = [f"== {r['file']} ({r['machine']} {kind}, {r['size']:,} bytes, {r['pdata_functions']:,} .pdata functions)"] + if r["cut_off_sections"]: + out.append(f"WARNING: cut off inside {', '.join(r['cut_off_sections'])}: the file ends before the section " + "data, so this report is incomplete") + if r["skipped"]: + out.append(r["skipped"]) + out.append(f"QueryApiImpl helper(s): {', '.join(r['helpers']) or 'none found'}; {r['thunks']} thunk(s) reach " + f"{len(r['classes'])} runtime class(es)") + if r["thunks"]: + if r["referenced_thunks"] is None: + out.append("References to the thunks are unknown (no .pdata function bounds).") + else: + out.append(f"{r['referenced_thunks']} of the {r['thunks']} thunks are referenced (called, jumped to, " + "address taken or stored) in this image; an unreferenced one is present but nothing in the " + "image reaches it (an incremental link does not remove unreferenced functions).") + out.append("args~N: the argument count after `this`, estimated from the registers and stack slots written " + "before the call.") + width = max([len(s["method"] or "unknown") + (len(s["named_from"]) + 7 if s["named_from"] else 0) + for c in r["classes"] for i in c["interfaces"] for s in i["slots"]] + [40]) + for cls in r["classes"]: + out.append("") + out.append(f"{cls['class'] or 'unknown class'} {cls['class_id']} {served_text(cls['served'])} " + f"{cls['thunks']} thunk(s), {referenced_text(cls['referenced_thunks'], cls['thunks'])}") + for iface in cls["interfaces"]: + names = iface["slots_named_from"] + source = "" if names is None or names in iface["interface"].split("/") else f", slots named from {names}" + out.append(f" interface {iface['interface']} {iface['interface_id']}{source}: " + f"slots {iface['slot_list']}") + if iface["without_layout"]: + out.append(f" (no documented layout for {', '.join(iface['without_layout'])}: its own methods, " + "if any, are named in its base's list; slots past the list are unknown)") + if iface["interface_id"] != cls["class_id"]: + out.append(" (requested with an interface id other than the class id)") + for s in iface["slots"]: + name = s["method"] or "unknown" + if s["named_from"]: + name += f" (from {s['named_from']})" + args = "/".join(str(a) for a in s["args_estimate"]) + out.append(f" slot {s['slot']:>3} {name:<{width}} args~{args:<4} {len(s['thunk_rvas'])} thunk(s), " + f"{referenced_text(s['referenced'], len(s['thunk_rvas']))}") + todo = [c for c in r["classes"] if c["served"] is not True] + if todo: + out.append("") + out.append("Not served by xgameruntime.cpp (class as interface: slots called; the referenced ones):" + if all(c["served"] is False for c in todo) else + "Served status unknown (class as interface: slots called; the referenced ones):") + for c in todo: + for iface in c["interfaces"]: + ref = iface["referenced_slot_list"] + ref = "unknown" if ref is None else (ref or "none") + out.append(f" {c['class'] or c['class_id']} as {iface['interface']}: {iface['slot_list']}; " + f"referenced: {ref}") + if r["helper_calls_without_slot_call"]: + out.append("") + out.append("Helper calls not followed to a slot (no class id read from rcx, or no slot call found after " + f"them): {len(r['helper_calls_without_slot_call'])}") + for u in r["helper_calls_without_slot_call"]: + if u["class_id"] is None: + out.append(f" {u['call']} class id not read; interface {u['interface_id'] or 'not read'}") + else: + out.append(f" {u['call']} {u['class'] or 'unknown class'} {u['class_id']} / {u['interface_id']}") + if r["unreached_classes"]: + out.append("") + out.append(f"Known runtime ids present but reached by no thunk ({len(r['unreached_classes'])} classes):") + for u in r["unreached_classes"]: + ids = ", ".join(f"{h['names']} {h['id']}" for h in u["ids"]) + out.append(f" {u['class']}: {ids}") + return "\n".join(out) + "\n" + + +def summary(r: dict) -> str: + todo = [c["class"] or c["class_id"] for c in r["classes"] if c["served"] is False] + live = [c["class"] or c["class_id"] for c in r["classes"] if c["served"] is False and c["referenced_thunks"]] + ref = "?" if r["referenced_thunks"] is None else r["referenced_thunks"] + text = (f"{r['file']:<32} thunks={r['thunks']} referenced={ref} classes={len(r['classes'])} " + f"not-served={','.join(todo) or '-'} not-served-referenced={','.join(live) or '-'}") + if r["cut_off_sections"]: + text += " CUT OFF" + return text + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0]) + ap.add_argument("image", nargs="+") + ap.add_argument("--json", action="store_true", help="print JSON instead of text") + ap.add_argument("--out", help="write .gdk_calls.txt and .json here and print a summary line per image") + ap.add_argument("--table", default=DEFAULT_TABLE, help="the class table (default: %(default)s)") + ap.add_argument("--runtime-source", default=DEFAULT_RUNTIME_SOURCE, + help="the shim whose `constexpr GUID k...Class` ids count as served (default: %(default)s)") + a = ap.parse_args(argv) + + try: + table = RuntimeTable.load(a.table) + except (OSError, ValueError, KeyError, TypeError) as e: + print(f"cannot read the class table {a.table}: {e}", file=sys.stderr) + return 1 + try: + with open(a.runtime_source, encoding="utf-8", errors="replace") as f: + served = served_classes(f.read()) + except OSError as e: + print(f"warning: cannot read {a.runtime_source} ({e.strerror or e}); 'served' is unknown", file=sys.stderr) + served = None + if a.out: + if os.path.isfile(a.out): + print(f"cannot create output directory {a.out}: path is a file, not a directory", file=sys.stderr) + return 1 + try: + os.makedirs(a.out, exist_ok=True) + except OSError as e: + print(f"cannot create output directory {a.out}: {e.strerror or e}", file=sys.stderr) + return 1 + + rc = 0 + reports, used = [], set() + for path in a.image: + try: + r = report(path, table, served) + except (PeFormatError, OSError) as e: + print(f"{path}: not a readable PE image ({e})", file=sys.stderr) + rc = 1 + continue + if r["cut_off_sections"]: + print(f"{path}: the file ends inside {', '.join(r['cut_off_sections'])}; the report is incomplete", + file=sys.stderr) + rc = 1 + reports.append(r) + if not a.out: + continue + name, n = r["file"], 1 + while name.lower() in used: + n += 1 + name = f"{r['file']}-{n}" + used.add(name.lower()) + if n > 1: + print(f"{path}: another input is also named {r['file']}; report written as {name}.gdk_calls.txt/.json", + file=sys.stderr) + stem = os.path.join(a.out, name + ".gdk_calls") + try: + with open(stem + ".json", "w", encoding="utf-8", newline="\n") as f: + json.dump({"table": table.source, **r}, f, indent=1) + f.write("\n") + with open(stem + ".txt", "w", encoding="utf-8", newline="\n") as f: + f.write(to_text(r)) + except OSError as e: + print(f"{path}: cannot write report ({e.strerror or e})", file=sys.stderr) + rc = 1 + continue + print(summary(r)) + + if not a.out: + if a.json: + print(json.dumps({"table": table.source, "images": reports}, indent=1)) + else: + print(f"(class table: {table.source})") + for r in reports: + print() + print(to_text(r), end="") + return rc + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/gdk_runtime_classes.json b/tools/gdk_runtime_classes.json new file mode 100644 index 000000000..16bb0a68e --- /dev/null +++ b/tools/gdk_runtime_classes.json @@ -0,0 +1,986 @@ +{ + "classes": { + "XAccessibilityImpl": { + "id": "3e241977-6237-41e9-8559-102c2d9983f1", + "implements": [ + "IXAccessibilityImpl2" + ] + }, + "XAppCaptureImpl": { + "id": "a4f1aee2-4bf1-4485-b008-a7c26d52ac27", + "implements": [ + "IXAppCaptureImpl4" + ] + }, + "XAppCaptureMetadataImpl": { + "id": "186d5592-a72d-45fb-9560-11aed0e6647a", + "implements": [ + "IXAppCaptureMetadataImpl" + ] + }, + "XDisplayImpl": { + "id": "03f0fe74-fdd9-4e5c-b630-f9339c47acc5", + "implements": [ + "IXDisplayImpl" + ] + }, + "XErrorImpl": { + "id": "8ca467f7-22e8-4096-8456-bb8aa13f79d8", + "implements": [ + "IXErrorImpl" + ] + }, + "XGameActivationImpl": { + "id": "7f0fe8b8-e075-49ab-9aa7-a1e065489a9e", + "implements": [ + "IXGameActivationImpl" + ] + }, + "XGameEventImpl": { + "id": "bbfbdcc7-bfe7-409b-a5ca-edf054960b4d", + "implements": [ + "IXGameEventImpl" + ] + }, + "XGameImpl": { + "id": "973a344e-24bf-4d0f-8457-56c534892b29", + "implements": [ + "IXGameImpl3" + ] + }, + "XGameInviteImpl": { + "id": "0651aae2-4012-4077-bf84-8b9097090e2c", + "implements": [ + "IXGameInviteImpl2" + ] + }, + "XGameProtocolImpl": { + "id": "95fd18d2-74dd-4d7c-aa1b-0b51827665d6", + "implements": [ + "IXGameProtocolImpl" + ] + }, + "XGameRuntimeFeatureImpl": { + "id": "8836fe87-edb9-4fe3-8dad-05f0d2cd5b40", + "implements": [ + "IXGameRuntimeFeatureImpl" + ] + }, + "XGameSaveImpl": { + "id": "704c3f58-e629-4cc2-b197-30511b996fe2", + "implements": [ + "IXGameSaveImpl3" + ] + }, + "XGameStreamingImpl": { + "id": "0a2192aa-b2d5-4d58-83be-383b6d80799e", + "implements": [ + "IXGameStreamingImpl3" + ] + }, + "XGameUiImpl": { + "id": "dfcd4649-4ff8-4043-ba07-35d607df98b0", + "implements": [ + "IXGameUiImpl4" + ] + }, + "XLauncherImpl": { + "id": "1b339674-328d-4283-a200-3171f18d3639", + "implements": [ + "IXLauncherImpl" + ] + }, + "XNetworkingImpl": { + "id": "37e56907-2f10-41e8-b72f-36edb185331a", + "implements": [ + "IXNetworkingImpl2" + ] + }, + "XPackageImpl": { + "id": "af406016-e850-4aa8-a88d-2f3dcb9dac7e", + "implements": [ + "IXPackageImpl4" + ] + }, + "XPersistentLocalStorageImpl": { + "id": "f4faf4d4-2d04-4fce-b3e0-474a713a3e84", + "implements": [ + "IXPersistentLocalStorageImpl3" + ] + }, + "XStoreImpl": { + "id": "0dd112ac-7c24-448c-b92b-3960fb5bd30c", + "implements": [ + "IXStoreImpl6" + ] + }, + "XSystemAnalyticsImpl": { + "id": "b884675d-b738-4a9c-815d-9a9a1e0c6c9b", + "implements": [ + "IXSystemAnalyticsImpl" + ] + }, + "XSystemImpl": { + "id": "e349bd1a-fc20-4e40-b99c-4178cc6b409f", + "implements": [ + "IXSystemImpl5" + ] + }, + "XThreadingImpl": { + "id": "073b7dcb-1fcf-4030-94be-e3c9eb623428", + "implements": [ + "IXThreadingImpl" + ] + }, + "XUserDeviceImpl": { + "id": "7d824997-10dc-45ab-86b7-2737767c0bf1", + "implements": [ + "IXUserDeviceImpl2" + ] + }, + "XUserImpl": { + "id": "01acd177-91f9-4763-a38e-ccbb55ce32e0", + "implements": [ + "IXUserImpl6", + "IXUserGamertagImpl" + ] + } + }, + "interfaces": { + "IXAccessibilityImpl": { + "class": "XAccessibilityImpl", + "id": "3e241977-6237-41e9-8559-102c2d9983f1", + "inherits": null, + "methods": [ + "XClosedCaptionGetProperties", + "XClosedCaptionSetEnabled", + "XHighContrastGetMode", + "XSpeechToTextSetPositionHint", + "XSpeechToTextSendString", + "XSpeechSynthesizerEnumerateInstalledVoices", + "XSpeechSynthesizerCreate", + "XSpeechSynthesizerCloseHandle", + "XSpeechSynthesizerSetDefaultVoice", + "XSpeechSynthesizerSetCustomVoice", + "XSpeechSynthesizerCreateStreamFromText", + "XSpeechSynthesizerCloseStreamHandle", + "XSpeechSynthesizerGetStreamDataSize", + "XSpeechSynthesizerGetStreamData", + "XSpeechToTextBeginHypothesisString", + "XSpeechToTextUpdateHypothesisString", + "XSpeechToTextFinalizeHypothesisString", + "XSpeechToTextCancelHypothesisString", + "XSpeechSynthesizerCreateStreamFromSsml" + ] + }, + "IXAccessibilityImpl2": { + "class": "XAccessibilityImpl", + "id": "d722b373-8c4d-4692-9e51-d6ad9b37aa7d", + "inherits": "IXAccessibilityImpl", + "methods": null + }, + "IXAppCaptureImpl": { + "class": "XAppCaptureImpl", + "id": "a4f1aee2-4bf1-4485-b008-a7c26d52ac27", + "inherits": null, + "methods": [ + "XAppCaptureTakeDiagnosticScreenshot", + "XAppCaptureRecordDiagnosticClip", + "XAppCaptureTakeScreenshot", + "XAppCaptureOpenScreenshotStream", + "XAppCaptureReadScreenshotStream", + "XAppCaptureCloseScreenshotStream", + "XAppCaptureEnableRecord", + "XAppCaptureDisableRecord" + ] + }, + "IXAppCaptureImpl2": { + "class": "XAppCaptureImpl", + "id": "3a949778-772e-4799-bdea-0a6639e96baa", + "inherits": "IXAppCaptureImpl", + "methods": [ + "XAppCaptureGetVideoCaptureSettings", + "XAppCaptureRecordTimespan", + "XAppCaptureReadLocalStream", + "XAppCaptureCloseLocalStream" + ] + }, + "IXAppCaptureImpl3": { + "class": "XAppCaptureImpl", + "id": "2bbca60a-619c-4fe1-812e-fb5c1dbdcf51", + "inherits": "IXAppCaptureImpl2", + "methods": [ + "XAppCaptureStartUserRecord", + "XAppCaptureStopUserRecord" + ] + }, + "IXAppCaptureImpl4": { + "class": "XAppCaptureImpl", + "id": "22e672d7-b4e3-406c-bd50-8f0d25236f9e", + "inherits": "IXAppCaptureImpl3", + "methods": [ + "XAppCaptureCancelUserRecord" + ] + }, + "IXAppCaptureMetadataImpl": { + "class": "XAppCaptureMetadataImpl", + "id": "186d5592-a72d-45fb-9560-11aed0e6647a", + "inherits": null, + "methods": [ + "XAppBroadcastIsAppBroadcasting", + "XAppBroadcastShowUI", + "XAppBroadcastGetStatus", + "XAppBroadcastRegisterIsAppBroadcastingChanged", + "XAppBroadcastUnregisterIsAppBroadcastingChanged", + "XAppCaptureMetadataAddStringEvent", + "XAppCaptureMetadataAddInt32Event", + "XAppCaptureMetadataAddDoubleEvent", + "XAppCaptureMetadataStartStringState", + "XAppCaptureMetadataStartInt32State", + "XAppCaptureMetadataStartDoubleState", + "XAppCaptureMetadataStopState", + "XAppCaptureMetadataStopAllStates", + "XAppCaptureMetadataRemainingStorageBytesAvailable", + "XAppCaptureRegisterMetadataPurged", + "XAppCaptureUnRegisterMetadataPurged" + ] + }, + "IXDisplayImpl": { + "class": "XDisplayImpl", + "id": "35f07670-706e-4bfb-9476-090798c5ebf3", + "inherits": null, + "methods": [ + null, + "XDisplayTryEnableHdrMode" + ] + }, + "IXErrorImpl": { + "class": "XErrorImpl", + "id": "8ca467f7-22e8-4096-8456-bb8aa13f79d8", + "inherits": null, + "methods": [ + null, + "XErrorSetCallback", + "XErrorSetOptions" + ] + }, + "IXGameActivationImpl": { + "class": "XGameActivationImpl", + "id": "2e4f76fe-0fc7-461e-ab4d-a4499434c3cf", + "inherits": null, + "methods": [ + "XGameActivationRegisterForEvent", + "XGameActivationUnregisterForEvent", + "XGameActivationAcceptPendingInvite" + ] + }, + "IXGameEventImpl": { + "class": "XGameEventImpl", + "id": "bbfbdcc7-bfe7-409b-a5ca-edf054960b4d", + "inherits": null, + "methods": [ + "XGameEventWrite" + ] + }, + "IXGameImpl": { + "class": "XGameImpl", + "id": "973a344e-24bf-4d0f-8457-56c534892b29", + "inherits": null, + "methods": [ + "XGameGetXboxTitleId" + ] + }, + "IXGameImpl2": { + "class": "XGameImpl", + "id": "50849859-0ad8-4f81-80e4-5bc78626f852", + "inherits": "IXGameImpl", + "methods": [ + "XLaunchNewGame" + ] + }, + "IXGameImpl3": { + "class": "XGameImpl", + "id": "2549f142-6419-4a06-97b5-931aab7c2f34", + "inherits": "IXGameImpl2", + "methods": [ + "XLaunchRestartOnCrash" + ] + }, + "IXGameInviteImpl": { + "class": "XGameInviteImpl", + "id": "0651aae2-4012-4077-bf84-8b9097090e2c", + "inherits": null, + "methods": [ + "XGameInviteRegisterForEvent", + "XGameInviteUnregisterForEvent" + ] + }, + "IXGameInviteImpl2": { + "class": "XGameInviteImpl", + "id": "014d1cc3-bcfe-41ff-b2f0-e1ef07155828", + "inherits": "IXGameInviteImpl", + "methods": [ + "XGameInviteRegisterForPendingEvent", + "XGameInviteUnregisterForPendingEvent", + "XGameInviteAcceptPendingInvite" + ] + }, + "IXGameProtocolImpl": { + "class": "XGameProtocolImpl", + "id": "026b010c-06c3-4cdd-bbcb-43f229db1cff", + "inherits": null, + "methods": [ + "XGameProtocolRegisterForActivation", + "XGameProtocolUnregisterForActivation" + ] + }, + "IXGameRuntimeFeatureImpl": { + "class": "XGameRuntimeFeatureImpl", + "id": "8836fe87-edb9-4fe3-8dad-05f0d2cd5b40", + "inherits": null, + "methods": [ + "XGameRuntimeIsFeatureAvailable" + ] + }, + "IXGameSaveImpl": { + "class": "XGameSaveImpl", + "id": "704c3f58-e629-4cc2-b197-30511b996fe2", + "inherits": null, + "methods": [ + "XGameSaveInitializeProvider", + "XGameSaveInitializeProviderAsync", + "XGameSaveInitializeProviderResult", + "XGameSaveCloseProvider", + "XGameSaveGetRemainingQuota", + "XGameSaveGetRemainingQuotaAsync", + "XGameSaveGetRemainingQuotaResult", + "XGameSaveDeleteContainer", + "XGameSaveDeleteContainerAsync", + "XGameSaveDeleteContainerResult", + "XGameSaveGetContainerInfo", + "XGameSaveEnumerateContainerInfo", + "XGameSaveEnumerateContainerInfoByName", + "XGameSaveCreateContainer", + "XGameSaveCloseContainer", + "XGameSaveEnumerateBlobInfo", + "XGameSaveEnumerateBlobInfoByName", + "XGameSaveReadBlobData", + "XGameSaveReadBlobDataAsync", + "XGameSaveReadBlobDataResult", + "XGameSaveCreateUpdate", + "XGameSaveCloseUpdate", + "XGameSaveSubmitBlobWrite", + "XGameSaveSubmitBlobDelete", + "XGameSaveSubmitUpdate", + "XGameSaveSubmitUpdateAsync", + "XGameSaveSubmitUpdateResult" + ] + }, + "IXGameSaveImpl2": { + "class": "XGameSaveImpl", + "id": "704c3f58-e629-4cc2-b197-30511b996ee2", + "inherits": "IXGameSaveImpl", + "methods": [ + "XGameSaveFilesGetFolderWithUiAsync", + "XGameSaveFilesGetFolderWithUiResult", + "XGameSaveFilesGetRemainingQuota" + ] + }, + "IXGameSaveImpl3": { + "class": "XGameSaveImpl", + "id": "1bfff3af-f14a-40a3-8e35-9ada906593f9", + "inherits": "IXGameSaveImpl2", + "methods": null + }, + "IXGameStreamingImpl": { + "class": "XGameStreamingImpl", + "id": "8aff07f5-a1bf-4db8-80a5-31cca0de51b7", + "inherits": null, + "methods": [ + "XGameStreamingInitialize", + "XGameStreamingUninitialize", + "XGameStreamingIsStreaming", + "XGameStreamingRegisterClientPropertiesChanged", + "XGameStreamingUnregisterClientPropertiesChanged", + "XGameStreamingGetStreamPhysicalDimensions", + "XGameStreamingGetClientCount", + "XGameStreamingGetClients", + "XGameStreamingGetConnectionState", + "XGameStreamingRegisterConnectionStateChanged", + "XGameStreamingUnregisterConnectionStateChanged", + "XGameStreamingGetStreamAddedLatency", + "XGameStreamingGetServerLocationNameSize", + "XGameStreamingGetServerLocationName", + "XGameStreamingHideTouchControls", + "XGameStreamingShowTouchControlLayout", + "XGameStreamingHideTouchControlsOnClient", + "XGameStreamingShowTouchControlLayoutOnClient", + "XGameStreamingIsTouchInputEnabled", + "XGameStreamingGetLastFrameDisplayed", + "XGameStreamingGetAssociatedFrame", + "XGameStreamingGetGamepadPhysicality", + "XGameStreamingUpdateTouchControlsState", + "XGameStreamingUpdateTouchControlsStateOnClient", + "XGameStreamingShowTouchControlsWithStateUpdate", + "XGameStreamingShowTouchControlsWithStateUpdateOnClient", + "XGameStreamingGetTouchBundleVersionNameSize", + "XGameStreamingGetTouchBundleVersion", + "XGameStreamingGetClientIPAddress" + ] + }, + "IXGameStreamingImpl2": { + "class": "XGameStreamingImpl", + "id": "5f5e5169-746c-4001-ad1c-da728d01c9eb", + "inherits": "IXGameStreamingImpl", + "methods": [ + "XGameStreamingGetSessionId" + ] + }, + "IXGameStreamingImpl3": { + "class": "XGameStreamingImpl", + "id": "57786622-6605-46d0-b917-0f22bbcd9c52", + "inherits": "IXGameStreamingImpl2", + "methods": [ + "XGameStreamingGetDisplayDetails", + "XGameStreamingSetResolution" + ] + }, + "IXGameUiImpl": { + "class": "XGameUiImpl", + "id": "6eeaa73e-9669-43ad-a2c7-d0da4e1f50a1", + "inherits": null, + "methods": [ + "XGameUiShowMessageDialogAsync", + "XGameUiShowMessageDialogResult", + "XGameUiShowSendGameInviteAsync", + "XGameUiShowSendGameInviteResult", + "XGameUiShowPlayerProfileCardAsync", + "XGameUiShowPlayerProfileCardResult", + "XGameUiShowAchievementsAsync", + "XGameUiShowAchievementsResult", + "XGameUiShowPlayerPickerAsync", + "XGameUiShowPlayerPickerResultCount", + "XGameUiShowPlayerPickerResult", + "XGameUiShowErrorDialogAsync", + "XGameUiShowErrorDialogResult", + "XGameUiSetNotificationPositionHint", + "XGameUiShowTextEntryAsync", + "XGameUiShowTextEntryResultSize", + "XGameUiShowTextEntryResult", + null, + null, + null, + null, + "XGameUiShowWebAuthenticationAsync", + "XGameUiShowWebAuthenticationResultSize", + "XGameUiShowWebAuthenticationResult", + "XGameUiShowWebAuthenticationWithOptionsAsync", + null, + null + ] + }, + "IXGameUiImpl2": { + "class": "XGameUiImpl", + "id": "36a03122-9ea3-4a3a-a8a4-899cfd85d7db", + "inherits": "IXGameUiImpl", + "methods": [ + "XGameUiShowMultiplayerActivityGameInviteAsync", + "XGameUiShowMultiplayerActivityGameInviteResult", + null, + null, + "XGameUiTextEntryOpen", + "XGameUiTextEntryClose", + "XGameUiTextEntryGetState", + "XGameUiTextEntryGetExtents", + "XGameUiTextEntryUpdatePositionHint", + "XGameUiTextEntryUpdateVisibility" + ] + }, + "IXGameUiImpl3": { + "class": "XGameUiImpl", + "id": "ade7eba1-2093-42ce-a544-a523a66790e0", + "inherits": "IXGameUiImpl2", + "methods": [ + "XGameUiShowStateShareAsync", + "XGameUiShowStateShareResult" + ] + }, + "IXGameUiImpl4": { + "class": "XGameUiImpl", + "id": "eaf669df-5542-4590-99a3-8dc061f837cc", + "inherits": "IXGameUiImpl3", + "methods": [ + "XGameUiSetUiCallbacks", + "XGameUiSetMessageDialogUiResponse", + "XGameUiSetPlayerPickerUiResponse", + "XGameUiSetTextEntryUiResponse", + "XGameUiSetPlayerProfileCardUiResponse", + "XGameUiSetSendGameInviteUiResponse", + "XGameUiSetAchievementsUiResponse", + "XGameUiSetMultiplayerActivityGameInviteUiResponse", + "XGameUiSetErrorDialogUiResponse" + ] + }, + "IXLauncherImpl": { + "class": "XLauncherImpl", + "id": "1b339674-328d-4283-a200-3171f18d3639", + "inherits": null, + "methods": [ + "XLaunchUri", + "XDisplayAcquireTimeoutDeferral", + "XDisplayCloseTimeoutDeferralHandle" + ] + }, + "IXNetworkingImpl": { + "class": "XNetworkingImpl", + "id": "37e56907-2f10-41e8-b72f-36edb185331a", + "inherits": null, + "methods": [ + "XNetworkingQueryPreferredLocalUdpMultiplayerPort", + "XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync", + "XNetworkingQueryPreferredLocalUdpMultiplayerPortAsyncResult", + "XNetworkingRegisterPreferredLocalUdpMultiplayerPortChanged", + "XNetworkingUnregisterPreferredLocalUdpMultiplayerPortChanged", + "XNetworkingQuerySecurityInformationForUrlAsync", + "XNetworkingQuerySecurityInformationForUrlAsyncResultSize", + "XNetworkingQuerySecurityInformationForUrlAsyncResult", + "XNetworkingQuerySecurityInformationForUrlUtf16Async", + "XNetworkingQuerySecurityInformationForUrlUtf16AsyncResultSize", + "XNetworkingQuerySecurityInformationForUrlUtf16AsyncResult", + "XNetworkingVerifyServerCertificate", + "XNetworkingGetConnectivityHint", + "XNetworkingRegisterConnectivityHintChanged", + "XNetworkingUnregisterConnectivityHintChanged" + ] + }, + "IXNetworkingImpl2": { + "class": "XNetworkingImpl", + "id": "bf2346b2-39af-4658-b5ea-44713c7e83b3", + "inherits": "IXNetworkingImpl", + "methods": [ + "XNetworkingQueryConfigurationSetting", + "XNetworkingSetConfigurationSetting", + "XNetworkingQueryStatistics" + ] + }, + "IXPackageImpl": { + "class": "XPackageImpl", + "id": "3720de07-e8e4-44a3-ad32-b359e8adbe55", + "inherits": null, + "methods": [ + "XPackageGetCurrentProcessPackageIdentifier", + "XPackageIsPackagedProcess", + "XPackageCreateInstallationMonitor", + "XPackageCloseInstallationMonitorHandle", + "XPackageGetInstallationProgress", + "XPackageUpdateInstallationMonitor", + "XPackageRegisterInstallationProgressChanged", + "XPackageUnregisterInstallationProgressChanged", + "XPackageGetUserLocale", + "XPackageFindChunkAvailability", + "XPackageEnumerateChunkAvailability", + "XPackageChangeChunkInstallOrder", + "XPackageInstallChunks", + "XPackageInstallChunksAsync", + "XPackageInstallChunksResult", + "XPackageEstimateDownloadSize", + "XPackageUninstallChunks", + null, + null, + "XPackageUnregisterPackageInstalled", + "XPackageMount", + "XPackageGetMountPathSize", + "XPackageGetMountPath", + "XPackageCloseMountHandle", + null, + "XPackageEnumeratePackages", + "XPackageRegisterPackageInstalled", + "XPackageGetWriteStats", + null, + "XPackageUninstallUWPInstance", + "XPackageEnumerateFeatures", + "XPackageUninstallPackage" + ] + }, + "IXPackageImpl2": { + "class": "XPackageImpl", + "id": "f92d8712-2b27-4d8a-bf01-11a6f8e3eb42", + "inherits": "IXPackageImpl", + "methods": [ + "XPackageEnumeratePackages", + "XPackageRegisterPackageInstalled", + "XPackageMountWithUiAsync", + "XPackageMountWithUiResult" + ] + }, + "IXPackageImpl3": { + "class": "XPackageImpl", + "id": "e2a4734b-2f4a-456d-aa8f-d065e04fb209", + "inherits": "IXPackageImpl2", + "methods": [ + "XPackageEnumeratePackages", + "XPackageRegisterPackageInstalled" + ] + }, + "IXPackageImpl4": { + "class": "XPackageImpl", + "id": "0b9d556e-ab70-43f4-baa0-9999ac4cb040", + "inherits": "IXPackageImpl3", + "methods": [ + "XPackageGetPackageKind" + ] + }, + "IXPersistentLocalStorageImpl": { + "class": "XPersistentLocalStorageImpl", + "id": "f4faf4d4-2d04-4fce-b3e0-474a713a3e84", + "inherits": null, + "methods": [ + "XPersistentLocalStorageGetPathSize", + "XPersistentLocalStorageGetPath", + "XPersistentLocalStorageGetSpaceInfo", + "XPersistentLocalStoragePromptUserForSpaceAsync", + "XPersistentLocalStoragePromptUserForSpaceResult" + ] + }, + "IXPersistentLocalStorageImpl2": { + "class": "XPersistentLocalStorageImpl", + "id": "d29411df-0794-4553-8b27-95fc02d0f75d", + "inherits": "IXPersistentLocalStorageImpl", + "methods": null + }, + "IXPersistentLocalStorageImpl3": { + "class": "XPersistentLocalStorageImpl", + "id": "41a4e10c-5a7e-41d9-8c37-37bde62a07d6", + "inherits": "IXPersistentLocalStorageImpl2", + "methods": [ + "XPersistentLocalStorageMountForPackage" + ] + }, + "IXStoreImpl": { + "class": "XStoreImpl", + "id": "0dd112ac-7c24-448c-b92b-3960fb5bd30c", + "inherits": null, + "methods": [ + "XStoreCreateContext", + "XStoreCloseContextHandle", + "XStoreQueryAssociatedProductsAsync", + "XStoreQueryAssociatedProductsResult", + "XStoreQueryProductsAsync", + "XStoreQueryProductsResult", + "XStoreQueryEntitledProductsAsync", + "XStoreQueryEntitledProductsResult", + "XStoreQueryProductForCurrentGameAsync", + "XStoreQueryProductForCurrentGameResult", + "XStoreQueryProductForPackageAsync", + "XStoreQueryProductForPackageResult", + "XStoreEnumerateProductsQuery", + "XStoreProductsQueryHasMorePages", + "XStoreProductsQueryNextPageAsync", + "XStoreProductsQueryNextPageResult", + "XStoreCloseProductsQueryHandle", + "XStoreAcquireLicenseForPackageAsync", + "XStoreAcquireLicenseForPackageResult", + "XStoreIsLicenseValid", + "XStoreCloseLicenseHandle", + "XStoreCanAcquireLicenseForStoreIdAsync", + "XStoreCanAcquireLicenseForStoreIdResult", + "XStoreCanAcquireLicenseForPackageAsync", + "XStoreCanAcquireLicenseForPackageResult", + "XStoreQueryGameLicenseAsync", + "XStoreQueryGameLicenseResult", + "XStoreQueryAddOnLicensesAsync", + "XStoreQueryAddOnLicensesResultCount", + "XStoreQueryAddOnLicensesResult", + "XStoreQueryConsumableBalanceRemainingAsync", + "XStoreQueryConsumableBalanceRemainingResult", + "XStoreReportConsumableFulfillmentAsync", + "XStoreReportConsumableFulfillmentResult", + "XStoreGetUserCollectionsIdAsync", + "XStoreGetUserCollectionsIdResultSize", + "XStoreGetUserCollectionsIdResult", + "XStoreGetUserPurchaseIdAsync", + "XStoreGetUserPurchaseIdResultSize", + "XStoreGetUserPurchaseIdResult", + "XStoreQueryLicenseTokenAsync", + "XStoreQueryLicenseTokenResultSize", + "XStoreQueryLicenseTokenResult", + null, + null, + null, + "XStoreShowPurchaseUIAsync", + "XStoreShowPurchaseUIResult", + "XStoreShowRateAndReviewUIAsync", + "XStoreShowRateAndReviewUIResult", + "XStoreShowRedeemTokenUIAsync", + "XStoreShowRedeemTokenUIResult", + "XStoreQueryGameAndDlcPackageUpdatesAsync", + "XStoreQueryGameAndDlcPackageUpdatesResultCount", + "XStoreQueryGameAndDlcPackageUpdatesResult", + "XStoreDownloadPackageUpdatesAsync", + "XStoreDownloadPackageUpdatesResult", + "XStoreDownloadAndInstallPackageUpdatesAsync", + "XStoreDownloadAndInstallPackageUpdatesResult", + "XStoreDownloadAndInstallPackagesAsync", + "XStoreDownloadAndInstallPackagesResultCount", + "XStoreDownloadAndInstallPackagesResult", + "XStoreQueryPackageIdentifier", + "XStoreRegisterGameLicenseChanged", + "XStoreUnregisterGameLicenseChanged", + "XStoreRegisterPackageLicenseLost", + "XStoreUnregisterPackageLicenseLost" + ] + }, + "IXStoreImpl2": { + "class": "XStoreImpl", + "id": "60b09f4e-1b85-45b1-826c-169118e230e1", + "inherits": "IXStoreImpl", + "methods": [ + "XStoreIsAvailabilityPurchasable" + ] + }, + "IXStoreImpl3": { + "class": "XStoreImpl", + "id": "2d42fea5-e71d-4b76-97cd-c50afbb3ae5d", + "inherits": "IXStoreImpl2", + "methods": [ + "XStoreAcquireLicenseForDurablesAsync", + "XStoreAcquireLicenseForDurablesResult" + ] + }, + "IXStoreImpl4": { + "class": "XStoreImpl", + "id": "de3dbdd4-0b37-4bdb-a10e-acf3a354d06a", + "inherits": "IXStoreImpl3", + "methods": [ + "XStoreShowAssociatedProductsUIAsync", + "XStoreShowAssociatedProductsUIResult", + "XStoreShowProductPageUIAsync", + "XStoreShowProductPageUIResult" + ] + }, + "IXStoreImpl5": { + "class": "XStoreImpl", + "id": "5c48dedf-0b67-4492-a4b5-6829b8e796e1", + "inherits": "IXStoreImpl4", + "methods": [ + "XStoreQueryAssociatedProductsForStoreIdAsync", + "XStoreQueryAssociatedProductsForStoreIdResult", + "XStoreQueryPackageUpdatesAsync", + "XStoreQueryPackageUpdatesResultCount", + "XStoreQueryPackageUpdatesResult" + ] + }, + "IXStoreImpl6": { + "class": "XStoreImpl", + "id": "b09d803c-2414-4a05-82c6-66dfdc9e9a44", + "inherits": "IXStoreImpl5", + "methods": [ + "XStoreShowGiftingUIAsync", + "XStoreShowGiftingUIResult" + ] + }, + "IXSystemAnalyticsImpl": { + "class": "XSystemAnalyticsImpl", + "id": "b884675d-b738-4a9c-815d-9a9a1e0c6c9b", + "inherits": null, + "methods": [ + "XSystemGetAnalyticsInfo" + ] + }, + "IXSystemImpl": { + "class": "XSystemImpl", + "id": "e349bd1a-fc20-4e40-b99c-4178cc6b409f", + "inherits": null, + "methods": [ + "XSystemGetConsoleId", + "XSystemGetXboxLiveSandboxId", + "XSystemGetAppSpecificDeviceId" + ] + }, + "IXSystemImpl2": { + "class": "XSystemImpl", + "id": "6fd71f09-7513-49f0-89bc-bfaf5df6f852", + "inherits": "IXSystemImpl", + "methods": null + }, + "IXSystemImpl3": { + "class": "XSystemImpl", + "id": "67ce4bfc-b1d1-4ac7-bc3a-cb9219a97a85", + "inherits": "IXSystemImpl2", + "methods": [ + "XSystemHandleTrack", + "XSystemIsHandleValid" + ] + }, + "IXSystemImpl4": { + "class": "XSystemImpl", + "id": "dadc2895-34b0-4ef5-a83e-45114d629b80", + "inherits": "IXSystemImpl3", + "methods": [ + "XSystemAllowFullDownloadBandwidth" + ] + }, + "IXSystemImpl5": { + "class": "XSystemImpl", + "id": "1861cf2e-e18b-4834-a9f5-b4a4e6efb4cf", + "inherits": "IXSystemImpl4", + "methods": null + }, + "IXThreadingImpl": { + "class": "XThreadingImpl", + "id": "073b7dcb-1fcf-4030-94be-e3c9eb623428", + "inherits": null, + "methods": [ + "XAsyncGetStatus", + "XAsyncGetResultSize", + "XAsyncCancel", + "XAsyncRun", + "XAsyncBegin", + "XAsyncBeginAlloc", + "XAsyncSchedule", + "XAsyncComplete", + "XAsyncGetResult", + "XTaskQueueCreate", + "XTaskQueueCreateComposite", + "XTaskQueueGetPort", + "XTaskQueueDuplicateHandle", + "XTaskQueueDispatch", + "XTaskQueueCloseHandle", + "XTaskQueueSubmitCallback", + "XTaskQueueSubmitDelayedCallback", + "XTaskQueueRegisterWaiter", + "XTaskQueueUnregisterWaiter", + "XTaskQueueTerminate", + "XTaskQueueRegisterMonitor", + "XTaskQueueUnregisterMonitor", + "XTaskQueueGetCurrentProcessTaskQueue", + "XTaskQueueSetCurrentProcessTaskQueue", + "XThreadSetTimeSensitive", + "XTaskQueueIsEmpty", + "XThreadAssertNotTimeSensitive", + "XThreadIsTimeSensitive" + ] + }, + "IXUserDeviceImpl": { + "class": "XUserDeviceImpl", + "id": "7d824997-10dc-45ab-86b7-2737767c0bf1", + "inherits": null, + "methods": [ + "XUserFindForDevice", + "XUserRegisterForDeviceAssociationChanged", + "XUserUnregisterForDeviceAssociationChanged", + "XUserGetDefaultAudioEndpointUtf16", + "XUserRegisterForDefaultAudioEndpointUtf16Changed", + "XUserUnregisterForDefaultAudioEndpointUtf16Changed", + "XUserFindControllerForUserWithUiAsync", + "XUserFindControllerForUserWithUiResult" + ] + }, + "IXUserDeviceImpl2": { + "class": "XUserDeviceImpl", + "id": "0cc6a956-e7e1-4fdf-9341-9d5da649ebc8", + "inherits": "IXUserDeviceImpl", + "methods": null + }, + "IXUserGamertagImpl": { + "class": "XUserImpl", + "id": "cef4fac0-7676-4a94-a119-4c43f9eb5b74", + "inherits": null, + "methods": [ + "XUserGetGamertag" + ] + }, + "IXUserImpl": { + "class": "XUserImpl", + "id": "01acd177-91f9-4763-a38e-ccbb55ce32e0", + "inherits": null, + "methods": [ + "XUserDuplicateHandle", + "XUserCloseHandle", + "XUserCompare", + "XUserGetMaxUsers", + "XUserAddAsync", + "XUserAddResult", + "XUserGetLocalId", + "XUserFindUserByLocalId", + "XUserGetId", + "XUserFindUserById", + "XUserGetIsGuest", + "XUserGetState", + null, + "XUserGetGamerPictureAsync", + "XUserGetGamerPictureResultSize", + "XUserGetGamerPictureResult", + "XUserGetAgeGroup", + "XUserCheckPrivilege", + "XUserResolvePrivilegeWithUiAsync", + "XUserResolvePrivilegeWithUiResult", + "XUserGetTokenAndSignatureAsync", + "XUserGetTokenAndSignatureResultSize", + "XUserGetTokenAndSignatureResult", + "XUserGetTokenAndSignatureUtf16Async", + "XUserGetTokenAndSignatureUtf16ResultSize", + "XUserGetTokenAndSignatureUtf16Result", + "XUserResolveIssueWithUiAsync", + "XUserResolveIssueWithUiResult", + "XUserResolveIssueWithUiUtf16Async", + "XUserResolveIssueWithUiUtf16Result", + "XUserRegisterForChangeEvent", + "XUserUnregisterForChangeEvent", + "XUserGetSignOutDeferral", + "XUserCloseSignOutDeferralHandle" + ] + }, + "IXUserImpl2": { + "class": "XUserImpl", + "id": "eb9bf948-18dc-4d82-bbcc-40e0a809c4c0", + "inherits": "IXUserImpl", + "methods": [ + "XUserAddByIdWithUiAsync", + "XUserAddByIdWithUiResult" + ] + }, + "IXUserImpl3": { + "class": "XUserImpl", + "id": "1bf2f8c5-d507-4e52-bb05-f726d0e71161", + "inherits": "IXUserImpl2", + "methods": [ + "XUserGetMsaTokenSilentlyAsync", + "XUserGetMsaTokenSilentlyResult", + "XUserGetMsaTokenSilentlyResultSize" + ] + }, + "IXUserImpl4": { + "class": "XUserImpl", + "id": "079415e3-6727-437f-8e9d-8f8f9b2439f7", + "inherits": "IXUserImpl3", + "methods": [ + "XUserIsStoreUser" + ] + }, + "IXUserImpl5": { + "class": "XUserImpl", + "id": "26f3c674-a2fe-44fa-b6c4-a323bc94ff53", + "inherits": "IXUserImpl4", + "methods": [ + "XUserPlatformRemoteConnectSetEventHandlers", + "XUserPlatformRemoteConnectCancelPrompt", + "XUserPlatformSpopPromptSetEventHandlers", + "XUserPlatformSpopPromptComplete" + ] + }, + "IXUserImpl6": { + "class": "XUserImpl", + "id": "5131d685-4394-4ee6-8c18-bfb5d4aef1ff", + "inherits": "IXUserImpl5", + "methods": [ + "XUserIsSignOutPresent", + "XUserSignOutAsync", + "XUserSignOutResult" + ] + } + }, + "licence": "The source is GPL-3.0. Facts only: ids, inheritance and method order; no text is copied.", + "note": "The runtime classes QueryApiImpl hands out. An interface's vtable is IUnknown's three slots, then the methods of its inheritance chain, base first. A null method is one the docs list as unknown; null 'methods' means the docs give no layout for that interface (its methods, if any, are listed under its base). Made by tools/gen_gdk_runtime_classes.py.", + "source": "https://github.com/xodus-gaming/xgameruntime-docs at 7090008692569aa6081e30dfdd9de58237741e24" +} diff --git a/tools/gen_gdk_runtime_classes.py b/tools/gen_gdk_runtime_classes.py new file mode 100644 index 000000000..83ddefe0c --- /dev/null +++ b/tools/gen_gdk_runtime_classes.py @@ -0,0 +1,148 @@ +"""Build tools/gdk_runtime_classes.json from a clone of xodus-gaming/xgameruntime-docs. + +Usage: + python -I tools/gen_gdk_runtime_classes.py [--out FILE] + +The docs (GPL-3.0) describe the COM classes the GDK runtime's QueryApiImpl hands out: one folder per class under +COM/, a README.md with the class id and the interfaces it implements, and one page per interface with its id, the +interface it inherits from and its "Layout" (the method order after IUnknown's three slots). This keeps the facts +only: ids, inheritance and method names in order. No text is copied. + +- A method the docs list as *unknown* stays in the list as null, so the methods after it keep their slot. +- An interface whose page has no "Layout" ("Layout changes unknown, all methods listed under ...", "No known + methods") gets "methods": null; its own methods, if any, are in its base's list. +- A class can implement more than one interface with its own vtable (XUserImpl: IXUserImpl6 and + IXUserGamertagImpl); each interface lists its own chain, so each starts at slot 3. + +tools/gdk_runtime_calls.py reads the output. Standard library only. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys + +ID = re.compile(r"(?:Interface|Class) Id: `([0-9a-fA-F-]{36})`") +INHERITS = re.compile(r"Inherits: (?:\[(I\w+)\]|IUnknown\b)") +LINKED_INTERFACE = re.compile(r"\[(I\w+)\]\(\w+\.md\)") +METHOD = re.compile(r"\[(\w+)\]|(\w+)") + + +def read_utf8(path: str) -> str: + with open(path, encoding="utf-8") as f: + return f.read() + + +def parse_layout(text: str) -> list[str | None] | None: + """The method names of a "Layout:" list in order (None for an *unknown* entry), or None without a list.""" + if "Layout:" not in text: + return None + methods: list[str | None] = [] + for line in text.split("Layout:", 1)[1].splitlines(): + line = line.strip() + if not line.startswith("- "): + if methods and line: + break # the paragraph after the list + continue + item = line[2:].strip() + m = METHOD.match(item) + methods.append(None if item.startswith("*unknown*") or not m else (m.group(1) or m.group(2))) + return methods + + +def parse_docs(root: str) -> tuple[dict, dict]: + com = os.path.join(root, "COM") + if not os.path.isdir(com): + raise FileNotFoundError(f"{root} has no COM folder; is it a clone of xgameruntime-docs?") + classes, interfaces = {}, {} + for cls in sorted(os.listdir(com)): + folder = os.path.join(com, cls) + if not os.path.isdir(folder): + continue + for name in sorted(os.listdir(folder)): + if not name.endswith(".md"): + continue + text = read_utf8(os.path.join(folder, name)) + m = ID.search(text) + if not m: + continue + guid = m.group(1).lower() + if name == "README.md": + implements = text.split("Implements:", 1)[1].splitlines()[0] if "Implements:" in text else "" + classes[cls] = {"id": guid, "implements": LINKED_INTERFACE.findall(implements)} + continue + inherits = INHERITS.search(text) + interfaces[name[:-3]] = { + "id": guid, + "class": cls, + "inherits": inherits.group(1) if inherits and inherits.group(1) else None, + "methods": parse_layout(text), + } + return classes, interfaces + + +def check(classes: dict, interfaces: dict) -> list[str]: + """Links the docs make that the table cannot follow.""" + problems = [] + for name, cls in classes.items(): + for iface in cls["implements"]: + if iface not in interfaces: + problems.append(f"{name} implements {iface}, which has no page") + for name, iface in interfaces.items(): + if iface["inherits"] and iface["inherits"] not in interfaces: + problems.append(f"{name} inherits {iface['inherits']}, which has no page") + return problems + + +def revision(root: str) -> str: + try: + out = subprocess.run(["git", "-C", root, "rev-parse", "HEAD"], capture_output=True, text=True, check=True) + return out.stdout.strip() or "unknown revision" + except (OSError, subprocess.CalledProcessError): + return "unknown revision" + + +def build(root: str) -> dict: + classes, interfaces = parse_docs(root) + return { + "source": f"https://github.com/xodus-gaming/xgameruntime-docs at {revision(root)}", + "licence": "The source is GPL-3.0. Facts only: ids, inheritance and method order; no text is copied.", + "note": ("The runtime classes QueryApiImpl hands out. An interface's vtable is IUnknown's three slots, then " + "the methods of its inheritance chain, base first. A null method is one the docs list as unknown; " + "null 'methods' means the docs give no layout for that interface (its methods, if any, are listed " + "under its base). Made by tools/gen_gdk_runtime_classes.py."), + "classes": classes, + "interfaces": interfaces, + } + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0]) + ap.add_argument("docs", help="a clone of xodus-gaming/xgameruntime-docs") + ap.add_argument("--out", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), + "gdk_runtime_classes.json")) + a = ap.parse_args(argv) + try: + table = build(a.docs) + except OSError as e: + print(f"cannot read the docs: {e}", file=sys.stderr) + return 1 + problems = check(table["classes"], table["interfaces"]) + for p in problems: + print(f"warning: {p}", file=sys.stderr) + with open(a.out, "w", encoding="utf-8", newline="\n") as f: + json.dump(table, f, indent=1, sort_keys=True) + f.write("\n") + print(f"{len(table['classes'])} classes, {len(table['interfaces'])} interfaces -> {a.out}") + return 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/glb_inspect.py b/tools/glb_inspect.py index 1485270aa..880fa4451 100644 --- a/tools/glb_inspect.py +++ b/tools/glb_inspect.py @@ -75,6 +75,16 @@ def _count(gltf: dict, key: str) -> int: return len(_array(gltf.get(key))) +ARRAY_FIELDS = ("scenes", "nodes", "meshes", "materials", "images", "skins", + "animations", "accessors") + + +def _invalid_types(gltf: dict) -> dict[str, str]: + """Known array fields that are present but hold a non-array value.""" + return {key: type(gltf[key]).__name__ for key in ARRAY_FIELDS + if key in gltf and not isinstance(gltf[key], list)} + + def _entry(gltf: dict, key: str, index: object) -> dict | None: """The object at ``gltf[key][index]``, or None for a missing/invalid index.""" if not _is_int(index) or index < 0: @@ -210,7 +220,10 @@ def _accessor_max(accessor: dict | None) -> float | None: upper = accessor.get("max") if (isinstance(upper, list) and upper and isinstance(upper[0], (int, float)) and not isinstance(upper[0], bool)): - return float(upper[0]) + try: + return float(upper[0]) + except (OverflowError, ValueError): + return None # an integer too large to be a float has no usable bound return None @@ -221,16 +234,22 @@ def _accessor_type(gltf: dict, index: object) -> str | None: def _animation_report(gltf: dict, index: int, animation: dict) -> dict: """Summarize an animation and flag references that cannot be resolved.""" - raw_samplers = _array(animation.get("samplers")) - raw_channels = _array(animation.get("channels")) issues: list[str] = [] + raw_samplers_value = animation.get("samplers") + if raw_samplers_value is not None and not isinstance(raw_samplers_value, list): + issues.append("animation samplers is not an array") + raw_samplers = _array(raw_samplers_value) + raw_channels_value = animation.get("channels") + if raw_channels_value is not None and not isinstance(raw_channels_value, list): + issues.append("animation channels is not an array") + raw_channels = _array(raw_channels_value) samplers: list[dict] = [] for sampler_index, sampler in enumerate(raw_samplers): if not isinstance(sampler, dict): issues.append(f"sampler[{sampler_index}] is not an object") samplers.append({"index": sampler_index, "input_accessor": None, "input_count": None, "output_accessor": None, "output_count": None, - "interpolation": None, "duration": None}) + "output_type": None, "interpolation": None, "duration": None}) continue input_index = _index(sampler.get("input")) output_index = _index(sampler.get("output")) @@ -240,8 +259,13 @@ def _animation_report(gltf: dict, index: int, animation: dict) -> dict: output_count = _accessor_count(gltf, output_index) input_type = _accessor_type(gltf, input_index) output_type = _accessor_type(gltf, output_index) - interpolation = _text(sampler.get("interpolation")) or "LINEAR" - duration = _accessor_max(input_accessor) + raw_interpolation = sampler.get("interpolation") + interpolation = _text(raw_interpolation) + if raw_interpolation is None: + interpolation = "LINEAR" + elif interpolation is None: + issues.append(f"sampler[{sampler_index}] has unknown interpolation {raw_interpolation!r}") + duration = _accessor_max(input_accessor) if input_count else None if input_accessor is None: issues.append(f"sampler[{sampler_index}] input accessor is missing") elif input_count is None or input_count == 0: @@ -257,7 +281,7 @@ def _animation_report(gltf: dict, index: int, animation: dict) -> dict: f"sampler[{sampler_index}] has {output_count} output values for {input_count} " f"keys with {interpolation} interpolation" ) - if interpolation not in ("LINEAR", "STEP", "CUBICSPLINE"): + if interpolation is not None and interpolation not in ("LINEAR", "STEP", "CUBICSPLINE"): issues.append(f"sampler[{sampler_index}] has unknown interpolation {interpolation!r}") samplers.append({ "index": sampler_index, @@ -491,6 +515,7 @@ def build_report(glb: dict, file_bytes: int) -> dict: count = sum(1 for entry in _array(gltf.get(key)) if not isinstance(entry, dict)) if count: invalid_counts[key] = count + invalid_types = _invalid_types(gltf) report = { "bytes": file_bytes, "asset": { @@ -516,6 +541,8 @@ def build_report(glb: dict, file_bytes: int) -> dict: } if any(invalid_counts.values()): report["invalid_counts"] = invalid_counts + if invalid_types: + report["invalid_types"] = invalid_types return report @@ -552,6 +579,9 @@ def format_report(report: dict) -> str: invalid = report.get("invalid_counts") if invalid: lines.append("invalid entries: " + " ".join(f"{key}={value}" for key, value in invalid.items() if value)) + invalid_types = report.get("invalid_types") + if invalid_types: + lines.append("invalid types: " + " ".join(f"{key}={value}" for key, value in invalid_types.items())) lines.append("chunks: " + ", ".join( f"{chunk['type']} {chunk['byte_length']} bytes (padding {_padding_text(chunk.get('padding'))})" for chunk in report["chunks"])) diff --git a/tools/glb_skinning.py b/tools/glb_skinning.py index 3e8a71b55..dcd943f38 100644 --- a/tools/glb_skinning.py +++ b/tools/glb_skinning.py @@ -122,6 +122,16 @@ def _number(value): return _is_int(value) or isinstance(value, float) +def _finite_number(value): + """True for a finite JSON number; an integer too large for float is not one.""" + if not _number(value): + return False + try: + return math.isfinite(value) + except OverflowError: + return False + + def _reject_json_constant(token): raise ValueError(f"non-finite JSON number {token}") @@ -289,7 +299,7 @@ class _Reader: if ( not isinstance(value, list) or len(value) != components - or not all(_number(v) and math.isfinite(v) for v in value) + or not all(_finite_number(v) for v in value) ): raise GlbSkinError( f"accessors[{index}].{key} must be {components} finite number(s)" @@ -427,7 +437,7 @@ def _validate_skins(gltf, reader, warnings, errors): for joint_offset, joint in enumerate(joints): if not _is_int(joint): raise GlbSkinError(f"{path}.joints[{joint_offset}] must be an integer") - if nodes and (joint < 0 or joint >= len(nodes)): + if joint < 0 or joint >= len(nodes): errors.append( f"{_skin_label(skin_index, name)} joint {joint_offset} references " f"node {joint}, but the GLB has {len(nodes)} nodes" @@ -437,7 +447,7 @@ def _validate_skins(gltf, reader, warnings, errors): if skeleton is not None: if not _is_int(skeleton): raise GlbSkinError(f"{path}.skeleton must be an integer") - if nodes and (skeleton < 0 or skeleton >= len(nodes)): + if skeleton < 0 or skeleton >= len(nodes): errors.append( f"{_skin_label(skin_index, name)} skeleton references node {skeleton}, " f"but the GLB has {len(nodes)} nodes" diff --git a/tools/glb_writer.py b/tools/glb_writer.py index 068794174..ded546fea 100644 --- a/tools/glb_writer.py +++ b/tools/glb_writer.py @@ -22,7 +22,7 @@ import struct import sys import tempfile import time -from collections.abc import Iterable +from collections.abc import Iterable, Iterator sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 @@ -195,6 +195,28 @@ def _triangulate_face(points: list[tuple[float, float, float]]) -> list[tuple[in return triangles +def _logical_obj_lines(text: str) -> Iterator[str]: + """Yield OBJ logical lines, joining trailing-backslash continuations with a space. + + A '#' starts an inline comment. A backslash inside that comment does not continue the line; + a backslash in the code before the comment does. + """ + pending = "" + for raw_line in text.splitlines(): + line = raw_line.rstrip() + if not line or line.lstrip().startswith("#"): + continue + code, _, _comment = line.partition("#") + code = code.rstrip() + if code.endswith("\\"): + pending += code[:-1].rstrip() + " " + continue + yield pending + code + pending = "" + if pending: + yield pending + + def parse_obj( text_or_path: str, *, @@ -247,7 +269,7 @@ def parse_obj( # Preserve order of appearance for (group_index, material_name) primitives. builders: dict[tuple[int, str], dict] = {} - for raw_line in text.removeprefix("\ufeff").splitlines(): + for raw_line in _logical_obj_lines(text.removeprefix("\ufeff")): line = raw_line.strip() if not line or line[0] == "#": continue diff --git a/tools/hw_oracle/asm.py b/tools/hw_oracle/asm.py index 6792bde8d..09e7cb7da 100644 --- a/tools/hw_oracle/asm.py +++ b/tools/hw_oracle/asm.py @@ -283,6 +283,7 @@ VALU_REMOVED = { "v_mad_f32": _MAD_GONE.format("v_fma_f32"), "v_mac_f32": _MAD_GONE.format("v_fmac_f32"), "v_madak_f32": _MAD_GONE.format("v_fmaak_f32"), + "v_madmk_f32": _MAD_GONE.format("v_fmamk_f32"), "v_mad_legacy_f32": _MAD_GONE.format("v_fma_dx9_zero_f32"), } # Same instruction, new mnemonic: the assembler takes the GFX10 spelling for GFX11 and encodes the GFX11 name. diff --git a/tools/hw_oracle/runner.py b/tools/hw_oracle/runner.py index f8e81f770..90ac008d8 100644 --- a/tools/hw_oracle/runner.py +++ b/tools/hw_oracle/runner.py @@ -125,7 +125,7 @@ def find_cc(): def build_command(kind, cc, src, out, workdir): - """argv that compiles src into out; MSVC's objects and the vcvars script go to workdir.""" + """argv that compiles src into out; MSVC's objects and the vcvars script go to workdir, the cwd to run it in.""" if kind == "gcc": return [cc, "-O1", src, "-o", out] cl = [cc if kind == "msvc" else "cl", "/nologo", "/O1", src, f"/Fe{out}", f"/Fo{os.path.join(workdir, '')}"] @@ -135,13 +135,16 @@ def build_command(kind, cc, src, out, workdir): # vcvars64.bat runs vswhere itself, so its folder goes on PATH first (as scripts/build_llvm_mc.ps1 does). installer = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Microsoft Visual Studio", "Installer") - script = os.path.join(workdir, "build_hw_oracle.cmd") + name = "build_hw_oracle.cmd" + script = os.path.join(workdir, name) # Written as UTF-8, with chcp 65001 so cmd.exe reads it as UTF-8 on any console code page: the checkout, %TEMP% # and Visual Studio paths in here reach cl intact when one has a character outside ASCII (a user name, say). with open(script, "w", encoding="utf-8", newline="\n") as f: f.write(f'@echo off\r\nchcp 65001 >nul\r\nset "PATH={installer};%PATH%"\r\ncall "{cc}" >nul || exit /b 1\r\n' + subprocess.list2cmdline(cl) + "\r\n") - return ["cmd.exe", "/d", "/c", script] + # Relative to workdir, not the full path: cmd.exe /c loses a full path's quotes when it holds & or ^ (and + # list2cmdline adds none without a space), and `.\` is still found with NoDefaultCurrentDirectoryInExePath set. + return ["cmd.exe", "/d", "/c", "." + os.sep + name] def detect_arch(clang): diff --git a/tools/image_d16_probe.py b/tools/image_d16_probe.py index a6e301431..dc29771b2 100644 --- a/tools/image_d16_probe.py +++ b/tools/image_d16_probe.py @@ -29,8 +29,8 @@ Usage: python -I tools/image_d16_probe.py --self-test # the rules, T# words and kernels, no GPU Exit 0 when the sweep ran (which rule the hardware follows is a finding, not a failure), 1 when image_load and -image_load_mip disagree, 2 on a harness error (a control word did not read back), 77 when the hardware oracle is -unavailable or the GPU is not GFX10. Nothing here reads game files. +image_load_mip disagree, 2 on a harness, CLI, or report write error (a control word did not read back), 77 when the +hardware oracle is unavailable or the GPU is not GFX10. Nothing here reads game files. """ import argparse import json @@ -242,6 +242,43 @@ def self_test(): return 1 if fails else 0 +def validate_json_path(path): + """Return an error string if `path` cannot be used as a --json output file, or None.""" + if not path or not path.strip(): + return "--json path must not be empty" + if "\x00" in path: + return "--json path contains a NUL byte" + if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path): + return f"--json path is a directory: {path}" + cur = os.path.dirname(os.path.abspath(path)) + while cur: + if os.path.isdir(cur): + break + if os.path.lexists(cur): + return f"--json parent is not a directory: {cur}" + nxt = os.path.dirname(cur) + if nxt == cur: + break + cur = nxt + return None + + +def write_json_report(path, report): + """Create missing parent directories and write `report` as LF-terminated JSON, or return an error string.""" + parent = os.path.dirname(os.path.abspath(path)) + if parent: + try: + os.makedirs(parent, exist_ok=True) + except OSError as e: + return f"cannot create directory for --json {path}: {e.strerror or e}" + try: + with open(path, "w", encoding="utf-8", newline="\n") as f: + json.dump(report, f, indent=1) + except OSError as e: + return f"cannot write --json {path}: {e.strerror or e}" + return None + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--dims", default=",".join(DIMS)) @@ -257,6 +294,11 @@ def main(argv=None): bad = [d for d in dims if d not in DIMS] + [f for f in fmts if f not in FORMATS] if bad or not dims or not fmts: ap.error("unknown or empty: " + ", ".join(bad or ["--dims/--formats"])) + if a.json is not None: + err = validate_json_path(a.json) + if err: + print(f"error: {err}", file=sys.stderr) + return 2 from hw_oracle import asm, runner try: oracle = runner.open_oracle(arch=a.hw_arch) @@ -301,9 +343,11 @@ def main(argv=None): return 2 finally: oracle.close() - if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=1) + if a.json is not None: + err = write_json_report(a.json, report) + if err: + print(f"error: {err}", file=sys.stderr) + return 2 return rc diff --git a/tools/image_fuzz.py b/tools/image_fuzz.py index 23285a887..ee610a873 100644 --- a/tools/image_fuzz.py +++ b/tools/image_fuzz.py @@ -581,7 +581,7 @@ def main() -> int: # runtime/build, as docs/shader_validation.md builds it and lds_fuzz/valu_fuzz default to; a Visual Studio build's # RelWithDebInfo/Release subfolder is found below. ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) - ap.add_argument("--work") + ap.add_argument("--work", help="keep each run's generated files in a new subfolder here") ap.add_argument("--show", action="store_true") ap.add_argument("--formats", default=",".join(FORMATS)) ap.add_argument("--oracle", default="translator", @@ -637,11 +637,18 @@ def main() -> int: print("note: GFX11 is RDNA3 or newer, not RDNA2: a match supports the model and does not prove RDNA2") a.build = find_test_program(a.build, HARNESS) or a.build cases = make_cases(a.programs, a.seed, formats) - work = a.work or tempfile.mkdtemp(prefix="image_fuzz_") - os.makedirs(work, exist_ok=True) code = 0 verdicts = {} try: + try: + parent = os.path.abspath(a.work) if a.work else None + if parent is not None: + os.makedirs(parent, exist_ok=True) + work = tempfile.mkdtemp(prefix="image_fuzz_", dir=parent) + except OSError as e: + print(f"ERROR: cannot create work directory: {e}", file=sys.stderr) + return 2 + print(f"work dir {work}") if "translator" in backends: passed, failed, skipped, verdicts = run_translator(cases, a, work) summary = f"{passed}/{passed + failed} programs that ran match" diff --git a/tools/image_query_probe.py b/tools/image_query_probe.py index 5110d408c..c9eff6331 100644 --- a/tools/image_query_probe.py +++ b/tools/image_query_probe.py @@ -37,9 +37,6 @@ import struct import sys HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) TYPE_2D, TYPE_2D_ARRAY = 9, 10 # SQ_RSRC_IMG_* in T# WORD3 [31:28] DIMS = {TYPE_2D: "SQ_RSRC_IMG_2D", TYPE_2D_ARRAY: "SQ_RSRC_IMG_2D_ARRAY"} @@ -262,6 +259,19 @@ def self_test(): return 1 if bad else 0 +def _import_oracle(): + """The optional hardware oracle, imported only for a GPU run. + + --help and --self-test must not touch it: finding AMD clang, the HIP runtime and a host compiler is the + expensive startup work this probe would otherwise pay before argparse can answer --help. + """ + sys.dont_write_bytecode = True + if HERE not in sys.path: + sys.path.insert(0, HERE) + from hw_oracle import asm, runner + return asm, runner + + def main(argv=None): p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) p.add_argument("--waves", default="32,64") @@ -273,7 +283,7 @@ def main(argv=None): waves = [int(w) for w in a.waves.split(",")] if any(w not in (32, 64) for w in waves): p.error("--waves takes 32 and/or 64") - from hw_oracle import asm, runner + asm, runner = _import_oracle() try: oracle = runner.open_oracle() except runner.Unavailable as e: diff --git a/tools/inline_scan.py b/tools/inline_scan.py index 0010c999a..6fd617cfd 100644 --- a/tools/inline_scan.py +++ b/tools/inline_scan.py @@ -20,6 +20,8 @@ back to the previous store-back of the same list, and sorts the site into: A PE is disassembled with MSVC `dumpbin /disasm:nobytes` (it comes with the build tools the runtime needs) and streamed, so an image of any size works in one pass; a saved dumpbin listing (with or without the byte column) works too, on any OS. Nothing is executed. The output is RVAs, counts and constants, no code bytes. +An input with no instructions in it (an empty or other text file, a PE dumpbin prints no code for) exits 2 +instead of reporting zero sites, so "UNCHECKED 0" always means something was scanned. The matcher knows the instruction shapes MSVC emits for these writes (see tests/test_inline_scan.py); a shape it does not know shows up as `unrelated`, so read a few of those by hand on a new image. """ @@ -137,11 +139,15 @@ def classify(window, base, stored): "bases": bases, "load_traced": load is not None and not broken} -def scan(lines): - """Yield one dict per cursor store-back site; fallback slots are filled in once the branch target is seen.""" +def scan(lines, stats=None): + """Yield one dict per cursor store-back site; fallback slots are filled in once the branch target is seen. + `stats["instructions"]` (if a dict is passed) counts the instructions read.""" + stats = {} if stats is None else stats + stats["instructions"] = 0 window = collections.deque(maxlen=LOOKBACK) pending, watching, tail = [], [], [] for idx, (addr, mnem, ops) in enumerate(instructions(lines)): + stats["instructions"] = idx + 1 for item in tail[:]: # list fields written right after the store-back (e.g. clearing +140h) count too site, left = item tail.remove(item) @@ -179,13 +185,14 @@ def limit_text(limit): return "none" if limit is None else "reg" if limit == REG_LIMIT else f"+0x{limit:x}" -def summarize(sites): +def summarize(sites, instructions=None): checked = [s for s in sites if s["checked"]] unchecked = [s for s in sites if not s["checked"] and s["list"]] unrelated = [s for s in sites if not s["list"]] plain = lambda v: "none" if v is None else str(v) - out = [f"list sites {len(checked) + len(unchecked)}: checked {len(checked)}, UNCHECKED {len(unchecked)} " - f"(plus {len(unrelated)} cursor-like stores with no list field nearby, likely other structures)"] + out = [] if instructions is None else [f"instructions scanned: {instructions}"] + out += [f"list sites {len(checked) + len(unchecked)}: checked {len(checked)}, UNCHECKED {len(unchecked)} " + f"(plus {len(unrelated)} cursor-like stores with no list field nearby, likely other structures)"] for title, key, group, fmt in (("limit offsets (checked)", "limit", checked, limit_text), ("fallback vtable slots (checked)", "fallback_slot", checked, plain), ("packet sizes, checked", "size", checked, plain), @@ -206,9 +213,14 @@ def main() -> int: if not args.source.is_file(): print(f"{args.source} not found", file=sys.stderr) return 2 - sites = list(scan(read_lines(args.source))) + stats = {} + sites = list(scan(read_lines(args.source), stats)) + if not stats["instructions"]: + print(f"{args.source}: no instructions found (not a dumpbin listing, or an image without code)", + file=sys.stderr) + return 2 base = args.base if args.base is not None else min((s["store_back"] for s in sites), default=0) & ~0xFFFFFFF - print(summarize(sites)) + print(summarize(sites, stats["instructions"])) if args.sites: rva = lambda a: "?" if a is None else f"+0x{a - base:x}" for s in sites: diff --git a/tools/lane_masks.py b/tools/lane_masks.py index 416f8a934..40f3cab34 100644 --- a/tools/lane_masks.py +++ b/tools/lane_masks.py @@ -122,6 +122,12 @@ def put(state, a, k): state[r] = k +def _maskable_b32(x): + return x["k"] in ("sgpr", "imm") or ( + x["k"] == "special" and (x.get("t", "").startswith(("exec", "vcc")) or x.get("t") == "null") + ) + + def lane_slot(vgpr, lane): """State key for a mask parked in one lane of a VGPR, or None unless both operands are plain.""" if vgpr["k"] != "vgpr" or lane["k"] != "imm": @@ -200,22 +206,37 @@ def step(state, ins): # VGPR (SHADER-21 part 2). Only per-lane mask computations take the all-lanes store, # because whole-wave readers (wave_mask, v_readfirstlane) read every lane's bit. return op != "v_mov_b32" - if "_saveexec_b" in op or "_wrexec_b" in op or op == "s_bfm_b64": + if "_saveexec_b" in op or "_wrexec_b" in op: + put(state, a[0], MASK_LO if op.endswith("_b32") else MASK) + elif op == "s_bfm_b64": put(state, a[0], MASK) elif op.startswith(COPIES) and len(a) > 1: k = kind(state, a[1]) - if k is None and op.endswith("b64") and a[0]["k"] == "special" and a[0].get("t") in ("vcc", "vcc_lo") and \ - a[1]["k"] == "imm": + dst_t = a[0].get("t") if a[0]["k"] == "special" else None + if k in (None, EITHER) and op.endswith("b64") and dst_t in ("vcc", "vcc_lo") and a[1]["k"] == "imm": k = MASK + elif op == "s_not_b32" and dst_t in ("vcc", "vcc_lo") and _maskable_b32(a[1]): + k = MASK + elif op == "s_not_b32" and dst_t == "vcc_hi" and state.get("vcc") in MASK_KINDS and _maskable_b32(a[1]): + return put(state, a[0], k) elif op.startswith(BITWISE): kinds = [kind(state, x) for x in a[1:]] ms = {k for k in kinds if k in MASK_KINDS} + dst_t = a[0].get("t") if a[0]["k"] == "special" else None if None not in kinds: - put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else EITHER) - elif op.endswith("b64") and (ms or (a[0]["k"] == "special" and a[0].get("t") in ("vcc", "vcc_lo"))) and \ + if op.endswith("b32") and dst_t == "vcc_hi" and state.get("vcc") in MASK_KINDS: + return + fallback = MASK if op.endswith("b64") and dst_t in ("vcc", "vcc_lo") else EITHER + put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else fallback) + elif op.endswith("b64") and (ms or dst_t in ("vcc", "vcc_lo")) and \ all(k is not None or x["k"] == "imm" for k, x in zip(kinds, a[1:])): put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else MASK) + elif op.endswith("b32") and dst_t in ("vcc", "vcc_lo") and all(_maskable_b32(x) for x in a[1:]): + put(state, a[0], MASK) + elif op.endswith("b32") and dst_t == "vcc_hi" and state.get("vcc") in MASK_KINDS and \ + all(_maskable_b32(x) for x in a[1:]): + return else: put(state, a[0], None) else: diff --git a/tools/lds_fuzz.py b/tools/lds_fuzz.py index 45f10b477..92461fd14 100644 --- a/tools/lds_fuzz.py +++ b/tools/lds_fuzz.py @@ -1098,7 +1098,7 @@ def main(): help="translate with --pc-tail-ubo and run vk_compute_test with LEONIDA_PC_TAIL_UBO=1 " "(128-byte push constants; also set by LEONIDA_PC_TAIL_UBO=1)") ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) - ap.add_argument("--work", default=None, help="keep the generated .asm and SPIR-V here") + ap.add_argument("--work", default=None, help="keep each run's generated .asm and SPIR-V in a new subfolder here") ap.add_argument("--model-only", action="store_true") ap.add_argument("--show", default=None, metavar="SEED:INDEX[:WAVE]") ap.add_argument("--max-report", type=int, default=12) @@ -1194,8 +1194,11 @@ def main(): try: if "translator" in backends: a.build = find_test_program(a.build, "vk_compute_test") or a.build # a Visual Studio config subfolder - work = Path(a.work).resolve() if a.work else Path(tempfile.mkdtemp(prefix="lds_fuzz_")) - work.mkdir(parents=True, exist_ok=True) + parent = Path(a.work).resolve() if a.work else None + if parent is not None: + parent.mkdir(parents=True, exist_ok=True) + work = Path(tempfile.mkdtemp(prefix="lds_fuzz_", dir=parent)) + print(f"work dir {work}") rcs.append(run_translator(progs, a, work, tally)) if oracle: if a.perturb: diff --git a/tools/mad_denorm_probe.py b/tools/mad_denorm_probe.py index daadab92b..18c1b3160 100644 --- a/tools/mad_denorm_probe.py +++ b/tools/mad_denorm_probe.py @@ -292,6 +292,9 @@ def main(argv=None): print(f"MODE denorm32 sanity error: {sanity}") return 2 print(f"MODE sanity (v_mul_f32 FLT_MIN * 0.5): denorm32=0 -> 0x{sanity[0]:08x}, denorm32=3 -> 0x{sanity[1]:08x}") + if sanity != [POS_ZERO, SUBNORM_HALF]: + print(f"MODE denorm32 sanity failed: expected [0x{POS_ZERO:08x}, 0x{SUBNORM_HALF:08x}], got {[hex(x) for x in sanity]}") + return 2 for wave in (32, 64): for name, mode in MODES: got = run_hw(oracle, CASES, wave, mode) diff --git a/tools/mc_command.py b/tools/mc_command.py index 79e6e459c..3e470d319 100644 --- a/tools/mc_command.py +++ b/tools/mc_command.py @@ -6,6 +6,9 @@ target: set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc +On Windows, arguments follow the MSVC C runtime's quoting rules. Double a trailing backslash in a quoted +argument before the closing quote. + run() starts such a command and turns a missing llvm-mc into one line instead of a FileNotFoundError traceback. """ from __future__ import annotations @@ -16,6 +19,44 @@ import shutil import subprocess +def split_windows_command(raw: str) -> list[str]: + """Decode an MSVC-style argument list, rejecting unmatched quotes.""" + args = [] + pos = 0 + while pos < len(raw): + if raw[pos] in " \t": + pos += 1 + continue + arg = [] + quoted = False + while pos < len(raw) and (quoted or raw[pos] not in " \t"): + start = pos + while pos < len(raw) and raw[pos] == "\\": + pos += 1 + backslashes = pos - start + if pos < len(raw) and raw[pos] == '"': + # Backslashes are special only before a quote. An odd final slash escapes that quote. + arg.append("\\" * (backslashes // 2)) + if backslashes % 2: + arg.append('"') + elif quoted and raw[pos + 1:pos + 2] == '"': + arg.append('"') + pos += 1 + else: + quoted = not quoted + pos += 1 + else: + arg.append("\\" * backslashes) + if pos == len(raw) or (not quoted and raw[pos] in " \t"): + break + arg.append(raw[pos]) + pos += 1 + if quoted: + raise ValueError("No closing quotation") + args.append("".join(arg)) + return args + + def split_command(raw: str) -> list[str]: """Split a command line without eating the backslashes of a Windows path (POSIX shlex would).""" raw = raw.strip() @@ -28,20 +69,11 @@ def split_command(raw: str) -> list[str]: # for it, but it is no file under that exact name, so it used to be split at its spaces. return [raw] try: - if os.name == "nt": - # Quotes can start inside an argument, as in -o="path with spaces". - lexer = shlex.shlex(raw, posix=True) - lexer.quotes = '"' - lexer.escape = "" - lexer.commenters = "" - lexer.whitespace_split = True - return list(lexer) - parts = shlex.split(raw) + return split_windows_command(raw) if os.name == "nt" else shlex.split(raw) except ValueError as e: # shader_disasm.py calls mc_command() at import time: a bad LLVM_MC must give one clear line, # not a ValueError traceback before any tool's own argument parsing runs. raise SystemExit(f"LLVM_MC: invalid command line {raw!r}: {e}") from None - return [p[1:-1] if len(p) > 1 and p[0] == p[-1] == '"' else p for p in parts] def mc_command(raw: str | None = None) -> list: diff --git a/tools/meshlet_page.py b/tools/meshlet_page.py index 42716fffe..25dc9b57a 100644 --- a/tools/meshlet_page.py +++ b/tools/meshlet_page.py @@ -27,8 +27,8 @@ Meshlet group (first u32 has bit 31 set): u32 w1: low u16 = first vertex reference, high u16 = first triangle (running sums) u32 w2, w3: bits 0-11 and 12-23 of w2 and bits 0-11 of w3 are the meshlet's centre in x, y and z as 12-bit steps around 2047, (field - 2047) * step (measured on `42 40` geometry; the default - 0x007FF7FF / 0x7FF is the origin). The step is 1/16 m, or 1/8 m when w2 bit 28 is set (large - meshlets out to +-256 m; the other w2 bits 24-31 are 0). w3 bits 14-30 are the normal cone: axis + 0x007FF7FF / 0x7FF is the origin). The step is 2^e / 16 m with e = w2 bits 28-31 (0 to 4 + seen; larger meshlets further out), and w2 bits 24-27 are 0. w3 bits 14-30 are the normal cone: axis octahedral u = bits 14-19, v = bits 20-25 (x / 31.5 - 1), sin(half-angle) = (31 - bits 26-30) / 31; all zero = no cone. then T u32 triangles: three 7-bit meshlet-local indices (bits 0-6, 7-13, 14-20), meshlet index in bits 21-31 @@ -233,8 +233,8 @@ def face_agreement(positions, triangles): def centre_step(w2): - """Metres per step of a meshlet record's centre fields: 1/16, or 1/8 when w2 bit 28 is set.""" - return 0.125 if (w2 >> 28) & 1 else 0.0625 + """Metres per step of a meshlet record's centre fields: 2^e / 16 with the exponent e in w2 bits 28-31.""" + return 2.0 ** ((w2 >> 28) & 15) / 16 def meshlet_centre(w2, w3): @@ -316,7 +316,7 @@ def centre_agreement(data, group, positions): if len(pts) != vc: raise PageError("meshlet references a vertex past its block") stored, size = meshlet_centre(w2, w3), centre_step(w2) - out["coarse_steps"] += size > 0.0625 + out["coarse_steps"] += (w2 >> 28) != 0 for i in range(3): step = round(((min(p[i] for p in pts) + max(p[i] for p in pts)) / 2 - stored[i]) / size) out["axes_exact"] += step == 0 @@ -763,8 +763,8 @@ def _resource_pointer(system, at, base, segment, size): return address -def drawable_geometries(system, drawable): - """Read the primary LOD geometry list at a caller-identified drawable.""" +def drawable_geometries(system, drawable, lod_index=0): + """Read one LOD geometry list at a caller-identified drawable.""" def pointer(at, size): return _resource_pointer(system, at, 0x50000000, system, size) @@ -776,7 +776,9 @@ def drawable_geometries(system, drawable): if not 0 <= drawable <= len(system) - 176: raise PageError("drawable outside the system segment") - lod = pointer(drawable + 80, 16) + if lod_index not in range(4): + raise PageError("drawable LOD index must be between 0 and 3") + lod = pointer(drawable + 80 + 8 * lod_index, 16) models = count(lod + 8) table = pointer(lod, 8 * models) for i in range(models): @@ -873,8 +875,11 @@ def main(argv=None): select.add_argument("--geometry-offset", action="append", type=lambda s: int(s, 0), help="known geometry record offset in the system segment (repeatable)") select.add_argument("--drawable-offset", type=lambda s: int(s, 0), - help="walk primary LOD geometry records from this system-segment drawable") + help="walk geometry records from this system-segment drawable") + ap.add_argument("--lod", type=int, choices=range(4), help="drawable LOD index (default: 0)") args = ap.parse_args(argv) + if args.lod is not None and args.drawable_offset is None: + ap.error("--lod requires --drawable-offset") if args.json: if os.path.isdir(args.json): print(f"error: --json {args.json} is a directory", file=sys.stderr) @@ -895,7 +900,7 @@ def main(argv=None): with open(args.inputs[0], "rb") as source: graphics = source.read() rows = [] - offsets = args.geometry_offset or drawable_geometries(system, args.drawable_offset) + offsets = args.geometry_offset or drawable_geometries(system, args.drawable_offset, args.lod or 0) try: for offset in offsets: try: diff --git a/tools/mission_tables.py b/tools/mission_tables.py index c38b8da09..f093048a6 100644 --- a/tools/mission_tables.py +++ b/tools/mission_tables.py @@ -363,7 +363,7 @@ def parse_blob(blob, name=""): blocks, _fill = psin_data.block_table(blob, first_section) except (ValueError, struct.error): blocks = [] - end = first_section if first_section >= RECORD_SIZE else len(blob) + end = first_section elements = scan_elements(blob, end) chunks = find_chunks(blob, end, elements) table_blocks = record_blocks(blob, blocks) if blocks else [] diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py index 30006e703..fe32b062b 100644 --- a/tools/navmesh_decode.py +++ b/tools/navmesh_decode.py @@ -604,6 +604,7 @@ def decode_navmesh(b, nstreams, stats, deep): stats["quadtree"]["nodes"] += qn stats["quadtree"]["leaves"] += ql stats["quadtree"]["max_depth"] = max(stats["quadtree"]["max_depth"], qd) + chk["volumes_valid"] = _walk_volumes(b, vol, dc, stats) stats["flags"][flags] += 1 stats["build"][hx(e8)] += 1 @@ -630,6 +631,41 @@ def _poly_chain(b, blocks, owner, pool): return nxt == pool, has_water +def _walk_volumes(b, vol, dc, stats): + """Paired 96-byte obstacle footprint records at +0xB8 (count u32@0xDC, ASSET-281).""" + if dc == 0: + return vol is None + if vol is None or dc % 2 != 0 or vol + 96 * dc > len(b): + return False + flags = Counter() + vertex_counts = Counter() + for p in range(dc // 2): + o0 = vol + (2 * p) * 96 + o1 = o0 + 96 + if b[o0:o0 + 20] != b[o1:o1 + 20]: + return False + xyz = _f32s(b, o0 + 8, 3) + if xyz is None or not all(math.isfinite(v) for v in xyz): + return False + f0, vc0 = b[o0 + 0x14], b[o0 + 0x15] + f1, vc1 = b[o1 + 0x14], b[o1 + 0x15] + if f0 not in (0, 4) or f1 != 8 or vc0 not in (4, 8) or vc1 != 4: + return False + if not (_zero(b, o0 + 0x16 + 4 * vc0, o0 + 0x56) and _zero(b, o0 + 0x5A, o0 + 0x60)): + return False + if not (_zero(b, o1 + 0x16 + 4 * vc1, o1 + 0x56) and _zero(b, o1 + 0x5A, o1 + 0x60)): + return False + flags[f0] += 1 + flags[f1] += 1 + vertex_counts[vc0] += 1 + vertex_counts[vc1] += 1 + vstats = stats["volumes"] + vstats["pairs"] += dc // 2 + vstats["flags"].update(flags) + vstats["vertex_counts"].update(vertex_counts) + return True + + # ------------------------------------------------------------------------------------------------------ grid def decode_grid(b, nstreams, stats, deep): @@ -656,6 +692,11 @@ def decode_grid(b, nstreams, stats, deep): chk["occupied_equals_entries"] = valid_ctrl and used == entries if deep: chk["values_bijective"] = chk["occupied_equals_entries"] and _grid_values(b, groups, entries) + if chk["values_bijective"] and chk["payload_in_bounds"]: + keys = _grid_slots(b, groups) + chk["keys_octree"] = len(keys) == entries and _grid_octree(keys) + if chk["keys_octree"]: + chk["inner_payload_ff00"] = _grid_payloads(b, payload, keys, stats) stats["groups"][groups] += 1 stats["extent"][ex[0]] += 1 oz = origin[2] if (origin and math.isfinite(origin[2])) else None @@ -679,6 +720,47 @@ def _grid_values(b, groups, entries): return all(seen) +def _grid_slots(b, groups): + """{key: value} of every occupied slot (call after _grid_values has accepted the table).""" + keys = {} + for g in range(groups): + base = 0x60 + GRID_GROUP * g + for k, c in enumerate(b[base:base + 16]): + if c < 0x80: + keys[_u64(b, base + 16 + 16 * k)] = _u64(b, base + 16 + 16 * k + 8) + return keys + + +def _grid_octree(keys): + """Keys are sentinel-bit linear octree keys: 1 is the root, a child is (parent << 3) | octant.""" + if 1 not in keys: + return False + for key in keys: + if key == 0 or (key.bit_length() - 1) % 3 or (key != 1 and key >> 3 not in keys): + return False + return True + + +GRID_INNER = 0x0000FF00 # payload of every node that has children +GRID_LEAF_KIND = {0x01: "low_byte_01", 0x03: "low_byte_03"} + + +def _grid_payloads(b, payload, keys, stats): + """Inner nodes carry 0x0000ff00; count leaf payloads by low byte and every key by depth.""" + inner = {key >> 3 for key in keys if key != 1} + words = {key: _u32(b, payload + 4 * value) for key, value in keys.items()} + if any(words[key] != GRID_INNER for key in inner): + return False + stats["inner_nodes"] += len(inner) + for key, word in words.items(): + stats["key_depth"][(key.bit_length() - 1) // 3] += 1 + if key in inner: + continue + kind = "ff00" if word == GRID_INNER else GRID_LEAF_KIND.get(word & 0xFF, "other") + stats["leaf_payload"][kind] += 1 + return True + + # ------------------------------------------------------------------------------------------------------ scan def new_stats(): @@ -694,9 +776,10 @@ def new_stats(): "navmesh": {"flags": Counter(), "build": Counter(), "totals": Counter(), "max": {}, "sectors": set(), "sector_x": [inf, -inf], "sector_y": [inf, -inf], "split_blocks_max": {}, "tile_bounds": [[inf] * 3, [-inf] * 3], "water_bit3": Counter(), - "quadtree": {"nodes": 0, "leaves": 0, "max_depth": 0}}, + "quadtree": {"nodes": 0, "leaves": 0, "max_depth": 0}, + "volumes": {"pairs": 0, "flags": Counter(), "vertex_counts": Counter()}}, "grid": {"groups": Counter(), "extent": Counter(), "oz": Counter(), "sectors": set(), "entries_total": 0, - "entries_max": 0}, + "entries_max": 0, "key_depth": Counter(), "inner_nodes": 0, "leaf_payload": Counter()}, "psin": {"version": Counter(), "complete": 0}, } @@ -911,6 +994,8 @@ def _summary(path, mode, start, end, carver, classes, checks, stats, elapsed): "tile_bounds": _box(n["tile_bounds"]), "water_bit3": dict(n["water_bit3"]), "quadtree": dict(n["quadtree"]), + "volumes": {"pairs": n["volumes"]["pairs"], "flags": _counter(n["volumes"]["flags"]), + "vertex_counts": _counter(n["volumes"]["vertex_counts"])}, }, "grid": { "groups": _counter(g["groups"]), @@ -921,6 +1006,9 @@ def _summary(path, mode, start, end, carver, classes, checks, stats, elapsed): "navmesh_sectors_not_in_grid": len(static - g["sectors"]), "entries_total": g["entries_total"], "entries_max": g["entries_max"], + "key_depth": _counter(g["key_depth"]), + "inner_nodes": g["inner_nodes"], + "leaf_payload": _counter(g["leaf_payload"]), }, "psin": {"version": _counter(stats["psin"]["version"]), "complete": stats["psin"]["complete"]}, "elapsed_s": round(elapsed, 1), @@ -1015,6 +1103,8 @@ def main(argv=None): for flag, path in (("--out", out), ("--csv", a.csv)): if not path: continue + if os.path.isdir(path): # open() on a folder ends the run in a PermissionError traceback + ap.error(f"{flag} is a directory: {path}") if same_report_path(path, a.input): ap.error(f"{flag} would overwrite the input {a.input}") if os.path.isfile(path) and os.path.isdir(a.input): diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py index 0ee070efa..7dcf5163d 100644 --- a/tools/navmesh_index.py +++ b/tools/navmesh_index.py @@ -314,8 +314,13 @@ def main() -> int: if a.csv and same_report_path(out_path, a.csv): ap.error("--out and --csv must refer to different files") for flag, path in (("--out", out_path), ("--csv", a.csv)): + if path and os.path.isdir(path): # open() on a folder ends the run in a PermissionError traceback + ap.error(f"{flag} is a directory: {path}") if path and is_scanned_input(path, a.input, a.pattern): ap.error(f"{flag} would overwrite the input {path}") + if not os.path.exists(a.input): + print(f"ERROR: {a.input}: does not exist", file=sys.stderr) + return 2 below_normal() if is_dir: diff --git a/tools/navmesh_links.py b/tools/navmesh_links.py new file mode 100644 index 000000000..7e74d5d4e --- /dev/null +++ b/tools/navmesh_links.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +"""Decode and verify navmesh +0x88 adjacent-polygon edges and +0xA8/+0xB0 special links. + +Reads a retail RPF9 navmeshes.rpf archive (or a directory of carved .bin streams) +in-place and validates the 12-byte adjacent-polygon edge records (+0x88, count u32@0x90), +the 32-byte special-link records (+0xA8, count u32@0xD4), the u16 special-link index +table (+0xB0, count u32@0xD8), and the polygon +0x20 special-link prefix-sum chain +across all 0x00010015 navmesh tiles. Emits aggregate counts and invariant pass/fail +totals only (no game data). +""" + +import argparse +from collections import Counter +import json +import mmap +import os +import struct +import sys + +try: + from tools import navmesh_decode as nd +except ImportError: # pragma: no cover - direct script execution + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + import navmesh_decode as nd + + +CHECK_NAMES = ( + "edges_valid", + "poly_link_chain", + "special_links_valid", + "link_indices_endpoints", +) + + +def _counter_top(counter, limit=32): + return {str(k): v for k, v in counter.most_common(limit)} + + +def verify_tile(b, stats): + """Verify +0x88 adjacent edges, polygon +0x20 link chain, and +0xA8/+0xB0 special links.""" + chk = {} + if len(b) < 0xF0: + for name in CHECK_NAMES: + chk[name] = False + return chk + + flags = nd._u32(b, 0x10) + c0, c4, c8, _, d4, d8 = (nd._u32(b, o) for o in (0xC0, 0xC4, 0xC8, 0xCC, 0xD4, 0xD8)) + pool = nd._u32(b, 0x90) + a8, b0 = nd._u64(b, 0xA8), nd._u64(b, 0xB0) + + # 1. 12-byte adjacent-polygon edges at +0x88 (count = pool = u32@0x90). + b88 = nd.split_array(b, 0x88, 12, pool) + edges_ok = b88 is not None + same_tile = 0 + unlinked = 0 + edge_flags_lo = Counter() + edge_meta_hi = Counter() + if edges_ok: + for bo, cnt in b88: + for asec, apoly, meta16, flags32 in struct.iter_unpack("> 8] += 1 + if not edges_ok: + break + chk["edges_valid"] = edges_ok + if edges_ok: + est = stats["edges"] + est["total"] += pool + est["same_tile"] += same_tile + est["unlinked"] += unlinked + est["flags_low_byte"].update(edge_flags_lo) + est["meta_high_byte"].update(edge_meta_hi) + + # 2. 32-byte special links at +0xA8 (count = d4 = u32@0xD4) and u16 index table at +0xB0 (count = d8 = u32@0xD8). + has_links = bool(flags & 2) + la = nd.offset_of(a8) if a8 else None + lb = nd.offset_of(b0) if b0 else None + if not has_links: + links_bounds_ok = (a8 == 0 and b0 == 0 and d4 == 0 and d8 == 0) + else: + links_bounds_ok = ( + d4 > 0 + and d8 > 0 + and la is not None + and lb is not None + and la + 32 * d4 <= len(b) + and lb + 2 * d8 <= len(b) + ) + + links_ok = links_bounds_ok + intra = cross_s0 = cross_s1 = 0 + f0_hist = Counter() + f1_hist = Counter() + if links_ok and d4 > 0: + for i in range(d4): + p0, p1, s0, s1, f0, f1, heading, pad = struct.unpack_from("= 256 or pad != 0: + links_ok = False + break + if s0 == c8 and s1 == c8: + if p0 >= c4 or p1 >= c4: + links_ok = False + break + intra += 1 + elif s0 == c8: + if p0 >= c4: + links_ok = False + break + cross_s0 += 1 + elif s1 == c8: + if p1 >= c4: + links_ok = False + break + cross_s1 += 1 + else: + links_ok = False + break + f0_hist[f0] += 1 + f1_hist[f1] += 1 + chk["special_links_valid"] = links_ok + if links_ok and d4 > 0: + lst = stats["special_links"] + lst["link_tiles"] += 1 + lst["total"] += d4 + lst["indices_total"] += d8 + lst["intra_tile"] += intra + lst["cross_tile_s0"] += cross_s0 + lst["cross_tile_s1"] += cross_s1 + lst["flags0"].update(f0_hist) + lst["flags1"].update(f1_hist) + + # 3. 44-byte polygons at +0x98: u32@0x20 packs (flags_hi9 << 23) | (link_start << 6) | link_count, + # chaining across all c4 polygons to d8 and indexing +0xB0 -> +0xA8 endpoints touching that polygon. + b98 = nd.split_array(b, 0x98, 44, c4) + chain_ok = b98 is not None and links_bounds_ok + endpoints_ok = chain_ok and links_ok + lidx = struct.unpack_from(f"<{d8}H", b, lb) if (links_bounds_ok and d8 > 0) else () + nxt = 0 + gpi = 0 + max_poly_links = 0 + w20_hi9 = Counter() + if b98 is not None: + for po, pcnt in b98: + for pi in range(pcnt): + w20 = struct.unpack_from("> 6) & 0x1FFFF + w20_hi9[w20 >> 23] += 1 + if cnt > max_poly_links: + max_poly_links = cnt + if start != nxt or start + cnt > d8: + chain_ok = False + endpoints_ok = False + break + if cnt > 0 and endpoints_ok: + for k in range(start, start + cnt): + li = lidx[k] + if li >= d4: + endpoints_ok = False + break + p0, p1, s0, s1 = struct.unpack_from(" pst["max_links_per_poly"]: + pst["max_links_per_poly"] = max_poly_links + pst["w20_hi9_flags"].update(w20_hi9) + return chk + + +def new_stats(): + return { + "tiles": 0, + "checks": {name: {"pass": 0, "fail": 0} for name in CHECK_NAMES}, + "edges": { + "total": 0, + "same_tile": 0, + "unlinked": 0, + "flags_low_byte": Counter(), + "meta_high_byte": Counter(), + }, + "polygons": { + "total": 0, + "max_links_per_poly": 0, + "w20_hi9_flags": Counter(), + }, + "special_links": { + "link_tiles": 0, + "total": 0, + "indices_total": 0, + "intra_tile": 0, + "cross_tile_s0": 0, + "cross_tile_s1": 0, + "flags0": Counter(), + "flags1": Counter(), + }, + } + + +def _iter_resources(path, start=0, limit=None): + if os.path.isdir(path): + files = sorted(f for f in os.listdir(path) if f.endswith(".bin")) + idx = 0 + while idx < len(files): + with open(os.path.join(path, files[idx]), "rb") as fh: + d0 = fh.read() + idx += 1 + if len(d0) < 64: + continue + cls = nd.classify(d0) + buf = bytearray(d0) + n = 1 + while nd.wants_more(cls, buf, n) and idx < len(files): + with open(os.path.join(path, files[idx]), "rb") as fh: + dn = fh.read() + if len(dn) >= 64 and nd.classify(dn) != "other": + break + buf.extend(dn) + idx += 1 + n += 1 + if cls == "navmesh": + yield bytes(buf) + return + + size = os.path.getsize(path) + if size < 8: + return + with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: + first = struct.unpack_from("= scan_end: + return + gen = nd.walk(m, scan_start, size) + pending = None + while True: + item = pending if pending is not None else next(gen, None) + pending = None + if item is None: + break + off0, _, d0 = item + if off0 >= scan_end: + break + if len(d0) < 64: + continue + cls = nd.classify(d0) + buf = bytearray(d0) + n = 1 + while nd.wants_more(cls, buf, n): + nxt = next(gen, None) + if nxt is None: + break + if len(nxt[2]) >= 64 and nd.classify(nxt[2]) != "other": + pending = nxt + break + buf.extend(nxt[2]) + n += 1 + if cls == "navmesh": + yield bytes(buf) + + +def scan(path, start=0, limit=None): + stats = new_stats() + for buf in _iter_resources(path, start=start, limit=limit): + stats["tiles"] += 1 + chk = verify_tile(buf, stats) + for name, ok in chk.items(): + stats["checks"][name]["pass" if ok else "fail"] += 1 + return { + "tiles": stats["tiles"], + "checks": stats["checks"], + "edges": { + "total": stats["edges"]["total"], + "same_tile": stats["edges"]["same_tile"], + "unlinked": stats["edges"]["unlinked"], + "flags_low_byte": _counter_top(stats["edges"]["flags_low_byte"]), + "meta_high_byte": _counter_top(stats["edges"]["meta_high_byte"]), + }, + "polygons": { + "total": stats["polygons"]["total"], + "max_links_per_poly": stats["polygons"]["max_links_per_poly"], + "w20_hi9_flags": _counter_top(stats["polygons"]["w20_hi9_flags"]), + }, + "special_links": { + "link_tiles": stats["special_links"]["link_tiles"], + "total": stats["special_links"]["total"], + "indices_total": stats["special_links"]["indices_total"], + "intra_tile": stats["special_links"]["intra_tile"], + "cross_tile_s0": stats["special_links"]["cross_tile_s0"], + "cross_tile_s1": stats["special_links"]["cross_tile_s1"], + "flags0": _counter_top(stats["special_links"]["flags0"]), + "flags1": _counter_top(stats["special_links"]["flags1"]), + }, + } + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("input", help="Path to navmeshes.rpf or a directory of carved .bin streams") + ap.add_argument("--start", type=int, default=0, help="Start byte offset inside an RPF9 archive") + ap.add_argument("--limit", type=int, default=None, help="Maximum byte span to scan") + ap.add_argument("--out", default=None, help="Optional JSON output path") + ap.add_argument("--quiet", action="store_true", help="Suppress stdout summary") + args = ap.parse_args(argv) + + if args.start < 0: + sys.stderr.write("error: --start must be >= 0\n") + return 2 + if args.limit is not None and args.limit < 1: + sys.stderr.write("error: --limit must be >= 1\n") + return 2 + if not os.path.exists(args.input): + sys.stderr.write(f"error: input path not found: {args.input}\n") + return 2 + if args.out is not None: + if os.path.isdir(args.out): + sys.stderr.write(f"error: --out path is a directory: {args.out}\n") + return 2 + if os.path.abspath(args.out) == os.path.abspath(args.input): + sys.stderr.write("error: --out must not overwrite the input path\n") + return 2 + + doc = scan(args.input, start=args.start, limit=args.limit) + if args.out is not None: + parent = os.path.dirname(os.path.abspath(args.out)) + if parent: + os.makedirs(parent, exist_ok=True) + with open(args.out, "w", encoding="utf-8", newline="\n") as fh: + json.dump(doc, fh, indent=2) + fh.write("\n") + if not args.quiet: + print(json.dumps(doc, indent=2)) + return 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/page_index.py b/tools/page_index.py index 1471ce8ea..8c82c0817 100644 --- a/tools/page_index.py +++ b/tools/page_index.py @@ -14,8 +14,9 @@ The header has no key: what earlier reports called a 64-bit key at +0x60 is the 29,297 of 29,298 measured pages. This tool reports `payload_at_0x60` instead. The +0x28 table (32-byte records) is reported raw as `q28_records`: the hash in its first u32 matches a +0x38 -hash on most pages, its +0x10 pointer resolves in the resource, and its +0x1c word behaves as flags.The +0x08 and +0x18 words are not decoded and are exported as `field_08` and `count_or_size`. The +0x30 and +0x40 -tables are reported by offset only; their internal layout is not decoded here. +hash on most pages, its +0x10 pointer resolves in the resource or is null (`target` null), and its +0x1c word +behaves as flags. The +0x08 and +0x18 words are not decoded and are exported as `field_08` and `count_or_size`. +The +0x30 and +0x40 tables are reported by offset only; their internal layout is not decoded here. Each page also carries a `resource`: the directory stream plus the continuations that reach the q38 table and its last record, their byte total, and the +0x20 count next to the 64 KiB units the group occupies. The count does not @@ -29,6 +30,7 @@ Usage: --start and --limit apply to a single archive only; with a directory they are an error (exit 2). """ import argparse +from collections import Counter import csv import json import mmap @@ -44,6 +46,7 @@ BASE = 0x50000000 HEADER_SIZE = 0x60 PAGE_UNIT = 0x10000 # 64 KiB: the unit a resource's declared +0x20 count is compared against MAX_CONTINUATIONS = 16 +Q28_UNREAD = "q28 table ends past the streams read for q38" COLUMNS = [ "page_offset", "stored", "inflated", "version", "page_count", "q28_count", "q30_count", "q38_count", "span", "complete", @@ -164,15 +167,24 @@ def _q38(data, q38, count): def _q28(data, q28, count): - """Parse the +0x28 table raw. Unresolved words keep their measured names.""" - if not count or q28 is None or q28 + 32 * count > len(data): + """Parse the +0x28 table raw. Unresolved words keep their measured names. + + A record whose pointer is null is kept with `target` None: its other words are set, and the records after + it are ordinary ones (3,672 such records on 3,511 of 22,823 `anim.rpf` pages). A table that ends past the + streams read for q38 is not read, and says so instead of looking like a page without one. + """ + if not count: return [], "" + if q28 is None: # none on data.rpf, navmeshes.rpf or anim.rpf; named so declared records cannot go missing + return [], "q28 is not a 0x50000000 pointer" + if q28 + 32 * count > len(data): + return [], Q28_UNREAD out = [] for i in range(count): hash_a, hash_b, field_08, pointer, count_or_size, flags = struct.unpack_from( " str: + s = _GPU_JUNK.sub(" ", name.lower()) + s = _SPLIT.sub(" ", s) # "rx9070xt" -> "rx 9070 xt" + s = re.sub(r"\bti\s*super\b", "ti super", s) + return re.sub(r"\s+", " ", s).strip() + + +GPU_INDEX = {_norm_gpu(n): (n, s) for n, s in GPU_TABLE} + +# Fallback for cards missing from GPU_TABLE: score by generation and tier, +# the same idea as the CPU tables. Newer generations than the table scale up. +NV_BASE = { + 10: {50: 30, 60: 40, 70: 52, 80: 62}, 16: {50: 36, 60: 48}, + 20: {60: 62, 70: 74, 80: 88}, 30: {50: 56, 60: 75, 70: 100, 80: 125, 90: 145}, + 40: {60: 88, 70: 130, 80: 200, 90: 270}, 50: {50: 82, 60: 105, 70: 150, 80: 220, 90: 310}, +} +RX_BASE = { + 5: {5: 40, 6: 62, 7: 70}, 6: {4: 28, 5: 42, 6: 70, 7: 92, 8: 115, 9: 140}, + 7: {6: 78, 7: 115, 8: 135, 9: 150}, 9: {6: 107, 7: 175}, +} +ARC_BASE = {1: {3: 30, 5: 70, 7: 85}, 2: {5: 92, 7: 120}} +GEN_GROWTH = 1.25 # assumed uplift per generation beyond the tables +_NV_SUFFIX = {"ti": 1.15, "super": 1.1, "ti super": 1.25} +_RX_SUFFIX = {"xt": 1.12, "xtx": 1.3, "gre": 0.9} +_VARIANT_WORDS = {"ti", "super", "xt", "xtx", "gre"} + + +def _gen_score(table: dict, series: int, tier: int, step: int): + top = max(table) + if series > top: + row, scale = table[top], GEN_GROWTH ** ((series - top) / step) + else: + known = [s for s in table if s <= series] + row, scale = table[max(known) if known else min(table)], 1.0 + return _pick(row, tier) * scale + + +def _estimate_gpu(n: str): + """Score from the model number of a normalised name, or None.""" + m = re.search(r"\b(?:rtx|gtx)\s*(\d{2})(\d{2})\b(?:\s*(ti super|super|ti)\b)?", n) + if m: + return (_gen_score(NV_BASE, int(m[1]), int(m[2]), 10) + * _NV_SUFFIX.get(m[3], 1.0)) + m = re.search(r"\brx\s*(\d{4})\b(?:\s*(xtx|xt|gre)\b)?", n) + if m: + num = int(m[1]) + tier = num // 100 % 10 if num < 9000 else num % 100 // 10 # RDNA4: 9060, 9070 + return _gen_score(RX_BASE, num // 1000, tier, 1) * _RX_SUFFIX.get(m[2], 1.0) + m = re.search(r"\barc\s*([abc])\s*(\d)(\d{2})\b", n) + if m: + return _gen_score(ARC_BASE, "abc".index(m[1]) + 1, int(m[2]), 1) + return None + + +def gpu_lookup(name: str): + """(score, exact). exact is False when the score is estimated from the model.""" + if not name or not name.strip(): + return None, False + raw = name.lower() + n = _norm_gpu(name) + if ("uhd" in raw or "iris" in raw or "hd graphics" in raw or n == "" + or re.fullmatch(r"vega \d+", n)): + return 15, True # integrated graphics + mult = 0.8 if ("laptop" in raw or "mobile" in raw or "max-q" in raw) else 1.0 + best = None + for key, (_disp, score) in GPU_INDEX.items(): + if re.search(rf"(? len(best[0]): + best = (key, score) + if best is not None: + # "rx 9070 gre" matches "rx 9070": a leftover variant suffix means the + # listed score is for a different card, so estimate instead + if set(n.replace(best[0], "", 1).split()) & _VARIANT_WORDS: + est = _estimate_gpu(n) + if est is not None: + return est * mult, False + return best[1] * mult, False + return best[1] * mult, True + est = _estimate_gpu(n) + return (est * mult, False) if est is not None else (None, False) + + +def gpu_score(name: str): + """Relative GPU score, or None if the name isn't recognised.""" + return gpu_lookup(name)[0] + + +# ---------------------------------------------------------------------------- +# CPU scores (relative to a Ryzen 5 5600 = 100). Known models are listed; +# the rest are estimated from generation and tier. +# ---------------------------------------------------------------------------- +CPU_EXPLICIT = { + "i3-12100": 85, "i5-12400": 102, "i5-12600": 118, "i5-12600k": 125, + "i7-12700": 135, "i7-12700k": 140, "i9-12900k": 155, + "i5-13400": 115, "i5-13500": 130, "i5-13600k": 150, "i7-13700k": 170, + "i9-13900k": 195, "i5-14400": 118, "i5-14600k": 155, "i7-14700k": 180, + "i9-14900k": 200, "i5-11400": 92, "i5-11600k": 100, "i7-11700": 103, + "i7-10700": 98, "i5-10400": 82, "i5-10600k": 92, "i9-10900k": 108, + "i7-9700k": 93, "i9-9900k": 105, "i5-9400": 75, "i7-8700k": 90, "i5-8400": 78, + "r5-5600": 100, "r5-5600x": 104, "r7-3700x": 100, "r5-3600": 90, + "r5-5500": 90, "r7-5700x": 115, "r7-5800x": 120, "r7-5800x3d": 140, + "r9-5900x": 135, "r5-7600": 130, "r7-7800x3d": 175, "r7-9800x3d": 190, +} +INTEL_BASE = { + 4: {3: 40, 5: 48, 7: 56, 9: 56}, 6: {3: 45, 5: 55, 7: 62, 9: 62}, + 7: {3: 52, 5: 60, 7: 70, 9: 70}, 8: {3: 68, 5: 80, 7: 90, 9: 100}, + 9: {3: 72, 5: 85, 7: 95, 9: 108}, 10: {3: 75, 5: 88, 7: 98, 9: 108}, + 11: {3: 80, 5: 95, 7: 103, 9: 112}, 12: {3: 85, 5: 108, 7: 135, 9: 155}, + 13: {3: 100, 5: 125, 7: 165, 9: 195}, 14: {3: 100, 5: 130, 7: 175, 9: 200}, +} +AMD_BASE = { + 1: {3: 45, 5: 60, 7: 70, 9: 70}, 2: {3: 55, 5: 68, 7: 80, 9: 80}, + 3: {3: 70, 5: 90, 7: 100, 9: 120}, 4: {3: 75, 5: 85, 7: 95, 9: 95}, + 5: {3: 85, 5: 100, 7: 118, 9: 138}, 7: {3: 100, 5: 130, 7: 148, 9: 175}, + 8: {3: 100, 5: 120, 7: 135, 9: 150}, 9: {3: 115, 5: 140, 7: 155, 9: 190}, +} +ULTRA_BASE = {3: 130, 5: 150, 7: 178, 9: 195} +# Intel mobile/low-power suffix -> multiplier (first matching prefix wins) +_MOBILE_MULT = [("hx", 1.0), ("hk", 0.9), ("h", 0.85), ("u", 0.55), ("p", 0.8), + ("g", 0.6), ("t", 0.8)] + + +def _pick(table: dict, key: int): + """Row for `key`, or the closest lower one (the lowest if there is none).""" + ks = sorted(table) + lower = [k for k in ks if k <= key] + return table[lower[-1] if lower else ks[0]] + + +def _mobile_mult(suffix: str) -> float: + for prefix, mult in _MOBILE_MULT: + if suffix.startswith(prefix): + return mult + return 1.0 + + +def cpu_lookup(name: str): + """(score, exact). exact is False when estimated from generation and tier.""" + if not name or not name.strip(): + return None, False + s = re.sub(r"\((?:r|tm)\)|[®™]", "", name.lower()) + + m = re.search(r"core\s*ultra\s*([3579])\s*(\d{3})([a-z]*)", s) + if m: + base = ULTRA_BASE[int(m[1])] + return (base if "k" in m[3] else base * 0.95), False + + m = re.search(r"\bi([3579])[- ]?(\d{4,5})([a-z]{0,2})\d?\b", s) + if m: + tier, num, suf = int(m[1]), m[2], m[3] + gen = int(num[:2]) if (len(num) == 5 or num[0] == "1") else int(num[0]) + is_k = suf in ("k", "kf", "ks") + key = f"i{tier}-{num}{'k' if is_k else ''}" + if key in CPU_EXPLICIT: + return CPU_EXPLICIT[key], True + base = _pick(INTEL_BASE, gen)[tier] + return base * (1.06 if is_k else 1.0) * _mobile_mult(suf), False + + m = re.search( + r"ryzen\s*(?:ai\s*)?([3579])\s*(?:pro\s*)?(\d{4})\s*" + r"(x3d|xt|x|gt|ge|g|f|hx|hs|h|u)?\b", s) + if m: + tier, num, suf = int(m[1]), m[2], m[3] or "" + sufkey = "x3d" if suf == "x3d" else ("x" if suf in ("x", "xt") else "") + key = f"r{tier}-{num}{sufkey}" + if key in CPU_EXPLICIT: + return CPU_EXPLICIT[key], True + base = _pick(AMD_BASE, int(num[0]))[tier] + mult = {"x3d": 1.15, "x": 1.04, "xt": 1.04, "g": 0.95, "ge": 0.9, "gt": 0.95, + "hx": 1.0, "hs": 0.8, "h": 0.85, "u": 0.55}.get(suf, 1.0) + return base * mult, False + return None, False + + +def cpu_score(name: str): + """Relative CPU score, or None if the name isn't recognised.""" + return cpu_lookup(name)[0] + + +CPU_CHOICES = [ + "Intel Core i3-10100F", "Intel Core i5-10400F", "Intel Core i7-10700K", + "Intel Core i5-11400F", "Intel Core i7-11700K", "Intel Core i3-12100F", + "Intel Core i5-12400F", "Intel Core i5-12600K", "Intel Core i7-12700K", + "Intel Core i9-12900K", "Intel Core i5-13400F", "Intel Core i5-13600K", + "Intel Core i7-13700K", "Intel Core i9-13900K", "Intel Core i5-14400F", + "Intel Core i5-14600K", "Intel Core i7-14700K", "Intel Core i9-14900K", + "Intel Core Ultra 5 245K", "Intel Core Ultra 7 265K", "Intel Core Ultra 9 285K", + "AMD Ryzen 5 2600", "AMD Ryzen 5 3600", "AMD Ryzen 7 3700X", "AMD Ryzen 5 5500", + "AMD Ryzen 5 5600", "AMD Ryzen 5 5600X", "AMD Ryzen 7 5700X", "AMD Ryzen 7 5800X", + "AMD Ryzen 7 5800X3D", "AMD Ryzen 9 5900X", "AMD Ryzen 5 7600", "AMD Ryzen 7 7700X", + "AMD Ryzen 7 7800X3D", "AMD Ryzen 9 7950X", "AMD Ryzen 5 9600X", + "AMD Ryzen 7 9700X", "AMD Ryzen 7 9800X3D", "AMD Ryzen 9 9950X", +] +GPU_CHOICES = [n for n, _ in GPU_TABLE] + +# ---------------------------------------------------------------------------- +# Reference profiles +# ---------------------------------------------------------------------------- +PROFILES = { + "Xbox Series X": { + "short": "Xbox Series X", + "subtitle": "Community comparison with Xbox Series X", + "cpu_ref": ["AMD Ryzen 7 3700X", "AMD Ryzen 5 5600"], + "cpu_text": "Ryzen 7 3700X or Ryzen 5 5600", + "gpu_ref": ["NVIDIA GeForce RTX 3060 Ti", "NVIDIA GeForce RTX 3070", + "AMD Radeon RX 6700 XT", "AMD Radeon RX 6800"], + "gpu_text": "RTX 3060 Ti / 3070 or RX 6700 XT / 6800", + "ram": 32, "ram_text": "32 GB suggested for PC", + }, + "Community 1080p Low estimate": { + "short": "the 1080p Low estimate", + "subtitle": "Community estimate for 1080p Low", + "cpu_ref": ["Intel Core i5-12400F", "AMD Ryzen 5 5600"], + "cpu_text": "i5-12400F or Ryzen 5 5600", + "gpu_ref": ["NVIDIA GeForce RTX 3060", "AMD Radeon RX 6700 XT"], + "gpu_text": "RTX 3060 12 GB or RX 6700 XT", + "ram": 16, "ram_text": "16 GB", + }, +} +CPU_TOL, GPU_TOL = 0.10, 0.05 + + +def _judge(score, lo, hi, tol): + if score is None: + return UNKNOWN + if score < lo * (1 - tol): + return BELOW + if score > hi * (1 + tol): + return ABOVE + return IN_RANGE + + +def _judge_ram(ram, ref): + if ram is None: + return UNKNOWN + if ram < ref * 0.9: + return BELOW + if ram <= ref * 1.1: + return IN_RANGE + return ABOVE + + +def _join(items): + """["CPU", "GPU", "RAM"] -> "CPU, GPU and RAM".""" + return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1] + + +def evaluate(profile_name: str, cpu: str, gpu: str, ram): + """Compare the hardware with a profile. Returns (headline, subtitle, rows).""" + p = PROFILES[profile_name] + cs = [cpu_score(n) for n in p["cpu_ref"]] + gs = [gpu_score(n) for n in p["gpu_ref"]] + cpu_s, cpu_exact = cpu_lookup(cpu) + gpu_s, gpu_exact = gpu_lookup(gpu) + rows = [ + ("CPU", _judge(cpu_s, min(cs), max(cs), CPU_TOL), p["cpu_text"], cpu.strip(), + cpu_s is not None and not cpu_exact), + ("GPU", _judge(gpu_s, min(gs), max(gs), GPU_TOL), p["gpu_text"], gpu.strip(), + gpu_s is not None and not gpu_exact), + ("RAM", _judge_ram(ram, p["ram"]), p["ram_text"], f"{ram} GB" if ram else "", False), + ] + weak = [r[0] for r in rows if r[1] == BELOW] + unknown = [r[3] or r[0] for r in rows if r[1] == UNKNOWN] + if weak: + verb = "is" if len(weak) == 1 else "are" + return ("Probably not enough", + f"The {_join(weak)} {verb} weaker than {p['short']}.", rows) + if unknown: + return ("Can't tell yet", + f"Not recognised: {_join(unknown)}. Pick it from the list to compare.", + rows) + return ("Looks good", p["subtitle"], rows) + + +def result_as_text(profile_name, headline, sub, rows): + lines = [f"Leonida PC Checker - vs {profile_name}", headline, sub, ""] + for label, st, ref, mine, est in rows: + note = ", score estimated" if est else "" + lines.append(f"{label}: {STATUS_TEXT[st]} (ref: {ref}; your PC: {mine or '?'}{note})") + lines += ["", f"{BOOT_NOTE[0]} ({BOOT_NOTE[1].rstrip('.')})."] + return "\n".join(lines) + + +# ---------------------------------------------------------------------------- +# Hardware detection +# ---------------------------------------------------------------------------- +def _run(cmd, timeout=10) -> str: + kw = {} + if os.name == "nt": + kw["creationflags"] = 0x08000000 # CREATE_NO_WINDOW + try: + r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", + errors="ignore", timeout=timeout, **kw) + return r.stdout.strip() if r.returncode == 0 else "" + except Exception: + return "" + + +def clean_name(name: str) -> str: + s = re.sub(r"\((?:r|tm)\)|[®™]", "", name, flags=re.I) + s = re.sub(r"@.*$", "", s) + s = re.sub(r"\b\d+-core processor\b|\bprocessor\b|\bcpu\b", "", s, flags=re.I) + return re.sub(r"\s+", " ", s).strip() + + +def detect_cpu() -> str: + try: + if sys.platform == "win32": + import winreg + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, + r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as k: + return clean_name(winreg.QueryValueEx(k, "ProcessorNameString")[0]) + if sys.platform == "darwin": + out = _run(["sysctl", "-n", "machdep.cpu.brand_string"]) + if out: + return clean_name(out) + else: + with open("/proc/cpuinfo", encoding="utf-8", errors="ignore") as f: + for line in f: + if line.lower().startswith("model name"): + return clean_name(line.split(":", 1)[1]) + except Exception: + pass + return clean_name(platform.processor() or "") + + +def _win_vram_map() -> dict: + """VRAM per adapter from the registry (Win32_VideoController caps at 4 GB).""" + found = {} + try: + import winreg + base = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, base) as root: + for i in range(32): + try: + with winreg.OpenKey(root, f"{i:04d}") as k: + desc = winreg.QueryValueEx(k, "DriverDesc")[0] + val = winreg.QueryValueEx(k, "HardwareInformation.qwMemorySize")[0] + if isinstance(val, bytes): + val = int.from_bytes(val, "little") + found[desc.lower()] = val / 2**30 + except OSError: + continue + except Exception: + pass + return found + + +def detect_gpus() -> list: + """All GPUs found, as (name, vram_gb or None).""" + gpus = [] + smi = shutil.which("nvidia-smi") + if smi: + out = _run([smi, "--query-gpu=name,memory.total", "--format=csv,noheader,nounits"]) + for line in out.splitlines(): + parts = [p.strip() for p in line.split(",")] + if not parts or not parts[0]: + continue + try: + gpus.append((parts[0], round(float(parts[1]) / 1024))) + except (IndexError, ValueError): + gpus.append((parts[0], None)) + + if sys.platform == "win32": + out = _run(["powershell", "-NoProfile", "-Command", + "Get-CimInstance Win32_VideoController | " + "Select-Object Name,AdapterRAM | ConvertTo-Json -Compress"]) + try: + data = json.loads(out) if out else [] + data = [data] if isinstance(data, dict) else data + except ValueError: + data = [] + vmap = _win_vram_map() + for d in data: + name = (d.get("Name") or "").strip() + if not name or any(name.lower() == g[0].lower() for g in gpus): + continue + vram = vmap.get(name.lower()) + if vram is None and d.get("AdapterRAM"): + vram = d["AdapterRAM"] / 2**30 + gpus.append((name, round(vram) if vram else None)) + elif sys.platform == "darwin": + out = _run(["system_profiler", "SPDisplaysDataType", "-json"], timeout=20) + try: + for d in json.loads(out).get("SPDisplaysDataType", []): + if d.get("sppci_model"): + gpus.append((d["sppci_model"], None)) + except ValueError: + pass + else: + for line in _run(["lspci", "-mm"]).splitlines(): + try: + tok = shlex.split(line) + except ValueError: + continue + if len(tok) < 4 or not re.search(r"vga|3d|display", tok[1], re.I): + continue + vend = tok[2].lower() + vname = ("NVIDIA" if "nvidia" in vend else + "AMD" if ("amd" in vend or "advanced micro" in vend) else + "Intel" if "intel" in vend else tok[2]) + br = re.search(r"\[(.+)\]", tok[3]) + name = f"{vname} {br.group(1) if br else tok[3]}" + if vname == "NVIDIA" and any("nvidia" in g[0].lower() for g in gpus): + continue # already reported by nvidia-smi + gpus.append((name, None)) + return gpus + + +def _total_ram_bytes(): + try: + if sys.platform == "win32": + class MemStat(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), + ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), + ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), + ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + st = MemStat() + st.dwLength = ctypes.sizeof(st) + ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(st)) + return st.ullTotalPhys + if sys.platform == "darwin": + return int(_run(["sysctl", "-n", "hw.memsize"])) + with open("/proc/meminfo", encoding="ascii") as f: + return int(f.readline().split()[1]) * 1024 + except Exception: + return None + + +def detect_ram_gb(): + total = _total_ram_bytes() + if not total: + return None + gb = total / 2**30 + # The OS reports a bit less than installed (31.8 GB for a 32 GB kit) + for common in (4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128): + if abs(gb - common) / common < 0.08: + return common + return max(4, min(128, round(gb))) + + +def detect_all() -> dict: + best = None + for name, vram in detect_gpus(): # with several GPUs, use the strongest + sc = gpu_score(name) + sc = -1 if sc is None else sc + if best is None or sc > best[0]: + best = (sc, name, vram) + gpu = "" + if best: + gpu = clean_name(best[1]) + if best[2]: + gpu += f" ({best[2]} GB VRAM)" + return {"cpu": detect_cpu(), "gpu": gpu, "ram": detect_ram_gb()} + + +# ---------------------------------------------------------------------------- +# Reusable API (for a launcher or a future boot check) +# ---------------------------------------------------------------------------- +SKIP_ENV = "LEONIDA_SKIP_SPEC_CHECK" +GOOD, WEAK = "good", "weak" # Report.verdict; the third value is UNKNOWN + + +@dataclass +class Check: + component: str + status: str + reference: str + detected: str + estimated: bool = False + + +@dataclass +class Report: + profile: str + headline: str + summary: str + checks: list + + @property + def verdict(self) -> str: + statuses = [c.status for c in self.checks] + if BELOW in statuses: + return WEAK + return UNKNOWN if UNKNOWN in statuses else GOOD + + @property + def weak_parts(self) -> list: + return [c.component for c in self.checks if c.status == BELOW] + + def as_text(self) -> str: + rows = [(c.component, c.status, c.reference, c.detected, c.estimated) + for c in self.checks] + return result_as_text(self.profile, self.headline, self.summary, rows) + + def as_dict(self) -> dict: + d = asdict(self) + d["verdict"] = self.verdict + return d + + +class SpecChecker: + """Compare a PC with a reference profile. + + checker = SpecChecker() + if not checker.warn_if_weak(): + sys.exit(0) # the player chose not to launch + """ + + def __init__(self, profile=None): + self.profile = profile or next(iter(PROFILES)) + if self.profile not in PROFILES: + raise ValueError(f"unknown profile {self.profile!r}; use one of {list(PROFILES)}") + + def check(self, cpu=None, gpu=None, ram=None) -> Report: + """Anything left as None is detected from this PC.""" + if cpu is None or gpu is None or ram is None: + info = detect_all() + cpu = info["cpu"] if cpu is None else cpu + gpu = info["gpu"] if gpu is None else gpu + ram = info["ram"] if ram is None else ram + headline, summary, rows = evaluate(self.profile, cpu, gpu, ram) + return Report(self.profile, headline, summary, [Check(*r) for r in rows]) + + def warn_if_weak(self, report=None) -> bool: + """Show a popup if the PC is weak. Returns False only if the player + chooses not to launch; it never blocks otherwise. Set + LEONIDA_SKIP_SPEC_CHECK=1 to skip the check.""" + if os.environ.get(SKIP_ENV): + return True + report = report or self.check() + if report.verdict != WEAK: + return True + msg = f"Leonida may run poorly on this PC.\n\n{report.summary}" + if tk is None or messagebox is None: + print(msg, file=sys.stderr) + return True + try: + root = tk.Tk() + root.withdraw() + try: + return messagebox.askyesno("Leonida", msg + "\n\nLaunch anyway?", + icon="warning") + finally: + root.destroy() + except tk.TclError: # no display available + print(msg, file=sys.stderr) + return True + + +# ---------------------------------------------------------------------------- +# GUI +# ---------------------------------------------------------------------------- +BG = "#161029" +CARD_L, BORDER_L = "#12162c", "#3b6b80" # teal side: your PC +CARD_R, BORDER_R = "#2b1a3d", "#7a4378" # pink side: result +DIVIDER, FIELD = "#5b3d63", "#0b0e1f" +FG, MUTED = "#f4f1fb", "#b7aecd" +PINK, MINT, ORANGE, GRAY = "#ff9fd2", "#7ff0d0", "#ffc078", "#9b97ad" +STATUS_COLOR = {IN_RANGE: MINT, ABOVE: MINT, BELOW: ORANGE, UNKNOWN: GRAY} +FONT = "Segoe UI" +NOTE = ("CPU and GPU scores are rough estimates, not benchmarks. Reference ranges " + "come from community comparisons.") + + +def _lerp(a: str, b: str, t: float) -> str: + ca = [int(a[i:i + 2], 16) for i in (1, 3, 5)] + cb = [int(b[i:i + 2], 16) for i in (1, 3, 5)] + return "#" + "".join(f"{round(x + (y - x) * t):02x}" for x, y in zip(ca, cb)) + + +class App: + def __init__(self, root): + self.root = root + root.title("Leonida PC Checker") + root.geometry("1000x640") + root.minsize(900, 600) + root.configure(bg=BG) + self.q = queue.Queue() + self.last_text = "" + self.wrapped = [] # (label, margin) pairs re-wrapped on resize + self._style() + + self.profile_var = tk.StringVar(value=list(PROFILES)[0]) + self.cpu_var = tk.StringVar() + self.gpu_var = tk.StringVar() + self.ram_var = tk.StringVar(value="16") + + self._stripe() + self._title() + body = tk.Frame(root, bg=BG) + body.pack(fill="both", expand=True, padx=40, pady=(0, 32)) + body.columnconfigure(0, weight=1, uniform="c") + body.columnconfigure(1, weight=1, uniform="c") + body.rowconfigure(0, weight=1) + self._left(body) + self._right(body) + + for v in (self.profile_var, self.cpu_var, self.gpu_var, self.ram_var): + v.trace_add("write", self.refresh) + self.refresh() + self.start_detect() + + def _style(self): + st = ttk.Style() + try: + st.theme_use("clam") + except tk.TclError: + pass + for name in ("TCombobox", "TSpinbox"): + st.configure(name, fieldbackground=FIELD, background=FIELD, foreground=FG, + arrowcolor=MINT, bordercolor=BORDER_L, lightcolor=FIELD, + darkcolor=FIELD, padding=6) + st.map(name, bordercolor=[("focus", MINT)]) + st.map("TCombobox", fieldbackground=[("readonly", FIELD)], + foreground=[("readonly", FG)], selectbackground=[("readonly", FIELD)], + selectforeground=[("readonly", FG)]) + self.root.option_add("*TCombobox*Listbox.background", FIELD) + self.root.option_add("*TCombobox*Listbox.foreground", FG) + self.root.option_add("*TCombobox*Listbox.selectBackground", BORDER_L) + self.root.option_add("*TCombobox*Listbox.font", (FONT, 11)) + + def _stripe(self): + """Thin pink-to-mint strip across the top.""" + c = tk.Canvas(self.root, height=4, bg=BG, highlightthickness=0) + c.pack(fill="x") + + def draw(e): + c.delete("all") + step = 4 + for x in range(0, e.width, step): + c.create_rectangle(x, 0, x + step, 4, width=0, + fill=_lerp(PINK, MINT, x / max(e.width, 1))) + c.bind("", draw) + + def _title(self): + t = tk.Frame(self.root, bg=BG) + t.pack(fill="x", padx=40, pady=(24, 18)) + f = (FONT, 26, "bold") + tk.Label(t, text="Can my PC run ", font=f, fg=FG, bg=BG).pack(side="left") + tk.Label(t, text="Leonida?", font=f, fg=PINK, bg=BG).pack(side="left") + + def _card(self, parent, col, bg, border, padx): + card = tk.Frame(parent, bg=bg, highlightbackground=border, highlightthickness=1, + padx=26, pady=22) + card.grid(row=0, column=col, sticky="nsew", padx=padx) + return card + + def _text(self, parent, bg, text="", size=10, bold=False, fg=MUTED, pady=0): + lb = tk.Label(parent, text=text, bg=bg, fg=fg, anchor="w", justify="left", + font=(FONT, size, "bold" if bold else "normal")) + lb.pack(fill="x", pady=pady) + self.wrapped.append((lb, 60)) + return lb + + def _rewrap(self, card): + w = card.winfo_width() - 60 + if w > 100: + for lb, _ in self.wrapped: + if lb.master is card or str(lb).startswith(str(card)): + lb.config(wraplength=w) + + def _left(self, body): + card = self._card(body, 0, CARD_L, BORDER_L, (0, 12)) + + self.btn = tk.Button(card, text="Detect my PC", font=(FONT, 11, "bold"), bg=MINT, + fg="#0b1f1a", activebackground="#a6f6e0", relief="flat", + cursor="hand2", pady=9, command=self.start_detect) + self.btn.pack(fill="x") + self.status = self._text(card, CARD_L, size=9, pady=(8, 0)) + + def label(text): + tk.Label(card, text=text, font=(FONT, 10), fg=MUTED, bg=CARD_L, anchor="w" + ).pack(fill="x", pady=(16, 4)) + + label("Compare against") + ttk.Combobox(card, textvariable=self.profile_var, values=list(PROFILES), + state="readonly", font=(FONT, 11)).pack(fill="x") + label("CPU") + ttk.Combobox(card, textvariable=self.cpu_var, values=CPU_CHOICES, + font=(FONT, 11)).pack(fill="x") + label("GPU") + ttk.Combobox(card, textvariable=self.gpu_var, values=GPU_CHOICES, + font=(FONT, 11)).pack(fill="x") + + row = tk.Frame(card, bg=CARD_L) + row.pack(fill="x", pady=(16, 0)) + tk.Label(row, text="RAM", font=(FONT, 10), fg=MUTED, bg=CARD_L).pack(side="left") + tk.Label(row, text="GB", font=(FONT, 11, "bold"), fg=FG, bg=CARD_L + ).pack(side="right") + ttk.Spinbox(row, from_=4, to=128, width=5, textvariable=self.ram_var, + font=(FONT, 11, "bold")).pack(side="right", padx=6) + card.bind("", lambda e: self._rewrap(card)) + + def _right(self, body): + card = self._card(body, 1, CARD_R, BORDER_R, (12, 0)) + + self.headline = self._text(card, CARD_R, size=22, bold=True, fg=FG) + self.sub = self._text(card, CARD_R, pady=(6, 4)) + + self.rows = [] + for name in ("CPU", "GPU", "RAM"): + tk.Frame(card, height=1, bg=DIVIDER).pack(fill="x", pady=(10, 0)) + f = tk.Frame(card, bg=CARD_R) + f.pack(fill="x", pady=(8, 0)) + top = tk.Frame(f, bg=CARD_R) + top.pack(fill="x") + tk.Label(top, text=name, font=(FONT, 11, "bold"), fg=FG, bg=CARD_R + ).pack(side="left") + res = tk.Label(top, text="", font=(FONT, 11, "bold"), bg=CARD_R) + res.pack(side="right") + ref = self._text(f, CARD_R, fg=FG) + mine = self._text(f, CARD_R, size=9) + self.rows.append((res, ref, mine)) + + tk.Frame(card, height=1, bg=DIVIDER).pack(fill="x", pady=(12, 0)) + self._text(card, CARD_R, BOOT_NOTE[0], bold=True, fg=FG, pady=(10, 0)) + self._text(card, CARD_R, BOOT_NOTE[1]) + + self.copy_btn = tk.Button(card, text="Copy result", font=(FONT, 10), bg="#3d2650", + fg=FG, activebackground="#52346b", activeforeground=FG, + relief="flat", cursor="hand2", pady=6, command=self.copy) + self.copy_btn.pack(side="bottom", fill="x", pady=(10, 0)) + self._text(card, CARD_R, NOTE, size=8, pady=(12, 0)).pack_configure(side="bottom") + card.bind("", lambda e: self._rewrap(card)) + + def get_ram(self): + try: + v = int(float(self.ram_var.get())) + return v if v > 0 else None + except ValueError: + return None + + def refresh(self, *_): + name = self.profile_var.get() + headline, sub, rows = evaluate(name, self.cpu_var.get(), self.gpu_var.get(), + self.get_ram()) + self.headline.config(text=headline) + self.sub.config(text=sub) + for (res, ref, mine), (_lbl, st, ref_text, mine_text, est) in zip(self.rows, rows): + res.config(text=STATUS_TEXT[st], fg=STATUS_COLOR[st]) + ref.config(text=f"Reference: {ref_text}") + mine.config(text=f"Your PC: {mine_text or 'no data'}" + + (" (score estimated)" if est else "")) + self.last_text = result_as_text(name, headline, sub, rows) + + def copy(self): + self.root.clipboard_clear() + self.root.clipboard_append(self.last_text) + self.copy_btn.config(text="Copied") + self.root.after(1500, lambda: self.copy_btn.config(text="Copy result")) + + # Detection runs in a thread so the window doesn't freeze + def start_detect(self): + self.btn.config(state="disabled") + self.status.config(text="Detecting...", fg=MUTED) + + def work(): + try: + info = detect_all() + except Exception: + info = {"cpu": "", "gpu": "", "ram": None} + self.q.put(info) + + threading.Thread(target=work, daemon=True).start() + self.root.after(150, self._poll) + + def _poll(self): + try: + info = self.q.get_nowait() + except queue.Empty: + self.root.after(150, self._poll) + return + self.btn.config(state="normal") + missing = [] + for key, var, label in (("cpu", self.cpu_var, "CPU"), ("gpu", self.gpu_var, "GPU"), + ("ram", self.ram_var, "RAM")): + if info[key]: + var.set(str(info[key])) + else: + missing.append(label) + if missing: + self.status.config(text=f"Couldn't detect {', '.join(missing)}. " + "Pick from the lists.", fg=ORANGE) + elif gpu_score(info["gpu"]) is None or cpu_score(info["cpu"]) is None: + self.status.config(text="Detected, but a component isn't recognised. " + "Pick the closest match from the list.", fg=ORANGE) + else: + self.status.config(text="Detected.", fg=MINT) + + +def run_gui(): + if sys.platform == "win32": + try: + ctypes.windll.shcore.SetProcessDpiAwareness(1) + except Exception: + pass + root = tk.Tk() + App(root) + root.mainloop() + + +# ---------------------------------------------------------------------------- +# CLI +# ---------------------------------------------------------------------------- +def _pick_profile(n: int) -> str: + names = list(PROFILES) + return names[max(1, min(n, len(names))) - 1] + + +def run_check(args) -> int: + """No window. Exit code: 0 good, 1 weak, 2 unknown, 3 player declined (--warn).""" + checker = SpecChecker(_pick_profile(args.profile)) + report = checker.check(args.cpu, args.gpu, args.ram) + print(json.dumps(report.as_dict(), indent=2) if args.json else report.as_text()) + if args.warn and not checker.warn_if_weak(report): + return 3 + return {GOOD: 0, WEAK: 1}.get(report.verdict, 2) + + +def run_cli(args): + profile = _pick_profile(args.profile) + info = detect_all() if not (args.cpu and args.gpu and args.ram) else {} + cpu = args.cpu or info.get("cpu", "") + gpu = args.gpu or info.get("gpu", "") + ram = args.ram or info.get("ram") + print(f"PC -> CPU: {cpu or '?'} | GPU: {gpu or '?'} | RAM: {ram or '?'} GB\n") + print(result_as_text(profile, *evaluate(profile, cpu, gpu, ram))) + + +def main(): + ap = argparse.ArgumentParser(description="Compare this PC with the Leonida reference specs") + ap.add_argument("--cli", action="store_true", help="text mode, no window") + ap.add_argument("--profile", type=int, default=1, + help="1 = Xbox Series X, 2 = community 1080p Low estimate") + ap.add_argument("--cpu", help="override the detected CPU") + ap.add_argument("--gpu", help="override the detected GPU") + ap.add_argument("--ram", type=int, help="override the detected RAM, in GB") + ap.add_argument("--check", action="store_true", + help="no window; exit code 0 good, 1 weak, 2 unknown (3 with --warn if declined)") + ap.add_argument("--json", action="store_true", help="with --check: print JSON") + ap.add_argument("--warn", action="store_true", + help="with --check: show a popup when the PC is weak") + args = ap.parse_args() + if args.check: + sys.exit(run_check(args)) + if args.cli or tk is None: + if tk is None and not args.cli: + print("tkinter isn't available; using text mode.\n") + run_cli(args) + else: + run_gui() + + +if __name__ == "__main__": + sys.stdout.reconfigure(errors="replace") + main() \ No newline at end of file diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py index fb4b6320a..d13aea617 100644 --- a/tools/pe_inspect.py +++ b/tools/pe_inspect.py @@ -465,6 +465,11 @@ def main(argv: list[str] | None = None) -> int: ap.add_argument("--game-dir") ap.add_argument("--out", default=os.path.join(os.path.dirname(__file__), "..", "reports", "pe")) a = ap.parse_args(argv) + missing = [img for img in a.image if not os.path.exists(img)] + if missing: + for img in missing: + print(f"ERROR: {img}: does not exist", file=sys.stderr) + return 2 if os.path.isfile(a.out): print(f"cannot create output directory {a.out}: path is a file, not a directory", file=sys.stderr) return 1 diff --git a/tools/ps_helper_probe.py b/tools/ps_helper_probe.py new file mode 100644 index 000000000..e2ec420fd --- /dev/null +++ b/tools/ps_helper_probe.py @@ -0,0 +1,288 @@ +r"""SHADER-681: measure pixel-shader helper lanes at a triangle edge on an AMD GPU (raw RDNA2 ISA, ps_oracle.py). + +docs/design.md's whole-quad-mode row left "helper-invocation behaviour at triangle edges" untested, and the +translator's model of a pixel wave's entry EXEC (helpers off until s_wqm turns their quad on) came from the ISA guide +and ACO. This draws one triangle whose edge cuts 2x2 quads of a 16 x 16 target (vertices (-1, -1), (1.3, -1), +(-1, 0.9); the varying at location 0 is the vertex position, so every lane's interpolated value is its own pixel +centre in NDC) and runs seven wave64 programs as the pixel shader: + + masks, self each covered lane exports its lane id, the wave's EXEC at entry and after s_wqm_b64 + nb12, nb3 after s_wqm, each covered lane reads its quad neighbours' interpolated x/y through DPP quad_perm, + so a helper's values reach the target through a covered pixel + nowqm_ij no s_wqm: a helper's raw I/J (v0/v1) and an unwritten VGPR, read with fetch-inactive DPP, and a + DPP read of an inactive lane without fi into a preloaded destination + nowqm_masks no s_wqm: EXEC at entry and later + helper_export after s_wqm (helpers on in EXEC) an `exp mrt0 ... done vm`: are pixels outside the triangle written? + +The template pixel shader takes a derivative (OpDPdx), so the driver builds it as a shader that needs quads. Every +check and its result is printed; --json writes the raw words. Standard library only, no game files. + + python -I tools/ps_helper_probe.py --build [--json out.json] + +Select the GPU with LEONIDA_VK_DEVICE, as for ps_oracle. Exit codes: 0 every check holds (the gfx1036 +measurement), 1 a check differs, 2 a harness error, 77 no pixel-shader oracle on this device (see ps_oracle) or a +wave32 pixel stage (the programs are wave64). +""" +import argparse +import json +import os +import struct +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import ps_oracle # noqa: E402 + +SIZE = (16, 16) +TRI = ((-1.0, -1.0), (1.3, -1.0), (-1.0, 0.9)) +CLEAR = (0xBF800000,) * 4 # vk_harness clears to -1.0 +SENTINEL = 0x11111111 + +VS_EDGE = """\ + OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint Vertex %main "main" %vid %pos %out0 + OpDecorate %vid BuiltIn VertexIndex + OpDecorate %pos BuiltIn Position + OpDecorate %out0 Location 0 + %void = OpTypeVoid + %fn = OpTypeFunction %void + %uint = OpTypeInt 32 0 + %int = OpTypeInt 32 1 + %float = OpTypeFloat 32 + %v4 = OpTypeVector %float 4 + %p_in = OpTypePointer Input %int + %p_out = OpTypePointer Output %v4 + %u3 = OpConstant %uint 3 + %arr = OpTypeArray %v4 %u3 + %p_arr = OpTypePointer Function %arr + %p_v4 = OpTypePointer Function %v4 + %fm1 = OpConstant %float -1 + %f0 = OpConstant %float 0 + %f1 = OpConstant %float 1 + %fx1 = OpConstant %float {bx} + %fy2 = OpConstant %float {cy} + %p0 = OpConstantComposite %v4 %fm1 %fm1 %f0 %f1 + %p1 = OpConstantComposite %v4 %fx1 %fm1 %f0 %f1 + %p2 = OpConstantComposite %v4 %fm1 %fy2 %f0 %f1 + %pa = OpConstantComposite %arr %p0 %p1 %p2 + %vid = OpVariable %p_in Input + %pos = OpVariable %p_out Output + %out0 = OpVariable %p_out Output + %main = OpFunction %void None %fn + %e = OpLabel + %vp = OpVariable %p_arr Function + OpStore %vp %pa + %i = OpLoad %int %vid + %pp = OpAccessChain %p_v4 %vp %i + %p = OpLoad %v4 %pp + OpStore %pos %p + OpStore %out0 %p + OpReturn + OpFunctionEnd +""".format(bx=TRI[1][0], cy=TRI[2][1]) + +PS_DERIV = """\ + OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %in0 %out + OpExecutionMode %main OriginUpperLeft + OpDecorate %out Location 0 + OpDecorate %in0 Location 0 + %void = OpTypeVoid + %fn = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4 = OpTypeVector %float 4 + %p_in = OpTypePointer Input %v4 + %p_out = OpTypePointer Output %v4 + %out = OpVariable %p_out Output + %in0 = OpVariable %p_in Input + %f1 = OpConstant %float 1 + %main = OpFunction %void None %fn + %e = OpLabel + %a = OpLoad %v4 %in0 + %x = OpCompositeExtract %float %a 0 + %y = OpCompositeExtract %float %a 1 + %dx = OpDPdx %float %x + %r = OpCompositeConstruct %v4 %x %y %dx %f1 + OpStore %out %r + OpReturn + OpFunctionEnd +""" + +DPP = " row_mask:0xf bank_mask:0xf" +# v0/v1 = I/J and M0 from s2, as --show-template prints for this template on gfx1036 (RADV) +HEAD = ["s_mov_b64 s[20:21], exec", "{wqm}", "s_mov_b64 s[22:23], exec", "s_mov_b32 m0, s2", + "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", + "v_interp_p1_f32_e32 v3, v0, attr0.y", "v_interp_p2_f32_e32 v3, v1, attr0.y", + "v_mbcnt_lo_u32_b32 v4, -1, 0", "v_mbcnt_hi_u32_b32 v4, -1, v4"] +RESTORE = ["s_mov_b64 exec, s[20:21]"] +X1, X2, X3 = "quad_perm:[1,0,3,2]", "quad_perm:[2,3,0,1]", "quad_perm:[3,2,1,0]" # lane ^ 1, ^ 2, ^ 3 +PROGRAMS = { + "masks": (True, RESTORE + ["v_mov_b32_e32 v5, s20", "v_mov_b32_e32 v6, s21", "v_mov_b32_e32 v7, s22", + "exp mrt0, v4, v5, v6, v7 done vm", "s_endpgm"]), + "self": (True, RESTORE + ["v_mov_b32_e32 v5, s23", "exp mrt0, v4, v5, v2, v3 done vm", "s_endpgm"]), + "nb12": (True, [f"v_mov_b32_dpp v5, v2 {X1}{DPP}", f"v_mov_b32_dpp v6, v3 {X1}{DPP}", + f"v_mov_b32_dpp v7, v2 {X2}{DPP}", f"v_mov_b32_dpp v8, v3 {X2}{DPP}"] + RESTORE + + ["exp mrt0, v5, v6, v7, v8 done vm", "s_endpgm"]), + "nb3": (True, [f"v_mov_b32_dpp v5, v2 {X3}{DPP}", f"v_mov_b32_dpp v6, v3 {X3}{DPP}"] + RESTORE + + ["exp mrt0, v5, v6, v5, v6 done vm", "s_endpgm"]), + "nowqm_ij": (False, ["v_mov_b32_e32 v9, 0x7fc0dead", + f"v_mov_b32_dpp v5, v0 {X1}{DPP} fi:1", f"v_mov_b32_dpp v6, v1 {X1}{DPP} fi:1", + f"v_mov_b32_dpp v7, v2 {X1}{DPP} fi:1", + f"v_mov_b32_e32 v8, 0x{SENTINEL:08x}", f"v_mov_b32_dpp v8, v9 {X1}{DPP}", + "exp mrt0, v5, v6, v7, v8 done vm", "s_endpgm"]), + "nowqm_masks": (False, ["v_mov_b32_e32 v5, s20", "v_mov_b32_e32 v6, s21", "v_mov_b32_e32 v7, s22", + "exp mrt0, v4, v5, v6, v7 done vm", "s_endpgm"]), + "helper_export": (True, ["v_mov_b32_e32 v5, 0x3f800000", "exp mrt0, v5, v5, v5, v5 done vm", "s_endpgm"]), +} + + +def program(name): + wqm, tail = PROGRAMS[name] + return [ln.format(wqm="s_wqm_b64 exec, exec" if wqm else "s_nop 0") for ln in HEAD] + tail + + +def f32(w): + return struct.unpack("> 1)) + + +def analyze(res, size=SIZE, tri=TRI): + """[(check, ok, detail)] from res: {program name: {(x, y): 4 words}}.""" + cov = {p for p, w in res["masks"].items() if tuple(w) != CLEAR} + lane = {p: res["masks"][p][0] for p in cov} + entry = {p: res["masks"][p][1] | res["masks"][p][2] << 32 for p in cov} + wqm = {p: res["masks"][p][3] | res["self"][p][1] << 32 for p in cov} + helpers = {(p, k) for p in cov for k in (1, 2, 3) if neighbour(p, k) not in cov} + out = [("partial quads at the edge", bool(helpers), f"{len(cov)} covered pixels, {len(helpers)} (covered lane, " + "helper neighbour) pairs")] + waves = {} + for p in cov: + waves.setdefault(entry[p], []).append(p) + entry_ok, wqm_ok, packed, detail = True, True, True, [] + for e, pix in sorted(waves.items()): + lanes = [lane[p] for p in pix] + quads = {ln // 4 for ln in lanes} + w = {wqm[p] for p in pix} + bits = lambda m: {i for i in range(64) if m >> i & 1} # noqa: E731 + entry_ok &= len(set(lanes)) == len(lanes) and bits(e) == set(lanes) + wqm_ok &= len(w) == 1 and bits(w.pop() if len(w) == 1 else 0) == {4 * q + i for q in quads for i in range(4)} + packed &= quads == set(range(len(quads))) + detail.append(f"0x{e:016x}: {len(pix)} covered lanes in {len(quads)} quads") + out.append(("entry EXEC = the covered pixels (helpers off)", entry_ok, f"{len(waves)} waves: " + "; ".join(detail))) + out.append(("s_wqm turns on exactly the quads with a covered pixel", wqm_ok, "")) + out.append(("quads packed from lane 0; none without a covered pixel", packed, "")) + order = {(p[0] & 1) + 2 * (p[1] & 1) == lane[p] % 4 for p in cov} + out.append(("lane % 4 = (x & 1) + 2 (y & 1): 0 top-left, 1 top-right, 2 bottom-left, 3 bottom-right", + order == {True}, "")) + err_c = max(max(abs(f32(res["self"][p][2]) - ndc(p, size)[0]), abs(f32(res["self"][p][3]) - ndc(p, size)[1])) + for p in cov) + err_h = 0.0 + for p, k in helpers: + got = {1: res["nb12"][p][0:2], 2: res["nb12"][p][2:4], 3: res["nb3"][p][0:2]}[k] + ex = ndc(neighbour(p, k), size) + err_h = max(err_h, abs(f32(got[0]) - ex[0]), abs(f32(got[1]) - ex[1])) + out.append(("after s_wqm a helper interpolates its own pixel centre, as precisely as a covered pixel", + err_h <= 1.5 * err_c + 1e-6, f"helper |error| max {err_h:.2e}, covered {err_c:.2e}")) + nm = res["nowqm_masks"] + out.append(("without s_wqm EXEC stays the entry mask", all( + (nm[p][1] | nm[p][2] << 32) == entry[p] and nm[p][3] == entry[p] & 0xFFFFFFFF for p in cov), "")) + h1 = [p for p in cov if neighbour(p, 1) not in cov] + ij = {p: (f32(res["nowqm_ij"][p][0]), f32(res["nowqm_ij"][p][1])) for p in h1} + err_ij = max([max(abs(g[0] - bary(neighbour(p, 1), size, tri)[0]), abs(g[1] - bary(neighbour(p, 1), size, tri)[1])) + for p, g in ij.items()] or [0.0]) + out.append(("without s_wqm a helper's v0/v1 already hold its own pixel's I/J (outside: I + J > 1)", + bool(ij) and err_ij < 1e-4 and all(i + j > 1 for i, j in ij.values()), + f"{len(ij)} helpers, |error| max {err_ij:.2e}")) + out.append(("DPP without fi from an inactive lane leaves the destination unchanged", + bool(h1) and {res["nowqm_ij"][p][3] for p in h1} == {SENTINEL}, "")) + written = [p for p, w in res["helper_export"].items() if p not in cov and tuple(w) != CLEAR] + out.append(("an exp ... vm with helpers on in EXEC writes no pixel outside the triangle", not written, + f"{len(written)} written")) + return out + + +def coverage_map(res, size=SIZE): + cov = {p for p, w in res["masks"].items() if tuple(w) != CLEAR} + return ["".join("#" if (x, y) in cov else "." for x in range(size[0])) for y in range(size[1])] + + +def measure(build): + """(device, {program: {(x, y): words}}) on the selected GPU.""" + with tempfile.TemporaryDirectory(prefix="ps_helper_probe_") as d: + vs, ps = os.path.join(d, "vs_edge.spvasm"), os.path.join(d, "ps_deriv.spvasm") + for path, text in ((vs, VS_EDGE), (ps, PS_DERIV)): + with open(path, "w", encoding="utf-8", newline="\n") as fh: + fh.write(text) + return _run(ps_oracle.Oracle(build, vs=vs, ps=ps, size=SIZE, work=os.path.join(d, "work"))) + + +def _run(o): + try: + if not o.wave64: + raise ps_oracle.Unavailable("the pixel stage is wave32; these programs are wave64") + res = {} + for name in PROGRAMS: + px = o.run(program(name)) + res[name] = {(i % SIZE[0], i // SIZE[0]): tuple(w) for i, w in enumerate(px)} + return o.device, res + finally: + o.close() + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--build", required=True, help="runtime build folder with vk_harness") + ap.add_argument("--json", help="write {device, checks, words} here") + a = ap.parse_args(argv) + try: + device, res = measure(a.build) + except ps_oracle.Unavailable as e: + print(f"ps_helper_probe unavailable: {e}") + return 77 + except (OSError, ValueError, RuntimeError) as e: + print(f"ps_helper_probe: {e}") + return 2 + print(f"device: {device}") + print("coverage (# covered):") + for row in coverage_map(res): + print(" " + row) + checks = analyze(res) + for name, ok, detail in checks: + print(f"{'ok ' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail else "")) + good = sum(ok for _n, ok, _d in checks) + print(f"{good}/{len(checks)} checks hold") + if a.json: + with open(a.json, "w", encoding="utf-8", newline="\n") as fh: + json.dump({"device": device, "checks": [[n, ok, d] for n, ok, d in checks], + "words": {n: {f"{x},{y}": list(w) for (x, y), w in px.items()} for n, px in res.items()}}, + fh, indent=1) + return 0 if good == len(checks) else 1 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/psin_data.py b/tools/psin_data.py index 1672fba31..973156330 100644 --- a/tools/psin_data.py +++ b/tools/psin_data.py @@ -285,7 +285,13 @@ class Walker: if t == 0x05: return self.struct(m["ref"], at, depth + 1) if t == 0x07: - r = c.resolve(at, 1, st, "struct pointer") + number, _ = c.pointer(at) + need = 1 + if 1 <= number <= len(c.blocks): + s = c.structs.get(c.blocks[number - 1][0]) + if s is not None: + need = max(1, s["size"]) + r = c.resolve(at, need, st, "struct pointer") if r is None: return None btype, absolute, number = r diff --git a/tools/rbf0_encode.py b/tools/rbf0_encode.py index 2cf46a68e..077888181 100644 --- a/tools/rbf0_encode.py +++ b/tools/rbf0_encode.py @@ -9,18 +9,20 @@ its content in tree order; text and strings with the bytes and terminating NUL t The encoder fails closed. When the tree cannot hold the original bytes it raises EncodeError with a short reason instead of writing something else: status the parse was not complete (bad, truncated, or bytes after the root closed) - utf8 a descriptor name, string or text had invalid UTF-8, which the decoder replaced with U+FFFD + utf8 a descriptor name, string or text had invalid UTF-8, or an edit contains an unpaired surrogate nan a float or vec3 component was NaN, whose bits the tree renders as text (infinities are exact) - order a value counted as an attribute came after the element's content started + order a value counted as an attribute came after the element's content started, or an element short of + its attribute count has a value in its content, which would decode as an attribute descriptor a descriptor index outside the table, or a first use out of order length a string or text no longer has its recorded byte length - value a value the record cannot hold (an integer out of range, an unknown type) + value a value the record cannot hold (an integer out of range, a float that overflows the layout, an + unknown type, more attribute records than the element's attribute count) Usage: python -I rbf0_encode.py --check [--limit N] Decode every RBF0 resource (joining 64 KiB continuations as rbf0_tree.py does), encode it, and compare the result with the original bytes. Prints counts only: exact, different, and refused by reason. Exit 1 when a - resource encodes to different bytes. + resource encodes to different bytes or was refused: only a run where every resource is exact exits 0. python -I rbf0_encode.py Write each resource of an rbf0_tree.py JSON report (possibly edited) as .rbf. The directory must be new or empty. @@ -155,6 +157,14 @@ class _Writer: attrs = node.get("attrs_declared", len(node.get("attributes", []))) if not isinstance(attrs, int) or isinstance(attrs, bool) or not 0 <= attrs <= 0xFFFF: raise EncodeError("value", f"attribute count {attrs!r}") + # The header word says how many of the following value records are attributes. One record more would decode + # as the element's first content value; with fewer, the next content value would decode as an attribute. + listed = len(node.get("attributes", [])) + if listed > attrs: + raise EncodeError("value", f"element {node.get('name')!r} has {listed} attribute records, count {attrs}") + if listed < attrs and any(c.get("kind") == "value" for c in node.get("content", [])): + raise EncodeError("order", f"element {node.get('name')!r} is short of its {attrs} attributes and has a " + "value in its content") self.record(node, 0x00) self.out += struct.pack(" int: + v &= 0xFFFF + return v - 0x10000 if v & 0x8000 else v + + +def _s12(v: int) -> int: + v &= 0xFFF + return v - 0x1000 if v & 0x800 else v + + +def _s21(v: int) -> int: + v &= 0x1FFFFF + return v - 0x200000 if v & 0x100000 else v + + +def _sreg(code: int, n: int) -> dict: + """Decode a scalar destination/source register code (0..127) with width `n` dwords.""" + if code <= 105: + if n <= 1: + return {"k": "sgpr", "r": code, "n": 1, "neg": False, "abs": False} + if code + n <= 106: + return {"k": "sgpr", "r": code, "n": n, "neg": False, "abs": False} + # LLVM VCCTuple spanning SGPRs into vcc_lo (106) / vcc_hi (107). + if code + n <= 108: + items = [] + for r in range(code, code + n): + if r <= 105: + items.append(r) + elif r == 106: + items.append("vcc_lo") + else: + items.append("vcc_hi") + return {"k": "slist", "r": items, "n": n} + return {"k": "sgpr", "r": code, "n": n, "neg": False, "abs": False} + if code == 106: + return {"k": "special", "t": "vcc" if n == 2 else "vcc_lo", "neg": False, "abs": False} + if code == 107: + return {"k": "special", "t": "vcc_hi", "neg": False, "abs": False} + if 108 <= code <= 123: + lo = code - 108 + t = f"ttmp{lo}" if n <= 1 else f"ttmp[{lo}:{lo + n - 1}]" + return {"k": "ttmp", "t": t} + if code == 124: + return {"k": "special", "t": "m0", "neg": False, "abs": False} + if code == 125: + return {"k": "special", "t": "null", "neg": False, "abs": False} + if code == 126: + return {"k": "special", "t": "exec" if n == 2 else "exec_lo", "neg": False, "abs": False} + if code == 127: + return {"k": "special", "t": "exec_hi", "neg": False, "abs": False} + return {"k": "raw", "t": f"sreg_{code}"} + + +def _vreg(reg: int, n: int = 1) -> dict: + return {"k": "vgpr", "r": reg & 0xFF, "n": max(1, n), "neg": False, "abs": False} + + +def _src(code: int, n: int, lit: int | None, *, neg: bool = False, absm: bool = False) -> dict: + """Decode a 9-bit RDNA2 source operand (0..511).""" + if code <= 127: + op = _sreg(code, n) + elif 128 <= code <= 192: + op = {"k": "imm", "v": code - 128} + elif 193 <= code <= 208: + op = {"k": "imm", "v": -(code - 192)} + elif code in _INLINE_FLOAT: + op = {"k": "fimm", "v": _INLINE_FLOAT[code], "abs": False} + elif code == 251: + op = {"k": "special", "t": "src_vccz", "neg": False, "abs": False} + elif code == 252: + op = {"k": "special", "t": "src_execz", "neg": False, "abs": False} + elif code == 253: + op = {"k": "special", "t": "src_scc", "neg": False, "abs": False} + elif code == 254: + op = {"k": "special", "t": "src_lds_direct", "neg": False, "abs": False} + elif code == 255: + op = {"k": "imm", "v": 0 if lit is None else lit} + elif 256 <= code <= 511: + op = _vreg(code - 256, n) + else: + op = {"k": "raw", "t": f"src_{code}"} + + if absm: + op["abs"] = True + if neg: + if op["k"] in ("imm", "fimm"): + # Preserve neg modifier on constants (same semantics as shader_ir.operand("neg(...)")). + op["neg"] = True + else: + op["neg"] = True + return op + + +def _vcc_operand(wave32: bool) -> dict: + return {"k": "special", "t": "vcc_lo" if wave32 else "vcc", "neg": False, "abs": False} + + +def _width(nregs: int, wave32: bool) -> int: + if nregs == -1: + return 1 if wave32 else 2 + return nregs + + +def _format_hwreg(simm16: int) -> str: + reg_id = simm16 & 0x3F + offset = (simm16 >> 6) & 0x1F + size = ((simm16 >> 11) & 0x1F) + 1 + rname = _HWREG_NAMES.get(reg_id, str(reg_id)) + if offset == 0 and size == 32: + return f"hwreg({rname})" + return f"hwreg({rname}, {offset}, {size})" + + +def _format_waitcnt(simm16: int) -> list[dict]: + # GFX10 s_waitcnt layout: vmcnt = bits[3:0] | (bits[15:14] << 4), expcnt = bits[6:4], lgkmcnt = bits[13:8]. + vmcnt = (simm16 & 0xF) | (((simm16 >> 14) & 0x3) << 4) + expcnt = (simm16 >> 4) & 0x7 + lgkmcnt = (simm16 >> 8) & 0x3F + parts = [] + if vmcnt != 63: + parts.append({"k": "special", "t": f"vmcnt({vmcnt})"}) + if expcnt != 7: + parts.append({"k": "special", "t": f"expcnt({expcnt})"}) + if lgkmcnt != 63: + parts.append({"k": "special", "t": f"lgkmcnt({lgkmcnt})"}) + if not parts: + parts.append({"k": "imm", "v": simm16}) + return parts + + +def _format_sendmsg(simm16: int) -> str: + msg_id = simm16 & 0xF + op = (simm16 >> 4) & 0x7 + stream = (simm16 >> 8) & 0x3 + mname = _SENDMSG_NAMES.get(msg_id) + if mname is None: + return f"sendmsg({simm16})" + if msg_id in (2, 3): + op_name = _GS_OPS.get(op, str(op)) + if op == 0: + return f"sendmsg({mname}|{op_name})" + return f"sendmsg({mname}|{op_name}|{stream})" + if op: + return f"sendmsg({mname}|{op})" + return f"sendmsg({mname})" + + +def _format_dpp16_ctrl(ctrl: int) -> str: + if ctrl <= 0xFF: + q = [(ctrl >> (2 * i)) & 3 for i in range(4)] + return f"quad_perm:[{q[0]},{q[1]},{q[2]},{q[3]}]" + if 0x101 <= ctrl <= 0x10F: + return f"row_shl:{ctrl - 0x100}" + if 0x111 <= ctrl <= 0x11F: + return f"row_shr:{ctrl - 0x110}" + if 0x121 <= ctrl <= 0x12F: + return f"row_ror:{ctrl - 0x120}" + if ctrl == 0x140: + return "row_mirror" + if ctrl == 0x141: + return "row_half_mirror" + if 0x150 <= ctrl <= 0x15F: + return f"row_share:{ctrl - 0x150}" + if 0x160 <= ctrl <= 0x16F: + return f"row_xmask:{ctrl - 0x160}" + return f"dpp_ctrl:0x{ctrl:x}" + + +def _format_ds_swizzle(offset16: int) -> str: + if (offset16 & 0x8000) == 0: + # Bitmask mode: bits [4:0] = and_mask, [9:5] = or_mask, [14:10] = xor_mask. + # Match LLVM's canonical aliases (SWAP, REVERSE, BROADCAST) before general BITMASK_PERM. + and_m = offset16 & 0x1F + or_m = (offset16 >> 5) & 0x1F + xor_m = (offset16 >> 10) & 0x1F + if and_m == 0x1F and or_m == 0: + if xor_m in (1, 2, 4, 8, 16): + return f"offset:swizzle(SWAP,{xor_m})" + if xor_m in (3, 7, 15, 31): + return f"offset:swizzle(REVERSE,{xor_m + 1})" + if xor_m == 0 and (or_m & and_m) == 0 and (0x1F ^ and_m) in (1, 3, 7, 15, 31): + grp = (0x1F ^ and_m) + 1 + return f"offset:swizzle(BROADCAST,{grp},{or_m})" + chars = [] + for bit in range(4, -1, -1): + a = (and_m >> bit) & 1 + o = (or_m >> bit) & 1 + x = (xor_m >> bit) & 1 + if a == 0 and o == 0 and x == 0: + chars.append("0") + elif a == 0 and o == 1 and x == 0: + chars.append("1") + elif a == 1 and o == 0 and x == 0: + chars.append("p") + elif a == 1 and o == 0 and x == 1: + chars.append("i") + else: + return f"offset:{offset16}" + return f'offset:swizzle(BITMASK_PERM,"{"".join(chars)}")' + if (offset16 & 0xFF00) == 0x8000: + p = [(offset16 >> (2 * i)) & 3 for i in range(4)] + return f"offset:swizzle(QUAD_PERM,{p[0]},{p[1]},{p[2]},{p[3]})" + return f"offset:{offset16}" + + +def _mimg_addr_count(name: str, dim: int, a16: bool) -> int: + """Number of address VGPRs for an MIMG instruction.""" + if name in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"): + return 11 if name == "image_bvh_intersect_ray" else 12 + if name == "image_get_resinfo": + return 1 + if name == "image_get_lod": + return _MIMG_DIM_COORDS.get(dim, 2) + base = _MIMG_DIM_COORDS.get(dim, 2) + if name.startswith("image_atomic_"): + return (base + 1) // 2 if a16 else base + # Separate 32-bit address components (offset, bias, z-compare, derivatives) from a16-packable coords/lod/clamp. + base_name = name[:-3] if name.endswith("_cl") else name + has_cl = name.endswith("_cl") + fixed32 = 0 + if base_name.endswith("_o") or "_o_" in base_name: + fixed32 += 1 + if "_b" in base_name and not base_name.startswith("image_bvh"): + fixed32 += 1 + if "_c" in base_name and not base_name.startswith(("image_atomic", "image_get")): + fixed32 += 1 + if "_d" in base_name and not base_name.startswith(("image_atomic", "image_get")): + fixed32 += 2 * _MIMG_GRAD_COORDS.get(dim, 2) + packable = base + if "_l" in base_name and "_lz" not in base_name and not base_name.startswith( + ("image_load", "image_store", "image_atomic", "image_get")): + packable += 1 + if has_cl: + packable += 1 + if base_name in ("image_load_mip", "image_store_mip"): + packable += 1 + if a16: + # On GFX10, a16 packs coordinates (and lod/clamp after coords) two 16-bit values per VGPR; clamp/lod + # after 2D coords starts a new VGPR when coords are even (e.g., 2D + cl -> 1 + 1 = 2 VGPRs). + packed = (base + 1) // 2 + (packable - base) + return fixed32 + packed + return fixed32 + packable + + +def _mimg_data_count(name: str, dmask: int, d16: bool, tfe: bool) -> int: + if name in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"): + return 4 + if name.startswith("image_atomic_"): + n = 2 if "cmpswap" in name else 1 + if name.endswith("_x2"): + n *= 2 + return n + if name.startswith("image_gather4"): + n = 4 + else: + n = bin(dmask & 0xF).count("1") or 1 + if d16: + n = (n + 1) // 2 + return n + (1 if tfe else 0) + + +def _decode_one(code: bytes, pc: int, wave32: bool) -> tuple[dict | None, int]: + """Decode one RDNA2 instruction at byte offset `pc`. Returns (ins_dict_or_None, byte_length).""" + if pc + 4 > len(code): + return None, len(code) - pc + w0 = struct.unpack_from(" bool: + return pc + nbytes <= len(code) + + def finish(op: str, args: list, mods: list, nbytes: int) -> tuple[dict, int]: + return { + "op": op, + "args": args, + "mods": mods, + "enc": code[pc:pc + nbytes].hex(), + "pc": pc, + }, nbytes + + # ---- 1. Bit 31 == 0: VOP1 / VOPC / VOP2 (plus DPP16 / DPP8 / SDWA / literal) ---- + if (w0 >> 31) == 0: + hi7 = w0 >> 25 + src0 = w0 & 0x1FF + is_dpp16 = src0 == 250 + is_dpp8 = src0 in (233, 234) + is_sdwa = src0 == 249 + + if hi7 == 0x3F: # VOP1 + opc = (w0 >> 9) & 0xFF + vdst = (w0 >> 17) & 0xFF + entry = T.VOP1.get(opc) + if entry is None: + return None, 4 + name, spec = entry + mods = [] + if is_dpp16 or is_dpp8 or is_sdwa: + if not need(8): + return None, 4 + w1 = struct.unpack_from("> 8) & 0x1FF + fi = (w1 >> 18) & 1 + bc = (w1 >> 19) & 1 + bank_m = (w1 >> 24) & 0xF + row_m = (w1 >> 28) & 0xF + neg0 = bool((w1 >> 20) & 1) + abs0 = bool((w1 >> 21) & 1) + s0 = _vreg(src0_reg, 1) + s0["neg"], s0["abs"] = neg0, abs0 + mods.append(_format_dpp16_ctrl(ctrl)) + mods.append(f"row_mask:0x{row_m:x}") + mods.append(f"bank_mask:0x{bank_m:x}") + if bc: + mods.append("bound_ctrl:1") + if fi: + mods.append("fi:1") + elif is_dpp8: + op_name = name + "_dpp" + lanes = [(w1 >> (8 + 3 * i)) & 7 for i in range(8)] + s0 = _vreg(src0_reg, 1) + mods.append(f"dpp8:[{','.join(str(x) for x in lanes)}]") + if src0 == 234: + mods.append("fi:1") + else: # SDWA + op_name = name + "_sdwa" + dst_sel = (w1 >> 8) & 7 + dst_unused = (w1 >> 11) & 3 + clamp = (w1 >> 13) & 1 + omod = (w1 >> 14) & 3 + src0_sel = (w1 >> 16) & 7 + src0_sext = bool((w1 >> 19) & 1) + src0_neg = bool((w1 >> 20) & 1) + src0_abs = bool((w1 >> 21) & 1) + s0_is_sgpr = bool((w1 >> 23) & 1) + s0 = _src(src0_reg, 1, None) if s0_is_sgpr else _vreg(src0_reg, 1) + if src0_sext: + s0["sext"] = True + s0["neg"], s0["abs"] = src0_neg, src0_abs + if clamp: + mods.append("clamp") + if omod in _OMOD_MODS: + mods.append(_OMOD_MODS[omod]) + mods.append(f"dst_sel:{_SDWA_SELS.get(dst_sel, 'DWORD')}") + mods.append(f"dst_unused:{_SDWA_UNUSED.get(dst_unused, 'UNUSED_PAD')}") + mods.append(f"src0_sel:{_SDWA_SELS.get(src0_sel, 'DWORD')}") + args = [] + for fn, nr, _ in spec: + w = _width(nr, wave32) + if fn == "VDST": + args.append(_vreg(vdst, w)) + elif fn == "SRC0": + args.append(s0) + return finish(op_name, args, mods, nbytes) + lit = None + nbytes = 4 + if src0 == 255: + if not need(8): + return None, 4 + lit = struct.unpack_from("> 17) & 0xFF + vsrc1 = (w0 >> 9) & 0xFF + entry = T.VOPC.get(opc) + if entry is None: + return None, 4 + name, spec = entry + mods = [] + if is_sdwa: + if not need(8): + return None, 4 + w1 = struct.unpack_from("> 8) & 0x7F + sd = bool((w1 >> 15) & 1) + src0_sel = (w1 >> 16) & 7 + src0_sext = bool((w1 >> 19) & 1) + src0_neg = bool((w1 >> 20) & 1) + src0_abs = bool((w1 >> 21) & 1) + s0_is_sgpr = bool((w1 >> 23) & 1) + src1_sel = (w1 >> 24) & 7 + src1_sext = bool((w1 >> 27) & 1) + src1_neg = bool((w1 >> 28) & 1) + src1_abs = bool((w1 >> 29) & 1) + s1_is_sgpr = bool((w1 >> 31) & 1) + s0 = _src(src0_reg, 1, None) if s0_is_sgpr else _vreg(src0_reg, 1) + s1 = _src(vsrc1, 1, None) if s1_is_sgpr else _vreg(vsrc1, 1) + if src0_sext: + s0["sext"] = True + if src1_sext: + s1["sext"] = True + s0["neg"], s0["abs"] = src0_neg, src0_abs + s1["neg"], s1["abs"] = src1_neg, src1_abs + mods.append(f"src0_sel:{_SDWA_SELS.get(src0_sel, 'DWORD')}") + mods.append(f"src1_sel:{_SDWA_SELS.get(src1_sel, 'DWORD')}") + dst_op = _sreg(sdst, 1 if wave32 else 2) if sd else _vcc_operand(wave32) + args = [dst_op, s0, s1] if not name.startswith("v_cmpx_") else [s0, s1] + return finish(name + "_sdwa", args, mods, 8) + lit = None + nbytes = 4 + if src0 == 255: + if not need(8): + return None, 4 + lit = struct.unpack_from("> 25) & 0x3F + vdst = (w0 >> 17) & 0xFF + vsrc1 = (w0 >> 9) & 0xFF + entry = T.VOP2.get(opc) + if entry is None: + return None, 4 + name, spec = entry + mods = [] + if is_dpp16 or is_dpp8 or is_sdwa: + if not need(8): + return None, 4 + w1 = struct.unpack_from("> 8) & 0x1FF + fi = (w1 >> 18) & 1 + bc = (w1 >> 19) & 1 + neg0 = bool((w1 >> 20) & 1) + abs0 = bool((w1 >> 21) & 1) + neg1 = bool((w1 >> 22) & 1) + abs1 = bool((w1 >> 23) & 1) + bank_m = (w1 >> 24) & 0xF + row_m = (w1 >> 28) & 0xF + s0 = _vreg(src0_reg, 1) + s0["neg"], s0["abs"] = neg0, abs0 + s1 = _vreg(vsrc1, 1) + s1["neg"], s1["abs"] = neg1, abs1 + mods.append(_format_dpp16_ctrl(ctrl)) + mods.append(f"row_mask:0x{row_m:x}") + mods.append(f"bank_mask:0x{bank_m:x}") + if bc: + mods.append("bound_ctrl:1") + if fi: + mods.append("fi:1") + elif is_dpp8: + op_name = name + "_dpp" + lanes = [(w1 >> (8 + 3 * i)) & 7 for i in range(8)] + s0 = _vreg(src0_reg, 1) + s1 = _vreg(vsrc1, 1) + mods.append(f"dpp8:[{','.join(str(x) for x in lanes)}]") + if src0 == 234: + mods.append("fi:1") + else: # SDWA + op_name = name + "_sdwa" + dst_sel = (w1 >> 8) & 7 + dst_unused = (w1 >> 11) & 3 + clamp = (w1 >> 13) & 1 + omod = (w1 >> 14) & 3 + src0_sel = (w1 >> 16) & 7 + src0_sext = bool((w1 >> 19) & 1) + src0_neg = bool((w1 >> 20) & 1) + src0_abs = bool((w1 >> 21) & 1) + s0_is_sgpr = bool((w1 >> 23) & 1) + src1_sel = (w1 >> 24) & 7 + src1_sext = bool((w1 >> 27) & 1) + src1_neg = bool((w1 >> 28) & 1) + src1_abs = bool((w1 >> 29) & 1) + s1_is_sgpr = bool((w1 >> 31) & 1) + s0 = _src(src0_reg, 1, None) if s0_is_sgpr else _vreg(src0_reg, 1) + s1 = _src(vsrc1, 1, None) if s1_is_sgpr else _vreg(vsrc1, 1) + if src0_sext: + s0["sext"] = True + if src1_sext: + s1["sext"] = True + s0["neg"], s0["abs"] = src0_neg, src0_abs + s1["neg"], s1["abs"] = src1_neg, src1_abs + if clamp: + mods.append("clamp") + if omod in _OMOD_MODS: + mods.append(_OMOD_MODS[omod]) + mods.append(f"dst_sel:{_SDWA_SELS.get(dst_sel, 'DWORD')}") + mods.append(f"dst_unused:{_SDWA_UNUSED.get(dst_unused, 'UNUSED_PAD')}") + mods.append(f"src0_sel:{_SDWA_SELS.get(src0_sel, 'DWORD')}") + mods.append(f"src1_sel:{_SDWA_SELS.get(src1_sel, 'DWORD')}") + args = [] + for fn, nr, _ in spec: + w = _width(nr, wave32) + if fn == "VDST": + args.append(_vreg(vdst, w)) + elif fn == "VCC": + args.append(_vcc_operand(wave32)) + elif fn == "SRC0": + args.append(s0) + elif fn == "VSRC1": + args.append(s1) + return finish(op_name, args, mods, 8) + + has_lit = (src0 == 255) or (opc in _VOP2_MANDATORY_LITERAL) + lit = None + nbytes = 4 + if has_lit: + if not need(8): + return None, 4 + lit = struct.unpack_from("> 30) == 0b10: + hi9 = w0 >> 23 + if hi9 == 0x17D: # SOP1 + opc = (w0 >> 8) & 0xFF + sdst = (w0 >> 16) & 0x7F + ssrc0 = w0 & 0xFF + entry = T.SOP1.get(opc) + if entry is None: + return None, 4 + name, spec = entry + lit = None + nbytes = 4 + if ssrc0 == 255: + if not need(8): + return None, 4 + lit = struct.unpack_from("> 16) & 0x7F + ssrc0 = w0 & 0xFF + ssrc1 = (w0 >> 8) & 0xFF + entry = T.SOPC.get(opc) + if entry is None: + return None, 4 + name, spec = entry + lit = None + nbytes = 4 + if ssrc0 == 255 or ssrc1 == 255: + if not need(8): + return None, 4 + lit = struct.unpack_from("> 16) & 0x7F + simm16 = w0 & 0xFFFF + entry = T.SOPP.get(opc) + if entry is None: + return None, 4 + name, spec = entry + if name in _SOPP_NO_OPERAND: + return finish(name, [], [], 4) + if name == "s_waitcnt": + return finish(name, _format_waitcnt(simm16), [], 4) + if name == "s_waitcnt_vscnt": + # s_waitcnt_vscnt is SOPK, not SOPP; kept defensive. + return finish(name, [{"k": "imm", "v": simm16}], [], 4) + if name == "s_sendmsg" or name == "s_sendmsghalt": + return finish(name, [{"k": "special", "t": _format_sendmsg(simm16)}], [], 4) + if name in _SOPP_BRANCHES: + return finish(name, [{"k": "imm", "v": _s16(simm16)}], [], 4) + if name == "s_clause": + return finish(name, [{"k": "imm", "v": simm16}], [], 4) + return finish(name, [{"k": "imm", "v": simm16}], [], 4) + + if (w0 >> 28) == 0xB: # SOPK + opc = (w0 >> 23) & 0x1F + sdst = (w0 >> 16) & 0x7F + simm16 = w0 & 0xFFFF + entry = T.SOPK.get(opc) + if entry is None: + return None, 4 + name, spec = entry + lit = None + nbytes = 4 + if opc in _SOPK_MANDATORY_LITERAL: + if not need(8): + return None, 4 + lit = struct.unpack_from("> 23) & 0x7F + sdst = (w0 >> 16) & 0x7F + ssrc1 = (w0 >> 8) & 0xFF + ssrc0 = w0 & 0xFF + entry = T.SOP2.get(opc) + if entry is None: + return None, 4 + name, spec = entry + lit = None + nbytes = 4 + if ssrc0 == 255 or ssrc1 == 255: + if not need(8): + return None, 4 + lit = struct.unpack_from("> 26 + + if hi6 == 0x32: # VINTRP (32-bit!) + opc = (w0 >> 16) & 3 + vdst = (w0 >> 18) & 0xFF + attr = (w0 >> 10) & 0x3F + chan = "xyzw"[(w0 >> 8) & 3] + vsrc = w0 & 0xFF + entry = T.VINTRP.get(opc) + if entry is None: + return None, 4 + name, _ = entry + if name == "v_interp_mov_f32": + p = {0: "p10", 1: "p20", 2: "p0"}.get(vsrc & 3, f"p{vsrc}") + args = [_vreg(vdst, 1), {"k": "interp", "t": p}, {"k": "attr", "a": attr, "c": (w0 >> 8) & 3}] + else: + args = [_vreg(vdst, 1), _vreg(vsrc, 1), {"k": "attr", "a": attr, "c": (w0 >> 8) & 3}] + return finish(name, args, [], 4) + + # All remaining encodings are at least 64 bits. + if not need(8): + return None, 4 + w1 = struct.unpack_from("> 16) & 0x7F + vdst = w0 & 0xFF + neg_hi = (w0 >> 8) & 7 + op_sel = (w0 >> 11) & 7 + op_sel_hi_2 = (w0 >> 14) & 1 + clamp = (w0 >> 15) & 1 + src0 = w1 & 0x1FF + src1 = (w1 >> 9) & 0x1FF + src2 = (w1 >> 18) & 0x1FF + op_sel_hi_01 = (w1 >> 27) & 3 + op_sel_hi = op_sel_hi_01 | (op_sel_hi_2 << 2) + neg_lo = (w1 >> 29) & 7 + entry = T.VOP3P.get(opc) + if entry is None: + return None, 4 + name, spec = entry + lit = None + nbytes = 8 + nsrc = sum(1 for fn, _, _ in spec if fn in ("SRC0", "SRC1", "SRC2")) + srcs_codes = [src0, src1, src2][:nsrc] + if 255 in srcs_codes: + if not need(12): + return None, 4 + lit = struct.unpack_from("> i) & 1 for i in range(nsrc)] + selhi_bits = [(op_sel_hi >> i) & 1 for i in range(nsrc)] + neglo_bits = [(neg_lo >> i) & 1 for i in range(nsrc)] + neghi_bits = [(neg_hi >> i) & 1 for i in range(nsrc)] + # v_fma_mix* uses op_sel/op_sel_hi with default [0,...]; standard packed ops default op_sel_hi to [1,...]. + is_mix = name.startswith("v_fma_mix") + if any(sel_bits): + mods.append(f"op_sel:[{','.join(str(b) for b in sel_bits)}]") + default_hi = [0] * nsrc if is_mix else [1] * nsrc + if selhi_bits != default_hi: + mods.append(f"op_sel_hi:[{','.join(str(b) for b in selhi_bits)}]") + if any(neglo_bits): + mods.append(f"neg_lo:[{','.join(str(b) for b in neglo_bits)}]") + if any(neghi_bits): + mods.append(f"neg_hi:[{','.join(str(b) for b in neghi_bits)}]") + if clamp: + mods.append("clamp") + return finish(name, args, mods, nbytes) + + if hi6 == 0x35: # VOP3 / VOP3B (64-bit, +literal) + opc = (w0 >> 16) & 0x3FF + vdst = w0 & 0xFF + clamp = (w0 >> 15) & 1 + src0 = w1 & 0x1FF + src1 = (w1 >> 9) & 0x1FF + src2 = (w1 >> 18) & 0x1FF + omod = (w1 >> 27) & 3 + neg = (w1 >> 29) & 7 + is_vop3b = opc in T.VOP3B + entry = T.VOP3B.get(opc) if is_vop3b else T.VOP3.get(opc) + if entry is None: + return None, 4 + name, spec = entry + sdst = (w0 >> 8) & 0x7F + abs_bits = 0 if is_vop3b else ((w0 >> 8) & 7) + op_sel = 0 if is_vop3b else ((w0 >> 11) & 0xF) + nsrc = sum(1 for fn, _, _ in spec if fn in ("SRC0", "SRC1", "SRC2")) + srcs_codes = [src0, src1, src2][:nsrc] + lit = None + nbytes = 8 + if 255 in srcs_codes: + if not need(12): + return None, 4 + lit = struct.unpack_from("> 6) & 3}) + if opc in (0x342, 0x343, 0x35A) and ((src0 >> 8) & 1): + mods.append("high") + else: + args.append(_src(src0, w, lit, neg=bool(neg & 1), absm=bool(abs_bits & 1))) + elif fn == "SRC1": + if opc == 0x202: # v_interp_mov_f32_e64: param selector p10/p20/p0 + p = {0: "p10", 1: "p20", 2: "p0"}.get(src1 & 3, f"p{src1}") + args.append({"k": "interp", "t": p}) + else: + args.append(_src(src1, w, lit, neg=bool(neg & 2), absm=bool(abs_bits & 2))) + elif fn == "SRC2": + args.append(_src(src2, w, lit, neg=bool(neg & 4), absm=bool(abs_bits & 4))) + if op_sel: + # op_sel prints [s0,s1,...,dst] (nsrc + 1 bits, or nsrc for VOPC). + nbits = nsrc if opc < 0x100 else (nsrc + 1) + bits = [(op_sel >> i) & 1 for i in range(nsrc)] + if nbits > nsrc: + bits.append((op_sel >> 3) & 1) + mods.append(f"op_sel:[{','.join(str(b) for b in bits)}]") + if clamp: + mods.append("clamp") + if omod in _OMOD_MODS: + mods.append(_OMOD_MODS[omod]) + return finish(op_name, args, mods, nbytes) + + if hi6 == 0x36: # DS (64-bit) + opc = (w0 >> 18) & 0xFF + offset0 = w0 & 0xFF + offset1 = (w0 >> 8) & 0xFF + gds = (w0 >> 17) & 1 + addr = w1 & 0xFF + data0 = (w1 >> 8) & 0xFF + data1 = (w1 >> 16) & 0xFF + vdst = (w1 >> 24) & 0xFF + entry = T.DS.get(opc) + if entry is None: + return None, 4 + name, spec = entry + args = [] + for fn, nr, _ in spec: + w = _width(nr, wave32) + if fn == "VDST": + args.append(_vreg(vdst, w)) + elif fn == "ADDR": + args.append(_vreg(addr, w)) + elif fn == "DATA0": + args.append(_vreg(data0, w)) + elif fn == "DATA1": + args.append(_vreg(data1, w)) + mods = [] + is_2addr = ("2_" in name or "2st64_" in name) + if name == "ds_swizzle_b32": + mods.append(_format_ds_swizzle(offset0 | (offset1 << 8))) + elif is_2addr: + if offset0: + mods.append(f"offset0:{offset0}") + if offset1: + mods.append(f"offset1:{offset1}") + else: + off16 = offset0 | (offset1 << 8) + if off16: + mods.append(f"offset:{off16}") + if gds: + mods.append("gds") + return finish(name, args, mods, 8) + + if hi6 == 0x37: # FLAT / SCRATCH / GLOBAL (64-bit) + seg = (w0 >> 14) & 3 + opc = (w0 >> 18) & 0x7F + off12 = w0 & 0xFFF + dlc = (w0 >> 12) & 1 + lds = (w0 >> 13) & 1 + glc = (w0 >> 16) & 1 + slc = (w0 >> 17) & 1 + addr = w1 & 0xFF + data = (w1 >> 8) & 0xFF + saddr = (w1 >> 16) & 0x7F + vdst = (w1 >> 24) & 0xFF + tbl = {0: T.FLAT, 1: T.SCRATCH, 2: T.GLOBAL}.get(seg) + if tbl is None or opc not in tbl: + return None, 4 + name, spec = tbl[opc] + is_atomic = "_atomic_" in name + has_saddr = seg in (1, 2) + saddr_off = saddr in (0x7D, 0x7F) # GFX10 null (125) or legacy 127 => off (64-bit vaddr) + args = [] + for fn, nr, _ in spec: + w = _width(nr, wave32) + if fn == "VDST": + if is_atomic and not glc: + continue + args.append(_vreg(vdst, w)) + elif fn == "ADDR": + aw = 2 if (seg == 0 or (seg == 2 and saddr_off)) else 1 + args.append(_vreg(addr, aw)) + elif fn == "DATA": + args.append(_vreg(data, w)) + elif fn == "SADDR" and has_saddr: + if saddr_off: + args.append({"k": "special", "t": "off", "neg": False, "abs": False}) + else: + args.append(_sreg(saddr, 2 if seg == 2 else 1)) + mods = [] + off_s = _s12(off12) if seg in (1, 2) else off12 + if off_s: + mods.append(f"offset:{off_s}") + if glc: + mods.append("glc") + if slc: + mods.append("slc") + if dlc: + mods.append("dlc") + if lds: + mods.append("lds") + return finish(name, args, mods, 8) + + if hi6 == 0x38: # MUBUF (64-bit) + opc = (w0 >> 18) & 0xFF + off12 = w0 & 0xFFF + offen = (w0 >> 12) & 1 + idxen = (w0 >> 13) & 1 + glc = (w0 >> 14) & 1 + dlc = (w0 >> 15) & 1 + lds = (w0 >> 16) & 1 + vaddr = w1 & 0xFF + vdata = (w1 >> 8) & 0xFF + srsrc = ((w1 >> 16) & 0x1F) * 4 + slc = (w1 >> 22) & 1 + tfe = (w1 >> 23) & 1 + soff = (w1 >> 24) & 0xFF + entry = T.MUBUF.get(opc) + if entry is None: + return None, 4 + name, spec = entry + args = [] + for fn, nr, _ in spec: + w = _width(nr, wave32) + if fn == "VDATA": + args.append(_vreg(vdata, w)) + elif fn == "VADDR": + if not offen and not idxen: + args.append({"k": "special", "t": "off", "neg": False, "abs": False}) + else: + args.append(_vreg(vaddr, 2 if (offen and idxen) else 1)) + elif fn == "SRSRC": + args.append(_sreg(srsrc, 4)) + elif fn == "SOFFSET": + args.append(_src(soff, 1, None)) + mods = [] + if idxen: + mods.append("idxen") + if offen: + mods.append("offen") + if off12: + mods.append(f"offset:{off12}") + if glc: + mods.append("glc") + if slc: + mods.append("slc") + if dlc: + mods.append("dlc") + if lds: + mods.append("lds") + if tfe: + mods.append("tfe") + return finish(name, args, mods, 8) + + if hi6 == 0x3A: # MTBUF (64-bit) + opc = ((w0 >> 16) & 0x7) | (((w1 >> 21) & 1) << 3) + off12 = w0 & 0xFFF + offen = (w0 >> 12) & 1 + idxen = (w0 >> 13) & 1 + glc = (w0 >> 14) & 1 + dlc = (w0 >> 15) & 1 + fmt_code = (w0 >> 19) & 0x7F + vaddr = w1 & 0xFF + vdata = (w1 >> 8) & 0xFF + srsrc = ((w1 >> 16) & 0x1F) * 4 + slc = (w1 >> 22) & 1 + tfe = (w1 >> 23) & 1 + soff = (w1 >> 24) & 0xFF + entry = T.MTBUF.get(opc) + if entry is None: + return None, 4 + name, spec = entry + args = [] + for fn, nr, _ in spec: + w = _width(nr, wave32) + if fn == "VDATA": + args.append(_vreg(vdata, w)) + elif fn == "VADDR": + if not offen and not idxen: + args.append({"k": "special", "t": "off", "neg": False, "abs": False}) + else: + args.append(_vreg(vaddr, 2 if (offen and idxen) else 1)) + elif fn == "SRSRC": + args.append(_sreg(srsrc, 4)) + elif fn == "SOFFSET": + args.append(_src(soff, 1, None)) + mods = [] + fmt_name = _GFX10_FORMATS.get(fmt_code) + if fmt_name and fmt_code != 1: # BUF_FMT_8_UNORM (code 1) is the GFX10 default + short = fmt_name.replace("GFX10_FORMAT_", "BUF_FMT_") + mods.append(f"format:[{short}]") + elif fmt_code != 1: + mods.append(f"format:{fmt_code}") + if idxen: + mods.append("idxen") + if offen: + mods.append("offen") + if off12: + mods.append(f"offset:{off12}") + if glc: + mods.append("glc") + if slc: + mods.append("slc") + if dlc: + mods.append("dlc") + if tfe: + mods.append("tfe") + return finish(name, args, mods, 8) + + if hi6 == 0x3C: # MIMG (64-bit + up to 3 NSA dwords) + nsa_dwords = (w0 >> 1) & 3 + dim = (w0 >> 3) & 7 + dlc = (w0 >> 7) & 1 + dmask = (w0 >> 8) & 0xF + unorm = (w0 >> 12) & 1 + glc = (w0 >> 13) & 1 + r128 = (w0 >> 15) & 1 + tfe = (w0 >> 16) & 1 + lwe = (w0 >> 17) & 1 + opc = ((w0 >> 18) & 0x7F) | ((w0 & 1) << 7) + vaddr0 = w1 & 0xFF + vdata = (w1 >> 8) & 0xFF + srsrc = ((w1 >> 16) & 0x1F) * 4 + ssamp = ((w1 >> 21) & 0x1F) * 4 + slc = (w1 >> 25) & 1 + a16 = (w1 >> 30) & 1 + d16 = (w1 >> 31) & 1 + entry = T.MIMG.get(opc) + if entry is None: + return None, 4 + name, spec = entry + nbytes = 8 + 4 * nsa_dwords + if not need(nbytes): + return None, 4 + n_addr = _mimg_addr_count(name, dim, bool(a16)) + if nsa_dwords: + # First address VGPR is vaddr0; remaining bytes sit in the trailing NSA dwords. + extra_bytes = code[pc + 8:pc + nbytes] + vregs = [vaddr0] + list(extra_bytes[:max(0, n_addr - 1)]) + vaddr_op = {"k": "vlist", "r": vregs} + else: + vaddr_op = _vreg(vaddr0, n_addr) + n_data = _mimg_data_count(name, dmask, bool(d16), bool(tfe)) + rsrc_w = 4 if (r128 or name.startswith("image_bvh")) else 8 + args = [] + for fn, nr, _ in spec: + if fn == "VDATA": + args.append(_vreg(vdata, n_data)) + elif fn == "VADDR": + args.append(vaddr_op) + elif fn == "SRSRC": + args.append(_sreg(srsrc, rsrc_w)) + elif fn == "SSAMP": + args.append(_sreg(ssamp, 4)) + mods = [] + if dmask and not name.startswith("image_bvh"): + mods.append(f"dmask:0x{dmask:x}") + if not name.startswith("image_bvh"): + mods.append(f"dim:{_MIMG_DIMS.get(dim, 'SQ_RSRC_IMG_2D')}") + if unorm: + mods.append("unorm") + if glc: + mods.append("glc") + if slc: + mods.append("slc") + if r128 and not name.startswith("image_bvh"): + mods.append("r128") + if tfe: + mods.append("tfe") + if lwe: + mods.append("lwe") + if a16: + mods.append("a16") + if d16: + mods.append("d16") + if dlc: + mods.append("dlc") + return finish(name, args, mods, nbytes) + + if hi6 == 0x3D: # SMEM (64-bit) + sbase = (w0 & 0x3F) * 2 + sdata = (w0 >> 6) & 0x7F + dlc = (w0 >> 14) & 1 + glc = (w0 >> 16) & 1 + opc = (w0 >> 18) & 0xFF + off21 = w1 & 0x1FFFFF + soff = (w1 >> 25) & 0x7F + entry = T.SMEM.get(opc) + if entry is None: + return None, 4 + name, spec = entry + is_buf = "buffer" in name + args = [] + mods = [] + for fn, nr, _ in spec: + w = _width(nr, wave32) + if fn == "SDATA": + args.append(_sreg(sdata, w)) + elif fn == "SBASE": + args.append(_sreg(sbase, w)) + elif fn in ("OFFSET", "SOFFSET"): + pass + # SMEM offset operands: soff != 125 (null) => register offset (+ optional offset:IMM); else immediate (or null if 0). + if any(fn in ("OFFSET", "SOFFSET") for fn, _, _ in spec): + imm_val = off21 if is_buf else _s21(off21) + if soff == 125: # null => immediate offset (or null when 0) + if imm_val == 0: + args.append({"k": "special", "t": "null", "neg": False, "abs": False}) + else: + args.append({"k": "imm", "v": imm_val}) + else: + args.append(_sreg(soff, 1)) + if imm_val > 0: + mods.append(f"offset:{imm_val:#x}") + elif imm_val < 0: + mods.append(f"offset:-0x{-imm_val:x}") + if glc: + mods.append("glc") + if dlc: + mods.append("dlc") + return finish(name, args, mods, 8) + + if hi6 == 0x3E: # EXP (64-bit) + en = w0 & 0xF + tgt = (w0 >> 4) & 0x3F + compr = (w0 >> 10) & 1 + done = (w0 >> 11) & 1 + vm = (w0 >> 12) & 1 + vsrcs = [(w1 >> (8 * i)) & 0xFF for i in range(4)] + if tgt <= 7: + tname = f"mrt{tgt}" + elif tgt == 8: + tname = "mrtz" + elif tgt == 9: + tname = "null" + elif 12 <= tgt <= 16: + tname = f"pos{tgt - 12}" + elif tgt == 20: + tname = "prim" + elif 32 <= tgt <= 63: + tname = f"param{tgt - 32}" + else: + tname = f"tgt{tgt}" + args = [{"k": "target", "t": tname}] + if compr: + # Compressed export: en bit 0/1 enables vsrc0 (printed twice), bit 2/3 enables vsrc1 (printed twice). + for pair in (0, 1): + enabled = bool((en >> (2 * pair)) & 3) + op = _vreg(vsrcs[pair], 1) if enabled else {"k": "special", "t": "off", "neg": False, "abs": False} + args.append(op) + args.append(dict(op)) + else: + for i in range(4): + if (en >> i) & 1: + args.append(_vreg(vsrcs[i], 1)) + else: + args.append({"k": "special", "t": "off", "neg": False, "abs": False}) + mods = [] + if done: + mods.append("done") + if compr: + mods.append("compr") + if vm: + mods.append("vm") + return finish("exp", args, mods, 8) + + return None, 4 + + +def _format_operand(a: dict) -> str: + k = a["k"] + if k in ("vgpr", "sgpr"): + p = "v" if k == "vgpr" else "s" + r, n = a["r"], a.get("n", 1) + s = f"{p}{r}" if n == 1 else f"{p}[{r}:{r + n - 1}]" + elif k == "vlist": + s = "[" + ",".join(f"v{r}" for r in a["r"]) + "]" + elif k == "slist": + s = "[" + ",".join(f"s{r}" if isinstance(r, int) else r for r in a["r"]) + "]" + elif k == "attr": + s = f"attr{a['a']}.{'xyzw'[a['c']]}" + elif k in ("special", "target", "interp", "ttmp", "raw"): + s = a["t"] + elif k == "imm": + v = a["v"] + s = f"0x{v:x}" if v >= 100 else str(v) + elif k == "fimm": + v = a["v"] + s = next((txt for code, txt in _INLINE_FLOAT_STR.items() if _INLINE_FLOAT[code] == v), repr(v)) + else: + s = str(a) + + if a.get("sext"): + s = f"sext({s})" + if a.get("abs"): + s = f"|{s}|" + if a.get("neg"): + if k in ("imm", "fimm"): + s = f"neg({s})" + else: + s = f"-{s}" + return s + + +def format_insn(ins: dict) -> str: + """Format one decoded instruction dict as an LLVM-compatible `.s` line.""" + op = ins["op"] + args = ins["args"] + mods = ins["mods"] + if op == "exp" and args: + head = f"{op} {_format_operand(args[0])} " + ", ".join(_format_operand(x) for x in args[1:]) + elif args: + head = f"{op} " + ", ".join(_format_operand(x) for x in args) + else: + head = op + if mods: + head += " " + " ".join(mods) + enc_bytes = bytes.fromhex(ins["enc"]) + enc_str = ",".join(f"0x{b:02x}" for b in enc_bytes) + return f"\t{head:<40s}; encoding: [{enc_str}]" + + +def decode_bytes(code: bytes, *, wave32: bool = True, code_start: int = 0, name: str = "") -> dict: + """Decode raw RDNA2 machine code into the exact dict layout `shader_ir.parse_file()` returns.""" + insns = [] + invalid = 0 + off = 0 + while off < len(code): + ins, nbytes = _decode_one(code, off, wave32) + if ins is None: + invalid += 1 + off += max(4, nbytes) + continue + ins["pc"] = code_start + off + insns.append(ins) + off += nbytes + return {"name": name, "code_start": code_start, "insns": insns, "invalid": invalid} + + +def disasm_bytes(code: bytes, *, wave32: bool = True, code_start: int = 0, name: str = "") -> tuple[str, int]: + """Decode raw RDNA2 machine code into `(llvm_compatible_text, invalid_word_count)`.""" + info = decode_bytes(code, wave32=wave32, code_start=code_start, name=name) + lines = [format_insn(ins) for ins in info["insns"]] + return "\n".join(lines) + ("\n" if lines else ""), info["invalid"] diff --git a/tools/rdna2_isa_tables.py b/tools/rdna2_isa_tables.py new file mode 100644 index 000000000..cab2596ee --- /dev/null +++ b/tools/rdna2_isa_tables.py @@ -0,0 +1,1537 @@ +"""RDNA2 (GFX10.1/GFX10.3) opcode tables for tools/rdna2_decode.py. + +Derived from AMD's machine-readable RDNA2 ISA specification (amdgpu_isa_rdna2.xml, +MIT licence; https://gpuopen.com/machine-readable-isa), plus the seven gfx1013 +legacy/waveid instructions documented in docs/isa_coverage.md. +""" + +DS = { + 0x0: ('ds_add_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x1: ('ds_sub_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x2: ('ds_rsub_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x3: ('ds_inc_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x4: ('ds_dec_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x5: ('ds_min_i32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x6: ('ds_max_i32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x7: ('ds_min_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x8: ('ds_max_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x9: ('ds_and_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0xa: ('ds_or_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0xb: ('ds_xor_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0xc: ('ds_mskor_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0xd: ('ds_write_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0xe: ('ds_write2_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0xf: ('ds_write2st64_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0x10: ('ds_cmpst_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0x11: ('ds_cmpst_f32', (('ADDR', 1, 'i'), ('DATA0', 1, 'f32'), ('DATA1', 1, 'f32'))), + 0x12: ('ds_min_f32', (('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), + 0x13: ('ds_max_f32', (('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), + 0x14: ('ds_nop', ()), + 0x15: ('ds_add_f32', (('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), + 0x18: ('ds_gws_sema_release_all', ()), + 0x19: ('ds_gws_init', (('ADDR', 1, 'i'),)), + 0x1a: ('ds_gws_sema_v', ()), + 0x1b: ('ds_gws_sema_br', (('ADDR', 1, 'i'),)), + 0x1c: ('ds_gws_sema_p', ()), + 0x1d: ('ds_gws_barrier', (('ADDR', 1, 'i'),)), + 0x1e: ('ds_write_b8', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x1f: ('ds_write_b16', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x20: ('ds_add_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x21: ('ds_sub_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x22: ('ds_rsub_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x23: ('ds_inc_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x24: ('ds_dec_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x25: ('ds_min_rtn_i32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x26: ('ds_max_rtn_i32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x27: ('ds_min_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x28: ('ds_max_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x29: ('ds_and_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x2a: ('ds_or_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x2b: ('ds_xor_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x2c: ('ds_mskor_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0x2d: ('ds_wrxchg_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0x2e: ('ds_wrxchg2_rtn_b32', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0x2f: ('ds_wrxchg2st64_rtn_b32', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0x30: ('ds_cmpst_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0x31: ('ds_cmpst_rtn_f32', (('VDST', 1, 'f32'), ('ADDR', 1, 'i'), ('DATA0', 1, 'f32'), ('DATA1', 1, 'f32'))), + 0x32: ('ds_min_rtn_f32', (('VDST', 1, 'f32'), ('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), + 0x33: ('ds_max_rtn_f32', (('VDST', 1, 'f32'), ('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), + 0x34: ('ds_wrap_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), + 0x35: ('ds_swizzle_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0x36: ('ds_read_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0x37: ('ds_read2_b32', (('VDST', 2, 'i'), ('ADDR', 1, 'i'))), + 0x38: ('ds_read2st64_b32', (('VDST', 2, 'i'), ('ADDR', 1, 'i'))), + 0x39: ('ds_read_i8', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0x3a: ('ds_read_u8', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0x3b: ('ds_read_i16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0x3c: ('ds_read_u16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0x3d: ('ds_consume', (('VDST', 1, 'i'),)), + 0x3e: ('ds_append', (('VDST', 1, 'i'),)), + 0x3f: ('ds_ordered_count', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0x40: ('ds_add_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x41: ('ds_sub_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x42: ('ds_rsub_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x43: ('ds_inc_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x44: ('ds_dec_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x45: ('ds_min_i64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x46: ('ds_max_i64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x47: ('ds_min_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x48: ('ds_max_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x49: ('ds_and_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x4a: ('ds_or_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x4b: ('ds_xor_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x4c: ('ds_mskor_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), + 0x4d: ('ds_write_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x4e: ('ds_write2_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), + 0x4f: ('ds_write2st64_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), + 0x50: ('ds_cmpst_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), + 0x51: ('ds_cmpst_f64', (('ADDR', 1, 'i'), ('DATA0', 2, 'f64'), ('DATA1', 2, 'f64'))), + 0x52: ('ds_min_f64', (('ADDR', 1, 'i'), ('DATA0', 2, 'f64'))), + 0x53: ('ds_max_f64', (('ADDR', 1, 'i'), ('DATA0', 2, 'f64'))), + 0x55: ('ds_add_rtn_f32', (('VDST', 1, 'f32'), ('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), + 0x60: ('ds_add_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x61: ('ds_sub_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x62: ('ds_rsub_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x63: ('ds_inc_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x64: ('ds_dec_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x65: ('ds_min_rtn_i64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x66: ('ds_max_rtn_i64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x67: ('ds_min_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x68: ('ds_max_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x69: ('ds_and_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x6a: ('ds_or_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x6b: ('ds_xor_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x6c: ('ds_mskor_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), + 0x6d: ('ds_wrxchg_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0x6e: ('ds_wrxchg2_rtn_b64', (('VDST', 4, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), + 0x6f: ('ds_wrxchg2st64_rtn_b64', (('VDST', 4, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), + 0x70: ('ds_cmpst_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), + 0x71: ('ds_cmpst_rtn_f64', (('VDST', 2, 'f64'), ('ADDR', 1, 'i'), ('DATA0', 2, 'f64'), ('DATA1', 2, 'f64'))), + 0x72: ('ds_min_rtn_f64', (('VDST', 2, 'f64'), ('ADDR', 1, 'i'), ('DATA0', 2, 'f64'))), + 0x73: ('ds_max_rtn_f64', (('VDST', 2, 'f64'), ('ADDR', 1, 'i'), ('DATA0', 2, 'f64'))), + 0x76: ('ds_read_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'))), + 0x77: ('ds_read2_b64', (('VDST', 4, 'i'), ('ADDR', 1, 'i'))), + 0x78: ('ds_read2st64_b64', (('VDST', 4, 'i'), ('ADDR', 1, 'i'))), + 0x7e: ('ds_condxchg32_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), + 0xa0: ('ds_write_b8_d16_hi', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0xa1: ('ds_write_b16_d16_hi', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0xa2: ('ds_read_u8_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0xa3: ('ds_read_u8_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0xa4: ('ds_read_i8_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0xa5: ('ds_read_i8_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0xa6: ('ds_read_u16_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0xa7: ('ds_read_u16_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), + 0xb0: ('ds_write_addtid_b32', (('DATA0', 1, 'i'),)), + 0xb1: ('ds_read_addtid_b32', (('VDST', 1, 'i'),)), + 0xb2: ('ds_permute_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0xb3: ('ds_bpermute_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), + 0xde: ('ds_write_b96', (('ADDR', 1, 'i'), ('DATA0', 3, 'i'))), + 0xdf: ('ds_write_b128', (('ADDR', 1, 'i'), ('DATA0', 4, 'i'))), + 0xfe: ('ds_read_b96', (('VDST', 3, 'i'), ('ADDR', 1, 'i'))), + 0xff: ('ds_read_b128', (('VDST', 4, 'i'), ('ADDR', 1, 'i'))), +} + +FLAT = { + 0x8: ('flat_load_ubyte', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0x9: ('flat_load_sbyte', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0xa: ('flat_load_ushort', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0xb: ('flat_load_sshort', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0xc: ('flat_load_dword', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0xd: ('flat_load_dwordx2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'))), + 0xe: ('flat_load_dwordx4', (('VDST', 4, 'i'), ('ADDR', 2, 'i'))), + 0xf: ('flat_load_dwordx3', (('VDST', 3, 'i'), ('ADDR', 2, 'i'))), + 0x18: ('flat_store_byte', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x19: ('flat_store_byte_d16_hi', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x1a: ('flat_store_short', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x1b: ('flat_store_short_d16_hi', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x1c: ('flat_store_dword', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x1d: ('flat_store_dwordx2', (('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x1e: ('flat_store_dwordx4', (('ADDR', 2, 'i'), ('DATA', 4, 'i'))), + 0x1f: ('flat_store_dwordx3', (('ADDR', 2, 'i'), ('DATA', 3, 'i'))), + 0x20: ('flat_load_ubyte_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0x21: ('flat_load_ubyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0x22: ('flat_load_sbyte_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0x23: ('flat_load_sbyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0x24: ('flat_load_short_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0x25: ('flat_load_short_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), + 0x30: ('flat_atomic_swap', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x31: ('flat_atomic_cmpswap', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x32: ('flat_atomic_add', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x33: ('flat_atomic_sub', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x35: ('flat_atomic_smin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x36: ('flat_atomic_umin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x37: ('flat_atomic_smax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x38: ('flat_atomic_umax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x39: ('flat_atomic_and', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x3a: ('flat_atomic_or', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x3b: ('flat_atomic_xor', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x3c: ('flat_atomic_inc', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x3d: ('flat_atomic_dec', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x3e: ('flat_atomic_fcmpswap', (('VDST', 1, 'f32'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x3f: ('flat_atomic_fmin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x40: ('flat_atomic_fmax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), + 0x50: ('flat_atomic_swap_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x51: ('flat_atomic_cmpswap_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 4, 'i'))), + 0x52: ('flat_atomic_add_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x53: ('flat_atomic_sub_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x55: ('flat_atomic_smin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x56: ('flat_atomic_umin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x57: ('flat_atomic_smax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x58: ('flat_atomic_umax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x59: ('flat_atomic_and_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x5a: ('flat_atomic_or_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x5b: ('flat_atomic_xor_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x5c: ('flat_atomic_inc_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x5d: ('flat_atomic_dec_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x5e: ('flat_atomic_fcmpswap_x2', (('VDST', 2, 'f64'), ('ADDR', 2, 'i'), ('DATA', 4, 'i'))), + 0x5f: ('flat_atomic_fmin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), + 0x60: ('flat_atomic_fmax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), +} + +GLOBAL = { + 0x8: ('global_load_ubyte', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0x9: ('global_load_sbyte', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0xa: ('global_load_ushort', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0xb: ('global_load_sshort', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0xc: ('global_load_dword', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0xd: ('global_load_dwordx2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0xe: ('global_load_dwordx4', (('VDST', 4, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0xf: ('global_load_dwordx3', (('VDST', 3, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0x16: ('global_load_dword_addtid', (('VDST', 1, 'i'), ('SADDR', 2, 'i'))), + 0x17: ('global_store_dword_addtid', (('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x18: ('global_store_byte', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x19: ('global_store_byte_d16_hi', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x1a: ('global_store_short', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x1b: ('global_store_short_d16_hi', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x1c: ('global_store_dword', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x1d: ('global_store_dwordx2', (('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x1e: ('global_store_dwordx4', (('ADDR', 2, 'i'), ('DATA', 4, 'i'), ('SADDR', 2, 'i'))), + 0x1f: ('global_store_dwordx3', (('ADDR', 2, 'i'), ('DATA', 3, 'i'), ('SADDR', 2, 'i'))), + 0x20: ('global_load_ubyte_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0x21: ('global_load_ubyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0x22: ('global_load_sbyte_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0x23: ('global_load_sbyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0x24: ('global_load_short_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0x25: ('global_load_short_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), + 0x30: ('global_atomic_swap', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x31: ('global_atomic_cmpswap', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x32: ('global_atomic_add', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x33: ('global_atomic_sub', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x34: ('global_atomic_csub', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x35: ('global_atomic_smin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x36: ('global_atomic_umin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x37: ('global_atomic_smax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x38: ('global_atomic_umax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x39: ('global_atomic_and', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x3a: ('global_atomic_or', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x3b: ('global_atomic_xor', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x3c: ('global_atomic_inc', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x3d: ('global_atomic_dec', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x3e: ('global_atomic_fcmpswap', (('VDST', 1, 'f32'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x3f: ('global_atomic_fmin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x40: ('global_atomic_fmax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), + 0x50: ('global_atomic_swap_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x51: ('global_atomic_cmpswap_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 4, 'i'), ('SADDR', 2, 'i'))), + 0x52: ('global_atomic_add_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x53: ('global_atomic_sub_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x55: ('global_atomic_smin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x56: ('global_atomic_umin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x57: ('global_atomic_smax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x58: ('global_atomic_umax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x59: ('global_atomic_and_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x5a: ('global_atomic_or_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x5b: ('global_atomic_xor_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x5c: ('global_atomic_inc_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x5d: ('global_atomic_dec_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x5e: ('global_atomic_fcmpswap_x2', (('VDST', 2, 'f64'), ('ADDR', 2, 'i'), ('DATA', 4, 'i'), ('SADDR', 2, 'i'))), + 0x5f: ('global_atomic_fmin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), + 0x60: ('global_atomic_fmax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), +} + +MIMG = { + 0x0: ('image_load', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x1: ('image_load_mip', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x2: ('image_load_pck', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x3: ('image_load_pck_sgn', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x4: ('image_load_mip_pck', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x5: ('image_load_mip_pck_sgn', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x8: ('image_store', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x9: ('image_store_mip', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0xa: ('image_store_pck', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0xb: ('image_store_mip_pck', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0xe: ('image_get_resinfo', (('VDATA', 4, 'i'), ('VADDR', 1, 'i'), ('SRSRC', 8, 'i'))), + 0xf: ('image_atomic_swap', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x10: ('image_atomic_cmpswap', (('VDATA', 1, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x11: ('image_atomic_add', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x12: ('image_atomic_sub', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x14: ('image_atomic_smin', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x15: ('image_atomic_umin', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x16: ('image_atomic_smax', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x17: ('image_atomic_umax', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x18: ('image_atomic_and', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x19: ('image_atomic_or', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x1a: ('image_atomic_xor', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x1b: ('image_atomic_inc', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x1c: ('image_atomic_dec', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x1d: ('image_atomic_fcmpswap', (('VDATA', 1, 'f32'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x1e: ('image_atomic_fmin', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x1f: ('image_atomic_fmax', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x20: ('image_sample', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x21: ('image_sample_cl', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x22: ('image_sample_d', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x23: ('image_sample_d_cl', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x24: ('image_sample_l', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x25: ('image_sample_b', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x26: ('image_sample_b_cl', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x27: ('image_sample_lz', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x28: ('image_sample_c', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x29: ('image_sample_c_cl', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x2a: ('image_sample_c_d', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x2b: ('image_sample_c_d_cl', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x2c: ('image_sample_c_l', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x2d: ('image_sample_c_b', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x2e: ('image_sample_c_b_cl', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x2f: ('image_sample_c_lz', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x30: ('image_sample_o', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x31: ('image_sample_cl_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x32: ('image_sample_d_o', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x33: ('image_sample_d_cl_o', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x34: ('image_sample_l_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x35: ('image_sample_b_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x36: ('image_sample_b_cl_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x37: ('image_sample_lz_o', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x38: ('image_sample_c_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x39: ('image_sample_c_cl_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x3a: ('image_sample_c_d_o', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x3b: ('image_sample_c_d_cl_o', (('VDATA', 4, 'i'), ('VADDR', 12, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x3c: ('image_sample_c_l_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x3d: ('image_sample_c_b_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x3e: ('image_sample_c_b_cl_o', (('VDATA', 4, 'i'), ('VADDR', 7, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x3f: ('image_sample_c_lz_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x40: ('image_gather4', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x41: ('image_gather4_cl', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x42: ('image_load_by2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x43: ('image_load_by4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x44: ('image_gather4_l', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x45: ('image_gather4_b', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x46: ('image_gather4_b_cl', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x47: ('image_gather4_lz', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x48: ('image_gather4_c', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x49: ('image_gather4_c_cl', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x4a: ('image_load_mip_by2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x4b: ('image_load_mip_by4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x4c: ('image_gather4_c_l', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x4d: ('image_gather4_c_b', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x4e: ('image_gather4_c_b_cl', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x4f: ('image_gather4_c_lz', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x50: ('image_gather4_o', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x51: ('image_gather4_cl_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x52: ('image_store_by2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x53: ('image_store_by4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x54: ('image_gather4_l_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x55: ('image_gather4_b_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x56: ('image_gather4_b_cl_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x57: ('image_gather4_lz_o', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x58: ('image_gather4_c_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x59: ('image_gather4_c_cl_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x5a: ('image_store_mip_by2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x5b: ('image_store_mip_by4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x5c: ('image_gather4_c_l_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x5d: ('image_gather4_c_b_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x5e: ('image_gather4_c_b_cl_o', (('VDATA', 4, 'i'), ('VADDR', 7, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x5f: ('image_gather4_c_lz_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x60: ('image_get_lod', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x61: ('image_gather4h', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x62: ('image_gather4h_pck', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x63: ('image_gather8h_pck', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x68: ('image_sample_cd', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x69: ('image_sample_cd_cl', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x6a: ('image_sample_c_cd', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x6b: ('image_sample_c_cd_cl', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x6c: ('image_sample_cd_o', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x6d: ('image_sample_cd_cl_o', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x6e: ('image_sample_c_cd_o', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x6f: ('image_sample_c_cd_cl_o', (('VDATA', 4, 'i'), ('VADDR', 12, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0x70: ('image_load_pck2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x71: ('image_load_pck4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x73: ('image_load_mip_pck2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x74: ('image_load_mip_pck4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x76: ('image_store_pck2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x77: ('image_store_pck4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x79: ('image_store_mip_pck2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x7a: ('image_store_mip_pck4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0x80: ('image_msaa_load', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), + 0xa2: ('image_sample_d_g16', (('VDATA', 4, 'i'), ('VADDR', 7, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xa3: ('image_sample_d_cl_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xaa: ('image_sample_c_d_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xab: ('image_sample_c_d_cl_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xb2: ('image_sample_d_o_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xb3: ('image_sample_d_cl_o_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xba: ('image_sample_c_d_o_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xbb: ('image_sample_c_d_cl_o_g16', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xe6: ('image_bvh_intersect_ray', (('VDATA', 4, 'i'), ('VADDR', 11, 'i'), ('SRSRC', 4, 'i'))), + 0xe7: ('image_bvh64_intersect_ray', (('VDATA', 4, 'i'), ('VADDR', 12, 'i'), ('SRSRC', 4, 'i'))), + 0xe8: ('image_sample_cd_g16', (('VDATA', 4, 'i'), ('VADDR', 7, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xe9: ('image_sample_cd_cl_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xea: ('image_sample_c_cd_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xeb: ('image_sample_c_cd_cl_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xec: ('image_sample_cd_o_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xed: ('image_sample_cd_cl_o_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xee: ('image_sample_c_cd_o_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), + 0xef: ('image_sample_c_cd_cl_o_g16', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), +} + +MTBUF = { + 0x0: ('tbuffer_load_format_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1: ('tbuffer_load_format_xy', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x2: ('tbuffer_load_format_xyz', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x3: ('tbuffer_load_format_xyzw', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x4: ('tbuffer_store_format_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x5: ('tbuffer_store_format_xy', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x6: ('tbuffer_store_format_xyz', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x7: ('tbuffer_store_format_xyzw', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x8: ('tbuffer_load_format_d16_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x9: ('tbuffer_load_format_d16_xy', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xa: ('tbuffer_load_format_d16_xyz', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xb: ('tbuffer_load_format_d16_xyzw', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xc: ('tbuffer_store_format_d16_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xd: ('tbuffer_store_format_d16_xy', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xe: ('tbuffer_store_format_d16_xyz', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xf: ('tbuffer_store_format_d16_xyzw', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), +} + +MUBUF = { + 0x0: ('buffer_load_format_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1: ('buffer_load_format_xy', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x2: ('buffer_load_format_xyz', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x3: ('buffer_load_format_xyzw', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x4: ('buffer_store_format_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x5: ('buffer_store_format_xy', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x6: ('buffer_store_format_xyz', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x7: ('buffer_store_format_xyzw', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x8: ('buffer_load_ubyte', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x9: ('buffer_load_sbyte', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xa: ('buffer_load_ushort', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xb: ('buffer_load_sshort', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xc: ('buffer_load_dword', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xd: ('buffer_load_dwordx2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xe: ('buffer_load_dwordx4', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xf: ('buffer_load_dwordx3', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x18: ('buffer_store_byte', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x19: ('buffer_store_byte_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1a: ('buffer_store_short', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1b: ('buffer_store_short_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1c: ('buffer_store_dword', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1d: ('buffer_store_dwordx2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1e: ('buffer_store_dwordx4', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1f: ('buffer_store_dwordx3', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x20: ('buffer_load_ubyte_d16', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x21: ('buffer_load_ubyte_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x22: ('buffer_load_sbyte_d16', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x23: ('buffer_load_sbyte_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x24: ('buffer_load_short_d16', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x25: ('buffer_load_short_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x26: ('buffer_load_format_d16_hi_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x27: ('buffer_store_format_d16_hi_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x30: ('buffer_atomic_swap', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x31: ('buffer_atomic_cmpswap', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x32: ('buffer_atomic_add', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x33: ('buffer_atomic_sub', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x34: ('buffer_atomic_csub', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x35: ('buffer_atomic_smin', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x36: ('buffer_atomic_umin', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x37: ('buffer_atomic_smax', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x38: ('buffer_atomic_umax', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x39: ('buffer_atomic_and', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x3a: ('buffer_atomic_or', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x3b: ('buffer_atomic_xor', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x3c: ('buffer_atomic_inc', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x3d: ('buffer_atomic_dec', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x3e: ('buffer_atomic_fcmpswap', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x3f: ('buffer_atomic_fmin', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x40: ('buffer_atomic_fmax', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x50: ('buffer_atomic_swap_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x51: ('buffer_atomic_cmpswap_x2', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x52: ('buffer_atomic_add_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x53: ('buffer_atomic_sub_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x55: ('buffer_atomic_smin_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x56: ('buffer_atomic_umin_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x57: ('buffer_atomic_smax_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x58: ('buffer_atomic_umax_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x59: ('buffer_atomic_and_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x5a: ('buffer_atomic_or_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x5b: ('buffer_atomic_xor_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x5c: ('buffer_atomic_inc_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x5d: ('buffer_atomic_dec_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x5e: ('buffer_atomic_fcmpswap_x2', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x5f: ('buffer_atomic_fmin_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x60: ('buffer_atomic_fmax_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x71: ('buffer_gl0_inv', ()), + 0x72: ('buffer_gl1_inv', ()), + 0x80: ('buffer_load_format_d16_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x81: ('buffer_load_format_d16_xy', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x82: ('buffer_load_format_d16_xyz', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x83: ('buffer_load_format_d16_xyzw', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x84: ('buffer_store_format_d16_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x85: ('buffer_store_format_d16_xy', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x86: ('buffer_store_format_d16_xyz', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x87: ('buffer_store_format_d16_xyzw', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), +} + +SCRATCH = { + 0x8: ('scratch_load_ubyte', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0x9: ('scratch_load_sbyte', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0xa: ('scratch_load_ushort', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0xb: ('scratch_load_sshort', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0xc: ('scratch_load_dword', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0xd: ('scratch_load_dwordx2', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0xe: ('scratch_load_dwordx4', (('VDST', 4, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0xf: ('scratch_load_dwordx3', (('VDST', 3, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0x18: ('scratch_store_byte', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), + 0x19: ('scratch_store_byte_d16_hi', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), + 0x1a: ('scratch_store_short', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), + 0x1b: ('scratch_store_short_d16_hi', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), + 0x1c: ('scratch_store_dword', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), + 0x1d: ('scratch_store_dwordx2', (('ADDR', 1, 'i'), ('DATA', 2, 'i'), ('SADDR', 1, 'i'))), + 0x1e: ('scratch_store_dwordx4', (('ADDR', 1, 'i'), ('DATA', 4, 'i'), ('SADDR', 1, 'i'))), + 0x1f: ('scratch_store_dwordx3', (('ADDR', 1, 'i'), ('DATA', 3, 'i'), ('SADDR', 1, 'i'))), + 0x20: ('scratch_load_ubyte_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0x21: ('scratch_load_ubyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0x22: ('scratch_load_sbyte_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0x23: ('scratch_load_sbyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0x24: ('scratch_load_short_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), + 0x25: ('scratch_load_short_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), +} + +SMEM = { + 0x0: ('s_load_dword', (('SDATA', 1, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), + 0x1: ('s_load_dwordx2', (('SDATA', 2, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), + 0x2: ('s_load_dwordx4', (('SDATA', 4, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), + 0x3: ('s_load_dwordx8', (('SDATA', 8, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), + 0x4: ('s_load_dwordx16', (('SDATA', 16, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), + 0x8: ('s_buffer_load_dword', (('SDATA', 1, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x9: ('s_buffer_load_dwordx2', (('SDATA', 2, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xa: ('s_buffer_load_dwordx4', (('SDATA', 4, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xb: ('s_buffer_load_dwordx8', (('SDATA', 8, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0xc: ('s_buffer_load_dwordx16', (('SDATA', 16, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), + 0x1f: ('s_gl1_inv', ()), + 0x20: ('s_dcache_inv', ()), + 0x24: ('s_memtime', (('SDATA', 2, 'i'),)), + 0x25: ('s_memrealtime', (('SDATA', 2, 'i'),)), + 0x2a: ('s_get_waveid_in_workgroup', (('SDATA', 1, 'i'),)), +} + +SOP1 = { + 0x3: ('s_mov_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x4: ('s_mov_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x5: ('s_cmov_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x6: ('s_cmov_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x7: ('s_not_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x8: ('s_not_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x9: ('s_wqm_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0xa: ('s_wqm_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0xb: ('s_brev_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0xc: ('s_brev_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0xd: ('s_bcnt0_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0xe: ('s_bcnt0_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), + 0xf: ('s_bcnt1_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x10: ('s_bcnt1_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), + 0x11: ('s_ff0_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x12: ('s_ff0_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), + 0x13: ('s_ff1_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x14: ('s_ff1_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), + 0x15: ('s_flbit_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x16: ('s_flbit_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), + 0x17: ('s_flbit_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x18: ('s_flbit_i32_i64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), + 0x19: ('s_sext_i32_i8', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x1a: ('s_sext_i32_i16', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x1b: ('s_bitset0_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x1c: ('s_bitset0_b64', (('SDST', 2, 'i'), ('SSRC0', 1, 'i'))), + 0x1d: ('s_bitset1_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x1e: ('s_bitset1_b64', (('SDST', 2, 'i'), ('SSRC0', 1, 'i'))), + 0x1f: ('s_getpc_b64', (('SDST', 2, 'i'),)), + 0x20: ('s_setpc_b64', (('SSRC0', 2, 'i'),)), + 0x21: ('s_swappc_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x22: ('s_rfe_b64', (('SSRC0', 2, 'i'),)), + 0x24: ('s_and_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x25: ('s_or_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x26: ('s_xor_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x27: ('s_andn2_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x28: ('s_orn2_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x29: ('s_nand_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x2a: ('s_nor_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x2b: ('s_xnor_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x2c: ('s_quadmask_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x2d: ('s_quadmask_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x2e: ('s_movrels_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x2f: ('s_movrels_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x30: ('s_movreld_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x31: ('s_movreld_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x34: ('s_abs_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x37: ('s_andn1_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x38: ('s_orn1_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x39: ('s_andn1_wrexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x3a: ('s_andn2_wrexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), + 0x3b: ('s_bitreplicate_b64_b32', (('SDST', 2, 'i'), ('SSRC0', 1, 'i'))), + 0x3c: ('s_and_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x3d: ('s_or_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x3e: ('s_xor_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x3f: ('s_andn2_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x40: ('s_orn2_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x41: ('s_nand_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x42: ('s_nor_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x43: ('s_xnor_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x44: ('s_andn1_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x45: ('s_orn1_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x46: ('s_andn1_wrexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x47: ('s_andn2_wrexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), + 0x49: ('s_movrelsd_2_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), +} + +SOP2 = { + 0x0: ('s_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x1: ('s_sub_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x2: ('s_add_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x3: ('s_sub_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x4: ('s_addc_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x5: ('s_subb_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x6: ('s_min_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x7: ('s_min_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x8: ('s_max_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x9: ('s_max_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0xa: ('s_cselect_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0xb: ('s_cselect_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0xe: ('s_and_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0xf: ('s_and_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x10: ('s_or_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x11: ('s_or_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x12: ('s_xor_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x13: ('s_xor_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x14: ('s_andn2_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x15: ('s_andn2_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x16: ('s_orn2_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x17: ('s_orn2_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x18: ('s_nand_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x19: ('s_nand_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x1a: ('s_nor_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x1b: ('s_nor_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x1c: ('s_xnor_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x1d: ('s_xnor_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x1e: ('s_lshl_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x1f: ('s_lshl_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), + 0x20: ('s_lshr_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x21: ('s_lshr_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), + 0x22: ('s_ashr_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x23: ('s_ashr_i64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), + 0x24: ('s_bfm_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x25: ('s_bfm_b64', (('SDST', 2, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x26: ('s_mul_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x27: ('s_bfe_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x28: ('s_bfe_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x29: ('s_bfe_u64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), + 0x2a: ('s_bfe_i64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), + 0x2c: ('s_absdiff_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x2e: ('s_lshl1_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x2f: ('s_lshl2_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x30: ('s_lshl3_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x31: ('s_lshl4_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x32: ('s_pack_ll_b32_b16', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x33: ('s_pack_lh_b32_b16', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x34: ('s_pack_hh_b32_b16', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x35: ('s_mul_hi_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x36: ('s_mul_hi_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), +} + +SOPC = { + 0x0: ('s_cmp_eq_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x1: ('s_cmp_lg_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x2: ('s_cmp_gt_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x3: ('s_cmp_ge_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x4: ('s_cmp_lt_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x5: ('s_cmp_le_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x6: ('s_cmp_eq_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x7: ('s_cmp_lg_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x8: ('s_cmp_gt_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0x9: ('s_cmp_ge_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0xa: ('s_cmp_lt_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0xb: ('s_cmp_le_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0xc: ('s_bitcmp0_b32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0xd: ('s_bitcmp1_b32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), + 0xe: ('s_bitcmp0_b64', (('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), + 0xf: ('s_bitcmp1_b64', (('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), + 0x12: ('s_cmp_eq_u64', (('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), + 0x13: ('s_cmp_lg_u64', (('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), +} + +SOPK = { + 0x0: ('s_movk_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x1: ('s_version', (('SIMM16', 1, 'i'),)), + 0x2: ('s_cmovk_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x3: ('s_cmpk_eq_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x4: ('s_cmpk_lg_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x5: ('s_cmpk_gt_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x6: ('s_cmpk_ge_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x7: ('s_cmpk_lt_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x8: ('s_cmpk_le_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x9: ('s_cmpk_eq_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0xa: ('s_cmpk_lg_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0xb: ('s_cmpk_gt_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0xc: ('s_cmpk_ge_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0xd: ('s_cmpk_lt_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0xe: ('s_cmpk_le_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0xf: ('s_addk_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x10: ('s_mulk_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x12: ('s_getreg_b32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x13: ('s_setreg_b32', (('SIMM16', 1, 'i'), ('SDST', 1, 'i'))), + 0x15: ('s_setreg_imm32_b32', (('SIMM16', 1, 'i'), ('LITERAL', 1, 'i'))), + 0x16: ('s_call_b64', (('SDST', 2, 'i'), ('SIMM16', 1, 'i'))), + 0x17: ('s_waitcnt_vscnt', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x18: ('s_waitcnt_vmcnt', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x19: ('s_waitcnt_expcnt', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x1a: ('s_waitcnt_lgkmcnt', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x1b: ('s_subvector_loop_begin', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), + 0x1c: ('s_subvector_loop_end', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), +} + +SOPP = { + 0x0: ('s_nop', (('SIMM16', 1, 'i'),)), + 0x1: ('s_endpgm', ()), + 0x2: ('s_branch', (('SIMM16', 1, 'i'),)), + 0x3: ('s_wakeup', ()), + 0x4: ('s_cbranch_scc0', (('SIMM16', 1, 'i'),)), + 0x5: ('s_cbranch_scc1', (('SIMM16', 1, 'i'),)), + 0x6: ('s_cbranch_vccz', (('SIMM16', 1, 'i'),)), + 0x7: ('s_cbranch_vccnz', (('SIMM16', 1, 'i'),)), + 0x8: ('s_cbranch_execz', (('SIMM16', 1, 'i'),)), + 0x9: ('s_cbranch_execnz', (('SIMM16', 1, 'i'),)), + 0xa: ('s_barrier', ()), + 0xb: ('s_setkill', (('SIMM16', 1, 'i'),)), + 0xc: ('s_waitcnt', (('SIMM16', 1, 'i'),)), + 0xd: ('s_sethalt', (('SIMM16', 1, 'i'),)), + 0xe: ('s_sleep', (('SIMM16', 1, 'i'),)), + 0xf: ('s_setprio', (('SIMM16', 1, 'i'),)), + 0x10: ('s_sendmsg', (('SIMM16', 1, 'i'),)), + 0x11: ('s_sendmsghalt', (('SIMM16', 1, 'i'),)), + 0x12: ('s_trap', (('SIMM16', 1, 'i'),)), + 0x13: ('s_icache_inv', ()), + 0x14: ('s_incperflevel', (('SIMM16', 1, 'i'),)), + 0x15: ('s_decperflevel', (('SIMM16', 1, 'i'),)), + 0x16: ('s_ttracedata', ()), + 0x17: ('s_cbranch_cdbgsys', (('SIMM16', 1, 'i'),)), + 0x18: ('s_cbranch_cdbguser', (('SIMM16', 1, 'i'),)), + 0x19: ('s_cbranch_cdbgsys_or_user', (('SIMM16', 1, 'i'),)), + 0x1a: ('s_cbranch_cdbgsys_and_user', (('SIMM16', 1, 'i'),)), + 0x1b: ('s_endpgm_saved', ()), + 0x1e: ('s_endpgm_ordered_ps_done', ()), + 0x1f: ('s_code_end', ()), + 0x20: ('s_inst_prefetch', (('SIMM16', 1, 'i'),)), + 0x21: ('s_clause', (('SIMM16', 1, 'i'),)), + 0x23: ('s_waitcnt_depctr', (('SIMM16', 1, 'i'),)), + 0x24: ('s_round_mode', (('SIMM16', 1, 'i'),)), + 0x25: ('s_denorm_mode', (('SIMM16', 1, 'i'),)), + 0x28: ('s_ttracedata_imm', (('SIMM16', 1, 'i'),)), +} + +VINTRP = { + 0x0: ('v_interp_p1_f32', (('VDST', 1, 'f32'), ('VSRC', 1, 'f32'), ('ATTR', 1, 'i'))), + 0x1: ('v_interp_p2_f32', (('VDST', 1, 'f32'), ('VSRC', 1, 'f32'), ('ATTR', 1, 'i'))), + 0x2: ('v_interp_mov_f32', (('VDST', 1, 'f32'), ('VSRC', 1, 'i'), ('ATTR', 1, 'i'))), +} + +VOP1 = { + 0x0: ('v_nop', ()), + 0x1: ('v_mov_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x2: ('v_readfirstlane_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x3: ('v_cvt_i32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), + 0x4: ('v_cvt_f64_i32', (('VDST', 2, 'f64'), ('SRC0', 1, 'i'))), + 0x5: ('v_cvt_f32_i32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x6: ('v_cvt_f32_u32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x7: ('v_cvt_u32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0x8: ('v_cvt_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0xa: ('v_cvt_f16_f32', (('VDST', 1, 'f16'), ('SRC0', 1, 'f32'))), + 0xb: ('v_cvt_f32_f16', (('VDST', 1, 'f32'), ('SRC0', 1, 'f16'))), + 0xc: ('v_cvt_rpi_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0xd: ('v_cvt_flr_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0xe: ('v_cvt_off_f32_i4', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0xf: ('v_cvt_f32_f64', (('VDST', 1, 'f32'), ('SRC0', 2, 'f64'))), + 0x10: ('v_cvt_f64_f32', (('VDST', 2, 'f64'), ('SRC0', 1, 'f32'))), + 0x11: ('v_cvt_f32_ubyte0', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x12: ('v_cvt_f32_ubyte1', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x13: ('v_cvt_f32_ubyte2', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x14: ('v_cvt_f32_ubyte3', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x15: ('v_cvt_u32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), + 0x16: ('v_cvt_f64_u32', (('VDST', 2, 'f64'), ('SRC0', 1, 'i'))), + 0x17: ('v_trunc_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x18: ('v_ceil_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x19: ('v_rndne_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x1a: ('v_floor_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x1b: ('v_pipeflush', ()), + 0x20: ('v_fract_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x21: ('v_trunc_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x22: ('v_ceil_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x23: ('v_rndne_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x24: ('v_floor_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x25: ('v_exp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x27: ('v_log_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x2a: ('v_rcp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x2b: ('v_rcp_iflag_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x2e: ('v_rsq_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x2f: ('v_rcp_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x31: ('v_rsq_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x33: ('v_sqrt_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x34: ('v_sqrt_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x35: ('v_sin_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x36: ('v_cos_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x37: ('v_not_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x38: ('v_bfrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x39: ('v_ffbh_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x3a: ('v_ffbl_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x3b: ('v_ffbh_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x3c: ('v_frexp_exp_i32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), + 0x3d: ('v_frexp_mant_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x3e: ('v_fract_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x3f: ('v_frexp_exp_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0x40: ('v_frexp_mant_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x41: ('v_clrexcp', ()), + 0x42: ('v_movreld_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x43: ('v_movrels_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x44: ('v_movrelsd_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x48: ('v_movrelsd_2_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x50: ('v_cvt_f16_u16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'))), + 0x51: ('v_cvt_f16_i16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'))), + 0x52: ('v_cvt_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x53: ('v_cvt_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x54: ('v_rcp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x55: ('v_sqrt_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x56: ('v_rsq_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x57: ('v_log_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x58: ('v_exp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x59: ('v_frexp_mant_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x5a: ('v_frexp_exp_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x5b: ('v_floor_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x5c: ('v_ceil_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x5d: ('v_trunc_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x5e: ('v_rndne_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x5f: ('v_fract_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x60: ('v_sin_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x61: ('v_cos_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x62: ('v_sat_pk_u8_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x63: ('v_cvt_norm_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x64: ('v_cvt_norm_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x65: ('v_swap_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x68: ('v_swaprel_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), +} + +VOP2 = { + 0x1: ('v_cndmask_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'), ('VCC', -1, 'i'))), + 0x2: ('v_dot2c_f32_f16', (('VDST', 1, 'f32'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x3: ('v_add_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x4: ('v_sub_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x5: ('v_subrev_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x6: ('v_fmac_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x7: ('v_mul_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x8: ('v_mul_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x9: ('v_mul_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xa: ('v_mul_hi_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xb: ('v_mul_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc: ('v_mul_hi_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd: ('v_dot4c_i32_i8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xf: ('v_min_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x10: ('v_max_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x11: ('v_min_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x12: ('v_max_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x13: ('v_min_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x14: ('v_max_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x16: ('v_lshrrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x18: ('v_ashrrev_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x1a: ('v_lshlrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x1b: ('v_and_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x1c: ('v_or_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x1d: ('v_xor_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x1e: ('v_xnor_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x1f: ('v_mac_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x20: ('v_madmk_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SIMM32', 0, 'f32'), ('VSRC1', 1, 'f32'))), + 0x21: ('v_madak_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'), ('SIMM32', 0, 'f32'))), + 0x25: ('v_add_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x26: ('v_sub_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x27: ('v_subrev_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x28: ('v_add_co_ci_u32', (('VDST', 1, 'i'), ('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'), ('VCC', -1, 'i'))), + 0x29: ('v_sub_co_ci_u32', (('VDST', 1, 'i'), ('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'), ('VCC', -1, 'i'))), + 0x2a: ('v_subrev_co_ci_u32', (('VDST', 1, 'i'), ('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'), ('VCC', -1, 'i'))), + 0x2b: ('v_fmac_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x2c: ('v_fmamk_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('LITERAL', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x2d: ('v_fmaak_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'), ('LITERAL', 1, 'f32'))), + 0x2f: ('v_cvt_pkrtz_f16_f32', (('VDST', 1, 'f16'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x32: ('v_add_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x33: ('v_sub_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x34: ('v_subrev_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x35: ('v_mul_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x36: ('v_fmac_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x37: ('v_fmamk_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('LITERAL', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x38: ('v_fmaak_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'), ('LITERAL', 1, 'f16'))), + 0x39: ('v_max_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x3a: ('v_min_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x3b: ('v_ldexp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x3c: ('v_pk_fmac_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), +} + +VOP3 = { + 0x0: ('v_cmp_f_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x1: ('v_cmp_lt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x2: ('v_cmp_eq_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x3: ('v_cmp_le_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x4: ('v_cmp_gt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x5: ('v_cmp_lg_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x6: ('v_cmp_ge_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x7: ('v_cmp_o_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x8: ('v_cmp_u_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x9: ('v_cmp_nge_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0xa: ('v_cmp_nlg_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0xb: ('v_cmp_ngt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0xc: ('v_cmp_nle_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0xd: ('v_cmp_neq_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0xe: ('v_cmp_nlt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0xf: ('v_cmp_tru_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x10: ('v_cmpx_f_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x11: ('v_cmpx_lt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x12: ('v_cmpx_eq_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x13: ('v_cmpx_le_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x14: ('v_cmpx_gt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x15: ('v_cmpx_lg_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x16: ('v_cmpx_ge_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x17: ('v_cmpx_o_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x18: ('v_cmpx_u_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x19: ('v_cmpx_nge_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x1a: ('v_cmpx_nlg_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x1b: ('v_cmpx_ngt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x1c: ('v_cmpx_nle_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x1d: ('v_cmpx_neq_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x1e: ('v_cmpx_nlt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x1f: ('v_cmpx_tru_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x20: ('v_cmp_f_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x21: ('v_cmp_lt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x22: ('v_cmp_eq_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x23: ('v_cmp_le_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x24: ('v_cmp_gt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x25: ('v_cmp_lg_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x26: ('v_cmp_ge_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x27: ('v_cmp_o_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x28: ('v_cmp_u_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x29: ('v_cmp_nge_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x2a: ('v_cmp_nlg_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x2b: ('v_cmp_ngt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x2c: ('v_cmp_nle_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x2d: ('v_cmp_neq_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x2e: ('v_cmp_nlt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x2f: ('v_cmp_tru_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x30: ('v_cmpx_f_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x31: ('v_cmpx_lt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x32: ('v_cmpx_eq_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x33: ('v_cmpx_le_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x34: ('v_cmpx_gt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x35: ('v_cmpx_lg_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x36: ('v_cmpx_ge_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x37: ('v_cmpx_o_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x38: ('v_cmpx_u_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x39: ('v_cmpx_nge_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x3a: ('v_cmpx_nlg_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x3b: ('v_cmpx_ngt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x3c: ('v_cmpx_nle_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x3d: ('v_cmpx_neq_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x3e: ('v_cmpx_nlt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x3f: ('v_cmpx_tru_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x80: ('v_cmp_f_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x81: ('v_cmp_lt_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x82: ('v_cmp_eq_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x83: ('v_cmp_le_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x84: ('v_cmp_gt_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x85: ('v_cmp_ne_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x86: ('v_cmp_ge_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x87: ('v_cmp_t_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x88: ('v_cmp_class_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'i'))), + 0x89: ('v_cmp_lt_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x8a: ('v_cmp_eq_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x8b: ('v_cmp_le_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x8c: ('v_cmp_gt_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x8d: ('v_cmp_ne_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x8e: ('v_cmp_ge_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x8f: ('v_cmp_class_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x90: ('v_cmpx_f_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x91: ('v_cmpx_lt_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x92: ('v_cmpx_eq_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x93: ('v_cmpx_le_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x94: ('v_cmpx_gt_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x95: ('v_cmpx_ne_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x96: ('v_cmpx_ge_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x97: ('v_cmpx_t_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x98: ('v_cmpx_class_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'i'))), + 0x99: ('v_cmpx_lt_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x9a: ('v_cmpx_eq_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x9b: ('v_cmpx_le_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x9c: ('v_cmpx_gt_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x9d: ('v_cmpx_ne_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x9e: ('v_cmpx_ge_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x9f: ('v_cmpx_class_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xa0: ('v_cmp_f_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xa1: ('v_cmp_lt_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xa2: ('v_cmp_eq_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xa3: ('v_cmp_le_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xa4: ('v_cmp_gt_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xa5: ('v_cmp_ne_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xa6: ('v_cmp_ge_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xa7: ('v_cmp_t_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xa8: ('v_cmp_class_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 1, 'i'))), + 0xa9: ('v_cmp_lt_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xaa: ('v_cmp_eq_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xab: ('v_cmp_le_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xac: ('v_cmp_gt_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xad: ('v_cmp_ne_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xae: ('v_cmp_ge_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xb0: ('v_cmpx_f_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xb1: ('v_cmpx_lt_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xb2: ('v_cmpx_eq_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xb3: ('v_cmpx_le_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xb4: ('v_cmpx_gt_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xb5: ('v_cmpx_ne_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xb6: ('v_cmpx_ge_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xb7: ('v_cmpx_t_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xb8: ('v_cmpx_class_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 1, 'i'))), + 0xb9: ('v_cmpx_lt_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xba: ('v_cmpx_eq_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xbb: ('v_cmpx_le_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xbc: ('v_cmpx_gt_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xbd: ('v_cmpx_ne_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xbe: ('v_cmpx_ge_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc0: ('v_cmp_f_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc1: ('v_cmp_lt_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc2: ('v_cmp_eq_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc3: ('v_cmp_le_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc4: ('v_cmp_gt_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc5: ('v_cmp_ne_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc6: ('v_cmp_ge_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc7: ('v_cmp_t_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc8: ('v_cmp_f_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xc9: ('v_cmp_lt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xca: ('v_cmp_eq_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xcb: ('v_cmp_le_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xcc: ('v_cmp_gt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xcd: ('v_cmp_lg_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xce: ('v_cmp_ge_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xcf: ('v_cmp_o_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xd0: ('v_cmpx_f_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd1: ('v_cmpx_lt_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd2: ('v_cmpx_eq_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd3: ('v_cmpx_le_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd4: ('v_cmpx_gt_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd5: ('v_cmpx_ne_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd6: ('v_cmpx_ge_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd7: ('v_cmpx_t_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd8: ('v_cmpx_f_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xd9: ('v_cmpx_lt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xda: ('v_cmpx_eq_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xdb: ('v_cmpx_le_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xdc: ('v_cmpx_gt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xdd: ('v_cmpx_lg_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xde: ('v_cmpx_ge_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xdf: ('v_cmpx_o_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xe0: ('v_cmp_f_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xe1: ('v_cmp_lt_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xe2: ('v_cmp_eq_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xe3: ('v_cmp_le_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xe4: ('v_cmp_gt_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xe5: ('v_cmp_ne_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xe6: ('v_cmp_ge_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xe7: ('v_cmp_t_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xe8: ('v_cmp_u_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xe9: ('v_cmp_nge_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xea: ('v_cmp_nlg_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xeb: ('v_cmp_ngt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xec: ('v_cmp_nle_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xed: ('v_cmp_neq_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xee: ('v_cmp_nlt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xef: ('v_cmp_tru_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xf0: ('v_cmpx_f_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xf1: ('v_cmpx_lt_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xf2: ('v_cmpx_eq_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xf3: ('v_cmpx_le_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xf4: ('v_cmpx_gt_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xf5: ('v_cmpx_ne_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xf6: ('v_cmpx_ge_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xf7: ('v_cmpx_t_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), + 0xf8: ('v_cmpx_u_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xf9: ('v_cmpx_nge_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xfa: ('v_cmpx_nlg_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xfb: ('v_cmpx_ngt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xfc: ('v_cmpx_nle_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xfd: ('v_cmpx_neq_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xfe: ('v_cmpx_nlt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0xff: ('v_cmpx_tru_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x101: ('v_cndmask_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', -1, 'i'))), + 0x103: ('v_add_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x104: ('v_sub_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x105: ('v_subrev_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x106: ('v_fmac_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x107: ('v_mul_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x108: ('v_mul_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x109: ('v_mul_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x10a: ('v_mul_hi_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x10b: ('v_mul_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x10c: ('v_mul_hi_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x10f: ('v_min_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x110: ('v_max_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x111: ('v_min_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x112: ('v_max_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x113: ('v_min_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x114: ('v_max_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x116: ('v_lshrrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x118: ('v_ashrrev_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x11a: ('v_lshlrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x11b: ('v_and_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x11c: ('v_or_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x11d: ('v_xor_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x11e: ('v_xnor_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x11f: ('v_mac_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x125: ('v_add_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x126: ('v_sub_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x127: ('v_subrev_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x12b: ('v_fmac_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x12f: ('v_cvt_pkrtz_f16_f32', (('VDST', 1, 'f16'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x132: ('v_add_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x133: ('v_sub_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x134: ('v_subrev_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x135: ('v_mul_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x136: ('v_fmac_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x139: ('v_max_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x13a: ('v_min_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x13b: ('v_ldexp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x140: ('v_fma_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x141: ('v_mad_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x142: ('v_mad_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x143: ('v_mad_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x144: ('v_cubeid_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x145: ('v_cubesc_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x146: ('v_cubetc_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x147: ('v_cubema_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x148: ('v_bfe_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x149: ('v_bfe_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x14a: ('v_bfi_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x14b: ('v_fma_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x14c: ('v_fma_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'), ('SRC2', 2, 'f64'))), + 0x14d: ('v_lerp_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x14e: ('v_alignbit_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x14f: ('v_alignbyte_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x150: ('v_mullit_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x151: ('v_min3_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x152: ('v_min3_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x153: ('v_min3_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x154: ('v_max3_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x155: ('v_max3_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x156: ('v_max3_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x157: ('v_med3_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x158: ('v_med3_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x159: ('v_med3_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x15a: ('v_sad_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x15b: ('v_sad_hi_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x15c: ('v_sad_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x15d: ('v_sad_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x15e: ('v_cvt_pk_u8_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x15f: ('v_div_fixup_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x160: ('v_div_fixup_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'), ('SRC2', 2, 'f64'))), + 0x164: ('v_add_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x165: ('v_mul_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x166: ('v_min_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x167: ('v_max_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), + 0x168: ('v_ldexp_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 1, 'i'))), + 0x169: ('v_mul_lo_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x16a: ('v_mul_hi_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x16c: ('v_mul_hi_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x16f: ('v_div_fmas_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x170: ('v_div_fmas_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'), ('SRC2', 2, 'f64'))), + 0x171: ('v_msad_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x172: ('v_qsad_pk_u16_u8', (('VDST', 2, 'i'), ('SRC0', 2, 'i'), ('SRC1', 1, 'i'), ('SRC2', 2, 'i'))), + 0x173: ('v_mqsad_pk_u16_u8', (('VDST', 2, 'i'), ('SRC0', 2, 'i'), ('SRC1', 1, 'i'), ('SRC2', 2, 'i'))), + 0x174: ('v_trig_preop_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 1, 'i'))), + 0x175: ('v_mqsad_u32_u8', (('VDST', 4, 'i'), ('SRC0', 2, 'i'), ('SRC1', 1, 'i'), ('SRC2', 4, 'i'))), + 0x178: ('v_xor3_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x180: ('v_nop', ()), + 0x181: ('v_mov_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x182: ('v_readfirstlane_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x183: ('v_cvt_i32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), + 0x184: ('v_cvt_f64_i32', (('VDST', 2, 'f64'), ('SRC0', 1, 'i'))), + 0x185: ('v_cvt_f32_i32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x186: ('v_cvt_f32_u32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x187: ('v_cvt_u32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0x188: ('v_cvt_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0x18a: ('v_cvt_f16_f32', (('VDST', 1, 'f16'), ('SRC0', 1, 'f32'))), + 0x18b: ('v_cvt_f32_f16', (('VDST', 1, 'f32'), ('SRC0', 1, 'f16'))), + 0x18c: ('v_cvt_rpi_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0x18d: ('v_cvt_flr_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0x18e: ('v_cvt_off_f32_i4', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x18f: ('v_cvt_f32_f64', (('VDST', 1, 'f32'), ('SRC0', 2, 'f64'))), + 0x190: ('v_cvt_f64_f32', (('VDST', 2, 'f64'), ('SRC0', 1, 'f32'))), + 0x191: ('v_cvt_f32_ubyte0', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x192: ('v_cvt_f32_ubyte1', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x193: ('v_cvt_f32_ubyte2', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x194: ('v_cvt_f32_ubyte3', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x195: ('v_cvt_u32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), + 0x196: ('v_cvt_f64_u32', (('VDST', 2, 'f64'), ('SRC0', 1, 'i'))), + 0x197: ('v_trunc_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x198: ('v_ceil_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x199: ('v_rndne_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x19a: ('v_floor_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x19b: ('v_pipeflush', ()), + 0x1a0: ('v_fract_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1a1: ('v_trunc_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1a2: ('v_ceil_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1a3: ('v_rndne_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1a4: ('v_floor_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1a5: ('v_exp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1a7: ('v_log_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1aa: ('v_rcp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1ab: ('v_rcp_iflag_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1ae: ('v_rsq_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1af: ('v_rcp_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x1b1: ('v_rsq_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x1b3: ('v_sqrt_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1b4: ('v_sqrt_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x1b5: ('v_sin_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1b6: ('v_cos_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1b7: ('v_not_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1b8: ('v_bfrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1b9: ('v_ffbh_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1ba: ('v_ffbl_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1bb: ('v_ffbh_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1bc: ('v_frexp_exp_i32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), + 0x1bd: ('v_frexp_mant_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x1be: ('v_fract_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), + 0x1bf: ('v_frexp_exp_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), + 0x1c0: ('v_frexp_mant_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), + 0x1c1: ('v_clrexcp', ()), + 0x1c2: ('v_movreld_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1c3: ('v_movrels_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1c4: ('v_movrelsd_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1c8: ('v_movrelsd_2_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1d0: ('v_cvt_f16_u16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'))), + 0x1d1: ('v_cvt_f16_i16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'))), + 0x1d2: ('v_cvt_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x1d3: ('v_cvt_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x1d4: ('v_rcp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1d5: ('v_sqrt_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1d6: ('v_rsq_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1d7: ('v_log_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1d8: ('v_exp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1d9: ('v_frexp_mant_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1da: ('v_frexp_exp_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x1db: ('v_floor_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1dc: ('v_ceil_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1dd: ('v_trunc_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1de: ('v_rndne_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1df: ('v_fract_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1e0: ('v_sin_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1e1: ('v_cos_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), + 0x1e2: ('v_sat_pk_u8_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), + 0x1e3: ('v_cvt_norm_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x1e4: ('v_cvt_norm_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), + 0x200: ('v_interp_p1_f32', (('VDST', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x201: ('v_interp_p2_f32', (('VDST', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'i'))), + 0x202: ('v_interp_mov_f32', (('VDST', 1, 'f32'), ('SRC1', 1, 'i'), ('SRC0', 1, 'i'))), + 0x2ff: ('v_lshlrev_b64', (('VDST', 2, 'i'), ('SRC0', 1, 'i'), ('SRC1', 2, 'i'))), + 0x300: ('v_lshrrev_b64', (('VDST', 2, 'i'), ('SRC0', 1, 'i'), ('SRC1', 2, 'i'))), + 0x301: ('v_ashrrev_i64', (('VDST', 2, 'i'), ('SRC0', 1, 'i'), ('SRC1', 2, 'i'))), + 0x303: ('v_add_nc_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x304: ('v_sub_nc_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x305: ('v_mul_lo_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x307: ('v_lshrrev_b16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x308: ('v_ashrrev_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x309: ('v_max_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x30a: ('v_max_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x30b: ('v_min_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x30c: ('v_min_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x30d: ('v_add_nc_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x30e: ('v_sub_nc_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x311: ('v_pack_b32_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x312: ('v_cvt_pknorm_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x313: ('v_cvt_pknorm_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x314: ('v_lshlrev_b16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x340: ('v_mad_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x342: ('v_interp_p1ll_f16', (('VDST', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'f16'))), + 0x343: ('v_interp_p1lv_f16', (('VDST', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'f16'), ('SRC2', 1, 'f16'))), + 0x344: ('v_perm_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x345: ('v_xad_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x346: ('v_lshl_add_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x347: ('v_add_lshl_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x34b: ('v_fma_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), + 0x351: ('v_min3_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), + 0x352: ('v_min3_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x353: ('v_min3_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x354: ('v_max3_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), + 0x355: ('v_max3_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x356: ('v_max3_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x357: ('v_med3_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), + 0x358: ('v_med3_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x359: ('v_med3_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x35a: ('v_interp_p2_f16', (('VDST', 1, 'f16'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'f16'), ('SRC2', 1, 'f32'))), + 0x35e: ('v_mad_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x35f: ('v_div_fixup_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), + 0x360: ('v_readlane_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x361: ('v_writelane_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x362: ('v_ldexp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'i'))), + 0x363: ('v_bfm_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x364: ('v_bcnt_u32_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x365: ('v_mbcnt_lo_u32_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x366: ('v_mbcnt_hi_u32_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x368: ('v_cvt_pknorm_i16_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x369: ('v_cvt_pknorm_u16_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), + 0x36a: ('v_cvt_pk_u16_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x36b: ('v_cvt_pk_i16_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x36d: ('v_add3_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x36f: ('v_lshl_or_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x371: ('v_and_or_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x372: ('v_or3_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x373: ('v_mad_u32_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x375: ('v_mad_i32_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x376: ('v_sub_nc_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x377: ('v_permlane16_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x378: ('v_permlanex16_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x37f: ('v_add_nc_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), +} + +VOP3B = { + 0x128: ('v_add_co_ci_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', -1, 'i'))), + 0x129: ('v_sub_co_ci_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', -1, 'i'))), + 0x12a: ('v_subrev_co_ci_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', -1, 'i'))), + 0x16d: ('v_div_scale_f32', (('VDST', 1, 'f32'), ('SDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), + 0x16e: ('v_div_scale_f64', (('VDST', 2, 'f64'), ('SDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'), ('SRC2', 2, 'f64'))), + 0x176: ('v_mad_u64_u32', (('VDST', 2, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 2, 'i'))), + 0x177: ('v_mad_i64_i32', (('VDST', 2, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 2, 'i'))), + 0x30f: ('v_add_co_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x310: ('v_sub_co_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x319: ('v_subrev_co_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), +} + +VOP3P = { + 0x0: ('v_pk_mad_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x1: ('v_pk_mul_lo_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x2: ('v_pk_add_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x3: ('v_pk_sub_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x4: ('v_pk_lshlrev_b16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x5: ('v_pk_lshrrev_b16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x6: ('v_pk_ashrrev_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x7: ('v_pk_max_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x8: ('v_pk_min_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0x9: ('v_pk_mad_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0xa: ('v_pk_add_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xb: ('v_pk_sub_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xc: ('v_pk_max_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xd: ('v_pk_min_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), + 0xe: ('v_pk_fma_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), + 0xf: ('v_pk_add_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x10: ('v_pk_mul_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x11: ('v_pk_min_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x12: ('v_pk_max_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), + 0x13: ('v_dot2_f32_f16', (('VDST', 1, 'f32'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f32'))), + 0x14: ('v_dot2_i32_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x15: ('v_dot2_u32_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x16: ('v_dot4_i32_i8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x17: ('v_dot4_u32_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x18: ('v_dot8_i32_i4', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x19: ('v_dot8_u32_u4', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x20: ('v_fma_mix_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x21: ('v_fma_mixlo_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), + 0x22: ('v_fma_mixhi_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), +} + +VOPC = { + 0x0: ('v_cmp_f_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x1: ('v_cmp_lt_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x2: ('v_cmp_eq_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x3: ('v_cmp_le_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x4: ('v_cmp_gt_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x5: ('v_cmp_lg_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x6: ('v_cmp_ge_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x7: ('v_cmp_o_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x8: ('v_cmp_u_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x9: ('v_cmp_nge_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0xa: ('v_cmp_nlg_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0xb: ('v_cmp_ngt_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0xc: ('v_cmp_nle_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0xd: ('v_cmp_neq_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0xe: ('v_cmp_nlt_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0xf: ('v_cmp_tru_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x10: ('v_cmpx_f_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x11: ('v_cmpx_lt_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x12: ('v_cmpx_eq_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x13: ('v_cmpx_le_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x14: ('v_cmpx_gt_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x15: ('v_cmpx_lg_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x16: ('v_cmpx_ge_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x17: ('v_cmpx_o_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x18: ('v_cmpx_u_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x19: ('v_cmpx_nge_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x1a: ('v_cmpx_nlg_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x1b: ('v_cmpx_ngt_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x1c: ('v_cmpx_nle_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x1d: ('v_cmpx_neq_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x1e: ('v_cmpx_nlt_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x1f: ('v_cmpx_tru_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), + 0x20: ('v_cmp_f_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x21: ('v_cmp_lt_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x22: ('v_cmp_eq_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x23: ('v_cmp_le_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x24: ('v_cmp_gt_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x25: ('v_cmp_lg_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x26: ('v_cmp_ge_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x27: ('v_cmp_o_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x28: ('v_cmp_u_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x29: ('v_cmp_nge_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x2a: ('v_cmp_nlg_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x2b: ('v_cmp_ngt_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x2c: ('v_cmp_nle_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x2d: ('v_cmp_neq_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x2e: ('v_cmp_nlt_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x2f: ('v_cmp_tru_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x30: ('v_cmpx_f_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x31: ('v_cmpx_lt_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x32: ('v_cmpx_eq_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x33: ('v_cmpx_le_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x34: ('v_cmpx_gt_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x35: ('v_cmpx_lg_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x36: ('v_cmpx_ge_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x37: ('v_cmpx_o_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x38: ('v_cmpx_u_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x39: ('v_cmpx_nge_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x3a: ('v_cmpx_nlg_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x3b: ('v_cmpx_ngt_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x3c: ('v_cmpx_nle_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x3d: ('v_cmpx_neq_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x3e: ('v_cmpx_nlt_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x3f: ('v_cmpx_tru_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), + 0x80: ('v_cmp_f_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x81: ('v_cmp_lt_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x82: ('v_cmp_eq_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x83: ('v_cmp_le_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x84: ('v_cmp_gt_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x85: ('v_cmp_ne_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x86: ('v_cmp_ge_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x87: ('v_cmp_t_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x88: ('v_cmp_class_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'i'))), + 0x89: ('v_cmp_lt_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x8a: ('v_cmp_eq_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x8b: ('v_cmp_le_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x8c: ('v_cmp_gt_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x8d: ('v_cmp_ne_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x8e: ('v_cmp_ge_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x8f: ('v_cmp_class_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0x90: ('v_cmpx_f_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x91: ('v_cmpx_lt_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x92: ('v_cmpx_eq_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x93: ('v_cmpx_le_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x94: ('v_cmpx_gt_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x95: ('v_cmpx_ne_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x96: ('v_cmpx_ge_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x97: ('v_cmpx_t_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x98: ('v_cmpx_class_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'i'))), + 0x99: ('v_cmpx_lt_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x9a: ('v_cmpx_eq_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x9b: ('v_cmpx_le_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x9c: ('v_cmpx_gt_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x9d: ('v_cmpx_ne_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x9e: ('v_cmpx_ge_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0x9f: ('v_cmpx_class_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xa0: ('v_cmp_f_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xa1: ('v_cmp_lt_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xa2: ('v_cmp_eq_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xa3: ('v_cmp_le_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xa4: ('v_cmp_gt_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xa5: ('v_cmp_ne_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xa6: ('v_cmp_ge_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xa7: ('v_cmp_t_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xa8: ('v_cmp_class_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 1, 'i'))), + 0xa9: ('v_cmp_lt_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xaa: ('v_cmp_eq_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xab: ('v_cmp_le_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xac: ('v_cmp_gt_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xad: ('v_cmp_ne_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xae: ('v_cmp_ge_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xb0: ('v_cmpx_f_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xb1: ('v_cmpx_lt_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xb2: ('v_cmpx_eq_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xb3: ('v_cmpx_le_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xb4: ('v_cmpx_gt_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xb5: ('v_cmpx_ne_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xb6: ('v_cmpx_ge_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xb7: ('v_cmpx_t_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xb8: ('v_cmpx_class_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 1, 'i'))), + 0xb9: ('v_cmpx_lt_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xba: ('v_cmpx_eq_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xbb: ('v_cmpx_le_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xbc: ('v_cmpx_gt_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xbd: ('v_cmpx_ne_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xbe: ('v_cmpx_ge_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc0: ('v_cmp_f_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc1: ('v_cmp_lt_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc2: ('v_cmp_eq_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc3: ('v_cmp_le_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc4: ('v_cmp_gt_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc5: ('v_cmp_ne_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc6: ('v_cmp_ge_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc7: ('v_cmp_t_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xc8: ('v_cmp_f_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xc9: ('v_cmp_lt_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xca: ('v_cmp_eq_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xcb: ('v_cmp_le_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xcc: ('v_cmp_gt_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xcd: ('v_cmp_lg_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xce: ('v_cmp_ge_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xcf: ('v_cmp_o_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xd0: ('v_cmpx_f_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd1: ('v_cmpx_lt_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd2: ('v_cmpx_eq_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd3: ('v_cmpx_le_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd4: ('v_cmpx_gt_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd5: ('v_cmpx_ne_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd6: ('v_cmpx_ge_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd7: ('v_cmpx_t_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), + 0xd8: ('v_cmpx_f_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xd9: ('v_cmpx_lt_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xda: ('v_cmpx_eq_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xdb: ('v_cmpx_le_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xdc: ('v_cmpx_gt_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xdd: ('v_cmpx_lg_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xde: ('v_cmpx_ge_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xdf: ('v_cmpx_o_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xe0: ('v_cmp_f_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xe1: ('v_cmp_lt_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xe2: ('v_cmp_eq_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xe3: ('v_cmp_le_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xe4: ('v_cmp_gt_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xe5: ('v_cmp_ne_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xe6: ('v_cmp_ge_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xe7: ('v_cmp_t_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xe8: ('v_cmp_u_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xe9: ('v_cmp_nge_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xea: ('v_cmp_nlg_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xeb: ('v_cmp_ngt_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xec: ('v_cmp_nle_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xed: ('v_cmp_neq_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xee: ('v_cmp_nlt_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xef: ('v_cmp_tru_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xf0: ('v_cmpx_f_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xf1: ('v_cmpx_lt_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xf2: ('v_cmpx_eq_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xf3: ('v_cmpx_le_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xf4: ('v_cmpx_gt_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xf5: ('v_cmpx_ne_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xf6: ('v_cmpx_ge_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xf7: ('v_cmpx_t_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), + 0xf8: ('v_cmpx_u_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xf9: ('v_cmpx_nge_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xfa: ('v_cmpx_nlg_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xfb: ('v_cmpx_ngt_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xfc: ('v_cmpx_nle_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xfd: ('v_cmpx_neq_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xfe: ('v_cmpx_nlt_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), + 0xff: ('v_cmpx_tru_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), +} + diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 809fc1b4b..773274030 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -30,6 +30,7 @@ from collections import Counter, defaultdict from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) +from report_paths import path_key, same_report_path # noqa: E402 from shader_ir import HDR, parse_file # noqa: E402 import cfg_structure # noqa: E402 import fssm_header # noqa: E402 @@ -61,6 +62,7 @@ W64G_COUNTS = Counter() # tiers of the wave64 VS/PS/GS translated so far, for # barycentrics, so .y/.z are AMD's i/j as with BaryCoordKHR. BARY_FALLBACK = False FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_fma, VK_KHR_shader_fma), not GLSL Fma +FMA_EXACT = False # --fma exact: fused multiply-adds are emulated from single-rounded f32 ops (Gen.fma_exact) # --texel-offset-fallback: image_sample*_o without VK_KHR_maintenance8. The run-time texel offset is folded into the # coordinate (coordinate + offset / size of the sampled mip level) instead of the SPIR-V Offset operand, which needs # maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original @@ -94,6 +96,7 @@ PC_TAIL_SET, PC_TAIL_BINDING = 1, 0 # can use there. F16_HALVES = False F16_HALF_TOP = 29 +OPT_SPIRV = False # --opt: run tools/spirv_opt.py basic-block peephole pass on emitted SPIR-V (#884) def pc_tail_chain(name, member, c): @@ -220,6 +223,7 @@ class Gen: self.consts = {} self.n = 0 self.outputs = {} + self.partial_color_outputs: set[str] = set() self.inputs = {} self.interpolated = set() # inputs read through v_interp_p1/p2; the rest are flat (v_interp_mov only) self.per_vertex = set() # PS: attribute numbers read by a *_f16 interp: PerVertexKHR, decoded per half @@ -292,6 +296,7 @@ class Gen: self.wave64 = False # compiled for 64-lane waves (64-bit EXEC writes, exec_hi, v_mbcnt_hi, ...) self.cur_uniform_readlane = False self.w64g = None # wave64 VS/PS/GS: wave64_halves.analyse() result (tier, reasons, rewrite sites) + self.w64_scalar_spills = set() # (vgpr, lane) pure scalar spill slots lowered to self.parked (SHADER-10) self.emulate = False # --wave64-emulate: exact wave64 on any subgroup size (cs/ms; see x_round) self.emulate_inline = False # emulate: current block emits direct inline barriers (no x_split) self.emulate_plan = None # emulate: structured plan from wave64_emulate_opt.plan_structured_emulation @@ -301,6 +306,7 @@ class Gen: self.x_marks = [] # emulate: (index into body, segment) where a segment of the current block ends self.x_segs = {} # emulate: continuation segment -> its SPIR-V lines self.x_spills = [] # emulate: (Function variable, pointer type) carrying a value across a round + self.eager_vars = [] # (Function variable, pointer type) a subgroup op's result is stored to (see eager) self.x_ptr_types = {} # emulate: value type -> Function pointer type declared for spills self.x_dirty = set() # emulate: (memory kind "lds"/"mem", "r"/"w") accessed since the last round self.x_tok = {} # emulate: register -> the SSA id last stored to it in this block (its value's identity) @@ -914,9 +920,104 @@ class Gen: if FMA_KHR: self.uses_fma_khr = True self.emit(f"{r} = OpFmaKHR %float {x} {y} {z}") + elif FMA_EXACT: + self.fma_exact(r, x, y, z) else: self.emit(f"{r} = OpExtInst %float %glsl Fma {x} {y} {z}") + def fma_exact(self, r, x, y, z): + """r = x * y + z rounded once to f32, built from single-rounded NoContraction f32 operations (--fma exact, + SHADER-497): for a device whose driver splits GLSL Fma into two roundings and that has no VK_KHR_shader_fma + (Intel UHD Graphics, Xe-LP, Windows driver 101.7088: cs_fma_fused words 0, 2, 3 and 5 split). + + Boldo and Melquiond's emulated FMA ("Emulation of a FMA and correctly-rounded sums: proved algorithms using + rounding to odd", IEEE Transactions on Computers 57(4), 2008): p + pe = x * y exactly (Dekker's product; the + factors are split into 12-bit halves by masking the low 12 mantissa bits, so the split cannot overflow), + th + tl = z + p exactly (TwoSum), v = tl + pe rounded to odd (as fma_f16_odd), and r = th + v rounded to + nearest, or th when v is zero (th + 0 would turn a -0 sum into +0). + + That needs every intermediate in the f32 normal range, so the operands are first scaled by powers of two, + which is exact, and the result scaled back: by 2^-64 when the product or z is at least 2^126 (the product may + overflow while z brings the sum back into range), by 2^96 when both are tiny (|x*y| < 2^-76 and + |z| < 2^-46), and a factor below 2^-100 is traded 2^64 against one above 2^-20, so the low split halves stay + normal on a driver that flushes f32 denormals. Infinite or NaN operands, and finite ones whose product is + beyond even the scaled range (the result is +-inf), take the plain Fma. Exact (checked against an exact + rational reference in tests/semantic/test_fma_exact.py) for finite operands with a normal or zero result, + with f32 denormals kept or flushed; a result in the denormal range is scaled back with a second rounding, + and a denormal operand follows the driver's denormal mode, as for every f32 operation here.""" + t = self.tmp + one = "%f1" + + def op(name, *args, ty="%float"): + o = t() + self.emit(f"{o} = {name} {ty} {' '.join(args)}") + return o + + def mag(v): + return op("OpBitwiseAnd", op("OpBitcast", v, ty="%uint"), self.cu(0x7FFFFFFF), ty="%uint") + + def below(m, k): + return op("OpULessThan", m, self.cu(k), ty="%bool") + + def above(m, k): + return op("OpUGreaterThan", m, self.cu(k), ty="%bool") + + def sel(c, a, b): + return op("OpSelect", c, a, b) + + up64, dn64, up96, dn96 = (self.fconst(2.0 ** e) for e in (64, -64, 96, -96)) + mx, my, mz = mag(x), mag(y), mag(z) + mp0 = mag(op("OpFMul", x, y)) + big = op("OpLogicalOr", above(mp0, 0x7E7FFFFF), above(mz, 0x7E7FFFFF), ty="%bool") # >= 2^126 (or inf) + tiny = self.emit_land(below(mp0, 0x19800000), below(mz, 0x28800000)) # < 2^-76, < 2^-46 + xsm = op("OpULessThan", mx, my, ty="%bool") + # big: the larger factor and z down by 2^64; tiny: the smaller factor and z up by 2^96; the result back. + fx = sel(big, sel(xsm, one, dn64), sel(tiny, sel(xsm, up96, one), one)) + fy = sel(big, sel(xsm, dn64, one), sel(tiny, sel(xsm, one, up96), one)) + fz = sel(big, dn64, sel(tiny, up96, one)) + fr = sel(big, up64, sel(tiny, dn96, one)) + x1, y1, z1 = op("OpFMul", x, fx), op("OpFMul", y, fy), op("OpFMul", z, fz) + # A factor below 2^-100 next to one above 2^-20: trade 2^64 between them (the product is unchanged). + mx1, my1 = mag(x1), mag(y1) + bx = self.emit_land(below(mx1, 0x0D800000), above(my1, 0x35800000)) + by = self.emit_land(below(my1, 0x0D800000), above(mx1, 0x35800000)) + xa = op("OpFMul", x1, sel(bx, up64, sel(by, dn64, one))) + ya = op("OpFMul", y1, sel(bx, dn64, sel(by, up64, one))) + # Dekker's product: p + pe = xa * ya, every partial product exact (12 x 12 bits). + p = op("OpFMul", xa, ya) + halves = [] + for v in (xa, ya): + hi = op("OpBitcast", op("OpBitwiseAnd", op("OpBitcast", v, ty="%uint"), self.cu(0xFFFFF000), ty="%uint")) + halves += [hi, op("OpFSub", v, hi)] + xh, xl, yh, yl = halves + t1 = op("OpFSub", op("OpFMul", xh, yh), p) + t2 = op("OpFAdd", t1, op("OpFMul", xh, yl)) + t3 = op("OpFAdd", t2, op("OpFMul", xl, yh)) + pe = op("OpFAdd", t3, op("OpFMul", xl, yl)) + + def two_sum(a, b): + s = op("OpFAdd", a, b) + bb = op("OpFSub", s, a) + e = op("OpFAdd", op("OpFSub", a, op("OpFSub", s, bb)), op("OpFSub", b, bb)) + return s, e + + th, tl = two_sum(p, z1) + # v = tl + pe rounded to odd: the nearest sum, moved one ulp towards its error when inexact and even. + s, e = two_sum(tl, pe) + sbits, ebits = op("OpBitcast", s, ty="%uint"), op("OpBitcast", e, ty="%uint") + even = op("OpIEqual", op("OpBitwiseAnd", sbits, self.cu(1), ty="%uint"), self.cu(0), ty="%bool") + inexact = self.emit_land(op("OpFUnordNotEqual", e, "%f0", ty="%bool"), op("OpFOrdEqual", e, e, ty="%bool")) + same = below(op("OpBitwiseXor", sbits, ebits, ty="%uint"), 0x80000000) # same sign: away from zero + adj = op("OpSelect", same, op("OpIAdd", sbits, self.cu(1), ty="%uint"), + op("OpISub", sbits, self.cu(1), ty="%uint"), ty="%uint") + v = op("OpBitcast", op("OpSelect", self.emit_land(even, inexact), adj, sbits, ty="%uint")) + rs = sel(op("OpFOrdEqual", v, "%f0", ty="%bool"), th, op("OpFAdd", th, v)) + rr = op("OpFMul", rs, fr) + special = op("OpLogicalOr", op("OpLogicalOr", above(mx, 0x7F7FFFFF), above(my, 0x7F7FFFFF), ty="%bool"), + op("OpLogicalOr", above(mz, 0x7F7FFFFF), op("OpIsNan", rr, ty="%bool"), ty="%bool"), ty="%bool") + g = op("OpExtInst", "%glsl Fma", x, y, z) + self.emit(f"{r} = OpSelect %float {special} {g} {rr}") + def fma_f16_odd(self, x, y, z): """fma(x, y, z) for f16 inputs (widened to f32), rounded to f32 with round-to-odd (SHADER-55). @@ -1041,6 +1142,21 @@ class Gen: self.emit(f"{r} = OpLogicalAnd %bool {a} {b}") return r + def eager(self, ty, val): + """val (a %uint or %bool), stored to a Function variable of its own and loaded back (SHADER-529). + + SPIRV-Cross (MoltenVK) inlines a result used once into the expression that uses it. On the right of an + OpLogicalAnd/OpLogicalOr that is a short-circuiting && / ||, and in an arm of a scalar OpSelect a ternary, + so a subgroup op there runs only in the lanes that get that far: a ballot misses the other lanes' bits and + a shuffle reads from lanes that never ran it. A store is a statement, which every lane runs.""" + ptr = {"%uint": "%_ptr_Function_uint", "%bool": "%_ptr_Function_bool"}[ty] + var = f"%eager{len(self.eager_vars)}" + self.eager_vars.append((var, ptr)) + self.emit(f"OpStore {var} {val}") + r = self.tmp() + self.emit(f"{r} = OpLoad {ty} {var}") + return r + def f16_pack2(self, lo, hi, exact_tiny=False): """Two f32 values -> one %uint of two f16 halves (lo | hi << 16), each rounded as f16_res, without PackHalf2x16.""" a, b, sh, r = self.f16_res(lo, exact_tiny), self.f16_res(hi, exact_tiny), self.tmp(), self.tmp() @@ -1162,6 +1278,9 @@ class Gen: val = self.sdwa_dst(a, val) if a["k"] == "special" and a["t"] == "null": return # result discarded + if self.wave64 and a["k"] == "special" and a["t"] in ("exec_lo", "exec_hi"): + self.exec_half_write(1 if a["t"] == "exec_hi" else 0, val) + return if a["k"] == "special" and a["t"] in ("exec_lo", "exec"): self.set_exec(val) return @@ -1965,86 +2084,30 @@ class Gen: self.emit(f"{lbl_exit} = OpLabel") return cur, lbl_exit - def global_atomic(self, op, a, mods): - """global_atomic_ [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: a 32-bit atomic at the global_* address - (RDNA2 ISA, FLAT/GLOBAL). With glc the pre-op value lands in vdst (the first operand); without it there is no - vdst. cmpswap takes vdata as a pair {DATA, CMP}: M = (M == CMP) ? DATA : M. inc/dec wrap unsigned against DATA - via a CAS loop. Inactive lanes don't touch memory and keep vdst. and/or/xor/swap_x2 work on a 64-bit element - (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics. That leaves the same memory for - a bitwise op, whose bits are independent, but not always for an exchange: two lanes swapping into one element - at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi). The returned pair is - two reads, so another lane's 64-bit op on the same element between them could be seen half done. The other - _x2 forms (add/sub/min/max/inc/dec carry or compare across the dwords, cmpswap_x2 compares all 64 bits) and - fcmpswap stay Unsupported.""" - kind = op[len("global_atomic_"):] - if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): - return self.global_atomic_x2(op, kind[:-3], a, mods) - if kind in ("fmin", "fmax"): - return self.global_atomic_float(op, kind, a, mods) - is_inc_dec = kind in ("inc", "dec") - if (kind not in self.BUF_ATOMICS and not is_inc_dec) or any(m in mods for m in ("slc", "dlc", "lds")): - raise Unsupported(op if (kind not in self.BUF_ATOMICS and not is_inc_dec) else op + " form") - rtn = "glc" in mods - if len(a) != (4 if rtn else 3): - raise Unsupported(op + " operands") - vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) - if vdata["k"] != "vgpr" or vdata.get("n", 1) != (2 if kind == "cmpswap" else 1) or \ - (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 1)): - raise Unsupported(op + " operands") - full = self.global_address(op, vaddr, saddr, mods) - val = self.load_reg("vgpr", vdata["r"]) - cmp = self.load_reg("vgpr", vdata["r"] + 1) if kind == "cmpswap" else None - old_d = self.load_reg("vgpr", vdst["r"]) if vdst is not None else self.cu(0) - lbl_do, lbl_end, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp() - pre = self.current_label_placeholder() - act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr, p = self.tmp(), self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") - if is_inc_dec: - res, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) - else: - res, done_lbl = self.tmp(), lbl_do - if kind == "cmpswap": - self.emit(f"{res} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") - else: - self.emit(f"{res} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {val}") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - self.emit(f"{old} = OpPhi %uint {res} {done_lbl} {old_d} {pre}") - if vdst is not None: - self.store_reg("vgpr", vdst["r"], old) + def atomic_aligned(self, addr, align_bytes): + """True iff 64-bit Xbox VA `addr` is naturally aligned to `align_bytes` (4 or 8). + Measured natively on RDNA2 (gfx1036, wave32 & wave64): unaligned buffer_atomic* and global_atomic* + leave memory untouched and active glc lanes receive 0 / (0, 0), while inactive lanes keep vdst.""" + lo, rem, ok = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{lo} = OpUConvert %uint {addr}") + self.emit(f"{rem} = OpBitwiseAnd %uint {lo} {self.cu(align_bytes - 1)}") + self.emit(f"{ok} = OpIEqual %bool {rem} {self.cu(0)}") + return ok - def global_atomic_float(self, op, kind, a, mods): - """global_atomic_{fmin,fmax} [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: 32-bit float min/max at the - global_* address via a CAS loop (OpAtomicCompareExchange + GLSL.std.450 NMin/NMax, so no shader float atomic - extension is needed). Inactive lanes don't touch memory and keep vdst.""" - if any(m in mods for m in ("slc", "dlc", "lds")): - raise Unsupported(op + " form") - rtn = "glc" in mods - if len(a) != (4 if rtn else 3): - raise Unsupported(op + " operands") - vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) - if vdata["k"] != "vgpr" or vdata.get("n", 1) != 1 or \ - (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 1)): - raise Unsupported(op + " operands") - full = self.global_address(op, vaddr, saddr, mods) - val_f = self.tof(self.load_reg("vgpr", vdata["r"])) - old_d = self.load_reg("vgpr", vdst["r"]) if vdst is not None else self.cu(0) + def _emit_atomic_fminmax_cas(self, kind, addr, val_f, cond): + """Shared CAS loop for 32-bit float atomic min/max (global_atomic_{fmin,fmax} and buffer_atomic_{fmin,fmax}). + Returns the pre-op uint word on taken lanes and 0 on skipped lanes (caller writes via self.dst so inactive + lanes keep their destination VGPR untouched).""" lbl_do, lbl_hdr, lbl_cont, lbl_exit, lbl_end = ( self.tmp() + s for s in ("_do", "_hdr", "_cont", "_exit", "_end")) pre = self.current_label_placeholder() - act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") + self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, p, init = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") - self.emit(f"{init} = OpLoad %uint {p} Aligned 4") + self.emit(f"{init} = OpAtomicLoad %uint {p} {self.cu(1)} {self.cu(0)}") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_hdr} = OpLabel") cur, cur_f, new_f, new_u, got, done = (self.tmp() for _ in range(6)) @@ -2063,9 +2126,85 @@ class Gen: self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") old = self.tmp() - self.emit(f"{old} = OpPhi %uint {cur} {lbl_exit} {old_d} {pre}") + self.emit(f"{old} = OpPhi %uint {cur} {lbl_exit} {self.cu(0)} {pre}") + return old + + def global_atomic(self, op, a, mods): + """global_atomic_ [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: a 32-bit atomic at the global_* address + (RDNA2 ISA, FLAT/GLOBAL). With glc the pre-op value lands in vdst (the first operand); without it there is no + vdst. cmpswap takes vdata as a pair {DATA, CMP}: M = (M == CMP) ? DATA : M. Inactive lanes don't touch memory + and keep vdst; active unaligned lanes (addr % 4 != 0, or addr % 8 != 0 for _x2) leave memory untouched and + write 0 / (0, 0) to vdst (measured natively on gfx1036). and/or/xor/swap_x2 work on a 64-bit element (two + dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics. That leaves the same memory for a + bitwise op, whose bits are independent, but not always for an exchange: two lanes swapping into one element at + once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi). The returned pair is two + reads, so another lane's 64-bit op on the same element between them could be seen half done. The other _x2 + forms (add/sub/min/max carry or compare across the dwords, cmpswap_x2 compares all 64 bits) and inc/dec stay + Unsupported.""" + kind = op[len("global_atomic_"):] + if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): + return self.global_atomic_x2(op, kind[:-3], a, mods) + if kind in ("fmin", "fmax"): + return self.global_atomic_float(op, kind, a, mods) + is_inc_dec = kind in ("inc", "dec") + if (kind not in self.BUF_ATOMICS and not is_inc_dec) or any(m in mods for m in ("slc", "dlc", "lds")): + raise Unsupported(op if (kind not in self.BUF_ATOMICS and not is_inc_dec) else op + " form") + rtn = "glc" in mods + if len(a) != (4 if rtn else 3): + raise Unsupported(op + " operands") + vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) + if vdata["k"] != "vgpr" or vdata.get("n", 1) != (2 if kind == "cmpswap" else 1) or \ + (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 1)): + raise Unsupported(op + " operands") + full = self.global_address(op, vaddr, saddr, mods) + val = self.load_reg("vgpr", vdata["r"]) + cmp = self.load_reg("vgpr", vdata["r"] + 1) if kind == "cmpswap" else None + al = self.atomic_aligned(full, 4) + cond = self.tmp() + self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") + lbl_do, lbl_end, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp() + pre = self.current_label_placeholder() + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") + self.emit(f"{lbl_do} = OpLabel") + ptr, p = self.tmp(), self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") + if is_inc_dec: + res, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) + else: + res, done_lbl = self.tmp(), lbl_do + if kind == "cmpswap": + self.emit(f"{res} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") + else: + self.emit(f"{res} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {val}") + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + self.emit(f"{old} = OpPhi %uint {res} {done_lbl} {self.cu(0)} {pre}") if vdst is not None: - self.store_reg("vgpr", vdst["r"], old) + self.dst(vdst, old) + + def global_atomic_float(self, op, kind, a, mods): + """global_atomic_{fmin,fmax} [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: 32-bit float min/max at the + global_* address via a CAS loop (OpAtomicCompareExchange + GLSL.std.450 NMin/NMax, so no shader float atomic + extension is needed). Inactive lanes don't touch memory and keep vdst; active unaligned lanes write 0.""" + if any(m in mods for m in ("slc", "dlc", "lds")): + raise Unsupported(op + " form") + rtn = "glc" in mods + if len(a) != (4 if rtn else 3): + raise Unsupported(op + " operands") + vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) + if vdata["k"] != "vgpr" or vdata.get("n", 1) != 1 or \ + (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 1)): + raise Unsupported(op + " operands") + full = self.global_address(op, vaddr, saddr, mods) + val_f = self.tof(self.load_reg("vgpr", vdata["r"])) + al = self.atomic_aligned(full, 4) + cond = self.tmp() + self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") + old = self._emit_atomic_fminmax_cas(kind, full, val_f, cond) + if vdst is not None: + self.dst(vdst, old) def global_atomic_x2(self, op, kind, a, mods): """global_atomic_{and,or,xor,swap}_x2 (see global_atomic): one 32-bit atomic per dword of the element.""" @@ -2080,13 +2219,14 @@ class Gen: raise Unsupported(op + " operands") full = self.global_address(op, vaddr, saddr, mods) vals = [self.load_reg("vgpr", vdata["r"] + w) for w in range(2)] - keep = [self.load_reg("vgpr", vdst["r"] + w) for w in range(2)] if vdst is not None else [self.cu(0)] * 2 spv = self.BUF_ATOMICS[kind][0] + al = self.atomic_aligned(full, 8) + cond = self.tmp() + self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre = self.current_label_placeholder() - act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") + self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr = self.tmp() self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") @@ -2101,18 +2241,21 @@ class Gen: olds = [] for w in range(2): # both OpPhi first: they must open the merge block old = self.tmp() - self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {keep[w]} {pre}") + self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {self.cu(0)} {pre}") olds.append(old) if vdst is not None: for w in range(2): - self.store_reg("vgpr", vdst["r"] + w, olds[w]) + self.dst({"k": "vgpr", "r": vdst["r"] + w, "n": 1}, olds[w]) def buffer_atomic(self, op, a, mods): """buffer_atomic_ vdata, vaddr, s[V#], soffset ...: 32-bit atomic at the element address (buffer device - address). With 'glc' the pre-op value is returned in vdata. Inactive or out-of-bounds lanes don't touch memory.""" + address). With 'glc' the pre-op value is returned in vdata. Inactive lanes don't touch memory and keep vdata; + active OOB or unaligned (addr % 4 != 0) lanes leave memory untouched and write 0 with glc (measured on gfx1036).""" kind = op[len("buffer_atomic_"):] if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): return self.buffer_atomic_x2(op, kind[:-3], a, mods) + if kind in ("fmin", "fmax"): + return self.buffer_atomic_float(op, kind, a, mods) is_inc_dec = kind in ("inc", "dec") if (kind not in self.BUF_ATOMICS and not is_inc_dec) or "x2" in kind: raise Unsupported(op) @@ -2121,9 +2264,11 @@ class Gen: raise Unsupported(op + " data") addr, _, in_b, _ = self.buffer_address(a, mods) val = self.load_reg("vgpr", vd["r"]) - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {in_b}") - # Guard all atomics with a structured if so inactive or OOB lanes never touch memory. + al = self.atomic_aligned(addr, 4) + ok, cond = self.tmp(), self.tmp() + self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") + self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") + # Guard all atomics with a structured if so inactive, OOB or unaligned lanes never touch memory. lbl_do, lbl_end, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp() pre_label = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") @@ -2150,21 +2295,44 @@ class Gen: if "glc" in mods: self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, old) + def buffer_atomic_float(self, op, kind, a, mods): + """buffer_atomic_{fmin,fmax} vdata, vaddr, s[V#], soffset ...: 32-bit float min/max at the MUBUF address via + the shared OpAtomicCompareExchange + GLSL.std.450 NMin/NMax CAS loop (no float-atomic extension needed). + Enforces V# bounds and 4-byte natural alignment; with glc returns the old word (0 when OOB/unaligned, + preserved when inactive).""" + if "lds" in mods: + raise Unsupported(op + " form") + vd = a[0] + if vd["k"] != "vgpr" or vd.get("n", 1) != 1: + raise Unsupported(op + " data") + addr, _, in_b, _ = self.buffer_address(a, mods) + val_f = self.tof(self.load_reg("vgpr", vd["r"])) + al = self.atomic_aligned(addr, 4) + ok, cond = self.tmp(), self.tmp() + self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") + self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") + old = self._emit_atomic_fminmax_cas(kind, addr, val_f, cond) + if "glc" in mods: + self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, old) + def buffer_atomic_x2(self, op, kind, a, mods): """buffer_atomic_{and,or,xor,swap}_x2 vdata[0:1], vaddr, s[V#], soffset: M = op(M, DATA) on the 64-bit element (two dwords, low first); with glc the old 64 bits are returned in vdata. Each dword is its own 32-bit atomic, so no Int64 atomics are needed. That leaves the same memory for a bitwise op, whose bits are independent, but an exchange can tear: two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi). The returned pair is two reads, so another lane's 64-bit op on the same element - between them could be seen half done. The bounds check covers the whole 8-byte element, all or nothing, as for a typed element (a 32_32 - format): how hardware treats a 64-bit atomic that is only partly in range is not measured.""" + between them could be seen half done. Measured natively on RDNA2 (gfx1036, wave32 & wave64): the bounds check + covers the whole 8-byte element all or nothing (fixed_fmt=62) and addresses with (addr & 7) != 0 are dropped + (memory untouched, active glc returns (0, 0), inactive preserves vdata).""" vd = a[0] if vd["k"] != "vgpr" or vd.get("n", 1) != 2: raise Unsupported(op + " data") addr, _, in_b, _ = self.buffer_address(a, mods, elem="fmt", fixed_fmt=62) # step: as buffer_atomic vals = [self.load_reg("vgpr", vd["r"] + w) for w in range(2)] - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {in_b}") + al = self.atomic_aligned(addr, 8) + ok, cond = self.tmp(), self.tmp() + self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") + self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") @@ -2183,7 +2351,7 @@ class Gen: olds = [] for w in range(2): # both OpPhi first: they must open the merge block old = self.tmp() - # an inactive or out-of-range lane returns 0, as buffer_atomic does + # an inactive, out-of-range or unaligned lane skips the atomic (active gets 0, inactive keeps vdata via dst) self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {self.cu(0)} {pre}") olds.append(old) if "glc" in mods: @@ -2213,7 +2381,10 @@ class Gen: self.uses_tex_array = True dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x3") dmask = int(dm.split(":")[1], 0) - vdata, addr = a[0], self.addr_regs(a[1]) + vdata = a[0] + if vdata["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the result goes + raise Unsupported("image_get_lod destination") + addr = self.addr_regs(a[1]) img_idx = self.desc_lookup_sgpr(a[2], 8) smp_idx = self.desc_lookup_sgpr(a[3], 4) ip, img, sp, smp, si = (self.tmp() for _ in range(5)) @@ -2245,19 +2416,40 @@ class Gen: out += 1 def decode_any_format(self, fmt, words): - """Decode every supported format from 4 packed dwords, then pick by FORMAT (0 for one outside FORMATS).""" - comps = [self.cu(0)] * 4 - for code in self.FORMATS: - dec = self.decode_format(words, code) - e = self.tmp() - self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") - nxt = [] - for c in range(4): - s = self.tmp() - self.emit(f"{s} = OpSelect %uint {e} {dec[c]} {comps[c]}") - nxt.append(s) - comps = nxt - return comps + """Decode 4 packed dwords by the run-time FORMAT (0 for one outside FORMATS), executing only that format's + decode: a binary search over the codes, marked DontFlatten (decoding every format to select one was about + 770 VALU instructions on every lane). Plain conditional branches, which the test interpreters run too.""" + return self.decode_format_search(fmt, words, sorted(self.FORMATS))[0] + + def decode_format_search(self, fmt, words, codes): + """decode_any_format over the sorted ``codes`` -> (4 ids, the label of the block that defines them, or None + for the block the search started in).""" + cond, yes, no, end = self.tmp(), self.tmp() + "_fy", self.tmp() + "_fn", self.tmp() + "_fe" + leaf = len(codes) == 1 + if leaf: + self.emit(f"{cond} = OpIEqual %bool {fmt} {self.cu(codes[0])}") + else: + mid = len(codes) // 2 + self.emit(f"{cond} = OpULessThan %bool {fmt} {self.cu(codes[mid])}") + self.emit(f"OpSelectionMerge {end} DontFlatten") + self.emit(f"OpBranchConditional {cond} {yes} {no}") + self.emit(f"{yes} = OpLabel") + if leaf: + a, a_end = self.decode_format(words, codes[0]), None + else: + a, a_end = self.decode_format_search(fmt, words, codes[:mid]) + self.emit(f"OpBranch {end}") + self.emit(f"{no} = OpLabel") + if leaf: + b, b_end = [self.cu(0)] * 4, None + else: + b, b_end = self.decode_format_search(fmt, words, codes[mid:]) + self.emit(f"OpBranch {end}") + self.emit(f"{end} = OpLabel") + out = [self.tmp() for _ in range(4)] + for o, x, y in zip(out, a, b): + self.emit(f"{o} = OpPhi %uint {x} {a_end or yes} {y} {b_end or no}") + return out, end def format_decode_call(self, fmt, words): """4 uint ids: the element decoded per the run-time FORMAT, through one function in the module. @@ -2289,6 +2481,10 @@ class Gen: from %fmt_size_tab. Typed loads used to select it through a chain over all of FORMATS per load (about 150 instructions); ScreenProbes_ActivateProbes has 3,281 such loads and its module was 2.5 M ids.""" self.uses_fmt_size = True + # The table's length and entries are constants: register them here, while the constant section can still + # take them, not at assembly (an OpTypeArray naming a constant declared after it fails spirv-val). + for v in {128, 0, *(f[0] for f in self.FORMATS.values())}: + self.cu(v) ptr, size = self.tmp(), self.tmp() self.emit(f"{ptr} = OpAccessChain %_ptr_Private_uint %fmt_size_tab {fmt}") self.emit(f"{size} = OpLoad %uint {ptr}") @@ -3545,12 +3741,13 @@ class Gen: self.emit(f"{do} = OpLabel") self.emit(f"{p} = OpAccessChain %_ptr_WG_uint %lds {i}") r = fn(p) + done_lbl = self.current_label_placeholder() self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") if r is None: return None v = self.tmp() - self.emit(f"{v} = OpPhi %uint {r} {do} {self.cu(0)} {pre}") + self.emit(f"{v} = OpPhi %uint {r} {done_lbl} {self.cu(0)} {pre}") return v def lds_load(self, addr, byte_off): @@ -3563,6 +3760,28 @@ class Gen: def lds_store(self, addr, byte_off, val): self.lds_access(addr, byte_off, lambda p: self.emit(f"OpStore {p} {val}")) + def lds_u16_cross_read(self, addr, byte_off, w, sh): + """A 16-bit LDS read at byte 3 of a dword (bit offset `sh` 24) also takes byte 0 of the next dword, as RDNA2 + LDS reads it in unaligned mode (llc -mcpu=gfx1030 -mattr=+unaligned-access-mode emits one ds_read_u16 at + offset 3). Returns (word, bit offset) for the 16-bit extract; the next dword is only read when crossing.""" + cross, lo, hi, comb, w2, sh2 = (self.tmp() for _ in range(6)) + x_do, x_end = self.tmp() + "_x", self.tmp() + "_xend" + self.emit(f"{cross} = OpIEqual %bool {sh} {self.cu(24)}") + pre = self.current_label_placeholder() + self.emit(f"OpSelectionMerge {x_end} None") + self.emit(f"OpBranchConditional {cross} {x_do} {x_end}") + self.emit(f"{x_do} = OpLabel") + nxt = self.lds_load(addr, byte_off + 1) + self.emit(f"{lo} = OpShiftRightLogical %uint {w} {self.cu(24)}") + self.emit(f"{hi} = OpShiftLeftLogical %uint {nxt} {self.cu(8)}") + self.emit(f"{comb} = OpBitwiseOr %uint {lo} {hi}") + last = self.current_label_placeholder() + self.emit(f"OpBranch {x_end}") + self.emit(f"{x_end} = OpLabel") + self.emit(f"{w2} = OpPhi %uint {comb} {last} {w} {pre}") + self.emit(f"{sh2} = OpSelect %uint {cross} {self.cu(0)} {sh}") + return w2, sh2 + def lds_atomic(self, addr, byte_off, rest): """`rest` is the atomic instruction after its result id, with {p} where the pointer goes.""" def f(p): @@ -3654,6 +3873,8 @@ class Gen: self.emit(f"{sh} = OpShiftLeftLogical %uint {s1} {self.cu(3)}") # byte address -> bit offset self.emit(f"{sh2} = OpBitwiseAnd %uint {sh} {self.cu(31)}") w = self.lds_load(addr, off) + if bits == 16: + w, sh2 = self.lds_u16_cross_read(addr, off, w, sh2) f = "OpBitFieldSExtract" if op.split("_")[2].startswith("i") else "OpBitFieldUExtract" self.emit(f"{v} = {f} %uint {w} {sh2} {self.cu(bits)}") d = a[0] @@ -3688,6 +3909,22 @@ class Gen: self.emit(f"{t1} = OpAtomicAnd %uint {p} {sc} {sem} {inv}") self.emit(f"{t2} = OpAtomicOr %uint {p} {sc} {sem} {pos}") self.lds_access(addr, off, sub_dword) + if bits == 16: + # A halfword at byte 3 writes its high byte to byte 0 of the next dword. + cross, hb, x_do, x_end = self.tmp(), self.tmp(), self.tmp() + "_x", self.tmp() + "_xend" + self.emit(f"{cross} = OpIEqual %bool {sh2} {self.cu(24)}") + self.emit(f"OpSelectionMerge {x_end} None") + self.emit(f"OpBranchConditional {cross} {x_do} {x_end}") + self.emit(f"{x_do} = OpLabel") + self.emit(f"{hb} = OpShiftRightLogical %uint {fld} {self.cu(8)}") + + def next_byte0(p): + t1, t2 = self.tmp(), self.tmp() + self.emit(f"{t1} = OpAtomicAnd %uint {p} {sc} {sem} {self.cu(0xFFFFFF00)}") + self.emit(f"{t2} = OpAtomicOr %uint {p} {sc} {sem} {hb}") + self.lds_access(addr, off + 1, next_byte0) + self.emit(f"OpBranch {x_end}") + self.emit(f"{x_end} = OpLabel") elif name in self.LDS_ATOMICS: d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) old = self.lds_atomic(self.src_u(ad), off, @@ -3820,50 +4057,56 @@ class Gen: if dat["k"] != "vgpr" or dat.get("n", 1) != 1 or \ (d is not None and (d["k"] != "vgpr" or d.get("n", 1) != 1)): raise Unsupported(op + " operands") - p = self.lds_ptr(self.src_u(ad), off) + addr = self.src_u(ad) val = self.src_u(dat) val_f = None if name in ("ds_min_f32", "ds_max_f32"): val_f = self.tmp() self.emit(f"{val_f} = OpBitcast %float {val}") - lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) - init = self.tmp() - self.emit(f"{init} = OpAtomicLoad %uint {p} {sc} {sem}") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_hdr} = OpLabel") - cur, got = self.tmp(), self.tmp() - self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") - if name == "ds_inc_u32": - wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") - self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") - elif name == "ds_dec_u32": - is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) - self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") - self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") - self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") - self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") - elif name == "ds_rsub_u32": - new_u = self.tmp() - self.emit(f"{new_u} = OpISub %uint {val} {cur}") - else: - cur_f, new_f, new_u = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{cur_f} = OpBitcast %float {cur}") - glsl_op = "NMin" if name == "ds_min_f32" else "NMax" - self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") - self.emit(f"{new_u} = OpBitcast %uint {new_f}") - done = self.tmp() - self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {sc} {sem} {sem} {new_u} {cur}") - self.emit(f"{done} = OpIEqual %bool {got} {cur}") - self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") - self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") - self.emit(f"{lbl_cont} = OpLabel") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_exit} = OpLabel") + + def cas(p): + entry_lbl = self.current_label_placeholder() + lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) + init = self.tmp() + self.emit(f"{init} = OpAtomicLoad %uint {p} {sc} {sem}") + self.emit(f"OpBranch {lbl_hdr}") + self.emit(f"{lbl_hdr} = OpLabel") + cur, got = self.tmp(), self.tmp() + self.emit(f"{cur} = OpPhi %uint {init} {entry_lbl} {got} {lbl_cont}") + if name == "ds_inc_u32": + wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") + self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") + self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") + elif name == "ds_dec_u32": + is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) + self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") + self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") + self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") + self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") + self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") + elif name == "ds_rsub_u32": + new_u = self.tmp() + self.emit(f"{new_u} = OpISub %uint {val} {cur}") + else: + cur_f, new_f, new_u = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{cur_f} = OpBitcast %float {cur}") + glsl_op = "NMin" if name == "ds_min_f32" else "NMax" + self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") + self.emit(f"{new_u} = OpBitcast %uint {new_f}") + done = self.tmp() + self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {sc} {sem} {sem} {new_u} {cur}") + self.emit(f"{done} = OpIEqual %bool {got} {cur}") + self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") + self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") + self.emit(f"{lbl_cont} = OpLabel") + self.emit(f"OpBranch {lbl_hdr}") + self.emit(f"{lbl_exit} = OpLabel") + return cur if d is not None else None + + old = self.lds_access(addr, off, cas) # bounds-checked when lds_bound is set (SHADER-309) if d is not None: - self.dst(d, cur) + self.dst(d, old) else: raise Unsupported(op) self.emit(f"OpBranch {lbl_end}") @@ -3958,7 +4201,18 @@ class Gen: def x_buf_bytes(self): """Workgroup bytes of %x_buf: the wave64 exchange (emulate) or the barrier-round counts (bar_rounds).""" - return 4 * (self.x_sizes()[3] + 1) if self.emulate else 12 if self.bar_rounds else 0 + if self.emulate: + return 4 * (self.x_sizes()[3] + 1) + return 12 if self.bar_rounds and not self.bar_counts_in_lds() else 0 + + def bar_counts_in_lds(self, lds_used=None): + """SHADER-579: whether the barrier rounds keep their count in a borrowed LDS word instead of %x_buf. Only + when the 12 bytes of %x_buf would take the total past 16384 B, the Vulkan minimum maxComputeSharedMemorySize: + a full 32 KiB LDS plus %x_buf is 32,780 B, over the 32,768 B of the AMD Windows and Intel drivers. Under + that, %x_buf fits on every device and costs no extra barriers (bar_scheduler). lds_used: before any code is + generated (fit_shared_memory), whether the shader will use its LDS is not known yet; assume it does.""" + used = self.uses_lds if lds_used is None else lds_used + return self.bar_rounds and used and 4 * self.lds_dwords + 12 > 16384 def fit_shared_memory(self): """SHADER-309: a compute shader's Workgroup memory, the LDS array plus %x_buf, must fit in MAX_SHARED_BYTES @@ -3969,7 +4223,7 @@ class Gen: the shader.""" if not self.cs: return - room = (MAX_SHARED_BYTES - self.x_buf_bytes()) // 4 + room = (MAX_SHARED_BYTES - (0 if self.bar_counts_in_lds(lds_used=True) else self.x_buf_bytes())) // 4 if self.lds_bound is None and self.lds_dwords > room >= max(self.lds_declared, 1): self.lds_dwords = self.lds_bound = self.lds_declared self.cu(self.lds_declared) @@ -4468,37 +4722,86 @@ class Gen: MASK_SOP2_B32 = ("s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32", "s_cselect_b32") + @staticmethod + def _maskable_b32(x): + return x["k"] in ("sgpr", "imm") or ( + x["k"] == "special" and (x.get("t", "").startswith(("exec", "vcc")) or x.get("t") == "null") + ) + + def _mask_b32_dst_half(self, d, srcs): + """For a 32-bit bitwise SALU op (s_not_b32 / MASK_SOP2_B32), return (to_mask_dst, half) where to_mask_dst + is True when d is EXEC or VCC (each lane holds its own bit) and half is 'lo'/'hi' in wave64 or None.""" + if d["k"] != "special": + return False, None + t = d.get("t", "") + if not self.wave64: + return t in ("exec_lo", "vcc_lo", "exec", "vcc"), None + if t in ("exec_lo", "exec_hi"): + return True, "hi" if t == "exec_hi" else "lo" + if t in ("vcc_lo", "vcc_hi") and ("vcc" in self.cur_masks or any(self.holds_lane_mask(s) for s in srcs)): + return True, "hi" if t == "vcc_hi" else "lo" + return False, None + + def _mask_b32_src(self, s, dst_half): + """Read one 32-bit source for a mask-writing bitwise SALU op (wave32, or wave64 half `dst_half`).""" + if self.wave64 and dst_half is not None and self.holds_lane_mask(s): + sh = self.mask_half(s) + if sh is not None and sh != dst_half: + # Opposite wave64 half (e.g. exec_lo <- vcc_hi): collect that half's 32-bit mask and take bit lane&31. + lo, hi = self.wave_mask(s) + word = hi if sh == "hi" else lo + lane = self.wave_lane() + s5, shr, bit, r = (self.tmp() for _ in range(4)) + self.emit(f"{s5} = OpBitwiseAnd %uint {lane} {self.cu(31)}") + self.emit(f"{shr} = OpShiftRightLogical %uint {word} {s5}") + self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") + self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + return r + return self.mask_src(s, wide=False) + + def _store_b32_mask_dst(self, d, val, to_mask_dst, dst_half): + """Store a 32-bit bitwise SALU result, preserving the untouched half of EXEC/VCC in wave64.""" + if to_mask_dst and self.wave64 and d["k"] == "special" and d.get("t") in ("vcc_lo", "vcc_hi"): + self.put_mask(d, val, dst_half) + if d["t"] == "vcc_hi": + self.emit(f"OpStore %vcc_hi {val}") + return + self.dst(d, val) + def sop2_b32_srcs(self, op, a): - """The two sources of a 32-bit SOP2. In a wave32 program a bitwise op (or s_cselect) that writes EXEC / VCC - reads both through mask_src, so a constant, inline or held in an SGPR, gives each lane its own bit; a mask is - read as before. Until 2026-11-22 - a constant was used whole: `s_and_b32 exec_lo, exec_lo, 0xff00` (or the same constant in an SGPR) left every - lane of EXEC on. Data ops, and wave64 programs (a b32 op there is on one half of a mask), are unchanged.""" - if op in self.MASK_SOP2_B32 and not self.wave64 and len(a) >= 3: - d = a[0] - to_mask = d["k"] == "special" and d.get("t", "") in ("exec_lo", "vcc_lo", "exec", "vcc") - maskable = all(x["k"] in ("sgpr", "imm") or (x["k"] == "special" and - x.get("t", "").startswith(("exec", "vcc"))) for x in a[1:3]) - # Only when the result is a mask (EXEC / VCC destination). An SGPR destination is classified by - # lane_masks.py, which calls it data when the other operand is a constant; a per-lane bit stored there - # would then be counted as data (s_and_b32 s20, exec_lo, 1; s_bcnt1_i32_b32 s21, s20 gave 32 and 0 - # instead of 1, found by @Pierre-Kookis on #1792), so that case keeps the data read. - if maskable and to_mask: - return self.mask_src(a[1], wide=False), self.mask_src(a[2], wide=False) + """The two sources of a 32-bit SOP2. A bitwise op (or s_cselect) that writes EXEC / VCC reads both through + _mask_b32_src / mask_src (in wave32 and on either half of a wave64 mask), so a constant, inline or held in + an SGPR, gives each lane its own bit; a mask is read as before. Until 2026-11-22 a constant was used whole: + `s_and_b32 exec_lo, exec_lo, 0xff00` (or the same constant in an SGPR) left every lane of EXEC on. An SGPR + destination stays a data read, because lane_masks.py classifies it as data when the other operand is a + constant (s_and_b32 s20, exec_lo, 1; s_bcnt1_i32_b32 s21, s20 gave 32 and 0 instead of 1, #1792).""" + if op in self.MASK_SOP2_B32 and len(a) >= 3: + to_mask, dst_half = self._mask_b32_dst_half(a[0], a[1:3]) + if to_mask and all(self._maskable_b32(x) for x in a[1:3]): + return self._mask_b32_src(a[1], dst_half), self._mask_b32_src(a[2], dst_half) return self.src_u(a[1]), self.src_u(a[2]) def scc_logic(self, a, r): - """SCC of a 32-bit bitwise SOP2 (s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. In a wave32 program - an operation on lane masks (a source holds one, or it writes EXEC) has the whole wave's mask as D, so SCC - is the vote of scc_from_mask, as for the _b64 forms. Until 2026-11-22 it was this lane's bit instead: - `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in the lanes whose own bit was 0 - although the wave runs it, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane - leave on its last iteration, before the wave did (tools/cf_diff.py, FUZZ-8). In a wave64 program the - same op works on one half of a mask (lanes 0-31 or 32-63), whose SCC would be a vote of that half only; - that case still takes the lane's bit and is not covered by the fuzzer yet.""" - writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec") - if not self.wave64 and (writes_exec or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2])): - self.scc_from_mask(r) + """SCC of a 32-bit bitwise SALU op (s_not_b32 and s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. + When the op works on a lane mask (writes EXEC/VCC or reads a lane-mask operand), D is the wave's mask + (or one 32-lane half of it in wave64), so SCC is a subgroup Any vote over the wave (wave32) or that half + (wave64, scc_any_half) rather than this lane's own bit.""" + srcs = a[1:] + to_mask_dst, dst_half = self._mask_b32_dst_half(a[0], srcs) + mask_srcs = [s for s in srcs if self.holds_lane_mask(s)] + if to_mask_dst: + self.scc_any_half(r, dst_half) + elif mask_srcs: + if not self.wave64: + self.scc_from_mask(r) + else: + halves = {self.mask_half(s) for s in mask_srcs} - {None} + if len(halves) == 1: + self.scc_any_half(r, halves.pop()) + elif not halves: + self.scc_from_mask(r) + else: + self.scc_nonzero(r) else: self.scc_nonzero(r) @@ -5347,8 +5650,10 @@ class Gen: ballot = self.tmp() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {self.active_b()}") self.uses_ballot = True - active = self.tmp() - self.emit(f"{active} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {ballot} {safe_sg}") + bit = self.tmp() + self.emit(f"{bit} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {ballot} {safe_sg}") + # Every lane runs the ballot, also the out-of-row lanes whose bit another lane reads (SHADER-529). + active = self.eager("%bool", bit) if in_bounds is not None: both = self.tmp() self.emit(f"{both} = OpLogicalAnd %bool {in_bounds} {active}") @@ -5356,8 +5661,10 @@ class Gen: src_ok = active if src.get("k") == "vgpr": self.uses_subgroup = True - shuffled = self.tmp() - self.emit(f"{shuffled} = OpGroupNonUniformShuffle %uint {self.cu(3)} {src_val} {safe_sg}") + sh_val = self.tmp() + self.emit(f"{sh_val} = OpGroupNonUniformShuffle %uint {self.cu(3)} {src_val} {safe_sg}") + # The shuffle is read in the arms of selects below; every lane must still run it (SHADER-529). + shuffled = self.eager("%uint", sh_val) else: shuffled = src_val @@ -5639,8 +5946,11 @@ class Gen: self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") self.dst(a[0], r) elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o", - "image_sample_c_lz_o") or op in ("image_sample", "image_sample_lz", "image_sample_l", "image_sample_b", "image_sample_c_lz", - "image_sample_c_l", "image_sample_d", "image_sample_d_cl", "image_load", "image_gather4_lz", "image_gather4_l", + "image_sample_c_lz_o", "image_sample_c_o", "image_sample_c_b_o", "image_sample_cl_o", "image_sample_b_cl_o", + "image_sample_c_cl_o", "image_sample_c_b_cl_o") or op in ("image_sample", "image_sample_lz", "image_sample_l", "image_sample_b", "image_sample_c_lz", + "image_sample_c_l", "image_sample_c", "image_sample_c_b", "image_sample_cl", "image_sample_b_cl", "image_sample_c_cl", + "image_sample_c_b_cl", + "image_sample_d", "image_sample_d_cl", "image_load", "image_gather4_lz", "image_gather4_l", "image_gather4_lz_o", "image_gather4_l_o"): self.image_op(op, a, mods) elif op in ("v_sin_f16", "v_cos_f16"): @@ -5716,27 +6026,34 @@ class Gen: self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") self.dst(a[0], r) elif op in ("v_dot2_i32_i16", "v_dot2_u32_u16", "v_dot4_u32_u8", "v_dot8_i32_i4", "v_dot8_u32_u4", - "v_dot2c_i32_i16", "v_dot8c_i32_i4"): - # Packed integer dot products (RDNA2 ISA VOP3P, plus VOP2/VOP3 accumulating v_dot2c_i32_i16 / v_dot8c_i32_i4): - # D = sum_{k=0..N-1} (S0.elem[k] * S1.elem[k]) + (D for *c*, S2 otherwise) - # Wrapping at 32 bits by default; VOP3/VOP3P clamp saturates to [INT32_MIN, INT32_MAX] (signed) or - # [0, UINT32_MAX] (unsigned). Hardware default for VOP3P is op_sel:[0,0,0] and op_sel_hi:[1,1,1]; - # any other op_sel/op_sel_hi (or any op_sel on VOP2/VOP3 *c*), neg_lo/neg_hi, DPP/SDWA, or source - # neg/abs are refused. - is_c = op in ("v_dot2c_i32_i16", "v_dot8c_i32_i4") - def bits(name, default): - m = next((m for m in mods if m.startswith(name + ":")), None) - return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default - other = [m for m in mods if m != "clamp" and not (not is_c and m.startswith(("op_sel:", "op_sel_hi:")))] - if (other or ins["op"].endswith(("_dpp", "_sdwa")) or any(s.get("neg") or s.get("abs") for s in a) or - (not is_c and (bits("op_sel", [0, 0, 0]) != [0, 0, 0] or - bits("op_sel_hi", [1, 1, 1]) != [1, 1, 1]))): - raise Unsupported(op + " modifiers") + "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4", "v_dot8c_u32_u4"): + # Packed integer dot products (RDNA2 ISA VOP3P and VOP2 accumulating v_dot*c_*): + # D = sum_{k=0..N-1} (S0.elem[k] * S1.elem[k]) + acc (acc = S2 for VOP3P, old D for VOP2) + # Wrapping at 32 bits by default; clamp saturates to [INT32_MIN, INT32_MAX] (signed) or + # [0, UINT32_MAX] (unsigned). For VOP3P, hardware default is op_sel:[0,0,0] and op_sel_hi:[1,1,1]; + # any other op_sel/op_sel_hi, neg_lo/neg_hi, DPP/SDWA, or source neg/abs are refused. For VOP2 + # v_dot*c_*, only optional clamp (VOP3 _e64) is accepted and D must be a VGPR. + is_c = op in ("v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4", "v_dot8c_u32_u4") + if is_c: + if a[0]["k"] != "vgpr": + raise Unsupported(op + " destination") + if any(m != "clamp" for m in mods) or ins["op"].endswith(("_dpp", "_sdwa")) or any( + s.get("neg") or s.get("abs") for s in a): + raise Unsupported(op + " modifiers") + x, y, acc = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[0]) + else: + def bits(name, default): + m = next((m for m in mods if m.startswith(name + ":")), None) + return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default + other = [m for m in mods if m != "clamp" and not m.startswith(("op_sel:", "op_sel_hi:"))] + if (other or ins["op"].endswith(("_dpp", "_sdwa")) or any(s.get("neg") or s.get("abs") for s in a) or + bits("op_sel", [0, 0, 0]) != [0, 0, 0] or bits("op_sel_hi", [1, 1, 1]) != [1, 1, 1]): + raise Unsupported(op + " modifiers") + x, y, acc = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[3]) width = 16 if ("_dot2_" in op or "_dot2c_" in op) else (8 if "_dot4" in op else 4) signed = op.endswith(("i16", "i4")) clamp = "clamp" in mods ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - x, y, acc = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[0] if is_c else a[3]) prods = [] for off in range(0, 32, width): xe, ye, p = self.tmp(), self.tmp(), self.tmp() @@ -5788,6 +6105,68 @@ class Gen: self.emit(f"{sat} = OpSelect %uint {nz} {bound} {r}") r = sat self.dst(a[0], r) + elif op in ("v_dot2_f32_f16", "v_dot2c_f32_f16"): + # Half-to-float dot product (RDNA2 ISA): D = S0.lo*S1.lo + S0.hi*S1.hi + acc (acc = S2 for VOP3P + # v_dot2_f32_f16, old D for VOP2 v_dot2c_f32_f16). + if a[0]["k"] != "vgpr": + raise Unsupported(op + " destination") + if ins["op"].endswith(("_dpp", "_sdwa")) or any(s.get("neg") or s.get("abs") for s in a): + raise Unsupported(op + " modifiers") + if op == "v_dot2_f32_f16": + def bits(name, default): + m = next((m for m in mods if m.startswith(name + ":")), None) + return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default + other = [m for m in mods if m != "clamp" and not m.startswith(("op_sel:", "op_sel_hi:", "neg_lo:", "neg_hi:"))] + if other: + raise Unsupported(op + " modifiers") + sel = bits("op_sel", [0, 0, 0]) + selhi = bits("op_sel_hi", [1, 1, 1]) + nlo = bits("neg_lo", [0, 0, 0]) + nhi = bits("neg_hi", [0, 0, 0]) + if any(len(v) != 3 or any(b not in (0, 1) for b in v) for v in (sel, selhi, nlo, nhi)): + raise Unsupported(op + " modifiers") + if sel[2] != 0 or selhi[2] != 1 or nhi[2] != 0: + raise Unsupported(op + " modifiers") + a0 = self.f16_in(a[1], sel[0]) + a1 = self.f16_in(a[1], selhi[0]) + b0 = self.f16_in(a[2], sel[1]) + b1 = self.f16_in(a[2], selhi[1]) + if nlo[0]: + t = self.tmp() + self.emit(f"{t} = OpFNegate %float {a0}") + a0 = t + if nhi[0]: + t = self.tmp() + self.emit(f"{t} = OpFNegate %float {a1}") + a1 = t + if nlo[1]: + t = self.tmp() + self.emit(f"{t} = OpFNegate %float {b0}") + b0 = t + if nhi[1]: + t = self.tmp() + self.emit(f"{t} = OpFNegate %float {b1}") + b1 = t + acc = self.flush_f32(self.src_f(a[3])) + if nlo[2]: + t = self.tmp() + self.emit(f"{t} = OpFNegate %float {acc}") + acc = t + else: + if any(m != "clamp" for m in mods): + raise Unsupported(op + " modifiers") + a0 = self.f16_in(a[1], 0) + a1 = self.f16_in(a[1], 1) + b0 = self.f16_in(a[2], 0) + b1 = self.f16_in(a[2], 1) + acc = self.flush_f32(self.src_f(a[0])) + p0, p1, s, r = (self.tmp() for _ in range(4)) + self.emit(f"{p0} = OpFMul %float {a0} {b0}") + self.emit(f"{p1} = OpFMul %float {a1} {b1}") + self.emit(f"{s} = OpFAdd %float {p0} {p1}") + self.emit(f"{r} = OpFAdd %float {s} {acc}") + r = self.clamp_mods(r, ["clamp"] if "clamp" in mods else []) + self.dst(a[0], self.tou(r)) elif op in ("v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16"): # Packed 16-bit shifts (VOP3P): result half h = src1 half (op_sel / op_sel_hi) shifted by src0 half & 15. def bits(name, default): @@ -5832,17 +6211,42 @@ class Gen: self.emit(f"{m} = OpFMul %float {x} {y}") self.emit(f"{r} = OpFAdd %float {m} {z}") self.dst(a[0], self.tou(r)) - elif op in ("v_bfi_b32", "v_lshl_or_b32", "v_lshl_add_u32", "v_add_lshl_u32", "v_or3_b32", "v_xor3_b32", + elif op == "v_bfi_b32": + mask = None if "sdwa_sel" in a[1] else self.imm_val(a[1]) + y, z = (self.src_u(t) for t in a[2:4]) + if mask == 0: + self.dst(a[0], z) + return + if mask == 0xFFFFFFFF: + self.dst(a[0], y) + return + if mask is not None: + offset = (mask & -mask).bit_length() - 1 + width = mask.bit_count() + if mask == ((1 << width) - 1) << offset: + # RDNA takes the field from its final bit positions; SPIR-V takes its low bits. + if offset: + shifted = self.tmp() + self.emit(f"{shifted} = OpShiftRightLogical %uint {y} {self.cu(offset)}") + y = shifted + r = self.tmp() + self.emit(f"{r} = OpBitFieldInsert %uint {z} {y} {self.cu(offset)} {self.cu(width)}") + self.dst(a[0], r) + return + x, n = self.cu(mask), self.cu(~mask) + else: + x, n = self.src_u(a[1]), self.tmp() + self.emit(f"{n} = OpNot %uint {x}") + p, q, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{p} = OpBitwiseAnd %uint {x} {y}") + self.emit(f"{q} = OpBitwiseAnd %uint {n} {z}") + self.emit(f"{r} = OpBitwiseOr %uint {p} {q}") + self.dst(a[0], r) + elif op in ("v_lshl_or_b32", "v_lshl_add_u32", "v_add_lshl_u32", "v_or3_b32", "v_xor3_b32", "v_add3_u32", "v_and_or_b32_"): x, y, z = (self.src_u(t) for t in a[1:4]) r = self.tmp() - if op == "v_bfi_b32": - p, n, q = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{p} = OpBitwiseAnd %uint {x} {y}") - self.emit(f"{n} = OpNot %uint {x}") - self.emit(f"{q} = OpBitwiseAnd %uint {n} {z}") - self.emit(f"{r} = OpBitwiseOr %uint {p} {q}") - elif op in ("v_lshl_or_b32", "v_lshl_add_u32"): + if op in ("v_lshl_or_b32", "v_lshl_add_u32"): s, m = self.tmp(), self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {y} {self.cu(31)}") self.emit(f"{s} = OpShiftLeftLogical %uint {x} {m}") @@ -5889,8 +6293,9 @@ class Gen: self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") self.dst(a[0], r) - elif op in ("v_cmp_class_f32", "v_cmpx_class_f32", "v_cmp_class_f16", "v_cmpx_class_f16", - "v_cmp_class_f64", "v_cmpx_class_f64"): + elif op in ("v_cmp_class_f32", "v_cmpx_class_f32", "v_cmp_class_f16", "v_cmpx_class_f16"): + # f64 goes to cmp_class_f64 below (the operand checks test_cmp_class_f64 pins); cmp_class's own f64 + # branch, merged later, has no operand-form checks. self.cmp_class(a, exec_only=op.startswith("v_cmpx_"), ty=op.rsplit("_", 1)[1], mods=mods) elif op in ("v_ffbl_b32", "v_ffbh_u32", "s_flbit_i32_b32") or \ (op == "s_ff1_i32_b32" and not self.holds_lane_mask(a[1])): # of a lane mask: further down @@ -5911,7 +6316,8 @@ class Gen: self.emit(f"{z} = OpIEqual %bool {x} {self.cu(0)}") self.emit(f"{r} = OpSelect %uint {z} {self.cu(0xFFFFFFFF)} {d}") self.dst(a[0], r) - elif op in ("image_get_resinfo", "image_load_mip", "image_store", "image_atomic_cmpswap") or op in self.IMG_ATOMICS: + elif op in ("image_get_resinfo", "image_load_mip", "image_store", "image_atomic_cmpswap") \ + or op in self.IMG_ATOMICS or op in self.IMG_ATOMICS_EXTRA: self.image_misc(op, a, mods) elif op in ("v_cubema_f32", "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32"): # Cube face selection (standard table): major axis Z if |z|>=|x| and |z|>=|y|, else Y if |y|>=|x|, @@ -6138,9 +6544,13 @@ class Gen: half = self.mask_half(a[1]) if half is not None: lo, hi = (hi if half == "hi" else lo), self.cu(0) - elif op.endswith("b32") or a[1]["k"] == "imm": - # A b32 source is a plain scalar value, not a lane mask; for b64 an immediate is the low word. + elif op.endswith("b32"): + # A b32 source is a plain scalar value, not a lane mask. lo, hi = self.src_u(a[1]), self.cu(0) + elif a[1]["k"] == "imm": + # A 64-bit constant's own 64 bits (inline negative constants sign-extend, literals zero-extend), + # matching s_bcnt0/1_i32_b64 and src64_data. + lo, hi = self.src64_data(a[1], op) elif a[1]["k"] != "sgpr" or a[1].get("n") != 2: lo, hi = self.mask_src(a[1]), self.cu(0) else: @@ -6397,6 +6807,12 @@ class Gen: # the bit of the one lane the mask was parked in. self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) return + if slot and slot[1:] in self.w64_scalar_spills: + # SHADER-10: wave64_halves proved this VGPR is pure scalar-spill storage (never read as a vector + # operand), so spills across all 64 lanes (including 32..63) reload from the parked scalar slot + # instead of shuffling from an out-of-range lane on a 32-wide subgroup. + self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) + return self.uses_subgroup = True v, ln = self.src_u(a[1]), self.src_u(a[2]) m, r = self.tmp(), self.tmp() @@ -6407,9 +6823,12 @@ class Gen: self.dst(a[0], r) elif op == "v_writelane_b32": # vD[lane] = sS: only the named lane changes (independent of EXEC, as on hardware). + slot = lane_masks.lane_slot(a[0], a[2]) + if slot and slot[1:] in self.w64_scalar_spills: + self.store_reg("sgpr", self.parked[slot[1:]], self.src_u(a[1])) + return self.uses_subgroup = True val, ln = self.src_u(a[1]), self.src_u(a[2]) - slot = lane_masks.lane_slot(a[0], a[2]) if slot and slot[1:] in self.parked: # somewhere a mask is fetched back from this lane: keep ours self.store_reg("sgpr", self.parked[slot[1:]], val) me, m, eq, old, r = (self.tmp() for _ in range(5)) @@ -6538,27 +6957,21 @@ class Gen: r = r2 self.dst(a[0], r) elif op == "v_lerp_u8": - # Per byte: D.b = (S0.b + S1.b + (bit 0 of S2.b)) >> 1, an unsigned average whose rounding comes from - # S2 (RDNA ISA pseudocode). The 9-bit sum never reaches past its own byte after the shift. if "clamp" in mods: raise Unsupported(op + " clamp") x, y, z = (self.src_u(t) for t in a[1:4]) - r = None - for off in (0, 8, 16, 24): - xb, yb, zb, t1, t2, avg = (self.tmp() for _ in range(6)) - self.emit(f"{xb} = OpBitFieldUExtract %uint {x} {self.cu(off)} {self.cu(8)}") - self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(8)}") - self.emit(f"{zb} = OpBitFieldUExtract %uint {z} {self.cu(off)} {self.cu(1)}") - self.emit(f"{t1} = OpIAdd %uint {xb} {yb}") - self.emit(f"{t2} = OpIAdd %uint {t1} {zb}") - self.emit(f"{avg} = OpShiftRightLogical %uint {t2} {self.cu(1)}") - if r is None: - r = avg - else: - sh, o = self.tmp(), self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {avg} {self.cu(off)}") - self.emit(f"{o} = OpBitwiseOr %uint {r} {sh}") - r = o + # Per byte, x + y = 2*(x & y) + (x ^ y). Clear each low bit before the shift so the + # next byte cannot leak in. An odd sum rounds up only when the corresponding bit of z is 1. + # Both additions fit in each byte: even the rounded average is at most 255. + different, shared, even, half, round_bits, rounding, average, r = (self.tmp() for _ in range(8)) + self.emit(f"{different} = OpBitwiseXor %uint {x} {y}") + self.emit(f"{shared} = OpBitwiseAnd %uint {x} {y}") + self.emit(f"{even} = OpBitwiseAnd %uint {different} {self.cu(0xFEFEFEFE)}") + self.emit(f"{half} = OpShiftRightLogical %uint {even} {self.cu(1)}") + self.emit(f"{round_bits} = OpBitwiseAnd %uint {different} {z}") + self.emit(f"{rounding} = OpBitwiseAnd %uint {round_bits} {self.cu(0x01010101)}") + self.emit(f"{average} = OpIAdd %uint {shared} {half}") + self.emit(f"{r} = OpIAdd %uint {average} {rounding}") self.dst(a[0], r) elif op == "v_xnor_b32": x, y = self.src_u(a[1]), self.src_u(a[2]) @@ -6663,12 +7076,9 @@ class Gen: cmpx = op.startswith("v_cmpx_") d, x, y = (None, a[-2], a[-1]) if cmpx else (a[0], a[1], a[2]) def pair64(sv): - if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: + if sv["k"] == "vgpr" and sv.get("n") == 2: return self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) - if sv["k"] == "imm": - v = sv["v"] & 0xFFFFFFFFFFFFFFFF - return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - raise Unsupported(op + " operand") + return self.src64_data(sv, op) (x0, x1), (y0, y1) = pair64(x), pair64(y) cond, signed = op.split("_")[2], op.endswith("_i64") hi_op = {"lt": "LessThan", "le": "LessThan", "gt": "GreaterThan", "ge": "GreaterThan"}[cond] @@ -7395,12 +7805,9 @@ class Gen: cmpx = op.startswith("v_cmpx_") d, x, y = (None, a[-2], a[-1]) if cmpx else (a[0], a[1], a[2]) def pair(s): - if s["k"] in ("vgpr", "sgpr") and s.get("n") == 2: + if s["k"] == "vgpr" and s.get("n") == 2: return self.load_reg(s["k"], s["r"]), self.load_reg(s["k"], s["r"] + 1) - if s["k"] == "imm": - v = s["v"] & 0xFFFFFFFFFFFFFFFF - return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - raise Unsupported(op + " operand") + return self.src64_data(s, op) (x0, x1), (y0, y1) = pair(x), pair(y) e0, e1, eq, r = (self.tmp() for _ in range(4)) self.emit(f"{e0} = OpIEqual %bool {x0} {y0}") @@ -7424,8 +7831,9 @@ class Gen: else: self.mask_dst(d, r) elif op == "s_not_b32": + to_mask_dst, dst_half = self._mask_b32_dst_half(a[0], a[1:2]) x_val = self.imm_val(a[1]) - if x_val is not None: + if x_val is not None and not to_mask_dst and not self.holds_lane_mask(a[1]): val = (~x_val) & 0xFFFFFFFF r = self.cu(val) self.dst(a[0], r) @@ -7433,13 +7841,12 @@ class Gen: self.sgpr_imm[a[0]["r"]] = val self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") else: - x = self.src_u(a[1]) + x = (self._mask_b32_src(a[1], dst_half) + if (to_mask_dst and self._maskable_b32(a[1])) else self.src_u(a[1])) r = self.tmp() self.emit(f"{r} = OpNot %uint {x}") - self.dst(a[0], r) - z = self.tmp() - self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") + self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) + self.scc_logic(a, r) elif op in ("s_cmp_eq_u64", "s_cmp_lg_u64"): # 64-bit compare of masks/pointers: equal iff both halves are equal. # Only canonical full-wave masks (exec, mask vcc, or a wave64 (MASK_LO, MASK_HI) pair) can take the @@ -7646,37 +8053,27 @@ class Gen: self.emit(f"{iinf} = OpIEqual %bool {mag} {self.cu(0x7C00)}") self.emit(f"{inan} = OpUGreaterThan %bool {mag} {self.cu(0x7C00)}") return mag, iz, iinf, inan - m0, _, _, _ = cls16(s0) + m0, _, _, nan0 = cls16(s0) _, z1, inf1, nan1 = cls16(s1) _, z2, inf2, nan2 = cls16(s2) - e1, e2, ediff, ediff_i, uf, of = (self.tmp() for _ in range(6)) - self.emit(f"{e1} = OpBitFieldUExtract %uint {s1} {self.cu(10)} {self.cu(5)}") - self.emit(f"{e2} = OpBitFieldUExtract %uint {s2} {self.cu(10)} {self.cu(5)}") - self.emit(f"{ediff} = OpISub %uint {e2} {e1}") - self.emit(f"{ediff_i} = OpBitcast %int {ediff}") - self.emit(f"{uf} = OpSLessThan %bool {ediff_i} {self.as_int(self.cu((-24) & 0xFFFFFFFF))}") - self.emit(f"{of} = OpSGreaterThanEqual %bool {ediff_i} {self.as_int(self.cu(16))}") - sx, sgn, qs2, qs1, inf_out, norm_out = (self.tmp() for _ in range(6)) + sx, sgn, inf_out, norm_out = (self.tmp() for _ in range(4)) self.emit(f"{sx} = OpBitwiseXor %uint {s1} {s2}") self.emit(f"{sgn} = OpBitwiseAnd %uint {sx} {self.cu(0x8000)}") - self.emit(f"{qs2} = OpBitwiseOr %uint {s2} {self.cu(0x0200)}") - self.emit(f"{qs1} = OpBitwiseOr %uint {s1} {self.cu(0x0200)}") self.emit(f"{inf_out} = OpBitwiseOr %uint {sgn} {self.cu(0x7C00)}") self.emit(f"{norm_out} = OpBitwiseOr %uint {sgn} {m0}") - b_zz, b_ii, b_ind, b_zero1, b_zero, b_inf1, b_inf = (self.tmp() for _ in range(7)) + b_zz, b_ii, b_ind, b_zero, b_inf1, b_inf = (self.tmp() for _ in range(6)) self.emit(f"{b_zz} = OpLogicalAnd %bool {z1} {z2}") self.emit(f"{b_ii} = OpLogicalAnd %bool {inf1} {inf2}") self.emit(f"{b_ind} = OpLogicalOr %bool {b_zz} {b_ii}") - self.emit(f"{b_zero1} = OpLogicalOr %bool {inf1} {z2}") - self.emit(f"{b_zero} = OpLogicalOr %bool {b_zero1} {uf}") + self.emit(f"{b_zero} = OpLogicalOr %bool {inf1} {z2}") self.emit(f"{b_inf1} = OpLogicalOr %bool {z1} {inf2}") - self.emit(f"{b_inf} = OpLogicalOr %bool {b_inf1} {of}") + self.emit(f"{b_inf} = OpLogicalOr %bool {b_inf1} {nan0}") r1, r2, r3, r4, r5 = (self.tmp() for _ in range(5)) self.emit(f"{r1} = OpSelect %uint {b_inf} {inf_out} {norm_out}") self.emit(f"{r2} = OpSelect %uint {b_zero} {sgn} {r1}") self.emit(f"{r3} = OpSelect %uint {b_ind} {self.cu(0xFE00)} {r2}") - self.emit(f"{r4} = OpSelect %uint {nan1} {qs1} {r3}") - self.emit(f"{r5} = OpSelect %uint {nan2} {qs2} {r4}") + self.emit(f"{r4} = OpSelect %uint {nan1} {s1} {r3}") + self.emit(f"{r5} = OpSelect %uint {nan2} {s2} {r4}") if has_omod: v2f, fv = self.tmp(), self.tmp() self.emit(f"{v2f} = OpExtInst %v2float %glsl UnpackHalf2x16 {r5}") @@ -7733,21 +8130,19 @@ class Gen: self.emit(f"{man_nz} = OpINotEqual %bool {man_or} {self.cu(0)}") self.emit(f"{inan} = OpLogicalAnd %bool {exp_max} {man_nz}") return mag, iz, iinf, inan - m0, _, _, _ = cls64(lo0, hi0) + m0, _, _, nan0 = cls64(lo0, hi0) _, z1, inf1, nan1 = cls64(lo1, hi1) _, z2, inf2, nan2 = cls64(lo2, hi2) - e1, e2, ediff, ediff_i, uf, of = (self.tmp() for _ in range(6)) + e1, e2, ediff, ediff_i, uf = (self.tmp() for _ in range(5)) self.emit(f"{e1} = OpBitFieldUExtract %uint {hi1} {self.cu(20)} {self.cu(11)}") self.emit(f"{e2} = OpBitFieldUExtract %uint {hi2} {self.cu(20)} {self.cu(11)}") self.emit(f"{ediff} = OpISub %uint {e2} {e1}") self.emit(f"{ediff_i} = OpBitcast %int {ediff}") - self.emit(f"{uf} = OpSLessThan %bool {ediff_i} {self.as_int(self.cu((-1074) & 0xFFFFFFFF))}") - self.emit(f"{of} = OpSGreaterThanEqual %bool {ediff_i} {self.as_int(self.cu(1024))}") - sx, sgn, qhi2, qhi1, inf_hi, norm_hi = (self.tmp() for _ in range(6)) + # Measured natively on RDNA2 gfx1036: underflow cutoff is e2 - e1 <= -1076 (no overflow check). + self.emit(f"{uf} = OpSLessThan %bool {ediff_i} {self.as_int(self.cu((-1075) & 0xFFFFFFFF))}") + sx, sgn, inf_hi, norm_hi = (self.tmp() for _ in range(4)) self.emit(f"{sx} = OpBitwiseXor %uint {hi1} {hi2}") self.emit(f"{sgn} = OpBitwiseAnd %uint {sx} {self.cu(0x80000000)}") - self.emit(f"{qhi2} = OpBitwiseOr %uint {hi2} {self.cu(0x00080000)}") - self.emit(f"{qhi1} = OpBitwiseOr %uint {hi1} {self.cu(0x00080000)}") self.emit(f"{inf_hi} = OpBitwiseOr %uint {sgn} {self.cu(0x7FF00000)}") self.emit(f"{norm_hi} = OpBitwiseOr %uint {sgn} {m0}") b_zz, b_ii, b_ind, b_zero1, b_zero, b_inf1, b_inf = (self.tmp() for _ in range(7)) @@ -7757,7 +8152,7 @@ class Gen: self.emit(f"{b_zero1} = OpLogicalOr %bool {inf1} {z2}") self.emit(f"{b_zero} = OpLogicalOr %bool {b_zero1} {uf}") self.emit(f"{b_inf1} = OpLogicalOr %bool {z1} {inf2}") - self.emit(f"{b_inf} = OpLogicalOr %bool {b_inf1} {of}") + self.emit(f"{b_inf} = OpLogicalOr %bool {b_inf1} {nan0}") z0 = self.cu(0) h1, l1, h2, l2, h3, l3, h4, l4, r_hi, r_lo = (self.tmp() for _ in range(10)) self.emit(f"{h1} = OpSelect %uint {b_inf} {inf_hi} {norm_hi}") @@ -7766,9 +8161,9 @@ class Gen: self.emit(f"{l2} = OpSelect %uint {b_zero} {z0} {l1}") self.emit(f"{h3} = OpSelect %uint {b_ind} {self.cu(0xFFF80000)} {h2}") self.emit(f"{l3} = OpSelect %uint {b_ind} {z0} {l2}") - self.emit(f"{h4} = OpSelect %uint {nan1} {qhi1} {h3}") + self.emit(f"{h4} = OpSelect %uint {nan1} {hi1} {h3}") self.emit(f"{l4} = OpSelect %uint {nan1} {lo1} {l3}") - self.emit(f"{r_hi} = OpSelect %uint {nan2} {qhi2} {h4}") + self.emit(f"{r_hi} = OpSelect %uint {nan2} {hi2} {h4}") self.emit(f"{r_lo} = OpSelect %uint {nan2} {lo2} {l4}") if has_omod: self.uses_f64 = True @@ -7934,10 +8329,11 @@ class Gen: elif op in ("s_add_i32", "s_sub_i32", "s_min_u32", "s_max_u32", "s_xor_b32", "s_andn2_b32", "s_cselect_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): val = None + to_mask_dst, dst_half = (self._mask_b32_dst_half(a[0], a[1:3]) + if op in self.MASK_SOP2_B32 else (False, None)) if op in ("s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec") - is_mask = not self.wave64 and (writes_exec or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2])) + is_mask = to_mask_dst or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2]) if x_val is not None and y_val is not None and not is_mask: if op == "s_xor_b32": val = (x_val ^ y_val) & 0xFFFFFFFF @@ -7993,7 +8389,7 @@ class Gen: k = {"s_add_i32": "OpIAdd", "s_sub_i32": "OpISub", "s_sub_u32": "OpISub", "s_xor_b32": "OpBitwiseXor"}[op] self.emit(f"{r} = {k} %uint {x} {y}") - self.dst(a[0], r) + self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) # SCC (RDNA ISA): bitwise ops -> result != 0; s_add/sub_i32 -> signed overflow; # s_min_u32 -> S0 < S1, s_max_u32 -> S0 > S1; s_cselect leaves SCC. if op in ("s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): @@ -8015,33 +8411,70 @@ class Gen: self.emit_fma(r, vals[0], vals[1], vals[2]) self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in ("v_div_fmas_f32", "v_div_fmas_f64"): - # Scaled FMA for IEEE-754 division (RDNA2 ISA VOP3): D = VCC ? (2^32 * fma(S0, S1, S2)) : fma(S0, S1, S2) - # for f32, and 2^64 for f64. To preserve tiny intermediates that would underflow before a post-FMA - # multiply (e.g. 2^-75 * 2^-75 -> 2^-118 in f32, 2^-540 * 2^-540 -> 2^-1016 in f64), pre-scale the - # operands (S0*2^16, S1*2^16, S2*2^32 for f32; S0*2^32, S1*2^32, S2*2^64 for f64) whenever none of the - # pre-scaled operands can overflow, falling back to post-FMA scaling otherwise. + # Scaled FMA for IEEE-754 division (RDNA2 ISA VOP3, measured natively on gfx1036 wave32/wave64): + # VCC == 0: fma(S0, S1, S2) + # VCC == 1: (exp(S2) > bias ? 2^S : 2^-S) * fma_exact(S0, S1, S2) + # where (bias, S) = (127, 64) for f32 and (1023, 128) for f64 (exp(S2) > bias <=> |S2| >= 2.0). + # Scale-up (|S2| >= 2.0): any non-zero cancellation residual against |S2| >= 2.0 stays well above + # normal minimum, and any intermediate overflow overflows after * 2^S too, so fma(x, y, z) * 2^S is + # exact. Scale-down (|S2| < 2.0): pre-scale only when |x*y| can overflow (|x|>=2^S & |y|>=1, or + # |y|>=2^S & |x|>=1, or |x|,|y|>=2^(S/2)), preserving a sticky bit when 0 < |z| < 2^(Emin+S); + # otherwise post-scale fma(x, y, z) * 2^-S (with f64 subnormal half-ULP tie correction so f64 + # subnormal outputs single-round, and f32 output denormal flush matching denorm32=0). vcc_b = self.tmp_bool_nz(self.mask_src({"k": "special", "t": "vcc"})) if op == "v_div_fmas_f32": x, y, z = (self.src_f(t) for t in a[1:4]) - ax, ay, az, lx, ly, lz, lxy, pre_ok = (self.tmp() for _ in range(8)) + ax, ay, az, f_plain, scale_up, f_up = (self.tmp() for _ in range(6)) self.emit(f"{ax} = OpExtInst %float %glsl FAbs {x}") self.emit(f"{ay} = OpExtInst %float %glsl FAbs {y}") self.emit(f"{az} = OpExtInst %float %glsl FAbs {z}") - self.emit(f"{lx} = OpFOrdLessThan %bool {ax} {self.fconst(2.0 ** 110)}") - self.emit(f"{ly} = OpFOrdLessThan %bool {ay} {self.fconst(2.0 ** 110)}") - self.emit(f"{lz} = OpFOrdLessThan %bool {az} {self.fconst(2.0 ** 95)}") - self.emit(f"{lxy} = OpLogicalAnd %bool {lx} {ly}") - self.emit(f"{pre_ok} = OpLogicalAnd %bool {lxy} {lz}") - xs, ys, zs, f_pre, f_plain, f_post, sc, r = (self.tmp() for _ in range(8)) - self.emit(f"{xs} = OpFMul %float {x} {self.fconst(2.0 ** 16)}") - self.emit(f"{ys} = OpFMul %float {y} {self.fconst(2.0 ** 16)}") - self.emit(f"{zs} = OpFMul %float {z} {self.fconst(2.0 ** 32)}") - self.emit_fma(f_pre, xs, ys, zs) self.emit_fma(f_plain, x, y, z) - self.emit(f"{f_post} = OpFMul %float {f_plain} {self.fconst(2.0 ** 32)}") - self.emit(f"{sc} = OpSelect %float {pre_ok} {f_pre} {f_post}") + self.emit(f"{scale_up} = OpFOrdGreaterThanEqual %bool {az} {self.fconst(2.0)}") + self.emit(f"{f_up} = OpFMul %float {f_plain} {self.fconst(2.0 ** 64)}") + gx64, gy1, bx, gy64, gx1, by, gx32, gy32, bxy, b1, big = (self.tmp() for _ in range(11)) + self.emit(f"{gx64} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(2.0 ** 64)}") + self.emit(f"{gy1} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(1.0)}") + self.emit(f"{bx} = OpLogicalAnd %bool {gx64} {gy1}") + self.emit(f"{gy64} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(2.0 ** 64)}") + self.emit(f"{gx1} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(1.0)}") + self.emit(f"{by} = OpLogicalAnd %bool {gy64} {gx1}") + self.emit(f"{gx32} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(2.0 ** 32)}") + self.emit(f"{gy32} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(2.0 ** 32)}") + self.emit(f"{bxy} = OpLogicalAnd %bool {gx32} {gy32}") + self.emit(f"{b1} = OpLogicalOr %bool {bx} {by}") + self.emit(f"{big} = OpLogicalOr %bool {b1} {bxy}") + xm64, ym64, xm32, ym32, xs1, xs, ys1, ys = (self.tmp() for _ in range(8)) + self.emit(f"{xm64} = OpFMul %float {x} {self.fconst(2.0 ** -64)}") + self.emit(f"{ym64} = OpFMul %float {y} {self.fconst(2.0 ** -64)}") + self.emit(f"{xm32} = OpFMul %float {x} {self.fconst(2.0 ** -32)}") + self.emit(f"{ym32} = OpFMul %float {y} {self.fconst(2.0 ** -32)}") + self.emit(f"{xs1} = OpSelect %float {by} {x} {xm32}") + self.emit(f"{xs} = OpSelect %float {bx} {xm64} {xs1}") + self.emit(f"{ys1} = OpSelect %float {by} {ym64} {ym32}") + self.emit(f"{ys} = OpSelect %float {bx} {y} {ys1}") + zu, zmag, znz, zlt, ztiny, zsgn, zst_u, zst, z_sc, zs = (self.tmp() for _ in range(10)) + self.emit(f"{zu} = OpBitcast %uint {z}") + self.emit(f"{zmag} = OpBitwiseAnd %uint {zu} {self.cu(0x7FFFFFFF)}") + self.emit(f"{znz} = OpINotEqual %bool {zmag} {self.cu(0)}") + self.emit(f"{zlt} = OpULessThan %bool {zmag} {self.cu(0x20800000)}") + self.emit(f"{ztiny} = OpLogicalAnd %bool {znz} {zlt}") + self.emit(f"{zsgn} = OpBitwiseAnd %uint {zu} {self.cu(0x80000000)}") + self.emit(f"{zst_u} = OpBitwiseOr %uint {zsgn} {self.cu(0x00800000)}") + self.emit(f"{zst} = OpBitcast %float {zst_u}") + self.emit(f"{z_sc} = OpFMul %float {z} {self.fconst(2.0 ** -64)}") + self.emit(f"{zs} = OpSelect %float {ztiny} {zst} {z_sc}") + f_pre, f_post, f_dn, sc, r = (self.tmp() for _ in range(5)) + self.emit_fma(f_pre, xs, ys, zs) + self.emit(f"{f_post} = OpFMul %float {f_plain} {self.fconst(2.0 ** -64)}") + self.emit(f"{f_dn} = OpSelect %float {big} {f_pre} {f_post}") + self.emit(f"{sc} = OpSelect %float {scale_up} {f_up} {f_dn}") self.emit(f"{r} = OpSelect %float {vcc_b} {sc} {f_plain}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + r = self.flush_f32(r) + if mods: + r = self.clamp_mods(r, mods) + if any(m in ("mul:2", "mul:4", "div:2") for m in mods): + r = self.flush_f32(r) + self.dst(a[0], self.tou(r)) else: def f64(sv): if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: @@ -8069,23 +8502,150 @@ class Gen: raise Unsupported(op + " destination") self.uses_f64 = True x, y, z = (f64(t) for t in a[1:4]) - ax, ay, az, lx, ly, lz, lxy, pre_ok = (self.tmp() for _ in range(8)) + ax, ay, az, f_plain, scale_up, f_up = (self.tmp() for _ in range(6)) self.emit(f"{ax} = OpExtInst %double %glsl FAbs {x}") self.emit(f"{ay} = OpExtInst %double %glsl FAbs {y}") self.emit(f"{az} = OpExtInst %double %glsl FAbs {z}") - self.emit(f"{lx} = OpFOrdLessThan %bool {ax} {self.dconst(2.0 ** 990)}") - self.emit(f"{ly} = OpFOrdLessThan %bool {ay} {self.dconst(2.0 ** 990)}") - self.emit(f"{lz} = OpFOrdLessThan %bool {az} {self.dconst(2.0 ** 958)}") - self.emit(f"{lxy} = OpLogicalAnd %bool {lx} {ly}") - self.emit(f"{pre_ok} = OpLogicalAnd %bool {lxy} {lz}") - xs, ys, zs, f_pre, f_plain, f_post, sc, r, v2, lo, hi = (self.tmp() for _ in range(11)) - self.emit(f"{xs} = OpFMul %double {x} {self.dconst(2.0 ** 32)}") - self.emit(f"{ys} = OpFMul %double {y} {self.dconst(2.0 ** 32)}") - self.emit(f"{zs} = OpFMul %double {z} {self.dconst(2.0 ** 64)}") - self.emit(f"{f_pre} = OpExtInst %double %glsl Fma {xs} {ys} {zs}") self.emit(f"{f_plain} = OpExtInst %double %glsl Fma {x} {y} {z}") - self.emit(f"{f_post} = OpFMul %double {f_plain} {self.dconst(2.0 ** 64)}") - self.emit(f"{sc} = OpSelect %double {pre_ok} {f_pre} {f_post}") + self.emit(f"{scale_up} = OpFOrdGreaterThanEqual %bool {az} {self.dconst(2.0)}") + self.emit(f"{f_up} = OpFMul %double {f_plain} {self.dconst(2.0 ** 128)}") + gx128, gy1, bx, gy128, gx1, by, gx64, gy64, bxy, b1, big = (self.tmp() for _ in range(11)) + self.emit(f"{gx128} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(2.0 ** 128)}") + self.emit(f"{gy1} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(1.0)}") + self.emit(f"{bx} = OpLogicalAnd %bool {gx128} {gy1}") + self.emit(f"{gy128} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(2.0 ** 128)}") + self.emit(f"{gx1} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(1.0)}") + self.emit(f"{by} = OpLogicalAnd %bool {gy128} {gx1}") + self.emit(f"{gx64} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(2.0 ** 64)}") + self.emit(f"{gy64} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(2.0 ** 64)}") + self.emit(f"{bxy} = OpLogicalAnd %bool {gx64} {gy64}") + self.emit(f"{b1} = OpLogicalOr %bool {bx} {by}") + self.emit(f"{big} = OpLogicalOr %bool {b1} {bxy}") + xm128, ym128, xm64, ym64, xs1, xs, ys1, ys = (self.tmp() for _ in range(8)) + self.emit(f"{xm128} = OpFMul %double {x} {self.dconst(2.0 ** -128)}") + self.emit(f"{ym128} = OpFMul %double {y} {self.dconst(2.0 ** -128)}") + self.emit(f"{xm64} = OpFMul %double {x} {self.dconst(2.0 ** -64)}") + self.emit(f"{ym64} = OpFMul %double {y} {self.dconst(2.0 ** -64)}") + self.emit(f"{xs1} = OpSelect %double {by} {x} {xm64}") + self.emit(f"{xs} = OpSelect %double {bx} {xm128} {xs1}") + self.emit(f"{ys1} = OpSelect %double {by} {ym128} {ym64}") + self.emit(f"{ys} = OpSelect %double {bx} {y} {ys1}") + zv2, zlo, zhi, zmag_hi, zmag_or, znz, zexp, zlt, ztiny, zsgn, zst_hi, zst_v2, zst, z_sc, zs = ( + self.tmp() for _ in range(15) + ) + self.emit(f"{zv2} = OpBitcast %v2uint_d {z}") + self.emit(f"{zlo} = OpCompositeExtract %uint {zv2} 0") + self.emit(f"{zhi} = OpCompositeExtract %uint {zv2} 1") + self.emit(f"{zmag_hi} = OpBitwiseAnd %uint {zhi} {self.cu(0x7FFFFFFF)}") + self.emit(f"{zmag_or} = OpBitwiseOr %uint {zmag_hi} {zlo}") + self.emit(f"{znz} = OpINotEqual %bool {zmag_or} {self.cu(0)}") + self.emit(f"{zexp} = OpBitwiseAnd %uint {zhi} {self.cu(0x7FF00000)}") + self.emit(f"{zlt} = OpULessThan %bool {zexp} {self.cu(129 << 20)}") + self.emit(f"{ztiny} = OpLogicalAnd %bool {znz} {zlt}") + self.emit(f"{zsgn} = OpBitwiseAnd %uint {zhi} {self.cu(0x80000000)}") + self.emit(f"{zst_hi} = OpBitwiseOr %uint {zsgn} {self.cu(0x00100000)}") + self.emit(f"{zst_v2} = OpCompositeConstruct %v2uint_d {self.cu(0)} {zst_hi}") + self.emit(f"{zst} = OpBitcast %double {zst_v2}") + self.emit(f"{z_sc} = OpFMul %double {z} {self.dconst(2.0 ** -128)}") + self.emit(f"{zs} = OpSelect %double {ztiny} {zst} {z_sc}") + f_pre = self.tmp() + self.emit(f"{f_pre} = OpExtInst %double %glsl Fma {xs} {ys} {zs}") + # Subnormal-output single-rounding tie adjustment when |f_plain| in [2^-947, 2^-894). + pv2, plo, phi, pe_shift, pe_exp, e_ge, e_le, in_rng = (self.tmp() for _ in range(8)) + self.emit(f"{pv2} = OpBitcast %v2uint_d {f_plain}") + self.emit(f"{plo} = OpCompositeExtract %uint {pv2} 0") + self.emit(f"{phi} = OpCompositeExtract %uint {pv2} 1") + self.emit(f"{pe_shift} = OpShiftRightLogical %uint {phi} {self.cu(20)}") + self.emit(f"{pe_exp} = OpBitwiseAnd %uint {pe_shift} {self.cu(0x7FF)}") + self.emit(f"{e_ge} = OpUGreaterThanEqual %bool {pe_exp} {self.cu(76)}") + self.emit(f"{e_le} = OpULessThanEqual %bool {pe_exp} {self.cu(128)}") + self.emit(f"{in_rng} = OpLogicalAnd %bool {e_ge} {e_le}") + sh_raw, sh_c, sh_is_hi, sh_lo, lo_shr, lo_mask, lo_m1, lo_half, lo_and, tie_lo = ( + self.tmp() for _ in range(10) + ) + self.emit(f"{sh_raw} = OpISub %uint {self.cu(129)} {pe_exp}") + self.emit(f"{sh_c} = OpSelect %uint {in_rng} {sh_raw} {self.cu(1)}") + self.emit(f"{sh_is_hi} = OpUGreaterThan %bool {sh_c} {self.cu(32)}") + self.emit(f"{sh_lo} = OpSelect %uint {sh_is_hi} {self.cu(1)} {sh_c}") + self.emit(f"{lo_shr} = OpISub %uint {self.cu(32)} {sh_lo}") + self.emit(f"{lo_mask} = OpShiftRightLogical %uint {self.cu(0xFFFFFFFF)} {lo_shr}") + self.emit(f"{lo_m1} = OpISub %uint {sh_lo} {self.cu(1)}") + self.emit(f"{lo_half} = OpShiftLeftLogical %uint {self.cu(1)} {lo_m1}") + self.emit(f"{lo_and} = OpBitwiseAnd %uint {plo} {lo_mask}") + self.emit(f"{tie_lo} = OpIEqual %bool {lo_and} {lo_half}") + sh2_raw, sh2, hi_m, hi_sig, hi_shr, hi_mask, hi_m1, hi_half, hi_and, hi_eq, lo_z, tie_hi, is_tie = ( + self.tmp() for _ in range(13) + ) + self.emit(f"{sh2_raw} = OpISub %uint {sh_c} {self.cu(32)}") + self.emit(f"{sh2} = OpSelect %uint {sh_is_hi} {sh2_raw} {self.cu(1)}") + self.emit(f"{hi_m} = OpBitwiseAnd %uint {phi} {self.cu(0xFFFFF)}") + self.emit(f"{hi_sig} = OpBitwiseOr %uint {hi_m} {self.cu(0x100000)}") + self.emit(f"{hi_shr} = OpISub %uint {self.cu(32)} {sh2}") + self.emit(f"{hi_mask} = OpShiftRightLogical %uint {self.cu(0xFFFFFFFF)} {hi_shr}") + self.emit(f"{hi_m1} = OpISub %uint {sh2} {self.cu(1)}") + self.emit(f"{hi_half} = OpShiftLeftLogical %uint {self.cu(1)} {hi_m1}") + self.emit(f"{hi_and} = OpBitwiseAnd %uint {hi_sig} {hi_mask}") + self.emit(f"{hi_eq} = OpIEqual %bool {hi_and} {hi_half}") + self.emit(f"{lo_z} = OpIEqual %bool {plo} {self.cu(0)}") + self.emit(f"{tie_hi} = OpLogicalAnd %bool {lo_z} {hi_eq}") + self.emit(f"{is_tie} = OpSelect %bool {sh_is_hi} {tie_hi} {tie_lo}") + # Exact residual rem = (x*y + z) - f_plain via product error + TwoSum. + d0 = self.dconst(0.0) + pmul, np, pe_raw, p_z, x_nz, y_nz, xy_nz, p_uf = (self.tmp() for _ in range(8)) + self.emit(f"{pmul} = OpFMul %double {x} {y}") + self.emit(f"{np} = OpFNegate %double {pmul}") + self.emit(f"{pe_raw} = OpExtInst %double %glsl Fma {x} {y} {np}") + self.emit(f"{p_z} = OpFOrdEqual %bool {pmul} {d0}") + self.emit(f"{x_nz} = OpFOrdNotEqual %bool {x} {d0}") + self.emit(f"{y_nz} = OpFOrdNotEqual %bool {y} {d0}") + self.emit(f"{xy_nz} = OpLogicalAnd %bool {x_nz} {y_nz}") + self.emit(f"{p_uf} = OpLogicalAnd %bool {p_z} {xy_nz}") + xv2, xhi, yv2, yhi, xysgn, psgn, pe_uf_v2, pe_uf, pe = (self.tmp() for _ in range(9)) + self.emit(f"{xv2} = OpBitcast %v2uint_d {x}") + self.emit(f"{xhi} = OpCompositeExtract %uint {xv2} 1") + self.emit(f"{yv2} = OpBitcast %v2uint_d {y}") + self.emit(f"{yhi} = OpCompositeExtract %uint {yv2} 1") + self.emit(f"{xysgn} = OpBitwiseXor %uint {xhi} {yhi}") + self.emit(f"{psgn} = OpBitwiseAnd %uint {xysgn} {self.cu(0x80000000)}") + self.emit(f"{pe_uf_v2} = OpCompositeConstruct %v2uint_d {self.cu(1)} {psgn}") + self.emit(f"{pe_uf} = OpBitcast %double {pe_uf_v2}") + self.emit(f"{pe} = OpSelect %double {p_uf} {pe_uf} {pe_raw}") + ssum, sv, s_sv, p_err, z_err, se, s_df, s_df_se, rem = (self.tmp() for _ in range(9)) + self.emit(f"{ssum} = OpFAdd %double {pmul} {z}") + self.emit(f"{sv} = OpFSub %double {ssum} {pmul}") + self.emit(f"{s_sv} = OpFSub %double {ssum} {sv}") + self.emit(f"{p_err} = OpFSub %double {pmul} {s_sv}") + self.emit(f"{z_err} = OpFSub %double {z} {sv}") + self.emit(f"{se} = OpFAdd %double {p_err} {z_err}") + self.emit(f"{s_df} = OpFSub %double {ssum} {f_plain}") + self.emit(f"{s_df_se} = OpFAdd %double {s_df} {se}") + self.emit(f"{rem} = OpFAdd %double {s_df_se} {pe}") + rem_nz, rem_pos, phi_pos, same_sgn, adj1, do_adj = (self.tmp() for _ in range(6)) + self.emit(f"{rem_nz} = OpFOrdNotEqual %bool {rem} {d0}") + self.emit(f"{rem_pos} = OpFOrdGreaterThan %bool {rem} {d0}") + self.emit(f"{phi_pos} = OpFOrdGreaterThan %bool {f_plain} {d0}") + self.emit(f"{same_sgn} = OpLogicalEqual %bool {rem_pos} {phi_pos}") + self.emit(f"{adj1} = OpLogicalAnd %bool {in_rng} {is_tie}") + self.emit(f"{do_adj} = OpLogicalAnd %bool {adj1} {rem_nz}") + lo_inc, lo_max, c_inc, hi_inc, lo_dec, c_dec, hi_dec = (self.tmp() for _ in range(7)) + self.emit(f"{lo_inc} = OpIAdd %uint {plo} {self.cu(1)}") + self.emit(f"{lo_max} = OpIEqual %bool {plo} {self.cu(0xFFFFFFFF)}") + self.emit(f"{c_inc} = OpSelect %uint {lo_max} {self.cu(1)} {self.cu(0)}") + self.emit(f"{hi_inc} = OpIAdd %uint {phi} {c_inc}") + self.emit(f"{lo_dec} = OpISub %uint {plo} {self.cu(1)}") + self.emit(f"{c_dec} = OpSelect %uint {lo_z} {self.cu(1)} {self.cu(0)}") + self.emit(f"{hi_dec} = OpISub %uint {phi} {c_dec}") + n_lo, n_hi, adj_lo, adj_hi, adj_v2, p_adj = (self.tmp() for _ in range(6)) + self.emit(f"{n_lo} = OpSelect %uint {same_sgn} {lo_inc} {lo_dec}") + self.emit(f"{n_hi} = OpSelect %uint {same_sgn} {hi_inc} {hi_dec}") + self.emit(f"{adj_lo} = OpSelect %uint {do_adj} {n_lo} {plo}") + self.emit(f"{adj_hi} = OpSelect %uint {do_adj} {n_hi} {phi}") + self.emit(f"{adj_v2} = OpCompositeConstruct %v2uint_d {adj_lo} {adj_hi}") + self.emit(f"{p_adj} = OpBitcast %double {adj_v2}") + f_post, f_dn, sc, r, v2, lo, hi = (self.tmp() for _ in range(7)) + self.emit(f"{f_post} = OpFMul %double {p_adj} {self.dconst(2.0 ** -128)}") + self.emit(f"{f_dn} = OpSelect %double {big} {f_pre} {f_post}") + self.emit(f"{sc} = OpSelect %double {scale_up} {f_up} {f_dn}") self.emit(f"{r} = OpSelect %double {vcc_b} {sc} {f_plain}") r = self.clamp_mods_f64(r, mods) self.emit(f"{v2} = OpBitcast %v2uint_d {r}") @@ -8166,7 +8726,25 @@ class Gen: # NaN -> 0, preserving the unwritten 16-bit half of the destination (op_sel:[src,dst] supported). # For |cl| >= 0.25, cl * (scale + 1) is an exact even integer in f32 so round_even(cl * scale) == # cl * (scale + 1) - RoundEven(cl), avoiding the f32 double-rounding ties near +-0.5. - if any(m == "clamp" or m.startswith(("mul:", "div:")) for m in mods): + # Measured natively on RDNA2 (gfx1036, wave32 & wave64, exhaustive 65,536 f16 sweep): VOP3 + # clamp and mul:2/mul:4/div:2 (and SDWA clamp) are hardware no-ops on these integer-destination + # normalized conversions. Keep rejecting unknown modifiers and invalid form/modifier combinations. + raw_op = ins["op"] + if raw_op.endswith("_sdwa"): + bad_mod = any( + m != "clamp" and m.split(":", 1)[0] not in ("src0_sel", "dst_sel", "dst_unused") + for m in mods + ) + elif raw_op.endswith("_dpp"): + bad_mod = bool(self.non_dpp_mods(raw_op, mods)) + elif raw_op.endswith("_e32"): + bad_mod = bool(mods) + else: + bad_mod = any( + m not in ("clamp", "mul:2", "mul:4", "div:2") and not m.startswith("op_sel:") + for m in mods + ) + if bad_mod: raise Unsupported(op + " output modifier") sel, dhi = self.opsel_bits(mods, 1) snorm = op == "v_cvt_norm_i16_f16" @@ -8346,15 +8924,27 @@ class Gen: attr = next((x for x in a if x["k"] == "attr"), None) if attr is None or self.stage != "ps": raise Unsupported(op + " form") + vsel = "p0" if op == "v_interp_mov_f32": sel = a[1] if len(a) > 1 else None - if not (sel and sel.get("k") == "interp" and sel.get("t") == "p0"): - what = sel.get("t") if sel is not None and sel.get("k") == "interp" else "operand" - raise Unsupported(f"v_interp_mov_f32 vertex select {what}: only p0 is modelled") + vsel = sel.get("t") if sel is not None and sel.get("k") == "interp" else "operand" + if vsel not in ("p0", "p10", "p20"): + raise Unsupported(f"v_interp_mov_f32 vertex select {vsel}") else: self.interp_pair_src(op, a, ins) - f = self.attribute(attr["a"], attr["c"], flat=op == "v_interp_mov_f32", ij=self.interp_weights(ins)) - if self.pixel_interpolants is not None and (self.pixel_interpolants[1] >> attr["a"]) & 1: + half16 = self.pixel_interpolants is not None and (self.pixel_interpolants[1] >> attr["a"]) & 1 + if vsel != "p0": + # P10 = P1 - P0 and P20 = P2 - P0, the deltas the hardware keeps beside P0 for the p1/p2 pair + # (RDNA2 ISA, VINTRP: D = {P10, P20, P0}[S]): one f32 subtraction of the PerVertexKHR words. + if attr["a"] not in self.per_vertex: + raise Unsupported(f"v_interp_mov_f32 vertex select {vsel} without per-vertex inputs") + if half16: + raise Unsupported(f"v_interp_mov_f32 vertex select {vsel} of a 16-bit interpolant") + f = self.attribute(attr["a"], attr["c"], vertex_delta=1 if vsel == "p10" else 2) + else: + f = self.attribute(attr["a"], attr["c"], flat=op == "v_interp_mov_f32", + ij=self.interp_weights(ins)) + if half16 and vsel == "p0": # 16-bit interpolant (FSSM table flag bit 4) read through a 32-bit op: the stored value only # has f16 precision, so round to nearest f16 and back. Reads through the *_f16 opcodes already # narrow to f16 and are unchanged. @@ -8412,19 +9002,71 @@ class Gen: # RDNA2 ISA SOP1: D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0). One invocation holds its own lane's bit # (0 or ~0), so f is the bitwise op on that bit, NOT included: a lane EXEC had off becomes active when f # gives 1 for it (nand, nor, orn2, xnor ...), as on hardware. Definitions as tools/cf_ref.py _SAVEEXEC. + # In wave64, the _b32 form operates strictly on EXEC_LO (lanes 0..31): EXEC_HI (lanes 32..63) is unchanged + # and SCC reflects EXEC_LO != 0 only. + kind = op[2:].split("_saveexec")[0] saved = self.exec_value() - src = self.mask_src(a[1], wide=op.endswith("b64")) - r = self.exec_logic(op[2:].split("_saveexec")[0], src, saved) - self.mask_dst(a[0], saved) - self.set_exec(r) - self.scc_from_mask(r) + half32 = self.wave64 and op.endswith("_b32") + if half32 and self.holds_lane_mask(a[1]) and self.mask_half(a[1]) == "hi": + _, hi_w = self.wave_mask(a[1]) + sh, shr, bit, src = (self.tmp() for _ in range(4)) + self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") + self.emit(f"{shr} = OpShiftRightLogical %uint {hi_w} {sh}") + self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") + self.emit(f"{src} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + else: + src = self.mask_src(a[1], wide=op.endswith("b64")) + r = self.exec_logic(kind, src, saved) + if half32: + if a[0]["k"] == "special" and a[0].get("t") in ("exec_hi", "vcc_hi"): + lo_w, _ = self.wave_mask({"k": "special", "t": "exec"}) + sh, shr, bit, mapped = (self.tmp() for _ in range(4)) + self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") + self.emit(f"{shr} = OpShiftRightLogical %uint {lo_w} {sh}") + self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") + self.emit(f"{mapped} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + self.put_mask(a[0], mapped, "hi") + else: + self.put_mask(a[0], saved, "lo") + self.exec_half_write(0, r) + self.scc_any_half(r, "lo") + else: + self.mask_dst(a[0], saved) + self.set_exec(r) + self.scc_from_mask(r) elif op in ("s_andn2_wrexec_b64", "s_andn2_wrexec_b32", "s_andn1_wrexec_b64", "s_andn1_wrexec_b32"): # RDNA ISA: andn2: EXEC = S0 & ~EXEC; andn1: EXEC = ~S0 & EXEC; then D = EXEC; SCC = (EXEC != 0). - x, y = self.mask_src(a[1], wide=op.endswith("b64")), self.exec_value() - r = self.exec_logic(op[2:].split("_wrexec")[0], x, y) - self.set_exec(r) - self.mask_dst(a[0], r) - self.scc_from_mask(r) + # In wave64, the _b32 form operates strictly on EXEC_LO (lanes 0..31). + kind = op[2:].split("_wrexec")[0] + half32 = self.wave64 and op.endswith("_b32") + if half32 and self.holds_lane_mask(a[1]) and self.mask_half(a[1]) == "hi": + _, hi_w = self.wave_mask(a[1]) + sh, shr, bit, x = (self.tmp() for _ in range(4)) + self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") + self.emit(f"{shr} = OpShiftRightLogical %uint {hi_w} {sh}") + self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") + self.emit(f"{x} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + else: + x = self.mask_src(a[1], wide=op.endswith("b64")) + y = self.exec_value() + r = self.exec_logic(kind, x, y) + if half32: + self.exec_half_write(0, r) + if a[0]["k"] == "special" and a[0].get("t") in ("exec_hi", "vcc_hi"): + lo_w, _ = self.wave_mask({"k": "special", "t": "exec"}) + sh, shr, bit, mapped = (self.tmp() for _ in range(4)) + self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") + self.emit(f"{shr} = OpShiftRightLogical %uint {lo_w} {sh}") + self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") + self.emit(f"{mapped} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + self.put_mask(a[0], mapped, "hi") + else: + self.put_mask(a[0], r, "lo") + self.scc_any_half(r, "lo") + else: + self.set_exec(r) + self.mask_dst(a[0], r) + self.scc_from_mask(r) elif op in ("s_bfe_u64", "s_bfe_i64"): # 64-bit bitfield extract: offset = S1[5:0], width = S1[22:16] (0-127). A width of 0 gives 0; a field # running past bit 63 stops there (LLVM constantFoldBFE: Src0 >> Offset, arithmetic for i64), so the @@ -8766,8 +9408,11 @@ class Gen: # exact product is just below or above it, and RoundEven then picks the even neighbour. The product's # error e = Fma(c, s, -p) is exact, and on such a tie its sign decides: floor(p) + 1 above, floor(p) # below, RoundEven when e is 0. Away from a tie both roundings agree, since k + 0.5 is an f32 here. - if "clamp" in mods: - raise Unsupported(op + " clamp") + # Measured natively on RDNA2 (gfx1036, wave32 & wave64 across 6 HW_REG_MODE configs): VOP3 + # clamp is a hardware no-op on v_cvt_pknorm_{i16,u16}_f32 (each lane is already clamped to + # [-1, 1] / [0, 1] and packed to 16-bit integer). Reject other unexpected modifiers. + if any(m != "clamp" for m in mods): + raise Unsupported(op + " modifiers") snorm = op == "v_cvt_pknorm_i16_f32" halves = [] for src in a[1:3]: @@ -9251,10 +9896,13 @@ class Gen: self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") self.dst(a[0], result) elif op in U2 or op in S2: + to_mask_dst, dst_half = (self._mask_b32_dst_half(a[0], a[1:3]) + if op in self.MASK_SOP2_B32 else (False, None)) if op in S2: x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec") - is_mask = not self.wave64 and (writes_exec or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2])) + is_mask = to_mask_dst or ( + op in self.MASK_SOP2_B32 and (self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2])) + ) if x_val is not None and y_val is not None and not is_mask: folded = None if op == "s_and_b32": @@ -9297,7 +9945,7 @@ class Gen: else: x, y = self.sop2_b32_srcs(op, a) # lane-mask sources as mask_src (s_and/or_b32 on EXEC) self.emit(f"{r} = {kind} %uint {x} {y}") - self.dst(a[0], r) + self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) if op in ("s_and_b32", "s_or_b32"): self.scc_logic(a, r) elif op in ("s_lshl_b32", "s_lshr_b32"): @@ -9522,8 +10170,10 @@ class Gen: stride bytes when the V# stride (dword1[29:16]) is not 0, else NUM_RECORDS bytes (V# dword2). The bound is per dword and does not see base & 3; IMM is unsigned. s_load*: IMM is sign-extended from 21 bits and the sum is formed in 64 bits; no bound. - Not measured, and inferred: s_load with sOFF + IMM < 0 (the 64-bit signed sum is used), x16 (same rule as - x8), an s_buffer_load immediate with bit 20 set or a negative one (kept as the 32-bit value, as before).""" + Measured on gfx1036 (RDNA2): x16 is bounded per dword like x8, NUM_RECORDS * stride is 64-bit (2^32 does not + wrap to 0), NUM_RECORDS >= 2^31 is unsigned, and an s_load with sOFF + IMM < 0 reads at the 64-bit signed sum. + An s_buffer_load immediate with bit 20 set does not follow the bound on hardware and is not modelled (kept as + the 32-bit value, as before).""" n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) d, base = a[0], a[1] # A single dword may also land in vcc_lo / m0 / vcc_hi (seen: s_buffer_load_dword vcc_lo, ...), and a wide @@ -10055,7 +10705,10 @@ class Gen: raise Unsupported(op + " glc " + dim.split("SQ_RSRC_IMG_")[-1]) dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") dmask = int(dm.split(":")[1], 0) - vdata, addr = a[0], self.addr_regs(a[1]) + vdata = a[0] + if vdata["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the result goes + raise Unsupported(op + " destination") + addr = self.addr_regs(a[1]) if op == "image_sample_c_l": # Vulkan Dref returns one scalar. Other component masks require the depth view's swizzle. if (dim != "dim:SQ_RSRC_IMG_2D" or dmask != 1 or len(addr) != (3 if a16 else 4) @@ -10076,8 +10729,9 @@ class Gen: # an f32. Until 2026-11-21 those were unpacked as pairs too, and the coordinates after them were read a # half early. A texel offset comes first and keeps its full dword under a16. extras = op[len("image_sample"):] if op.startswith("image_sample") else "" - w_off = 1 if extras.endswith("_o") else 0 + w_off = 1 if op.endswith("_o") else 0 extras = extras[:-2] if w_off else extras + extras = extras[:-3] if extras.endswith("_cl") else extras # the clamp is packed with the coordinates w_bias = 1 if extras in ("_b", "_c_b") else 0 w_grad = 2 * grad_width if extras in ("_d", "_d_cl") else 0 whole = w_off + w_bias + (1 if extras.startswith("_c") else 0) + w_grad @@ -10133,8 +10787,8 @@ class Gen: goff = None if op in ("image_gather4_lz_o", "image_gather4_l_o"): # first address dword: signed 6-bit texel offsets x [5:0], y [13:8] - if a16: - raise Unsupported(op + " a16") + if a16 and ("tfe" in mods or "lwe" in mods): + raise Unsupported(op + " a16 status") parts = [] for k in range(2): u, i = self.tmp(), self.tmp() @@ -10294,16 +10948,19 @@ class Gen: if not TEXEL_OFFSET_FALLBACK: self.uses_img_offset = True minlod = None - clamp = kind == "_d_cl" # _d plus a min-LOD clamp, read after the gradients + clamp = kind.endswith("_cl") # a min-LOD clamp, read after the coordinates (after the gradients for _d) if clamp: - kind = "_d" + kind = kind[:-3] + if kind not in ("", "_b", "_c", "_c_b", "_d"): + raise Unsupported(op) self.uses_minlod = True - ref = None - if kind.startswith("_c"): - ref, f = f[0], f[1:] + # Address order after the offset: bias, z-compare, gradients, coordinates, LOD, clamp. bias = None if kind in ("_b", "_c_b"): bias, f = f[0], f[1:] + ref = None + if kind.startswith("_c"): + ref, f = f[0], f[1:] grads = None if kind == "_d": # Address order: all dP/dx components, all dP/dy components, then the coordinates. @@ -10357,37 +11014,61 @@ class Gen: dmask, vdata, d16, sample) return res = self.tmp() - if off is not None and kind not in ("", "_lz", "_l", "_b", "_c_lz"): + if off is not None and kind not in ("", "_lz", "_l", "_b", "_c_lz", "_c", "_c_b"): raise Unsupported(op) - implicit = kind in ("", "_b") and self.stage == "ps" + implicit = kind in ("", "_b", "_c", "_c_b") and self.stage == "ps" grads_fb = None if off is not None and TEXEL_OFFSET_FALLBACK: uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit, lod, bias) off = None + # A min-LOD clamp (_cl): MinLod goes with the implicit-LOD forms and Grad. Without derivatives (outside the + # PS) the LOD is 0 and the clamp raises it, so the explicit LOD is max(0, clamp) and no MinLod operand. + lod_zero = "%f0" + if minlod is not None and not implicit and kind != "_d": + lod_zero = self.tmp() + self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax %f0 {minlod}") + def opnd(mask, args): - """Image operands with the texel offset appended (Offset = 0x10 sorts after Lod/Bias).""" - if off is None: - return f" {mask} {args}" if mask else "" - return f" {mask + '|' if mask else ''}Offset {args + ' ' if args else ''}{off}" + """Image operands in SPIR-V mask order: Bias / Lod, Offset (0x10), MinLod (0x80, implicit forms).""" + masks, vals = ([mask], [args]) if mask else ([], []) + if off is not None: + masks.append("Offset") + vals.append(off) + if minlod is not None and mask in ("", "Bias") and implicit: + masks.append("MinLod") + vals.append(minlod) + return f" {'|'.join(masks)} {' '.join(vals)}" if masks else "" if kind == "_d": if minlod is not None: self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad|MinLod {grads[0]} {grads[1]} {minlod}") else: self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad {grads[0]} {grads[1]}") - elif grads_fb is not None: - self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad {grads_fb[0]} {grads_fb[1]}") + elif grads_fb is not None and not kind.startswith("_c"): + self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad{'|MinLod' if minlod else ''} " + f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") elif kind == "": self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('', '')}" if self.stage == "ps" else - f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', '%f0')}") + f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod_zero)}") elif kind in ("_lz", "_l"): self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod)}") elif kind == "_b" and self.stage == "ps": self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('Bias', bias)}") - elif kind in ("_c_lz", "_c_l"): - lod = f[ncoord] if kind == "_c_l" else "%f0" + elif kind in ("_c_lz", "_c_l", "_c", "_c_b"): d = self.tmp() - self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', lod)}") + if kind in ("_c_lz", "_c_l") or (self.stage != "ps" and kind == "_c"): + # _c outside the PS has no derivatives and samples LOD 0, like image_sample + lod = f[ncoord] if kind == "_c_l" else lod_zero + self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', lod)}") + elif self.stage != "ps": + raise Unsupported(op) + elif grads_fb is not None: + self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Grad{'|MinLod' if minlod else ''} " + f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") + elif kind == "_c_b": + self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', bias)}") + else: + self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('', '')}") if d16: # d16: the compare result is an f16 in the low half, as in the other d16 paths below. Until # 2026-11-21 it was written as f32 bits, whose low half is 0 for every result (1.0 = 0x3f800000). @@ -10423,6 +11104,8 @@ class Gen: "image_atomic_or": ("OpAtomicOr", 0), "image_atomic_xor": ("OpAtomicXor", 0), "image_atomic_and": ("OpAtomicAnd", 0xFFFFFFFF), "image_atomic_add": ("OpAtomicIAdd", 0), "image_atomic_sub": ("OpAtomicISub", 0)} + IMG_ATOMICS_EXTRA = ("image_atomic_swap", "image_atomic_inc", "image_atomic_dec", + "image_atomic_fmin", "image_atomic_fmax", "image_atomic_fcmpswap") # image_store views: dim -> (index, SPIR-V Dim, arrayed, coordinate count). Bindings 8 + 3 * index + class, # class 0 = float, 1 = uint, 2 = sint (Vulkan needs the shader's component type to match the image format). @@ -10742,11 +11425,117 @@ class Gen: vals[i] = kept return vals + [lv] + def emit_image_atomic_extra(self, op, ip, iv, vdata, mods): + """Lower 32-bit image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap} on an r32ui storage image (2D or 3D). + Inactive lanes skip the op and preserve vdata. CAS loops use OpAtomicLoad (valid on Image pointers) + + OpAtomicCompareExchange, requiring no shader float atomic extension.""" + need_n = 2 if op == "image_atomic_fcmpswap" else 1 + if vdata["k"] != "vgpr" or vdata.get("n", 1) != need_n: + raise Unsupported(op + " operands") + val = self.load_reg("vgpr", vdata["r"]) + cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_fcmpswap" else None + act = self.active_b() + lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") + self.emit(f"{lbl_do} = OpLabel") + tp = self.tmp() + self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") + sc, sem = self.cu(1), self.cu(0) + if op == "image_atomic_swap": + old = self.tmp() + self.emit(f"{old} = OpAtomicExchange %uint {tp} {sc} {sem} {val}") + if "glc" in mods: + self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) + elif op == "image_atomic_fcmpswap": + # IEEE-754 binary32 ordered equality on raw 32-bit words (denormal-safe on drivers with + # shaderDenormPreserveFloat32 = false): equal iff neither is NaN and (cur == cmpv or both are +-0.0). + abs_cmp, nan_cmp, init = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{abs_cmp} = OpBitwiseAnd %uint {cmpv} {self.cu(0x7FFFFFFF)}") + self.emit(f"{nan_cmp} = OpUGreaterThan %bool {abs_cmp} {self.cu(0x7F800000)}") + self.emit(f"{init} = OpAtomicLoad %uint {tp} {sc} {sem}") + lbl_hdr, lbl_try, lbl_after, lbl_cont, lbl_exit = ( + self.tmp() + s for s in ("_hdr", "_try", "_after", "_cont", "_exit")) + self.emit(f"OpBranch {lbl_hdr}") + self.emit(f"{lbl_hdr} = OpLabel") + cur, got, abs_cur, nan_cur, any_nan, not_nan, same_bits, or_abs, both_zero, eq_val, eq_f = ( + self.tmp() for _ in range(11)) + self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") + self.emit(f"{abs_cur} = OpBitwiseAnd %uint {cur} {self.cu(0x7FFFFFFF)}") + self.emit(f"{nan_cur} = OpUGreaterThan %bool {abs_cur} {self.cu(0x7F800000)}") + self.emit(f"{any_nan} = OpLogicalOr %bool {nan_cur} {nan_cmp}") + self.emit(f"{not_nan} = OpLogicalNot %bool {any_nan}") + self.emit(f"{same_bits} = OpIEqual %bool {cur} {cmpv}") + self.emit(f"{or_abs} = OpBitwiseOr %uint {abs_cur} {abs_cmp}") + self.emit(f"{both_zero} = OpIEqual %bool {or_abs} {self.cu(0)}") + self.emit(f"{eq_val} = OpLogicalOr %bool {same_bits} {both_zero}") + self.emit(f"{eq_f} = OpLogicalAnd %bool {not_nan} {eq_val}") + self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") + self.emit(f"OpBranchConditional {eq_f} {lbl_try} {lbl_exit}") + self.emit(f"{lbl_try} = OpLabel") + self.emit(f"{got} = OpAtomicCompareExchange %uint {tp} {sc} {sem} {sem} {val} {cur}") + done = self.tmp() + self.emit(f"{done} = OpIEqual %bool {got} {cur}") + self.emit(f"OpSelectionMerge {lbl_after} None") + self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_after}") + self.emit(f"{lbl_after} = OpLabel") + self.emit(f"OpBranch {lbl_cont}") + self.emit(f"{lbl_cont} = OpLabel") + self.emit(f"OpBranch {lbl_hdr}") + self.emit(f"{lbl_exit} = OpLabel") + if "glc" in mods: + self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, cur) + else: + val_f = None + if op in ("image_atomic_fmin", "image_atomic_fmax"): + val_f = self.tmp() + self.emit(f"{val_f} = OpBitcast %float {val}") + init = self.tmp() + self.emit(f"{init} = OpAtomicLoad %uint {tp} {sc} {sem}") + lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) + self.emit(f"OpBranch {lbl_hdr}") + self.emit(f"{lbl_hdr} = OpLabel") + cur, got = self.tmp(), self.tmp() + self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") + if op == "image_atomic_inc": + wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") + self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") + self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") + elif op == "image_atomic_dec": + is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) + self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") + self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") + self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") + self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") + self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") + else: + cur_f, new_f, new_u = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{cur_f} = OpBitcast %float {cur}") + glsl_op = "NMin" if op == "image_atomic_fmin" else "NMax" + self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") + self.emit(f"{new_u} = OpBitcast %uint {new_f}") + done = self.tmp() + self.emit(f"{got} = OpAtomicCompareExchange %uint {tp} {sc} {sem} {sem} {new_u} {cur}") + self.emit(f"{done} = OpIEqual %bool {got} {cur}") + self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") + self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") + self.emit(f"{lbl_cont} = OpLabel") + self.emit(f"OpBranch {lbl_hdr}") + self.emit(f"{lbl_exit} = OpLabel") + if "glc" in mods: + self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, cur) + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + def image_misc(self, op, a, mods): """Query sampled image dimensions, load mip texels and handle storage image operations.""" + if a and a[0]["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the data goes + raise Unsupported(op + " data") dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") array_query = op == "image_get_resinfo" and dim == "dim:SQ_RSRC_IMG_2D_ARRAY" - is3d_atomic = dim == "dim:SQ_RSRC_IMG_3D" and (op in self.IMG_ATOMICS or op == "image_atomic_cmpswap") + is_atomic = op in self.IMG_ATOMICS or op == "image_atomic_cmpswap" or op in self.IMG_ATOMICS_EXTRA + is3d_atomic = dim == "dim:SQ_RSRC_IMG_3D" and is_atomic if op == "image_store": self.image_store(a, mods, dim) return @@ -10771,7 +11560,6 @@ class Gen: self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, idx, int(dm.split(":")[1], 0), vdata, xs[3], d16="d16" in mods) return - is_atomic = op in self.IMG_ATOMICS or op == "image_atomic_cmpswap" packed_mip = op == "image_load_mip" and "tfe" not in mods and "lwe" not in mods if ((dim != "dim:SQ_RSRC_IMG_2D" and not (is3d_atomic or array_query)) or ("a16" in mods and not (is_atomic or packed_mip)) @@ -10799,9 +11587,13 @@ class Gen: # 3D r32ui storage image atomics (binding 7). self.uses_storage3d = True coords = atomic_coords(3) - iv, ip, tp, old, safe = (self.tmp() for _ in range(5)) + iv, ip = self.tmp(), self.tmp() self.emit(f"{iv} = OpCompositeConstruct %v3int {coords[0]} {coords[1]} {coords[2]}") self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}") + if op in self.IMG_ATOMICS_EXTRA: + self.emit_image_atomic_extra(op, ip, iv, vdata, mods) + return + tp, old, safe = self.tmp(), self.tmp(), self.tmp() val = self.load_reg("vgpr", vdata["r"]) if op == "image_atomic_cmpswap": cmpv = self.load_reg("vgpr", vdata["r"] + 1) @@ -10827,7 +11619,7 @@ class Gen: if op == "image_store": self.image_store(a, mods, dim) return - if op in self.IMG_ATOMICS or op == "image_atomic_cmpswap": + if is_atomic: # Storage image (2D r32ui). Atomics: vdata holds the operand; with 'glc' the pre-op value comes back. self.uses_storage = True coords = atomic_coords(2) @@ -10835,6 +11627,9 @@ class Gen: self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}") ip = self.tmp() self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg %simages {idx}") + if op in self.IMG_ATOMICS_EXTRA: + self.emit_image_atomic_extra(op, ip, iv, vdata, mods) + return val = self.load_reg("vgpr", vdata["r"]) if op == "image_store": # Writes dmask component 0 as r32ui; only active lanes store. @@ -10956,7 +11751,7 @@ class Gen: self.emit(f"{t} = OpBitcast %float {u}") return t - def attribute(self, n, comp, flat=False, half=None, ij=None): + def attribute(self, n, comp, flat=False, half=None, ij=None, vertex_delta=None): """Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n). An attribute in per_vertex is a PerVertexKHR vec4[3] of the producer's raw 32-bit words. For a packed @@ -10964,6 +11759,7 @@ class Gen: word as an f32; the three values are then weighted as AMD does, P0 + i(P1 - P0) + j(P2 - P0) with i, j = BaryCoordKHR.y, .z, or vertex 0's taken when `flat`. `ij` overrides the weights with the given SPIR-V values (computed-I/J sites, SHADER-177: the pair the program wrote into the operand registers). + `vertex_delta` 1/2 returns P1 - P0 / P2 - P0 instead (v_interp_mov_f32 p10/p20; n must be in per_vertex). --f16-interp-fallback: an f16 read (`half` 0/1) of an attribute in f16_halves is component `comp` of the smooth input at f16_half_location(n, half), which the producer fills with that half decoded to f32 (F16_HALVES). @@ -10999,6 +11795,10 @@ class Gen: pv.append(v) if flat: return pv[0] + if vertex_delta is not None: + d = self.tmp() + self.emit(f"{d} = OpFSub %float {pv[vertex_delta]} {pv[0]}") + return d if ij is not None: i, j = ij else: @@ -11046,7 +11846,7 @@ class Gen: self.emit(f"{q} = OpImageQueryLod %v2float {si} {uvs}") self.emit(f"{qx} = OpCompositeExtract %float {q} 0") level_f = qx - if kind == "_b" and bias is not None: + if kind in ("_b", "_c_b") and bias is not None: qb = self.tmp() self.emit(f"{qb} = OpFAdd %float {qx} {bias}") level_f = qb @@ -11082,7 +11882,7 @@ class Gen: dx, dy = self.tmp(), self.tmp() self.emit(f"{dx} = OpDPdx {vf} {uvs}") self.emit(f"{dy} = OpDPdy {vf} {uvs}") - if kind == "_b" and bias is not None: + if kind in ("_b", "_c_b") and bias is not None: e, ev, sdx, sdy = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{e} = OpExtInst %float %glsl Exp2 {bias}") if spatial == 1: @@ -11270,7 +12070,7 @@ class Gen: org = [f(r) for r in rest[1:4]] dirv = [f(r) for r in rest[4:7]] inv = [f(r) for r in rest[7:10]] - INF, ONE, NEGMAX, POSMAX = (self.tof(self.cu(x)) for x in (0x7F800000, 0x3F800000, 0xFF7FFFFF, 0x7F7FFFFF)) + INF, ONE, NEGINF = (self.tof(self.cu(x)) for x in (0x7F800000, 0x3F800000, 0xFF800000)) out = lambda k, v: self.dst({"k": "vgpr", "r": vd["r"] + k, "n": 1}, v) def fop(o, x, y): @@ -11439,7 +12239,6 @@ class Gen: e(f"OpSelectionMerge {L['end2']} None") e(f"OpBranchConditional {is_box} {L['box']} {L['oth']}") e(f"{L['box']} = OpLabel") - invc = [fext("FClamp", d, NEGMAX, POSMAX) for d in inv] dist, idx = [], [] for i in range(4): child = ldw(i) @@ -11455,20 +12254,31 @@ class Gen: e(f"{x} = OpCompositeExtract %float {v2} {c}") m16.append(x) mm = [sel(is_b16, m16[c], m32[c]) for c in range(6)] - b0 = [fop("OpFMul", fop("OpFSub", mm[c], org[c]), invc[c]) for c in range(3)] - b1 = [fop("OpFMul", fop("OpFSub", mm[3 + c], org[c]), invc[c]) for c in range(3)] - tmin = fext("FMax", fext("FMax", fext("FMin", b0[0], b1[0]), fext("FMin", b0[1], b1[1])), - fext("FMin", b0[2], b1[2])) - tmx = fext("FMin", fext("FMin", fext("FMax", b0[0], b1[0]), fext("FMax", b0[1], b1[1])), - fext("FMax", b0[2], b1[2])) - notnan = T() - e(f"{notnan} = OpFOrdEqual %bool {mm[0]} {mm[0]}") - h1 = bop("OpFOrdGreaterThanEqual", tmx, fext("FMax", "%f0", tmin)) + b0 = [fop("OpFMul", fop("OpFSub", mm[c], org[c]), inv[c]) for c in range(3)] + b1 = [fop("OpFMul", fop("OpFSub", mm[3 + c], org[c]), inv[c]) for c in range(3)] + near, far, nnan, fnan = [], [], [], [] + for c in range(3): + pos = bop("OpFOrdGreaterThanEqual", inv[c], "%f0") + n_, f_ = sel(pos, b0[c], b1[c]), sel(pos, b1[c], b0[c]) + nn, fn = T(), T() + e(f"{nn} = OpIsNan %bool {n_}") + e(f"{fn} = OpIsNan %bool {f_}") + near.append(sel(nn, NEGINF, n_)) + far.append(sel(fn, INF, f_)) + nnan.append(nn) + fnan.append(fn) + tmin = fext("FMax", fext("FMax", near[0], near[1]), near[2]) + tmx = fext("FMin", fext("FMin", far[0], far[1]), far[2]) + nonan = T() + e(f"{nonan} = OpLogicalNot %bool " + f"{orr(andd(andd(nnan[0], nnan[1]), nnan[2]), andd(andd(fnan[0], fnan[1]), fnan[2]))}") + tnear = fext("FMax", "%f0", tmin) + h1 = bop("OpFOrdGreaterThanEqual", tmx, tnear) h2 = bop("OpFOrdLessThan", tmin, tmax) - hb = andd(notnan, andd(h1, h2)) - dist.append(sel(hb, tmin, INF)) + hb = andd(nonan, andd(h1, h2)) + dist.append(sel(hb, tnear, INF)) idx.append(sel(hb, child, self.cu(0xFFFFFFFF), "%uint")) - for p_, q_ in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): + for p_, q_ in ((0, 2), (1, 3), (0, 1), (2, 3), (1, 2)): sw = andd(sort, bop("OpFOrdLessThan", dist[q_], dist[p_])) dist[p_], dist[q_] = sel(sw, dist[q_], dist[p_]), sel(sw, dist[p_], dist[q_]) idx[p_], idx[q_] = sel(sw, idx[q_], idx[p_], "%uint"), sel(sw, idx[p_], idx[q_], "%uint") @@ -11642,7 +12452,7 @@ class Gen: regs = [srcs[0], srcs[2]] if len(srcs) >= 3 else srcs[:1] for x in regs: if x["k"] == "special" and x["t"] == "off": - comps += ["%f0", "%f0"] + comps += [None, None] continue u = self.src_u(x) v2 = self.tmp() @@ -11654,14 +12464,13 @@ class Gen: else: for x in a[1:5]: if x["k"] == "special" and x["t"] == "off": - comps.append("%f0") + comps.append(None) else: comps.append(self.src_f(x)) while len(comps) < 4: - comps.append("%f0") + comps.append(None) comps = comps[:4] v = self.tmp() - self.emit(f"{v} = OpCompositeConstruct %v4float {' '.join(comps)}") name = {"pos0": "%out_pos"}.get(tgt) if name is None: if tgt.startswith("param") and self.stage == "vs": @@ -11676,6 +12485,14 @@ class Gen: # Exports from inactive lanes don't happen: keep the previous output value. old, sel = self.tmp(), self.tmp() self.emit(f"{old} = OpLoad %v4float {name}") + if self.stage == "ps" and tgt.startswith("mrt") and None in comps: + # EN gates each component (each RG/BA pair when compressed). Keep the previous export in off slots. + self.partial_color_outputs.add(name) + for i, comp in enumerate(comps): + if comp is None: + comps[i] = self.tmp() + self.emit(f"{comps[i]} = OpCompositeExtract %float {old} {i}") + self.emit(f"{v} = OpCompositeConstruct %v4float {' '.join(comp or '%f0' for comp in comps)}") self.emit(f"{sel} = OpSelect %v4float {self.active_b()} {v} {old}") self.emit(f"OpStore {name} {sel}") if F16_HALVES and tgt.startswith("param") and self.stage == "vs": @@ -11896,7 +12713,7 @@ def assemble(gen): [("%ms_out_vtx" if ms_blk else "%ms_out_pos"), "%ms_prim_idx", "%ms_cull"] + [f"%ms_out_param{n}" for n in sorted(gen.ms_params)] + [f"%ms_out_f16h{n}_{h}" for n in ms_halves for h in (0, 1)])) if ms else []) + ( - ["%x_buf"] if gen.emulate or gen.bar_rounds else []) + ( + ["%x_buf"] if gen.emulate or gen.bar_rounds and not gen.bar_counts_in_lds() else []) + ( ([("%gs_in_pos" if sv == 1 else f"%gs_in{r}") for r, sv in gen.gs["in"]] + [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + (["%fmt_uint_mask", "%fmt_sint_mask"] if gen.uses_store_views or gen.uses_int_fetch else []) + \ (["%fmt_size_tab"] if gen.uses_fmt_size else []) + \ @@ -12198,7 +13015,10 @@ def assemble(gen): types.append("%v4uint_bal = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 if gen.uses_bvh and not any(t.startswith("%v3float = ") for t in types): types.append("%v3float = OpTypeVector %float 3") - gvars = [f"{n} = OpVariable %_ptr_Output_v4 Output" for n in gen.outputs] + if gen.partial_color_outputs: + types.append("%initial_mrt = OpConstantNull %v4float") + gvars = [f"{n} = OpVariable %_ptr_Output_v4 Output" + (" %initial_mrt" if n in gen.partial_color_outputs else "") + for n in gen.outputs] # Push constants: s0..s31 user data, then the tail: the 64-bit host address of the Xbox GPU VA window (heap # base), the code base and, with --mesh-compute, the output address. --pc-tail-ubo moves the tail to %pc_tail. tail = ["%uint"] * (6 if msc else 4) @@ -12332,8 +13152,9 @@ def assemble(gen): types += [f"%x_arr = OpTypeArray %uint {gen.cu(x_sink + 1)}", "%_ptr_WG_x_arr = OpTypePointer Workgroup %x_arr", "%_ptr_WG_uint_x = OpTypePointer Workgroup %uint"] gvars += ["%x_buf = OpVariable %_ptr_WG_x_arr Workgroup"] - elif gen.bar_rounds: + elif gen.bar_rounds and not gen.bar_counts_in_lds(): # Barrier rounds: one count of the invocations not done per round, 3 slots by round mod 3 (bar_scheduler). + # With a large LDS the count borrows an LDS word instead (SHADER-579, bar_counts_in_lds). types += [f"%x_arr = OpTypeArray %uint {gen.cu(3)}", "%_ptr_WG_x_arr = OpTypePointer Workgroup %x_arr", "%_ptr_WG_uint_x = OpTypePointer Workgroup %uint"] gvars += ["%x_buf = OpVariable %_ptr_WG_x_arr Workgroup"] @@ -12430,7 +13251,8 @@ def assemble(gen): "%vcc_hi = OpVariable %_ptr_Function_uint Function %c0", "%scc = OpVariable %_ptr_Function_uint Function %c0", *(["%mode_r16 = OpVariable %_ptr_Function_uint Function %c0"] if gen.round_mode else []), - "%active = OpVariable %_ptr_Function_bool Function %true"] + "%active = OpVariable %_ptr_Function_bool Function %true", + *[f"{var} = OpVariable {ptr} Function" for var, ptr in gen.eager_vars]] if gen.vm_latch: fn += ["%vm_mask = OpVariable %_ptr_Function_bool Function %true", "%vm_set = OpVariable %_ptr_Function_bool Function %false"] @@ -12446,6 +13268,8 @@ def assemble(gen): elif gen.bar_rounds: fn += ["%x_it = OpVariable %_ptr_Function_uint Function %c0", "%x_bar = OpVariable %_ptr_Function_bool Function %false"] + if gen.bar_counts_in_lds(): + fn.append("%xb_save = OpVariable %_ptr_Function_uint Function %c0") fn += [f"{var} = OpVariable {ptr} Function" for var, ptr in gen.x_spills] # User data: s0..s31 are loaded at entry from a push-constant block (the driver's user-SGPR setup). if gen.uses_heap: @@ -12760,7 +13584,15 @@ def assemble(gen): "%mix = OpCompositeConstruct %v3uint %mi0 %mi1 %mi2", "%mixp = OpAccessChain %_ptr_Out_v3u_ms %ms_prim_idx %mli", "OpStore %mixp %mix", f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}", "%mnull = OpINotEqual %bool %mnb %c0", - f"%mcp = OpAccessChain %_ptr_Out_bool_ms %ms_cull %mli {c(0)}", "OpStore %mcp %mnull", + f"%mcp = OpAccessChain %_ptr_Out_bool_ms %ms_cull %mli {c(0)}", + # CullPrimitiveEXT gets a constant on each side of a branch, not the computed bool: llvmpipe + # (Mesa 25.2.8, LLVM 20) aborts compiling a computed per-primitive bool store in the wave64-emulated + # mesh epilogue ("Cannot emit physreg copy instruction"), and Mesa 26.3.1 drew no primitives for the + # same shaders (SHADER-575). Same result on every driver. + "OpSelectionMerge %ms_cend None", "OpBranchConditional %mnull %ms_cull1 %ms_cull0", + "%ms_cull1 = OpLabel", "OpStore %mcp %true", "OpBranch %ms_cend", + "%ms_cull0 = OpLabel", "OpStore %mcp %false", "OpBranch %ms_cend", + "%ms_cend = OpLabel", "OpBranch %ms_pend", "%ms_pend = OpLabel"] end_lock = "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L) + end_lock if gen.uses_active and gen.stage == "ps": @@ -12893,7 +13725,11 @@ def halves_analysis(g, blocks, succ): g.w64g = wave64_halves.analyse(blocks, succ, g.lane_masks, g.stage) except Exception as e: # the analysis must never cost a translation; what it could not decide is tier C g.w64g = {"tier": "C", "reasons": ["analysis-error"], "idioms": [], "uniform_readlane": set(), - "sites": [("analysis-error", None, type(e).__name__)]} + "scalar_spills": [], "sites": [("analysis-error", None, type(e).__name__)]} + for slot in g.w64g.get("scalar_spills", ()): + if slot not in g.parked: + g.parked[slot] = g.SGPRS + len(g.parked) + g.w64_scalar_spills.add(slot) W64G_COUNTS[g.w64g["tier"]] += 1 if g.w64g["tier"] == "C" and WAVE64_GRAPHICS == "error": raise Unsupported("wave64 graphics tier C: " + ", ".join(g.w64g["reasons"])) @@ -12907,7 +13743,7 @@ def fold_far_branches(insns): while i < len(insns): w = insns[i:i + 4] ops4 = [base_op(x["op"]) for x in w] - if len(w) == 4 and ops4 in (["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"], + if len(w) == 4 and all(x.get("enc") for x in w) and ops4 in (["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"], ["s_getpc_b64", "s_sub_u32", "s_subb_u32", "s_setpc_b64"]): g, ad, ac, sp = w r = g["args"][0].get("r") if g["args"] and g["args"][0]["k"] == "sgpr" else None @@ -13024,8 +13860,9 @@ def read_before_write_vgprs(insns): regs += range(x["r"], x["r"] + x.get("n", 1)) elif x["k"] == "vlist": regs += x["r"] - if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", - "v_dot2c_i32_i16", "v_dot8c_i32_i4", "v_pk_fmac_f16") or + if (base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", + "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", + "v_dot8c_i32_i4", "v_dot8c_u32_u4") or (op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half regs.append(a[0]["r"]) for r in regs: @@ -13257,8 +14094,9 @@ def reg_reads_writes(insns): regs += range(x["r"], x["r"] + x.get("n", 1)) elif x["k"] == "vlist": regs += x["r"] - if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", - "v_dot2c_i32_i16", "v_dot8c_i32_i4", "v_pk_fmac_f16") and a[0]["k"] == "vgpr": + if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", + "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", + "v_dot8c_i32_i4", "v_dot8c_u32_u4") and a[0]["k"] == "vgpr": regs.append(a[0]["r"]) rr.update(regs) if not reads_all and a[0]["k"] == "vgpr": @@ -13624,7 +14462,12 @@ def translate(path): else: g.wave64 = code_w64 or stage == "ms" # NGG mesh shaders here are wave64 (thread = wave id * 64 + lane) if stage == "gs": - ins_sig = [(reg, sv) for reg, mask, sv, ctype in input_signature(path, info["name"])] + ins_by_reg = {} + for reg, mask, sv, ctype in input_signature(path, info["name"]): + if reg in ins_by_reg and (ins_by_reg[reg] == 1) != (sv == 1): + raise Unsupported("gs signature") + ins_by_reg.setdefault(reg, sv) + ins_sig = sorted(ins_by_reg.items()) outs = output_signature(path, info["name"]) if not ins_sig or not outs: raise Unsupported("gs signature") @@ -13660,10 +14503,8 @@ def translate(path): k, _, v = m.partition(":") if not v[:1].isdigit(): continue - if k == "offset": - need = max(need, int(v, 0) // 4 + 4) - elif k in ("offset0", "offset1"): - need = max(need, int(v, 0) * (64 if "st64" in ins["op"] else 1) * 2 + 4) + if k in ("offset", "offset0", "offset1"): + need = max(need, ds_const_extent(ins["op"], k, int(v, 0))) n = 16 while n < need: n *= 2 @@ -13765,11 +14606,14 @@ def translate(path): mixed_f32 = attr_reads["v_interp_mov_f32"] & (attr_reads["v_interp_p1_f32"] | attr_reads["v_interp_p2_f32"]) if mixed_f32 and (BARY_FALLBACK or F16_HALVES): raise Unsupported("flat and interpolated reads of one f32 attribute need per-vertex inputs") + mov_delta = {x["a"] for i in insns if base_op(i["op"]) == "v_interp_mov_f32" + and any(x.get("k") == "interp" and x.get("t") in ("p10", "p20") for x in i["args"]) + for x in i["args"] if x["k"] == "attr"} if F16_HALVES: # decoded halves from the producer: no per-vertex inputs (and no barycentrics) g.f16_halves = f16_read elif not BARY_FALLBACK: # A smooth input alone cannot supply P0 for a MOV reading the same location. - g.per_vertex = f16_read | mixed_f32 + g.per_vertex = f16_read | mixed_f32 | mov_delta for r in layout: g.cu(r) # FSSM pixel-input table (tools/fssm_header.py): the authoritative interpolant list. Position i of the @@ -13856,7 +14700,11 @@ def translate(path): break g.insn(ins) translate.last_gen = g - return assemble(g) + out = assemble(g) + if OPT_SPIRV: + import spirv_opt + out = spirv_opt.optimize(out) + return out # ---- basic blocks ---- def next_pc(ins): @@ -14174,7 +15022,11 @@ def translate(path): assert succ == g.succ, "the lane-mask analysis ran on a different graph" g.body = [] translate.last_gen = g - return assemble(g) + out = assemble(g) + if OPT_SPIRV: + import spirv_opt + out = spirv_opt.optimize(out) + return out _DEF = re.compile(r"(%\w+) = (Op\w+)(?: (%\w+))?") @@ -14463,28 +15315,31 @@ def bar_scheduler(gen): %x_buf holds 3 counts, by round mod 3: round r adds to its own slot before the barrier and reads it after, and invocation 0 clears the slot of round r + 1, last read in round r - 2 (before the barrier of r - 1). + With a large LDS (bar_counts_in_lds, SHADER-579) there is no %x_buf: the count borrows LDS word 0 between + rounds, when no invocation runs shader code (see bar_scheduler_tail), and starts cleared in every round. The first two lines are the Function variables %pc and %done, as for the dispatch loop.""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 sx, sy, _ = gen.cs["size"] + in_lds = gen.bar_counts_in_lds() return ["%pc = OpVariable %_ptr_Function_uint Function %c0", "%done = OpVariable %_ptr_Function_bool Function %false", "%xb_lid = OpLoad %v3uint %local_id", "%xb_lx = OpCompositeExtract %uint %xb_lid 0", "%xb_ly = OpCompositeExtract %uint %xb_lid 1", "%xb_lz = OpCompositeExtract %uint %xb_lid 2", f"%xb_ly2 = OpIMul %uint %xb_ly {c(sx)}", f"%xb_lz2 = OpIMul %uint %xb_lz {c(sx * sy)}", "%xb_lxy = OpIAdd %uint %xb_lx %xb_ly2", "%xb_li = OpIAdd %uint %xb_lxy %xb_lz2", - f"%xb_first = OpIEqual %bool %xb_li {c(0)}", + f"%xb_first = OpIEqual %bool %xb_li {c(0)}"] + ([] if in_lds else [ # Workgroup memory starts undefined: invocation 0 clears round 0's count before the first round. "OpSelectionMerge %xb_z_end None", "OpBranchConditional %xb_first %xb_z %xb_z_end", "%xb_z = OpLabel", f"%xb_zp = OpAccessChain %_ptr_WG_uint_x %x_buf {c(0)}", f"OpStore %xb_zp {c(0)}", "OpBranch %xb_z_end", "%xb_z_end = OpLabel", - f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}", + f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}"]) + [ "OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", - "OpBranch %xb_round", "%xb_round = OpLabel", - "%xb_itv = OpLoad %uint %x_it", f"%xb_s = OpUMod %uint %xb_itv {c(3)}", + "OpBranch %xb_round", "%xb_round = OpLabel", "%xb_itv = OpLoad %uint %x_it"] + ([] if in_lds else [ + f"%xb_s = OpUMod %uint %xb_itv {c(3)}", f"%xb_n1 = OpIAdd %uint %xb_itv {c(1)}", f"%xb_sn = OpUMod %uint %xb_n1 {c(3)}", "OpSelectionMerge %xb_r_end None", "OpBranchConditional %xb_first %xb_r %xb_r_end", "%xb_r = OpLabel", "%xb_rp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_sn", f"OpStore %xb_rp {c(0)}", - "OpBranch %xb_r_end", "%xb_r_end = OpLabel", + "OpBranch %xb_r_end", "%xb_r_end = OpLabel"]) + [ "%xb_d = OpLoad %bool %done", "OpSelectionMerge %xb_ran None", "OpBranchConditional %xb_d %xb_ran %xb_run", "%xb_run = OpLabel", # The invocation's blocks, until an s_barrier (%x_bar) or the end (%done). @@ -14496,13 +15351,46 @@ def bar_scheduler(gen): def bar_scheduler_tail(gen): - """Barrier rounds: the end of a round, after the switch (see bar_scheduler).""" + """Barrier rounds: the end of a round, after the switch (see bar_scheduler). + + SHADER-579, the count in LDS (bar_counts_in_lds): after s_barrier's own barrier (A) every invocation is done or + waits, so no shader code touches LDS until the next round. Invocation 0 saves LDS word 0 in a Function variable + and clears it; barrier B; every invocation not done adds 1; barrier C; all read the count; barrier D; + invocation 0 puts the saved word back; barrier E, before the next round's code. The shader sees its LDS + unchanged, and B to E only add workgroup barriers at a point where the whole workgroup already waits.""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - return ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", + bar = f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}" + head = ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", "%sw_merge = OpLabel", "OpBranch %xb_in_cont", "%xb_in_cont = OpLabel", "%xb_d1 = OpLoad %bool %done", "%xb_b1 = OpLoad %bool %x_bar", "%xb_stop = OpLogicalOr %bool %xb_d1 %xb_b1", - "OpBranchConditional %xb_stop %xb_in_merge %xb_in_head", "%xb_in_merge = OpLabel", + "OpBranchConditional %xb_stop %xb_in_merge %xb_in_head", "%xb_in_merge = OpLabel"] + if gen.bar_counts_in_lds(): + return head + [ + "OpBranch %xb_ran", "%xb_ran = OpLabel", + bar, # A: s_barrier's own barrier + f"%xb_wp = OpAccessChain %_ptr_WG_uint %lds {c(0)}", + "OpSelectionMerge %xb_sv_end None", "OpBranchConditional %xb_first %xb_sv %xb_sv_end", + "%xb_sv = OpLabel", "%xb_old = OpLoad %uint %xb_wp", "OpStore %xb_save %xb_old", + f"OpStore %xb_wp {c(0)}", "OpBranch %xb_sv_end", "%xb_sv_end = OpLabel", + bar, # B: the word is cleared + "%xb_d2 = OpLoad %bool %done", + "OpSelectionMerge %xb_c_end None", "OpBranchConditional %xb_d2 %xb_c_end %xb_c", "%xb_c = OpLabel", + f"%xb_ca = OpAtomicIAdd %uint %xb_wp {c(2)} {c(0)} {c(1)}", + "OpBranch %xb_c_end", "%xb_c_end = OpLabel", + bar, # C: every count is in + "%xb_left = OpLoad %uint %xb_wp", + bar, # D: every invocation has read it + "OpSelectionMerge %xb_rs_end None", "OpBranchConditional %xb_first %xb_rs %xb_rs_end", + "%xb_rs = OpLabel", "%xb_old2 = OpLoad %uint %xb_save", "OpStore %xb_wp %xb_old2", + "OpBranch %xb_rs_end", "%xb_rs_end = OpLabel", + "OpBranch %loop_cont", "%loop_cont = OpLabel", + bar, # E: the shader's word is back + "OpStore %x_bar %false", + f"%xb_it1 = OpIAdd %uint %xb_itv {c(1)}", "OpStore %x_it %xb_it1", + f"%xb_fin = OpIEqual %bool %xb_left {c(0)}", "OpBranchConditional %xb_fin %loop_exit %loop_head", + "%loop_exit = OpLabel"] + return head + [ # Not done: count this invocation in the round's slot. "%xb_d2 = OpLoad %bool %done", "OpSelectionMerge %xb_c_end None", "OpBranchConditional %xb_d2 %xb_c_end %xb_c", "%xb_c = OpLabel", @@ -14852,6 +15740,10 @@ def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as"): """ with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f: tmp = Path(f.name) + # spirv-as reads the .spvasm from stdin, and both tools run in the output folder with the staging file's bare + # name. On Windows they read their command line in the ANSI code page, so a folder name outside it (a Cyrillic or + # CJK user name, say) reached them as '?' and every shader failed with "file does not exist". + folder = os.path.dirname(os.path.abspath(tmp)) try: if assembler == "python": import spirv_asm @@ -14862,12 +15754,23 @@ def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as"): except (OSError, spirv_asm.SpirvAsmError) as exc: result = subprocess.CompletedProcess(["spirv_asm"], 1, "", str(exc)) else: - result = subprocess.run(["spirv-as", sa, "-o", str(tmp), "--target-env", "vulkan1.2"], - capture_output=True, text=True) + try: + with open(sa, "rb") as f: + source = f.read() + except OSError as exc: + result = subprocess.CompletedProcess(["spirv-as"], 1, "", f"error: cannot read {sa}: {exc}") + else: + result = subprocess.run(["spirv-as", "-", "-o", tmp.name, "--target-env", "vulkan1.2"], + input=source, capture_output=True, cwd=folder) + # stdin is bytes, so the output is too; a test double may already answer in text. + if isinstance(result.stdout, bytes): + result.stdout = result.stdout.decode("utf-8", "replace") + if isinstance(result.stderr, bytes): + result.stderr = result.stderr.decode("utf-8", "replace") if result.returncode == 0: # Offset on non-gather: VK_KHR_maintenance8 result = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", - str(tmp)], capture_output=True, text=True) + tmp.name], capture_output=True, text=True, cwd=folder) if result.returncode == 0: tmp.replace(sv) else: @@ -14899,6 +15802,20 @@ def _shard_arg(text): return si, sn +def _out_inside_input(src, out): + """True when --out is the input folder or a folder inside it: translating there writes among the inputs. + + `src` is a .s file or the folder of them; a single file's folder is its input folder. `same_report_path` + covers the same spelling, `..`, links and (on Windows) case; `path_key` folds a case-insensitive macOS + volume for the containment test. Standard library only. + """ + folder = src if os.path.isdir(src) else os.path.dirname(os.path.abspath(src)) + if same_report_path(folder, out): + return True + root, target = path_key(folder), path_key(out) + return target.startswith(root.rstrip(os.sep) + os.sep) + + def main(): global MAX_SHARED_BYTES ap = argparse.ArgumentParser() @@ -14940,11 +15857,13 @@ def main(): help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " "VK_EXT_mesh_shader (e.g. NVIDIA Pascal)") - ap.add_argument("--fma", choices=("glsl", "khr"), default="glsl", + ap.add_argument("--fma", choices=("glsl", "khr", "exact"), default="glsl", help="how fused multiply-adds (v_fma_f32, v_fmac_f32, v_fmaak/fmamk_f32, v_fma_mix*) are emitted: " "glsl = GLSL.std.450 Fma (default; the Vulkan spec lets a driver round twice), khr = OpFmaKHR " "(guaranteed single rounding; needs VK_KHR_shader_fma + shaderFmaFloat32, listed in the " - "shader's metadata as capability FMAKHR / feature shaderFmaFloat32)") + "shader's metadata as capability FMAKHR / feature shaderFmaFloat32), exact = a single " + "rounding built from NoContraction f32 ops, for a device that splits Fma and has no " + "VK_KHR_shader_fma (about 110 instructions, 31 NoContraction decorations and 13 constants per multiply-add; no extension needed)") ap.add_argument("--f16-interp-fallback", action="store_true", help="16-bit interpolation without PerVertexKHR inputs, for devices that can't compile them " "(MoltenVK): VS and mesh params also export their f16 halves decoded to f32, which the PS " @@ -14958,6 +15877,9 @@ def main(): help="keep only s0..s31 (128 bytes) in push constants and read the heap base, code base and " "--mesh-compute output address from a uniform block at set 1, binding 0 (metadata: pc_tail), " "for devices whose maxPushConstantsSize is below 144") + ap.add_argument("--opt", action="store_true", + help="run basic-block SPIR-V peephole optimization (tools/spirv_opt.py: register store-to-load " + "forwarding, OpAccessChain CSE, dead-store elimination, OpSelect/CopyObject folding, DCE)") a = ap.parse_args() # A file at --out (or one above it) can never become a folder. Refuse it here, before # --merge publishes an index or os.makedirs raises a traceback. Same check as #1607's @@ -14975,10 +15897,12 @@ def main(): if ancestor and not os.path.isdir(ancestor): ap.error(f"cannot create {a.out}: {ancestor} is a file, not a folder") MAX_SHARED_BYTES = a.max_shared_memory - global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, F16_HALVES + global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, F16_HALVES, OPT_SPIRV global PC_TAIL_UBO PC_TAIL_UBO = a.pc_tail_ubo + global FMA_EXACT FMA_KHR = a.fma == "khr" + FMA_EXACT = a.fma == "exact" STRUCTURED = not a.dispatch_loop global FLOAT_CONTROLS FLOAT_CONTROLS = not a.no_float_controls @@ -14988,11 +15912,21 @@ def main(): TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback MESH_COMPUTE = a.mesh_compute F16_HALVES = a.f16_interp_fallback + OPT_SPIRV = a.opt if a.merge: try: merged = merge_shard_parts(a.out) except ShardSetError as e: print(f"ERROR: {e}", file=sys.stderr) + # The parts no longer describe the old index: leaving it would let the next run take the failed merge + # as a finished translation. It is regenerated by the next successful --merge. + index = os.path.join(a.out, "index.json") + try: + os.remove(index) + except FileNotFoundError: + pass + except OSError as remove_error: + print(f"WARNING: cannot remove the stale {index}: {remove_error}", file=sys.stderr) return 2 # The stubs go first: index.json is what tells make_game.py the translation finished. import spirv_stubs @@ -15013,6 +15947,13 @@ def main(): si, sn = a.shard files = files[si::sn] shard = si + # Writing translations into the input folder mixes them with the .s inputs (and a rerun then scans its + # own output); refuse it before mkdir, the index or any module is written. --merge above is exempt: its + # src is not read, and merging parts in place is how a shard run finishes. + if _out_inside_input(a.src, a.out): + print(f"ERROR: --out {a.out} is the input folder or inside it; choose a separate output folder", + file=sys.stderr) + return 2 try: os.makedirs(a.out, exist_ok=True) except OSError as e: # a trailing separator on a file, or a symlink changed since the check above @@ -15047,7 +15988,16 @@ def main(): if write_asm: with open(sa, "w", encoding="utf-8", newline="\n") as f: f.write(asm) - r = assemble_spirv(sa, sv, asm_text=asm, assembler=a.assembler) + try: + r = assemble_spirv(sa, sv, asm_text=asm, assembler=a.assembler) + except OSError as e: + # A missing spirv-as/spirv-val fails every shader the same way; report it once as a setup + # error (exit 2) instead of a FileNotFoundError traceback from the first one. + if e.filename not in ("spirv-as", "spirv-val"): + raise + print(f"ERROR: {e.filename} not found; install SPIRV-Tools (spirv-as, spirv-val) " + "and put it on PATH", file=sys.stderr) + return 2 if r.returncode == 0: valid += 1 try: diff --git a/tools/restofworld_model_join.py b/tools/restofworld_model_join.py index 96e744eb9..c8dc98414 100644 --- a/tools/restofworld_model_join.py +++ b/tools/restofworld_model_join.py @@ -605,7 +605,7 @@ def inspect_model_resource(sys_bytes, gfx_bytes, gfx_page_sizes): } -def _inflate_exact(buf, offset, end, max_inflate): +def _inflate_exact(buf, offset, end, max_inflate, *, min_inflate=64): """Inflate one zlib stream at `offset` inside `buf[offset:end]`.""" d = zlib.decompressobj() p = offset @@ -629,7 +629,7 @@ def _inflate_exact(buf, offset, end, max_inflate): break except zlib.error: return None, 0, False - if not d.eof or total < 64: + if not d.eof or total < min_inflate: return None, 0, False used = p - offset - len(d.unused_data) if used <= 0: @@ -930,6 +930,7 @@ def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): raise ValueError("start offset is outside the archive") end = min(file_size, pos + limit) if limit is not None else file_size last = pos + system_pages_remaining = 0 while pos < end: found = ZHDR.search(m, pos, end) if not found: @@ -961,16 +962,21 @@ def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): "head_tag": "bink2", }) last = pos = s + blen + system_pages_remaining = 0 continue - data, used, too_big = _inflate_exact(m, s, end, max_inflate) + continued_system = (system_pages_remaining > 0 and s == ((last + 15) & ~15) + and not any(m[last:s])) + # A declared final system page can be smaller than the minimum for a scanned stream. + data, used, too_big = _inflate_exact( + m, s, end, max_inflate, min_inflate=1 if continued_system and system_pages_remaining == 1 else 64) if data is None: if too_big: skipped += 1 pos = s + 1 continue gap = m[last:s] - streams.append({ + meta = { "stream_index": len(streams), "offset": s, "stored": used, @@ -984,7 +990,18 @@ def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): "is_0drp": len(data) >= 0x14 and data[0x10:0x14] == b"0DRP", "u64_at_8": struct.unpack_from("= 16 else 0, "head_tag": classify_graphics_head(data), - }) + } + streams.append(meta) + if continued_system: + system_pages_remaining = system_pages_remaining - 1 if len(data) % 65536 == 0 else 0 + else: + system_pages_remaining = 0 + if (meta["align4k_plus16"] and meta["pre16_zero"] and len(data) % 65536 == 0 + and classify_system_root(data) in ("drawable", "drawable_dict", "fragment")): + try: + system_pages_remaining = parse_page_map(data)["system_pages"] - 1 + except JoinError: + pass # The full join checks page maps that extend into another system page. last = pos = s + used cache = {} @@ -994,7 +1011,8 @@ def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): if len(cache) >= 64: cache.clear() meta = streams[s_idx] - payload, _, _ = _inflate_exact(m, meta["offset"], meta["offset"] + meta["stored"], max_inflate) + payload, _, _ = _inflate_exact(m, meta["offset"], meta["offset"] + meta["stored"], max_inflate, + min_inflate=meta["size"]) cache[s_idx] = payload return cache[s_idx] diff --git a/tools/rootsig_census.py b/tools/rootsig_census.py index 53363a1d7..40d0203a9 100644 --- a/tools/rootsig_census.py +++ b/tools/rootsig_census.py @@ -236,8 +236,12 @@ def census(root, disasm=None): state_path = os.path.join(root, "fspx", name + ".json") user_sgprs = None if os.path.exists(state_path): - with open(state_path, encoding="utf-8") as fh: - user_sgprs = json.load(fh).get("user_sgprs") + try: + with open(state_path, encoding="utf-8") as fh: + user_sgprs = json.load(fh).get("user_sgprs") + except (ValueError, AttributeError) as e: + errors.append(f"{state_path}: {e}") + continue if b"RTS0" not in chunks: rows.append({"name": name, "error": "no RTS0 part", "user_sgprs": user_sgprs}) continue diff --git a/tools/rsc8_audio.py b/tools/rsc8_audio.py index 0fa66bbba..388464bd4 100644 --- a/tools/rsc8_audio.py +++ b/tools/rsc8_audio.py @@ -21,7 +21,10 @@ counts, hashes, string storage/lengths, frame counts, durations and track types Usage: python -I tools/rsc8_audio.py [out.json|out.csv] - [--start N] [--limit BYTES] [--max-banks N] [--no-deep] [--summary-only] [--quiet] + [--start N] [--limit BYTES] [--max-banks N] [--no-deep] [--curves] [--summary-only] [--quiet] + +`--curves` also decodes every clip's keyframes (the blocks are the sequence layout of +tools/anim_clips.py) and counts the outcome; it reports counts only, never a value. """ import argparse import csv @@ -34,6 +37,8 @@ import tempfile import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import anim_clips # noqa: E402 from file_mode import published_mode # noqa: E402 RSC8_MAGIC = b"RSC8" @@ -44,7 +49,7 @@ RSC8_FLAGS = 1 RSC8_VIRTUAL_BASE = 0x10 RSC8_VPTR_BASE = 0x50000000 RSC8_VPTR_LIMIT = 0x60000000 -TRACK_SCHEMA_HASH = 0x364D3BDB +TRACK_SCHEMA_HASH = 0x364D3BDB # joaat("facialtranslation"): the track type of every directory entry ADAT_MAGIC = b"ADAT" TAG_PEAK = 0x36 @@ -340,7 +345,62 @@ def _has_embedded_audio_container(data): return False -def decode_rsc8(data, *, stream_id=None, deep=True): +def decode_facial_curves(virt, anim, anim_desc, stats=None): + """Decode the keyframes of one clip: `({track index: [value tuple per frame]}, frames, tracks)`. + + `virt` is the resource from `RSC8_VIRTUAL_BASE` on; `anim` and `anim_desc` come from `decode_rsc8`. + A packed block is one sequence of tools/anim_clips.py (0x20-byte header, version 2, 11 channel + types) and the track directory is its 12-byte `{id hash, track-type hash, value format}` list, so + the block and track decoders are that tool's. `tracks` is the directory as stored. Raises + `anim_clips.DecodeError` when a block does not decode. + """ + system = anim_clips.System(bytes(virt)) + at, count = anim_desc["track_ptr"] or 0, anim_desc["track_count"] or 0 + if count and at + 12 * count > len(system.d): + raise anim_clips.DecodeError("track directory runs past the resource") + tracks = [struct.unpack_from(":"` per track, and whether the frame count and the header's + quantised-bit sum agree with the decoded data. + """ + stats = anim_clips.new_stats() + try: + values, frames, tracks = decode_facial_curves(virt, anim, anim_desc, stats) + except anim_clips.DecodeError as e: + return {"decoded": False, "error": str(e)[:80]} + components = {} + for index, rows in values.items(): + key = f"{tracks[index][2]}:{len(rows[0]) if rows else 0}" + components[key] = components.get(key, 0) + 1 + blocks = len(anim["blocks"]) + return { + "decoded": True, + "error": None, + "frames": frames, + "frames_match": frames == anim["frame_count"] and stats["frames_sum_matches"] == 1, + "quantize_bits_match": stats["quantize_bits_match"] == blocks, + "tracks_with_values": len(values), + "channels": {k[len("channel:"):]: v for k, v in sorted(stats.items()) if k.startswith("channel:")}, + "delta2_boundaries": stats["delta2_boundaries"], + "delta2_boundaries_closed": stats["delta2_boundaries_closed"], + "components": components, + } + + +def decode_rsc8(data, *, stream_id=None, deep=True, curves=False): """Decode one `RSC8` (version 8001) facial/lip-sync animation resource. Accepts `bytes`, `bytearray`, or `memoryview`. Returns a structured dict of decoded fields @@ -400,6 +460,7 @@ def decode_rsc8(data, *, stream_id=None, deep=True): "anim_desc": None, "properties": None, "tracks": None, + "curves": None, "checks": checks, "valid": False, } @@ -661,6 +722,14 @@ def decode_rsc8(data, *, stream_id=None, deep=True): "tracks_in_bounds", "no_embedded_audio_container", ] + if ( + curves + and out["anim"] + and out["anim_desc"] + and checks["anim_blocks_in_bounds"] + and checks["tracks_in_bounds"] + ): + out["curves"] = facial_curve_summary(virt, out["anim"], out["anim_desc"]) if deep: core_checks.extend(("clip_duration_matches_frames", "tracks_sorted", "tracks_schema_ok")) else: @@ -777,30 +846,29 @@ MAX_INDEXRUN_GROUPS = 1 << 20 def decode_grid20_table(blob): """Structurally decode the undocumented ``0x5a`` companion table. - Measured on every one of the 1,185 ``audio.rpf`` streams that carry the tag: a u32 - ``12345678`` marker, a u32 of unknown meaning, then ``N`` 20-byte entries:: + Measured on every one of the 1,185 ``audio.rpf`` streams that carry the tag (ASSET-256, framing + from @kotorvr's finding in #3232): a u32 ``12345678`` marker, ``N`` 20-byte entries, then an f32 + trailer, so ``size == 8 + 20 * N``:: - +0 f32 value - +4 u16 p (a multiple of 32 on every measured entry) - +6 u16 z (0..16 measured) - +8 u16 index_lo, +10 u16 index_hi - +12 u16 s, +14 u16 t - +16 u32 counter: a sample position, strictly increasing and below the stream's 0x76 sample - count, on every entry but the last; the last entry holds an f32 there (2/3 on 1,182 - of the 1,185 streams), returned as ``tail_f32`` (ASSET-256) + +0 u32 position (a sample position at the stream's rate: strictly increasing, below the + stream's 0x76 sample count) + +4 f32 value (3.66..146.8; (position[k+1] - position[k]) * value[k] / rate is within 1% of 1 + on 365,803 of the 386,048 entry pairs, so it reads as a pitch in Hz) + +8 u16 p (a multiple of 512 on every measured entry), +10 u16 z (0..16 measured) + +12 u16 index_lo, +14 u16 index_hi + +16 u16 s, +18 u16 t + trailer: f32 (2/3 on 1,182 of the 1,185 streams), returned as ``tail_f32`` - Nothing is guessed about the meaning of ``value``, ``s``, ``t`` or the tail float; the return - value carries the structural facts and the invariant checks only. ``counter_first``, - ``counter_last`` and ``counter_increasing`` cover the counters, so the last entry is left out. + Nothing is guessed about ``p``, ``z``, ``s``, ``t`` or the trailer; the return value carries the + structural facts and the invariant checks only. """ out = { "size_ok": False, "magic_ok": None, - "unknown": None, "entries": None, - "counter_first": None, - "counter_last": None, - "counter_increasing": None, + "position_first": None, + "position_last": None, + "position_increasing": None, "tail_f32": None, "p_multiple_of_32": None, } @@ -808,32 +876,27 @@ def decode_grid20_table(blob): if len(raw) < 8 or len(raw) > MAX_GRID20_BYTES or (len(raw) - 8) % 20: return out out["size_ok"] = True - magic, unknown = struct.unpack_from("= 4 else b"" - if len(fb) == 4 and grid["counter_last"] >= _u32(fb, 0): - tally["grid20_counter_past_samples"] += 1 + if len(fb) == 4 and grid["position_last"] >= _u32(fb, 0): + tally["grid20_position_past_samples"] += 1 if TAG_INDEXRUN in tmap: io, isz = tmap[TAG_INDEXRUN][0] runs = None @@ -1132,7 +1196,7 @@ def _tally_undocumented_tables(read_slice, bank_base, tmap, tally): firsts[key] = firsts.get(key, 0) + 1 -def decode_awc_bank(data, bank_offset=0, *, deep=True): +def decode_awc_bank(data, bank_offset=0, *, deep=True, curves=False): """Decode all `0x5c` (`RSC8` v8001) entries in one in-memory AWC (`ADAT`) bank.""" bank = parse_adat_header_bytes(data, 0, len(data)) if bank is None: @@ -1161,7 +1225,7 @@ def decode_awc_bank(data, bank_offset=0, *, deep=True): if len(blob) < 4 or blob[:4] != RSC8_MAGIC: non_rsc8_0x5c += 1 continue - dec = decode_rsc8(blob, stream_id=sid, deep=deep) + dec = decode_rsc8(blob, stream_id=sid, deep=deep, curves=curves) comp = _decode_companion_tags(read_slice, 0, tmap) records.append(_make_record(bank_offset, bank_offset + toff, sid, dec, comp)) @@ -1216,6 +1280,15 @@ def _new_summary(mode, source): "max_tag_size": None, "elapsed_seconds": 0.0, **_new_grid_tally(), + "curve_clips": 0, + "curve_clips_decoded": 0, + "curve_errors": {}, + "curve_frames_mismatch": 0, + "curve_quantize_bits_mismatch": 0, + "curve_channels": {}, + "curve_components": {}, + "curve_delta2_boundaries": 0, + "curve_delta2_boundaries_closed": 0, } @@ -1283,6 +1356,22 @@ def _accumulate_record(summary, rec, *, in_adat=True, has_audio=None): ck = f"codec={rec['audio_codec']},ch={rec['audio_channels']},sr={rec['audio_sample_rate']}" summary["audio_codecs"][ck] = summary["audio_codecs"].get(ck, 0) + 1 + cv = rec.get("curves") + if cv is not None: + summary["curve_clips"] += 1 + if not cv["decoded"]: + summary["curve_errors"][cv["error"]] = summary["curve_errors"].get(cv["error"], 0) + 1 + else: + summary["curve_clips_decoded"] += 1 + summary["curve_frames_mismatch"] += not cv["frames_match"] + summary["curve_quantize_bits_mismatch"] += not cv["quantize_bits_match"] + summary["curve_delta2_boundaries"] += cv["delta2_boundaries"] + summary["curve_delta2_boundaries_closed"] += cv["delta2_boundaries_closed"] + for key in ("channels", "components"): + into = summary["curve_" + key] + for name, n in cv[key].items(): + into[name] = into.get(name, 0) + n + def _bank_covering(fh, start, file_size): """The `ADAT` bank that starts before `start` and runs past it, or `None`. @@ -1306,7 +1395,8 @@ def _bank_covering(fh, start, file_size): return None -def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_records=True, progress=None): +def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_records=True, progress=None, + curves=False): """Scan an RPF9 archive sequentially for `ADAT` banks and `RSC8` v8001 resources. With a window (`start`/`limit`), `adat_bytes` counts the window's bytes that belong to a bank, so it never @@ -1407,7 +1497,7 @@ def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_re summary["rsc8_non_rsc8_0x5c"] += 1 continue blob = bank_read_slice(aoff + toff, tsz) - dec = decode_rsc8(blob, stream_id=sid, deep=deep) + dec = decode_rsc8(blob, stream_id=sid, deep=deep, curves=curves) comp = _decode_companion_tags(bank_read_slice, aoff, tmap) rec = _make_record(aoff, aoff + toff, sid, dec, comp) _accumulate_record(summary, rec, in_adat=True, has_audio=comp["has_audio_data"]) @@ -1457,7 +1547,7 @@ def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_re return records, summary -def scan_dir(path, *, max_banks=None, deep=True, collect_records=True): +def scan_dir(path, *, max_banks=None, deep=True, collect_records=True, curves=False): """Scan a directory of `.awc` banks and/or standalone `.rsc8` files.""" t0 = time.time() summary = _new_summary("directory", path) @@ -1485,7 +1575,7 @@ def scan_dir(path, *, max_banks=None, deep=True, collect_records=True): raise ValueError(f"AWC bank exceeds {MAX_AWC_FILE_BYTES} bytes") with open(fp, "rb") as f: raw = f.read() - bank_res = decode_awc_bank(raw, 0, deep=deep) + bank_res = decode_awc_bank(raw, 0, deep=deep, curves=curves) summary["adat_banks"] += 1 summary["adat_streams"] += bank_res["stream_count"] summary["adat_bytes"] += bank_res["bank_size"] @@ -1502,7 +1592,7 @@ def scan_dir(path, *, max_banks=None, deep=True, collect_records=True): raise ValueError(f"RSC8 file exceeds {MAX_RSC8_BYTES} bytes") with open(fp, "rb") as f: raw = f.read() - dec = decode_rsc8(raw, deep=deep) + dec = decode_rsc8(raw, deep=deep, curves=curves) rec = _make_record(0, 0, None, dec, None) _accumulate_record(summary, rec, in_adat=False, has_audio=None) if collect_records: @@ -1517,7 +1607,8 @@ def scan_dir(path, *, max_banks=None, deep=True, collect_records=True): return records, summary -def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, collect_records=True, progress=None): +def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, collect_records=True, progress=None, + curves=False): """Inspect a single `.rsc8`, `.awc`, or `.rpf` file.""" fsize = os.path.getsize(path) with open(path, "rb") as f: @@ -1528,7 +1619,7 @@ def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, co t0 = time.time() with open(path, "rb") as f: raw = f.read() - dec = decode_rsc8(raw, deep=deep) + dec = decode_rsc8(raw, deep=deep, curves=curves) rec = _make_record(0, 0, None, dec, None) summary = _new_summary("rsc8", path) _accumulate_record(summary, rec, in_adat=False, has_audio=None) @@ -1538,7 +1629,7 @@ def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, co t0 = time.time() with open(path, "rb") as f: raw = f.read() - bank_res = decode_awc_bank(raw, 0, deep=deep) + bank_res = decode_awc_bank(raw, 0, deep=deep, curves=curves) summary = _new_summary("awc", path) summary["adat_banks"] = 1 summary["adat_streams"] = bank_res["stream_count"] @@ -1558,6 +1649,7 @@ def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, co deep=deep, collect_records=collect_records, progress=progress, + curves=curves, ) @@ -1644,6 +1736,8 @@ def main(argv=None): ap.add_argument("--limit", type=_parse_pos_int, default=None, help="maximum bytes to scan (single archive only)") ap.add_argument("--max-banks", type=_parse_pos_int, default=None, help="stop after N ADAT banks") ap.add_argument("--no-deep", action="store_true", help="skip per-track and property-attribute walks") + ap.add_argument("--curves", action="store_true", + help="also decode every clip's keyframes and count the outcome (slower; counts only)") ap.add_argument("--summary-only", action="store_true", help="do not store per-clip records in memory/JSON") ap.add_argument("--quiet", action="store_true", help="suppress progress output") args = ap.parse_args(argv) @@ -1670,6 +1764,7 @@ def main(argv=None): max_banks=args.max_banks, deep=not args.no_deep, collect_records=collect, + curves=args.curves, ) except (OSError, ValueError) as e: print(f"{args.source}: {e}", file=sys.stderr) @@ -1691,6 +1786,7 @@ def main(argv=None): deep=not args.no_deep, collect_records=collect, progress=progress, + curves=args.curves, ) except (OSError, ValueError) as e: print(f"{args.source}: {e}", file=sys.stderr) diff --git a/tools/rtti_scan.py b/tools/rtti_scan.py index c64a62a85..9082b2f6d 100644 --- a/tools/rtti_scan.py +++ b/tools/rtti_scan.py @@ -102,13 +102,291 @@ def load_pe64_image(data: bytes) -> tuple[int, bytes, list[dict]]: return image_base, bytes(img), sections +_CV = {"A": (), "B": ("const",), "C": ("volatile",), "D": ("const", "volatile")} +_BUILTIN = {"X": "void", "C": "signed char", "D": "char", "E": "unsigned char", "F": "short", "G": "unsigned short", + "H": "int", "I": "unsigned int", "J": "long", "K": "unsigned long", "M": "float", "N": "double", + "O": "long double", "_D": "__int8", "_E": "unsigned __int8", "_F": "__int16", "_G": "unsigned __int16", + "_H": "__int32", "_I": "unsigned __int32", "_J": "__int64", "_K": "unsigned __int64", "_L": "__int128", + "_M": "unsigned __int128", "_N": "bool", "_Q": "char8_t", "_S": "char16_t", "_U": "char32_t", + "_W": "wchar_t"} +_OPERATOR = {"2": " new", "3": " delete", "4": "=", "5": ">>", "6": "<<", "7": "!", "8": "==", "9": "!=", "A": "[]", + "B": "", "C": "->", "D": "*", "E": "++", "F": "--", "G": "-", "H": "+", "I": "&", "J": "->*", "K": "/", + "L": "%", "M": "<", "N": "<=", "O": ">", "P": ">=", "Q": ",", "R": "()", "S": "~", "T": "^", "U": "|", + "V": "&&", "W": "||", "X": "*=", "Y": "+=", "Z": "-=", "_0": "/=", "_1": "%=", "_2": ">>=", + "_3": "<<=", "_4": "&=", "_5": "|=", "_6": "^=", "_U": " new[]", "_V": " delete[]"} +_POINTER = {"P": " *", "Q": " * const", "R": " * volatile", "S": " * const volatile", "A": " &", "B": " & volatile"} +_QUALIFIERS = re.compile(r"(?: const| volatile)*$") +_SLOT = "\0" # in a function or array type: where a further `*`, `&` or qualifier goes, `void (*|)(int)` +_LOCAL_SCOPE = re.compile(r"\?(?:\d|[B-P][A-P]*@)\?") +# How a type descriptor's name ends: '@@'; a local scope's function ('@?...Z@', '_E@' when noexcept); a back-reference. +_NAME_END = re.compile(rb"(?:@@|@\?[\x21-\x7e]*(?:Z|_E)@|@\d+@)\x00$") + + +class _TypeName: + """A reader for the part of MSVC's name mangling that a class name can contain: scopes, templates and their + arguments, back-references, anonymous namespaces and names local to a function. A form it does not know + raises ValueError (or runs off the end: IndexError); it never guesses.""" + + def __init__(self, text): + self.s, self.i = text, 0 + self.names, self.params = [], [] # the back-reference tables: name pieces, function parameter types + + def peek(self): + return self.s[self.i:self.i + 1] + + def next(self): + c = self.s[self.i] + self.i += 1 + return c + + def eat(self, text): + if self.s.startswith(text, self.i): + self.i += len(text) + return True + return False + + def number(self): + negative = self.eat("?") + c = self.next() + if c.isdigit(): + value = int(c) + 1 + else: + value = 0 + while c != "@": + if not "A" <= c <= "P": + raise ValueError("bad number") + value = value * 16 + ord(c) - ord("A") + c = self.next() + return -value if negative else value + + def memorize(self, name): + if name not in self.names and len(self.names) < 10: + self.names.append(name) + + def simple(self): + end = self.s.index("@", self.i) + name = self.s[self.i:end] + if not name or name[0] in "?$" or name[0].isdigit(): + raise ValueError("bad name") + self.i = end + 1 + self.memorize(name) + return name + + def piece(self): + """One piece of a scope chain.""" + c = self.peek() + if c.isdigit(): + self.i += 1 + return self.names[int(c)] + if self.s.startswith("?$", self.i): + name = self.template() + self.memorize(name) + return name + if self.eat("?A"): + self.i = self.s.index("@", self.i) + 1 + self.memorize("`anonymous namespace'") + return "`anonymous namespace'" + if _LOCAL_SCOPE.match(self.s, self.i): + self.i += 1 + ordinal = self.number() + self.i += 1 + return f"`{self.symbol()}'::`{ordinal}'" + return self.simple() + + def qualified(self): + pieces = [self.piece()] + while not self.eat("@"): + pieces.append(self.piece()) + return "::".join(reversed(pieces)) + + def template(self): + """`?$name@arguments@`. A template name has back-reference tables of its own.""" + self.i += 2 + outer = self.names, self.params + self.names, self.params = [], [] + name = self.operator() if self.peek() == "?" else self.simple() + if name == "operator": + raise ValueError("a conversion operator template is not read") + arguments = [] + while not self.eat("@"): + if self.eat("$$$V") or self.eat("$$V") or self.eat("$$Z") or self.eat("$S"): + continue # an empty pack, or the boundary between two packs + if self.eat("$M"): # a value of a deduced (`auto`) type: the type, the value + self.type() + if not self.eat("0"): + raise ValueError("unknown template argument") + arguments.append(str(self.number())) + elif self.eat("$0"): + arguments.append(str(self.number())) + elif self.eat("$$Y"): + arguments.append(self.qualified()) + else: + arguments.append(self.type().replace(_SLOT, "")) + self.names, self.params = outer + return f"{name}<{', '.join(arguments)}>" + + def operator(self): + self.i += 1 + code = self.next() + if code == "_": + code += self.next() + if code in ("0", "1"): + return code # constructor, destructor: named after the class + if code not in _OPERATOR: + raise ValueError("unknown special name") + return "operator" + _OPERATOR[code] + + def symbol(self): + """A whole decorated function name, as a local scope holds one. Returns its qualified name; the signature + is read, to find where it ends, and dropped.""" + if not self.eat("?"): + raise ValueError("not a symbol") + c = self.peek() + if c.isdigit(): + self.i += 1 + name = self.names[int(c)] + elif self.s.startswith("?$", self.i): + name = self.template() + elif c == "?": + name = self.operator() + else: + name = self.simple() + scope = [] + while not self.eat("@"): + scope.append(self.piece()) + if name[0] in "01": + if not scope: + raise ValueError("a constructor outside a class") + name = ("~" if name[0] == "1" else "") + scope[0] + name[1:] + kind = self.next() + if kind in "ABEFIJMNQRUV": # a non-static member: `this` qualifiers + while self.peek() in ("E", "F", "G", "H", "I"): + self.i += 1 + self.cv() + elif kind not in "CDKLSTYZ": + raise ValueError("not a plain function") + result = self.signature()[0] + if name == "operator": # a conversion: named after the type it returns + name += " " + result.replace(_SLOT, "") + return "::".join(scope[::-1] + [name]) + + def cv(self): + return _CV[self.next()] + + def sizes(self): + """An array's dimensions: how many, then each.""" + count = self.number() + sizes = [self.number() for _ in range(count)] + if count < 1 or min(sizes) < 0: + raise ValueError("bad array dimensions") + return "".join(f"[{n}]" for n in sizes) + + @staticmethod + def declare(text, declarator, keep=False): + """The type `text` with `declarator` (` *`, ` (*)(int)`, ` [4]`, ...) applied. It goes after a plain type, + and inside the brackets of a function or array type: a pointer to `void (*)(int)` is `void (**)(int)`. + `keep` leaves the slot after a `*` or `&`; a function or array declarator brings its own.""" + if _SLOT in text: + return text.replace(_SLOT, declarator.lstrip() + (_SLOT if keep else "")) + return text + declarator + + @staticmethod + def qualify(text, qualifiers): + """`text` with `const`/`volatile` after it. A const pointer is marked twice, by its own code and by the + qualifiers of whatever refers to it, so one that is already there is not repeated.""" + head, slot, tail = text.partition(_SLOT) + present = _QUALIFIERS.search(head).group(0).split() + return head + "".join(f" {q}" for q in qualifiers if q not in present) + slot + tail + + def signature(self): + """Calling convention, return type, parameters, exception specification: (return type, parameters, + ` noexcept` or nothing).""" + if not "A" <= self.next() <= "W": + raise ValueError("unknown calling convention") + result = "" if self.eat("@") else self.type() + parameters = [] + if self.eat("X"): + parameters.append("void") + else: + while not self.eat("@"): + if self.eat("Z"): + parameters.append("...") + break + if self.peek().isdigit(): + parameters.append(self.params[int(self.next())]) + continue + start = self.i + parameters.append(self.type().replace(_SLOT, "")) + if self.i - start > 1 and len(self.params) < 10: + self.params.append(parameters[-1]) + if self.eat("_E"): + return result, parameters, " noexcept" + if not self.eat("Z"): + raise ValueError("no exception specification") + return result, parameters, "" + + def function(self, declarator): + result, parameters, noexcept = self.signature() + return self.declare(result, f" {declarator}({', '.join(parameters)}){noexcept}") + + def indirect(self, suffix): + """What a pointer or reference refers to, with `suffix` (` *`, ` &`, ...) after it.""" + unaligned = () + while self.peek() in ("E", "F", "I"): # __ptr64, __unaligned, __restrict + if self.next() == "F": + unaligned = ("__unaligned",) + if self.eat("6"): + return self.function(f"({suffix.strip()}{_SLOT})") + if self.eat("$A"): # a C++/CX handle + suffix = suffix.replace("*", "^") + qualifiers = self.cv() + if self.eat("Y"): + sizes = self.sizes() + return self.declare(self.qualify(self.type(), qualifiers + unaligned), f" ({suffix.strip()}{_SLOT}){sizes}") + return self.declare(self.qualify(self.type(), qualifiers + unaligned), suffix, keep=True) + + def type(self): + if self.eat("$$Q"): + return self.indirect(" &&") + if self.eat("$$T"): + return "std::nullptr_t" + if self.eat("$$A6"): + return self.function("") + if self.eat("$$C") or self.eat("?"): # a qualified type passed by value + qualifiers = self.cv() + return self.qualify(self.type(), qualifiers) + if self.eat("$$BY"): # an array passed as a template argument + sizes = self.sizes() + return self.declare(self.type(), " " + sizes) + c = self.next() + if c == "_": + c += self.next() + if c in _BUILTIN: + return _BUILTIN[c] + if c in ("T", "U", "V"): + return self.qualified() + if c == "W": + if not "0" <= self.next() <= "7": + raise ValueError("bad enum") + return self.qualified() + if c in _POINTER: + return self.indirect(_POINTER[c]) + raise ValueError("unknown type") + + def simple_name(mangled: str) -> str: - """'.?AVFoo@bar@@' -> 'bar::Foo' (enough to read; full demangling isn't needed here).""" - m = re.match(r"\.\?A[VUW](.*)@@$", mangled) - if not m: + """'.?AVFoo@bar@@' -> 'bar::Foo', '.?AV?$Foo@H@bar@@' -> 'bar::Foo'. The `class`/`struct`/`enum` keywords, + calling conventions and the signature of a function that a local class sits in are left out. A name with a + form this does not read (a member pointer or an array as a template argument, say) is returned as it is.""" + m = re.match(r"\.\?A(?:[TUV]|W[0-7]?)", mangled) + if not m or not mangled.endswith("@"): return mangled - parts = [p for p in m.group(1).split("@") if p] - return "::".join(reversed(parts)) + reader = _TypeName(mangled[m.end():]) + try: + name = reader.qualified() + except (ValueError, IndexError, KeyError, RecursionError): + return mangled + return name.replace(_SLOT, "") if reader.i == len(reader.s) else mangled def scan_pe64_rtti(data: bytes) -> dict: @@ -126,10 +404,14 @@ def scan_pe64_rtti(data: bytes) -> dict: def u32(rva): return struct.unpack_from("= 0: tds[rva] = m.group(0)[:-1].decode("latin-1") @@ -229,6 +511,9 @@ def main(): ap.add_argument("image") ap.add_argument("--out") a = ap.parse_args() + if not os.path.exists(a.image): + print(f"ERROR: {a.image}: does not exist", file=sys.stderr) + return 2 path = a.out or re.sub(r"\.(exe|dll)$", "", a.image, flags=re.I) + ".rtti.json" same_path = os.path.normcase(os.path.realpath(a.image)) == os.path.normcase(os.path.realpath(path)) try: diff --git a/tools/sampler_lod_probe.py b/tools/sampler_lod_probe.py index 3ea0e76e8..f439cfaff 100644 --- a/tools/sampler_lod_probe.py +++ b/tools/sampler_lod_probe.py @@ -1,7 +1,7 @@ r"""SHADER-539: measure on an AMD GPU (tools/hw_oracle) which mip level image_sample_l and image_sample_lz read under the S#'s MIN_LOD / MAX_LOD / LOD_BIAS / MIP_FILTER and the T#'s MIN_LOD and BASE_LEVEL. - python -I tools/sampler_lod_probe.py # the Vulkan rule's levels only (no GPU) + python -I tools/sampler_lod_probe.py # each row's level under both rules below (no GPU) python -I tools/sampler_lod_probe.py --oracle hw # native AMD GPU, wave32 and wave64, compared with the rule docs/d3d12_vulkan.md ("vk_sampler_test") says the S# LOD fields apply to an explicit LOD as Vulkan's minLod, maxLod and @@ -12,14 +12,17 @@ dword offset of the texel it read: the start of the level it came from. The leve calibration row per level (image_sample_l at LOD n, no clamp) finds them, and every other row's result is named by that table. -The rule the rows are compared with is Vulkan's (and the runtime's mapping in runtime/src/gfx10_descriptors.h): - lambda = LOD (0 for _lz) + S# LOD_BIAS, clamped to [S# MIN_LOD, S# MAX_LOD] - MIP_FILTER none: the view's base level; point: base + nearest level (ceil(lambda + 0.5) - 1), clamped to the view - T# MIN_LOD: the level is at least floor(MIN_LOD), counted from the resource's level 0 (VK_EXT_image_view_min_lod) -A row the hardware answers differently is printed as DIFFERS; that is the measurement, not a harness failure. +Two rules are computed for every row: + - rdna2_level, the rule the hardware rows are checked against: the model the gfx1036 measurement fits (see its + docstring; an exact half level rounds up, and the T#'s MIN_LOD clamps the fractional LOD before that rounding); + - vulkan_level, for comparison: Vulkan's rule for the sampler and view the runtime makes of the same S# and T# + (runtime/src/gfx10_descriptors.h): nearest is ceil(lambda + 0.5) - 1, and VK_EXT_image_view_min_lod raises the + integer level to floor(minLod). Rows where it differs are marked "Vulkan reads n"; that is not a failure. +DIFFERS means the hardware disagrees with the RDNA2 model, not with Vulkan. Standard library only; the texture is built here, no game files. -Exit codes: 0 every row matches the rule, 1 a row differs, 2 harness error, 77 no hardware oracle. +Exit codes: 0 every row matches the RDNA2 model (not "the hardware equals Vulkan"), 1 a row differs, 2 harness +error, 77 no hardware oracle. """ import argparse import math @@ -190,8 +193,9 @@ def main(): return 0 import asm import runner + import tsharp try: - oracle = runner.Oracle() + oracle = runner.open_oracle() except runner.Unavailable as e: print(f"hardware oracle unavailable: {e}") return 77 @@ -208,7 +212,7 @@ def main(): if isinstance(res, str): print(f"wave{wave}: kernel rejected: {res}") return 2 - got[wave] = [struct.unpack(" --entities --models --textures \ + [--center X Y] [--radius M] [--max-props N] (--window | --check) + +It packs the props around --center with tools/sandbox_scene.py, picks a translated VS/PS pair from +/shaders/spirv/index.json and runs runtime/build/vk_sandbox. The pair is chosen by what the shaders read, +not by name (the material -> program table is in the executable, #2519): a vertex shader with POSITION, NORMAL +and TEXCOORD inputs, user SGPR 8 as its only user data and no bindings, whose listing loads three descriptors from +s[8:9] at 0x0/0x40/0x60, a world translation at 0x30 and a 4x4 at 0x160; and a pixel shader with TEXCOORD and +COLOR inputs that loads one T# from s[8:9] + 0x20 and samples it once. vk_sandbox fills that table (see its +header). --check renders one frame headless and prints only counts: exit 0 when the frame is covered and, with +textures, shows texture detail; 77 when the package, the pair or a GPU is missing. Standard library only. +""" +import argparse +import json +import os +import re +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import sandbox_scene # noqa: E402 + +VS_LAYOUT = (r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], (?:null|0)\b", r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], 0x40\b", + r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], 0x60\b", r"s_buffer_load_dwordx16 s\[\d+:\d+\], s\[\d+:\d+\], 0x160\b", + r"s_buffer_load_dwordx4 s\[\d+:\d+\], s\[\d+:\d+\], 0x30\b") +SKY = bytes((140, 173, 217)) # vk_sandbox's clear colour (0.55, 0.68, 0.85) in 8 bits +PS_LAYOUT = (r"s_load_dwordx8 s\[\d+:\d+\], s\[8:9\], 0x20\b", r"\bimage_sample\b", r"\bexp mrt0\b") + + +def _signature(entry): + return [(e.get("semantic"), e.get("semantic_index"), e.get("mask")) for e in entry.get("input_signature") or []] + + +def _listing_matches(disasm_dir, name, patterns): + try: + with open(os.path.join(disasm_dir, name + ".s"), encoding="utf-8", errors="replace") as f: + text = f.read() + except OSError: + return False + return text.count("image_sample") <= 1 and all(re.search(p, text) for p in patterns) + + +def pick_pair(shaders_dir): + """(vs.spv, ps.spv) paths of the first matching pair in name order, or None.""" + spirv = os.path.join(shaders_dir, "spirv") + disasm = os.path.join(shaders_dir, "dxbc", "disasm") + try: + with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: + index = json.load(f) + except (OSError, ValueError): + return None + ptr8 = {"kind": "ptr32_lo", "sgpr": 8} + vs = ps = None + for name in sorted(index): + e = index[name] + if not os.path.isfile(os.path.join(spirv, name + ".spv")): + continue + if (vs is None and e.get("stage") == "vs" and not e.get("bindings") + and e.get("user_sgpr_reads") == [ptr8] + and _signature(e) == [("POSITION", 0, 7), ("NORMAL", 0, 7), ("TEXCOORD", 0, 3)] + and _listing_matches(disasm, name, VS_LAYOUT)): + vs = name + elif (ps is None and e.get("stage") == "ps" and e.get("bindings") == [0, 1, 2] + and ptr8 in (e.get("user_sgpr_reads") or []) + and [s[0] for s in _signature(e)] == ["SV_Position", "TEXCOORD", "COLOR"] + and _listing_matches(disasm, name, PS_LAYOUT)): + ps = name + if vs and ps: + return os.path.join(spirv, vs + ".spv"), os.path.join(spirv, ps + ".spv") + return None + + +def find_tool(build): + for name in ("vk_sandbox.exe", "vk_sandbox"): + path = os.path.join(build, name) + if os.path.isfile(path): + return path + return None + + +def read_ppm(path): + with open(path, "rb") as f: + data = f.read() + head = data.split(b"\n", 3) + w, h = (int(v) for v in head[1].split()) + return w, h, head[3] + + +def check_frame(path, textured): + """(ok, message) from the rendered frame: coverage and, with textures, colour variety.""" + w, h, px = read_ppm(path) + sky = SKY + covered, colours = 0, set() + for i in range(0, len(px), 3): + p = px[i:i + 3] + if abs(p[0] - sky[0]) > 1 or abs(p[1] - sky[1]) > 1 or abs(p[2] - sky[2]) > 1: + covered += 1 + colours.add(p) + ok = covered >= w * h // 100 and (not textured or len(colours) >= 256) + return ok, f"{covered} of {w * h} pixels covered, {len(colours)} distinct colours" + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--work", required=True, help="make_game.py work folder (holds shaders/spirv and shaders/dxbc)") + ap.add_argument("--entities", required=True) + ap.add_argument("--models", required=True) + ap.add_argument("--textures", action="append", default=[]) + ap.add_argument("--center", type=float, nargs=2, metavar=("X", "Y")) + ap.add_argument("--radius", type=float, default=150.0) + ap.add_argument("--max-props", type=int, default=400) + ap.add_argument("--build", default=os.path.join(HERE, "..", "runtime", "build")) + ap.add_argument("--scene", help="scene file to write (default: a temporary file)") + mode = ap.add_mutually_exclusive_group(required=True) + mode.add_argument("--window", action="store_true") + mode.add_argument("--check", action="store_true") + a = ap.parse_args(argv) + + tool = find_tool(a.build) + pair = pick_pair(os.path.join(a.work, "shaders")) + if not tool or not pair or not os.path.isfile(a.entities): + print("unsupported: " + ("vk_sandbox is not built" if not tool else + "no matching translated shader pair" if not pair else "no entities file")) + return 77 + tmp = frame = None + scene = a.scene + if not scene: + fd, scene = tempfile.mkstemp(suffix=".bin") + os.close(fd) + tmp = scene + try: + try: + stats = sandbox_scene.build(argparse.Namespace(entities=a.entities, models=a.models, textures=a.textures, + center=a.center, radius=a.radius, max_props=a.max_props, + tex_size=256, out=scene)) + except SystemExit as e: # build() exits when no entity resolves to an exported model + print(f"unsupported: {e}") + return 77 + print(f"scene: {stats['placed']} props, {stats['draws']} draws, {stats['textures']} textures, " + f"{stats['textured_draws']} textured draws") + if stats["draws"] == 0: + print("unsupported: no prop near the centre resolves to an exported model") + return 77 + x, y, z = stats["center"] + cam = [str(x - 40), str(y - 40), str(z + 25), "45", "-20"] + if a.window: + return subprocess.call([tool, scene, *pair, "--window", "--cam", *cam]) + frame = scene + ".ppm" + r = subprocess.run([tool, scene, *pair, "--out", frame, "--size", "640", "360", "--cam", *cam], + capture_output=True, text=True) + if r.returncode: + print((r.stdout + r.stderr).strip().splitlines()[-1] if (r.stdout + r.stderr).strip() else "vk_sandbox failed") + return r.returncode + ok, msg = check_frame(frame, stats["textured_draws"] > 0) + print(("PASS: " if ok else "FAIL: ") + msg) + return 0 if ok else 1 + finally: + for path in (tmp, frame): + if path and os.path.exists(path): + os.remove(path) + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/sandbox_scene.py b/tools/sandbox_scene.py new file mode 100644 index 000000000..98fe02e84 --- /dev/null +++ b/tools/sandbox_scene.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Pack the placed props around one spot into a scene file for runtime/test/vk_sandbox. + +Reads the same inputs as ``world_build.py --placements`` (``world_index.py --entities-out`` rows, the +``rpf9dump models`` manifests and the ``rpf9dump ttpf`` texture manifests), keeps the entities within +--radius metres of --center (RAGE world x y, Z-up), and writes one little-endian file: + + "LSB1", u32 version 1, u32 textures, u32 meshes, u32 draws, f32 center[3] + textures: u32 w, u32 h, w*h RGBA8 (the material's DiffuseTex, mip 0 box-scaled to --tex-size) + meshes: u32 vertex count, u32 index count, vertices (f32 pos[3], f32 normal[3], f32 uv[2]), u32 indices + draws: u32 mesh, i32 texture (-1: none), f32 rows[4][3] + +Positions stay in model space; a draw's rows are the entity's world transform as three basis rows plus the +translation, world = x*row0 + y*row1 + z*row2 + row3 (RAGE Z-up). The file holds decoded game data, so it +stays in the user's work folder. Standard library only. +""" +import argparse +import math +import os +import struct +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import dds_png # noqa: E402 +import glb_writer # noqa: E402 +import world_build # noqa: E402 + +DIFFUSE_TEX = "C8E8C282" # joaat("DiffuseTex"), the albedo Param of a material texture reference +# Two-layer blend materials have no DiffuseTex; their first layer's albedo sits in this slot (name not known yet; +# beside it are the second layer's albedo, two normal maps, packed material maps and the blend mask). +LAYER0_ALBEDO = "346394EA" + + +def select_rows(rows, center, radius, limit): + """Rows within radius of center (x, y), nearest first, at most limit.""" + cx, cy = center + near = [] + for row in rows: + dx, dy = row["_pos"][0] - cx, row["_pos"][1] - cy + d = math.hypot(dx, dy) + if d <= radius: + near.append((d, row)) + near.sort(key=lambda t: t[0]) + return [row for _, row in near[:limit]] + + +def draw_rows(rotation, scale_xy, scale_z, position): + """The VS's world rows (basis vectors then translation) for one entity.""" + m, _, _ = world_build.entity_transform(rotation, scale_xy, scale_z) + rows = [[m[i][j] for i in range(3)] for j in range(3)] # column j of M is the image of model axis j + rows.append([float(v) for v in position]) + return rows + + +def mesh_bytes(prim): + pos, nrm, uvs, idx = prim["positions"], prim.get("normals") or [], prim.get("uvs") or [], prim["indices"] + out = bytearray(struct.pack("= 0 + stats["placed"] += 1 + stats["z"].append(row["_pos"][2]) + if stats["placed"] >= args.max_props: + break + z = sorted(stats.pop("z")) or [0.0] + center = [args.center[0], args.center[1], z[len(z) // 2]] + with open(args.out, "wb") as f: + f.write(b"LSB1" + struct.pack("<4I3f", 1, len(textures), len(meshes), len(draws), *center)) + for blob in textures + meshes + draws: + f.write(blob) + stats.update(textures=len(textures), meshes=len(meshes), draws=len(draws), center=center, + selected_rows=counts["selected"]) + return stats + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--entities", required=True, help="world_index.py --entities-out file (JSON lines)") + ap.add_argument("--models", required=True, help="folder holding rpf9dump models manifests") + ap.add_argument("--textures", action="append", default=[], help="folder holding rpf9dump ttpf manifests (repeatable)") + ap.add_argument("--center", type=float, nargs=2, metavar=("X", "Y"), help="RAGE world x y (default: densest 50 m cell)") + ap.add_argument("--radius", type=float, default=150.0) + ap.add_argument("--max-props", type=int, default=400, help="entities to place, nearest first (each can be several draws)") + ap.add_argument("--tex-size", type=int, default=256) + ap.add_argument("--out", required=True) + stats = build(ap.parse_args(argv)) + print(" ".join(f"{k}={v}" for k, v in stats.items())) + return 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/saves.py b/tools/saves.py index 71165e93e..7f150b2fb 100644 --- a/tools/saves.py +++ b/tools/saves.py @@ -109,7 +109,7 @@ def parse_jsav(d): try: body_text = d[body_off:].rstrip(b'\0').decode('utf-8') _, json_end = json.JSONDecoder().raw_decode(body_text) - except (UnicodeError, json.JSONDecodeError) as exc: + except (UnicodeError, json.JSONDecodeError, RecursionError) as exc: raise ValueError(f'JSAV body is not valid UTF-8 JSON: {exc}') from None # raw_decode returns a character offset, while the entry table uses byte offsets. # The last nonzero byte is not the JSON boundary: corrupt data can follow the document's padding. @@ -301,7 +301,7 @@ def pack_from_dir(src): try: idx = json.loads(read(index_path)) - except ValueError as exc: + except (ValueError, RecursionError) as exc: raise ValueError(f'{index_path}: invalid JSON ({exc})') from None if not isinstance(idx, dict): invalid('index', 'an object') diff --git a/tools/sdwa_diff.py b/tools/sdwa_diff.py index 22d9b89c3..d4b83a614 100644 --- a/tools/sdwa_diff.py +++ b/tools/sdwa_diff.py @@ -41,10 +41,10 @@ Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the f differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always has them): * a constant shift amount (inline constant or seeded SGPR) for v_lshlrev_b32 / v_lshrrev_b32 / v_ashrrev_i32 with - src0_sel other than DWORD or sext(): the translator's constant fold shifted by the whole constant (#2005); - * a 16-bit result with dst_sel:DWORD: the translator keeps the destination's high half (finding in #1902); - * a float inline constant with a src_sel other than DWORD in an f16 op: the translator reads the whole constant - (finding in #1902). + src0_sel other than DWORD or sext(): the translator's constant fold shifted by the whole constant (#2005). +Two forms that used to be listed here are generated in every run again now that main translates them: a 16-bit +result with dst_sel:DWORD (the high half zeroed, #2187) and a float inline constant with a src_sel other than DWORD +in an f16 op (the selection made from the f16 value, #2209). With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/) and the hardware's four words are compared with the reference: that validates the reference itself. SDWA exists on GFX9 and GFX10 only, so the @@ -506,10 +506,6 @@ SHIFTS = ("v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32") KNOWN_DIVERGENCES = { "shift-const-sel": "a constant shift amount (inline or seeded SGPR) with src0_sel or sext(): until #2005 the " "translator shifts by the whole constant", - "dword-16bit": "a 16-bit result (f16 ops, v_cvt_{u16,i16}_f16, v_cvt_f16_{u16,i16}) with dst_sel:DWORD: the " - "hardware zeroes the high half, the translator keeps it", - "f16-const-sel": "a float inline constant with a src_sel other than DWORD in an f16 op: the hardware selects from " - "the f16 value (0x3c00 for 1.0), the translator reads the whole constant", } @@ -533,11 +529,6 @@ def emit(rng, name): inner = a[5:-1] if a.startswith("sext(") else a if name in SHIFTS and inner[0] != "v": s0, a = "DWORD", inner - if family == "f16": - s0 = "DWORD" if a in FLOAT_CONSTS else s0 - s1 = "DWORD" if b in FLOAT_CONSTS and name != "v_cmp_class_f16" else s1 - if form != "vopc" and width == 16 and dsel == "DWORD": - dsel = rng.choice(sels[:-1]) if form == "vopc": return f"{name}_sdwa vcc_lo, {a}, {b} src0_sel:{s0} src1_sel:{s1}" tail = f"{clamp} dst_sel:{dsel} dst_unused:{unused} src0_sel:{s0}" diff --git a/tools/shader_carve.py b/tools/shader_carve.py index ce112ed40..d7c9404cd 100644 --- a/tools/shader_carve.py +++ b/tools/shader_carve.py @@ -86,7 +86,10 @@ def main(argv=None) -> int: ap.error(f"{src} is empty") if os.path.isfile(out): ap.error(f"{out} is a file, not a folder") - os.makedirs(out, exist_ok=True) + try: + os.makedirs(out, exist_ok=True) + except OSError as e: # a regular file where a parent folder is expected + ap.error(f"cannot create {out}: {e.strerror or e}") index, seen, used, bad = [], {}, set(), 0 with open(src, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: pos = 0 diff --git a/tools/shader_diff.py b/tools/shader_diff.py index 89f493db3..3e97c36be 100644 --- a/tools/shader_diff.py +++ b/tools/shader_diff.py @@ -240,8 +240,6 @@ def run_one(name, lines, writers): gc.collect() except rdna2spirv.Unsupported as e: return ("skip", f"translator unsupported: {e}") - except (IndexError, KeyError, ValueError) as e: - return ("skip", f"translator error {type(e).__name__}: {e}") try: out = run_fragment(spvasm) except UnsupportedConstruct as e: diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index 1b8d1040e..fa03dcdc9 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -22,6 +22,7 @@ from concurrent.futures import ThreadPoolExecutor sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from mc_command import mc_command # noqa: E402 from shader_stage_manifest import shader_stems # noqa: E402 +import rdna2_decode # noqa: E402 TRIPLE = "amdgcn--amdpal" ENDPGM = b"\x00\x00\x81\xbf" @@ -67,7 +68,10 @@ def probe(mcpu: str) -> None: f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") -def disasm(code: bytes, mcpu: str): +def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True): + if backend == "python": + asm, bad = rdna2_decode.disasm_bytes(code, wave32=wave32) + return asm, bad, "" text = " ".join(f"0x{b:02x}" for b in code) try: p = subprocess.run(MC + ["--disassemble", f"-triple={TRIPLE}", f"-mcpu={mcpu}", "-show-encoding"], @@ -81,10 +85,31 @@ def disasm(code: bytes, mcpu: str): return p.stdout, bad, p.stderr +MAX_DATA_DWORDS = 1 << 16 + + +def data_block_start(b: bytes, start: int, end: int) -> int: + """Where a constant-data block begins at the end of the code range [start, end), or `end` if there is none. + + Some blobs carry, after the last real s_endpgm, a block laid out as: s_endpgm, a dword count N, N dwords + of data, then one more s_endpgm (the one the range ends on) and s_code_end padding. The data is not code: + llvm-mc reports its words as invalid (and reads a 0xBF810000 inside it as a second program end). The + block is recognised only when the count N matches the distance to the closing s_endpgm and the dword + before the count is itself an s_endpgm, so ordinary code is not cut.""" + last = end - 4 + for n in range(min(MAX_DATA_DWORDS, (last - start) // 4 - 1) + 1): + count = last - 4 * (n + 1) + if count - 4 < start: + break + if struct.unpack_from("= 0xC4 else 0 @@ -94,7 +119,7 @@ def code_range(b: bytes): while last >= 0 and (last - start) % 4: last = b.rfind(ENDPGM, start, last) if last >= 0: - return start, last + 4, "header" + return start, data_block_start(b, start, last + 4), "header" end = b.find(ENDPGM) # Fallback instructions are dword-aligned in the blob. A matching byte sequence can straddle metadata words. while end >= 0 and end % 4: @@ -102,7 +127,7 @@ def code_range(b: bytes): return None, end + 4 if end >= 0 else None, "scan" -def one(path, out, mcpu): +def one(path, out, mcpu, backend="llvm-mc"): with open(path, "rb") as f: b = f.read() start, end, how = code_range(b) @@ -112,13 +137,13 @@ def one(path, out, mcpu): # Walk back in 4-byte steps from the end and keep the longest clean decode. start, best = end - 4, None for s in range(end - 4, max(0x100, end - 0x4000) - 1, -4): - _, bad, _ = disasm(b[s:end], mcpu) + _, bad, _ = disasm(b[s:end], mcpu, backend=backend) if bad == 0: best = s if best is None: return "scan failed" start = best - asm, bad, err = disasm(b[start:end], mcpu) + asm, bad, err = disasm(b[start:end], mcpu, backend=backend) if not asm.strip(): # a broken toolchain, not a shader: never report this as "clean" reason = (err.strip().splitlines() or ["no output"])[0] FAILED.append((path, reason)) @@ -147,6 +172,8 @@ def main(): ap.add_argument("--out") ap.add_argument("--skip-existing", action="store_true", help="reuse complete listings from a matching run") ap.add_argument("--mcpu", default="gfx1013") + ap.add_argument("--backend", choices=("llvm-mc", "python"), default="llvm-mc", + help="disassembler backend: llvm-mc (default) or pure-Python RDNA2 decoder (#1901)") ap.add_argument("--limit", type=positive_int) ap.add_argument("--jobs", type=positive_int, default=max(1, (os.cpu_count() or 2) // 2)) a = ap.parse_args() @@ -168,6 +195,9 @@ def main(): if entry.name.endswith(".fssm") and entry.is_file()) except (OSError, ValueError) as e: fail(f"cannot list shaders in {a.src}: {e}") + elif not os.path.exists(a.src): + print(f"ERROR: {a.src}: does not exist", file=sys.stderr) + return 2 else: fail(f"{a.src} is not a file or folder") if not files: @@ -192,9 +222,10 @@ def main(): pending.append(path) files = pending if files: - probe(a.mcpu) + if a.backend == "llvm-mc": + probe(a.mcpu) with ThreadPoolExecutor(a.jobs) as ex: - res.update(ex.map(lambda p: one(p, out, a.mcpu), files)) + res.update(ex.map(lambda p: one(p, out, a.mcpu, backend=a.backend), files)) print(f"{total} shaders -> {os.path.abspath(out)}: {dict(res)}") if FAILED: path, reason = FAILED[0] diff --git a/tools/skin_streams.py b/tools/skin_streams.py index 1320efa35..13b1dcc24 100644 --- a/tools/skin_streams.py +++ b/tools/skin_streams.py @@ -118,7 +118,11 @@ def resource_kind(b): return None if sys_ptr(u64(b, 8)) and sys_ptr(u64(b, 32)) and sys_ptr(u64(b, 48)) and 0 < u16(b, 56) <= 4096 \ and u16(b, 56) == u16(b, 58) == u16(b, 40) == u16(b, 42): - return "dictionary" + # DrawableDictionaryCheckBytes also reads the first child when its pointer array is inside + # the prefix; beyond it the decoder accepts the header without that read. + values = u64(b, 48) - 0x50000000 + if values > len(b) - 8 or sys_ptr(u64(b, values)): + return "dictionary" if all(sys_ptr(u64(b, at)) for at in (8, 24, 168)) \ and all(p == 0 or sys_ptr(p) for p in (u64(b, 16), u64(b, 32), u64(b, 40))) \ and 0 < u16(b, 48) <= 4096 and u16(b, 50) <= 4096 \ diff --git a/tools/skinned_glb.py b/tools/skinned_glb.py index d4ffc8616..bb1412527 100644 --- a/tools/skinned_glb.py +++ b/tools/skinned_glb.py @@ -199,8 +199,12 @@ def _finite_matrix(m) -> bool: # ------------------------------------------------------------------------ files def _load_json(path: str) -> dict: - with open(path, encoding="utf-8") as handle: - value = json.load(handle) + # An interrupted export leaves an empty or cut-off model.json: report it like any other bad input (BUILD-1031). + try: + with open(path, encoding="utf-8") as handle: + value = json.load(handle) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise SkinError(f"{path}: invalid JSON: {exc}") from exc if not isinstance(value, dict): raise SkinError(f"{path}: model.json root is not an object") return value @@ -482,7 +486,7 @@ def infer_ped_parent(name: str, ped_by_name: dict[str, dict]) -> int | None: for alias in aliases: if alias in ped_set: score += 10 - elif any(token.startswith(alias) for token in ped_set): + elif not alias[-1].isdigit() and any(token.startswith(alias) for token in ped_set): score += 5 if score: candidate = (score, -len(ped_name), -index, index) diff --git a/tools/smem_neg_probe.py b/tools/smem_neg_probe.py index 6371f8254..2c9617433 100644 --- a/tools/smem_neg_probe.py +++ b/tools/smem_neg_probe.py @@ -98,10 +98,10 @@ def kernel_lines(): return lines, order -def main(): +def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--oracle", choices=("translator", "hw"), default="translator") - a = ap.parse_args() + a = ap.parse_args(argv) want = expected() if a.oracle == "translator": for name, vals in want.items(): @@ -110,20 +110,23 @@ def main(): import asm import runner try: - oracle = runner.Oracle() + oracle = runner.open_oracle() except runner.Unavailable as e: print(f"hardware oracle unavailable: {e}") return 77 - lines, order = kernel_lines() - n = len(order) - got = {} - for wave in (32, 64): - res = oracle.run([asm.Kernel(lines, wave=wave, threads=1, words=n, raw=True, vgprs=8, sgprs=64)])[0] - if isinstance(res, str): - print(f"wave{wave}: kernel rejected: {res}") - return 2 - got[wave] = res - print(f"device: {oracle.device} ({oracle.arch})") + try: + lines, order = kernel_lines() + n = len(order) + got = {} + for wave in (32, 64): + res = oracle.run([asm.Kernel(lines, wave=wave, threads=1, words=n, raw=True, vgprs=8, sgprs=64)])[0] + if isinstance(res, str): + print(f"wave{wave}: kernel rejected: {res}") + return 2 + got[wave] = res + print(f"device: {oracle.device} ({oracle.arch})") + finally: + oracle.close() bad, i = 0, 0 for name, _ls, regs, _soff, _xs in ROWS: w32 = got[32][i:i + len(regs)] diff --git a/tools/spirv_asm.py b/tools/spirv_asm.py index 52cb779b7..e004ca0c8 100644 --- a/tools/spirv_asm.py +++ b/tools/spirv_asm.py @@ -206,17 +206,22 @@ def _parse_float_bits(tok: str, width: int, lineno: int) -> int: return (sign << (exp_bits + mant_bits)) | (exp_max << mant_bits) +def _encode_integer(val: int, width: int, signedness: int) -> list[int]: + # A hexadecimal bit pattern for a signed narrow value still needs a sign-extended word. + if signedness and 0 < width < 32 and (1 << (width - 1)) <= val < (1 << width): + val -= 1 << width + if width == 64: + return [val & 0xFFFFFFFF, (val >> 32) & 0xFFFFFFFF] + return [val & 0xFFFFFFFF] + + def _encode_context_number(tok: str, type_info, lineno: int) -> list[int]: if type_info is None: raise SpirvAsmError(f"line {lineno}: OpConstant references unknown scalar type") kind, width = type_info[0], type_info[1] if kind == "int": - val = _parse_int(tok, lineno) - if width <= 32: - return [val & 0xFFFFFFFF] - if width == 64: - u64 = val & 0xFFFFFFFFFFFFFFFF - return [u64 & 0xFFFFFFFF, (u64 >> 32) & 0xFFFFFFFF] + if width <= 32 or width == 64: + return _encode_integer(_parse_int(tok, lineno), width, type_info[2]) raise SpirvAsmError(f"line {lineno}: unsupported integer constant width {width}") if kind == "float": bits = _parse_float_bits(tok, width, lineno) @@ -255,7 +260,7 @@ def assemble(text: str, target_env: str = "vulkan1.2") -> bytes: def encode_operand(kind: str, toks: list[str], idx: int, lineno: int, res_type_id: int | None, cur_ext_table: dict[str, int] | None, - switch_width: int, out: list[int]) -> int: + switch_type: tuple[int, int], out: list[int]) -> int: if kind in _ID_KINDS: out.append(get_id(toks[idx], lineno)) return idx + 1 @@ -279,13 +284,7 @@ def assemble(text: str, target_env: str = "vulkan1.2") -> bytes: out.append(_parse_int(tok, lineno) & 0xFFFFFFFF) return idx + 1 if kind == "PairLiteralIntegerIdRef": - val = _parse_int(toks[idx], lineno) - if switch_width == 64: - u64 = val & 0xFFFFFFFFFFFFFFFF - out.append(u64 & 0xFFFFFFFF) - out.append((u64 >> 32) & 0xFFFFFFFF) - else: - out.append(val & 0xFFFFFFFF) + out.extend(_encode_integer(_parse_int(toks[idx], lineno), *switch_type)) if idx + 1 >= len(toks): raise SpirvAsmError(f"line {lineno}: missing label in {kind}") out.append(get_id(toks[idx + 1], lineno)) @@ -313,14 +312,14 @@ def assemble(text: str, target_env: str = "vulkan1.2") -> bytes: for sk, sq in sub[3]: if sq == "*": while idx < len(toks): - idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out) + idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) elif sq == "?": if idx < len(toks): - idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out) + idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) else: if idx >= len(toks): raise SpirvAsmError(f"line {lineno}: missing operand {sk} for {opname}") - idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out) + idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) return idx venum = VALUE_ENUMS.get(kind) @@ -339,7 +338,7 @@ def assemble(text: str, target_env: str = "vulkan1.2") -> bytes: for pk in params: if idx >= len(toks): raise SpirvAsmError(f"line {lineno}: missing parameter {pk} for {kind}.{tok}") - idx = encode_operand(pk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out) + idx = encode_operand(pk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) return idx benum = BIT_ENUMS.get(kind) @@ -366,7 +365,7 @@ def assemble(text: str, target_env: str = "vulkan1.2") -> bytes: for pk in params: if idx >= len(toks): raise SpirvAsmError(f"line {lineno}: missing parameter {pk} for {kind} {tok!r}") - idx = encode_operand(pk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out) + idx = encode_operand(pk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) return idx raise SpirvAsmError(f"line {lineno}: unsupported operand kind {kind!r}") @@ -452,26 +451,26 @@ def assemble(text: str, target_env: str = "vulkan1.2") -> bytes: ext_imports[res_id] = _EXT_SETS[ext_name] cur_ext_table = None - switch_width = 32 + switch_type = (32, 0) if opname == "OpExtInst" and arg_idx < len(toks): cur_ext_table = ext_imports.get(get_id(toks[arg_idx], lineno)) elif opname == "OpSwitch" and arg_idx < len(toks): sel_id = get_id(toks[arg_idx], lineno) sel_ti = type_info.get(id_to_type.get(sel_id)) if sel_ti and sel_ti[0] == "int": - switch_width = sel_ti[1] + switch_type = (sel_ti[1], sel_ti[2]) for kind, quant in op_specs: if quant == "*": while arg_idx < len(toks): - arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_width, out) + arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_type, out) elif quant == "?": if arg_idx < len(toks): - arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_width, out) + arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_type, out) else: if arg_idx >= len(toks): raise SpirvAsmError(f"line {lineno}: {opname} missing operand ({kind})") - arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_width, out) + arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_type, out) if arg_idx != len(toks): raise SpirvAsmError(f"line {lineno}: {opname} unexpected trailing tokens {toks[arg_idx:]!r}") diff --git a/tools/spirv_gs_to_compute.py b/tools/spirv_gs_to_compute.py index ea63780bf..7ec2a9a29 100644 --- a/tools/spirv_gs_to_compute.py +++ b/tools/spirv_gs_to_compute.py @@ -112,7 +112,7 @@ def layout_of(text): "input_vars": inputs, "output_vars": outputs, "builtins": builtins} -def rewrite(text): +def rewrite(text: str, *, version: tuple[int, int] = (1, 5)) -> tuple[str, dict[str, int | str | list[str]]]: """Return (compute module text, layout dict for --layout).""" lay = layout_of(text) defs, _ = parse(text) @@ -130,13 +130,15 @@ def rewrite(text): def k(v): return f"%gsc_k{v}" + # Before SPIR-V 1.3, storage buffers use Uniform with BufferBlock in core SPIR-V. + buffer_storage, buffer_block = ("StorageBuffer", "Block") if version >= (1, 3) else ("Uniform", "BufferBlock") decos = ["OpDecorate %gsc_gid BuiltIn GlobalInvocationId", "OpDecorate %gsc_rt_v4 ArrayStride 16", "OpDecorate %gsc_rt_u ArrayStride 4", "OpDecorate %gsc_pad ArrayStride 4", - "OpDecorate %gsc_in_t Block", "OpMemberDecorate %gsc_in_t 0 Offset 0", + f"OpDecorate %gsc_in_t {buffer_block}", "OpMemberDecorate %gsc_in_t 0 Offset 0", "OpMemberDecorate %gsc_in_t 1 Offset 4", "OpMemberDecorate %gsc_in_t 2 Offset 16", - "OpDecorate %gsc_rec_t Block", "OpMemberDecorate %gsc_rec_t 0 Offset 0", - "OpDecorate %gsc_meta_t Block", "OpMemberDecorate %gsc_meta_t 0 Offset 0", + f"OpDecorate %gsc_rec_t {buffer_block}", "OpMemberDecorate %gsc_rec_t 0 Offset 0", + f"OpDecorate %gsc_meta_t {buffer_block}", "OpMemberDecorate %gsc_meta_t 0 Offset 0", "OpDecorate %gsc_in DescriptorSet 1", "OpDecorate %gsc_in Binding 0", "OpDecorate %gsc_in NonWritable", "OpDecorate %gsc_rec DescriptorSet 1", "OpDecorate %gsc_rec Binding 1", "OpDecorate %gsc_meta DescriptorSet 1", "OpDecorate %gsc_meta Binding 2"] @@ -149,24 +151,27 @@ def rewrite(text): f"%gsc_pad = OpTypeArray {uint} {k(3)}", f"%gsc_in_t = OpTypeStruct {uint} %gsc_pad %gsc_rt_v4", "%gsc_rec_t = OpTypeStruct %gsc_rt_v4", "%gsc_meta_t = OpTypeStruct %gsc_rt_u", - "%gsc_ptr_in_t = OpTypePointer StorageBuffer %gsc_in_t", - "%gsc_ptr_rec_t = OpTypePointer StorageBuffer %gsc_rec_t", - "%gsc_ptr_meta_t = OpTypePointer StorageBuffer %gsc_meta_t", - f"%gsc_ptr_sb_v4 = OpTypePointer StorageBuffer {v4}", - f"%gsc_ptr_sb_u = OpTypePointer StorageBuffer {uint}", - f"%gsc_ptr_sb_f = OpTypePointer StorageBuffer {f32}", + f"%gsc_ptr_in_t = OpTypePointer {buffer_storage} %gsc_in_t", + f"%gsc_ptr_rec_t = OpTypePointer {buffer_storage} %gsc_rec_t", + f"%gsc_ptr_meta_t = OpTypePointer {buffer_storage} %gsc_meta_t", + f"%gsc_ptr_sb_v4 = OpTypePointer {buffer_storage} {v4}", + f"%gsc_ptr_sb_u = OpTypePointer {buffer_storage} {uint}", + f"%gsc_ptr_sb_f = OpTypePointer {buffer_storage} {f32}", f"%gsc_ptr_pv_v4 = OpTypePointer Private {v4}", f"%gsc_ptr_pv_f = OpTypePointer Private {f32}", f"%gsc_ptr_pv_u = OpTypePointer Private {uint}", "%gsc_gid = OpVariable %gsc_ptr_in_v3u Input", - "%gsc_in = OpVariable %gsc_ptr_in_t StorageBuffer", - "%gsc_rec = OpVariable %gsc_ptr_rec_t StorageBuffer", - "%gsc_meta = OpVariable %gsc_ptr_meta_t StorageBuffer", + f"%gsc_in = OpVariable %gsc_ptr_in_t {buffer_storage}", + f"%gsc_rec = OpVariable %gsc_ptr_rec_t {buffer_storage}", + f"%gsc_meta = OpVariable %gsc_ptr_meta_t {buffer_storage}", f"%gsc_n = OpVariable %gsc_ptr_pv_u Private {k(0)}"] out_vars = {v: f"%gsc_out{i}" for i, v in enumerate(outs)} types += [f"{nv} = OpVariable %gsc_ptr_pv_v4 Private" for nv in out_vars.values()] in_slot = {v: i for i, v in enumerate(ins)} gone = set(ins) | set(outs) | {v for v, b in builtins.items() if b in ("PrimitiveId", "InvocationId")} - new_globals = ["%gsc_gid", "%gsc_in", "%gsc_rec", "%gsc_meta", "%gsc_n"] + list(out_vars.values()) + capture_interface = ["%gsc_gid"] + # Before SPIR-V 1.4, the interface only lists Input and Output variables. + if version >= (1, 4): + capture_interface += ["%gsc_in", "%gsc_rec", "%gsc_meta", "%gsc_n"] + list(out_vars.values()) count = 0 @@ -177,14 +182,17 @@ def rewrite(text): out = [] entry_label = None - state = "header" # header -> body (in main, entry block) -> after the entry check + cur_block = None + block_tail = {} + main_start = None + state = "header" # header -> main_entry -> main_vars -> main -> other for ln in text.splitlines(): s = ln.strip() if s == "OpCapability Geometry": continue m = re.match(r"OpEntryPoint Geometry (%\w+) (\"[^\"]*\")(.*)$", s) if m: - iface = [v for v in m.group(3).split() if v not in gone] + new_globals + iface = [v for v in m.group(3).split() if v not in gone] + capture_interface out += [f"OpEntryPoint GLCompute {m.group(1)} {m.group(2)} {' '.join(iface)}", f"OpExecutionMode {m.group(1)} LocalSize {LOCAL_SIZE} 1 1"] continue @@ -205,13 +213,25 @@ def rewrite(text): types = [] if m.group(1) == main: state = "main_entry" + main_start = len(out) out.append(ln) continue if s == "OpFunctionEnd": + if state in ("main", "main_vars") and main_start is not None and block_tail: + # Any block split by the primitive-count check or by OpEmitVertex now terminates in its final + # merge label; update every OpPhi predecessor (including loop-header back-edges) to that label. + for idx in range(main_start, len(out)): + m_phi = re.match(r"^(\s*%\w+\s*=\s*OpPhi\s+%\w+)\s+(.*)$", out[idx]) + if m_phi: + ops = m_phi.group(2).split() + ops[1::2] = [block_tail.get(lbl, lbl) for lbl in ops[1::2]] + out[idx] = f"{m_phi.group(1)} {' '.join(ops)}" state = "other" + cur_block = None if state == "main_entry" and re.match(r"%\w+ = OpLabel$", s): state = "main_vars" entry_label = s.split()[0] + cur_block = entry_label out.append(ln) continue if state == "main_vars" and not re.match(r"%\w+ = OpVariable ", s): @@ -225,18 +245,16 @@ def rewrite(text): f"%gsc_inbase = OpIMul {uint} %gsc_prim {k(vin)}", f"%gsc_recbase = OpIMul {uint} %gsc_prim {k(mv)}", f"%gsc_metabase = OpIMul {uint} %gsc_prim {k(mv + 1)}"] + block_tail[entry_label] = "%gsc_body" if state not in ("main", "main_vars"): out.append(ln) continue # ---- the body of main ---- - # The primitive-count check splits the entry block: what followed its variables now sits in %gsc_body, so - # an OpPhi naming the entry label as a predecessor names %gsc_body instead. - m = re.match(r"(%\w+ = OpPhi %\w+) (.*)$", s) - if m: - ops = m.group(2).split() - ops[1::2] = ["%gsc_body" if lbl == entry_label else lbl for lbl in ops[1::2]] - s = f"{m.group(1)} {' '.join(ops)}" - ln = s + m_lbl = re.match(r"(%\w+) = OpLabel$", s) + if m_lbl: + cur_block = m_lbl.group(1) + out.append(ln) + continue m = re.match(r"(%\w+) = Op(?:InBounds)?AccessChain (%\w+) (%\w+) (.*)$", s) if m and m.group(3) in in_slot: idx = m.group(4).split() @@ -268,17 +286,31 @@ def rewrite(text): break raise Unsupported(f"unhandled use of {v}: {s}") if s == "OpEmitVertex": - n, a = tmp(), tmp() - out += [f"{n} = OpLoad {uint} %gsc_n", f"{a} = OpIAdd {uint} %gsc_recbase {n}"] - for i, nv in enumerate(out_vars.values()): - b, c, val, p = tmp(), tmp(), tmp(), tmp() - out += [f"{b} = OpIMul {uint} {a} {k(nout)}", f"{c} = OpIAdd {uint} {b} {k(i)}", - f"{val} = OpLoad {v4} {nv}", f"{p} = OpAccessChain %gsc_ptr_sb_v4 %gsc_rec {k(0)} {c}", - f"OpStore {p} {val}"] + # Guard stores and counter increment on n < OutputVertices so over-emitting drops extra vertices + # instead of overflowing into primitive p+1's record/meta slots; %gsc_n stays <= mv for OpEndPrimitive + # and OpReturn as well (SHADER-617). + n, ok, lbl_do, lbl_end = tmp(), tmp(), tmp(), tmp() + out += [f"{n} = OpLoad {uint} %gsc_n", + f"{ok} = OpULessThan {boolt} {n} {k(mv)}", + f"OpSelectionMerge {lbl_end} None", + f"OpBranchConditional {ok} {lbl_do} {lbl_end}", + f"{lbl_do} = OpLabel"] + if out_vars: + a = tmp() + out.append(f"{a} = OpIAdd {uint} %gsc_recbase {n}") + for i, nv in enumerate(out_vars.values()): + b, c, val, p = tmp(), tmp(), tmp(), tmp() + out += [f"{b} = OpIMul {uint} {a} {k(nout)}", f"{c} = OpIAdd {uint} {b} {k(i)}", + f"{val} = OpLoad {v4} {nv}", f"{p} = OpAccessChain %gsc_ptr_sb_v4 %gsc_rec {k(0)} {c}", + f"OpStore {p} {val}"] d, e, q, n1 = tmp(), tmp(), tmp(), tmp() out += [f"{d} = OpIAdd {uint} %gsc_metabase {n}", f"{e} = OpIAdd {uint} {d} {k(1)}", f"{q} = OpAccessChain %gsc_ptr_sb_u %gsc_meta {k(0)} {e}", f"OpStore {q} {k(0)}", - f"{n1} = OpIAdd {uint} {n} {k(1)}", f"OpStore %gsc_n {n1}"] + f"{n1} = OpIAdd {uint} {n} {k(1)}", f"OpStore %gsc_n {n1}", + f"OpBranch {lbl_end}", + f"{lbl_end} = OpLabel"] + if cur_block is not None: + block_tail[cur_block] = lbl_end continue if s == "OpEndPrimitive": # flag the last emitted vertex: meta[base + 1 + (n - 1)]; with none emitted this writes the count slot, @@ -330,13 +362,14 @@ def main(argv): dis = os.environ.get("SPIRV_DIS", "spirv-dis") asm = os.environ.get("SPIRV_AS", "spirv-as") text = subprocess.run([dis, "--raw-id", args[0]], check=True, capture_output=True, text=True).stdout + ver = re.search(r"; Version: (\d+)\.(\d+)", text) + version = (int(ver[1]), int(ver[2])) if ver else (1, 5) try: - new, lay = rewrite(text) + new, lay = rewrite(text, version=version) except Unsupported as e: print(f"{args[0]}: not supported: {e}", file=sys.stderr) return 1 - ver = re.search(r"; Version: (\d+)\.(\d+)", text) - target = f"spv{ver.group(1)}.{ver.group(2)}" if ver else "vulkan1.2" + target = f"spv{version[0]}.{version[1]}" if ver else "vulkan1.2" subprocess.run([asm, "--target-env", target, "-", "-o", args[1]], input=new, check=True, text=True) if lay_path: with open(lay_path, "w", encoding="utf-8", newline="\n") as f: diff --git a/tools/spirv_opt.py b/tools/spirv_opt.py new file mode 100644 index 000000000..d9f0e6aa3 --- /dev/null +++ b/tools/spirv_opt.py @@ -0,0 +1,1147 @@ +"""Sound dominator-tree SPIR-V optimizer for tools/rdna2spirv.py output (#884). + +Targets the main source of SPIR-V size and driver compile-time bloat in translated +RDNA2 shaders: per-instruction Function-scope register array OpAccessChain / OpLoad / +OpStore traffic, repeated OpLoad %bool %active guards (including across blocks when +%active is never stored or along single-predecessor CFG edges), duplicate immutable +Input / PushConstant loads, OpSelect on constant booleans, OpCopyObject wrappers, +round-trip OpBitcast pairs, integer/bit constant folding and algebraic identities, +trivial OpPhi nodes, dead local stores, dead Function-scope OpVariables, and dead +SSA temporaries. + +Every transform is strictly sound: + - Only Function-scope OpVariables that do not escape (never passed to OpFunctionCall, + OpAtomic*, OpCopyMemory, etc.) are tracked. + - Dynamic OpAccessChain indices (e.g. v_movrels / s_movrels) are detected per variable: + dynamic stores invalidate all cached slots of that variable in the current block; + dynamic loads prevent killing earlier stores to that variable; variables with any + dynamic index are excluded from whole-function dead-slot and never-stored-slot + elimination. + - Pure value / OpAccessChain / immutable (Input, PushConstant) OpLoad CSE runs in + dominator-tree preorder, guaranteeing SSA dominance for every replacement (including + OpPhi operands). + - Mutable Function-scope slot forwarding inherits across single-predecessor CFG edges + (where the sole predecessor strictly dominates the block) and from whole-function + read-only initializers (never-stored variables or never-stored static slots of + zero-initialized variables), resetting at multi-predecessor joins and loop headers. + Dead overwritten-store elimination stays strictly intra-block. + - Constant folding only replaces an instruction when an existing module OpConstant / + OpConstantTrue / OpConstantFalse already matches the result type and value. + - Pure DCE uses an explicit allowlist of side-effect-free opcodes and drops any + OpDecorate / OpName lines that reference deleted SSA IDs. + +As a module: + from spirv_opt import optimize + opt_spvasm = optimize(spvasm) + +As a CLI: + python3 -I tools/spirv_opt.py input.spvasm -o output.spvasm +""" +import argparse +import sys + +_PURE_OPS = frozenset(( + "OpAccessChain", + "OpCopyObject", + "OpSelect", + "OpBitcast", + "OpIAdd", "OpISub", "OpIMul", "OpUDiv", "OpSDiv", "OpUMod", "OpSMod", "OpSRem", + "OpFAdd", "OpFSub", "OpFMul", "OpFDiv", "OpFNegate", "OpFmaKHR", + "OpBitwiseOr", "OpBitwiseAnd", "OpBitwiseXor", "OpNot", + "OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic", + "OpBitFieldUExtract", "OpBitFieldSExtract", "OpBitFieldInsert", + "OpBitReverse", "OpBitCount", + "OpIEqual", "OpINotEqual", + "OpUGreaterThan", "OpUGreaterThanEqual", "OpULessThan", "OpULessThanEqual", + "OpSGreaterThan", "OpSGreaterThanEqual", "OpSLessThan", "OpSLessThanEqual", + "OpFOrdEqual", "OpFOrdNotEqual", + "OpFOrdGreaterThan", "OpFOrdGreaterThanEqual", "OpFOrdLessThan", "OpFOrdLessThanEqual", + "OpFUnordEqual", "OpFUnordNotEqual", + "OpFUnordGreaterThan", "OpFUnordGreaterThanEqual", "OpFUnordLessThan", "OpFUnordLessThanEqual", + "OpIsNan", "OpIsInf", + "OpLogicalAnd", "OpLogicalOr", "OpLogicalNot", "OpLogicalEqual", "OpLogicalNotEqual", + "OpCompositeConstruct", "OpCompositeExtract", "OpCompositeInsert", + "OpVectorShuffle", "OpVectorExtractDynamic", "OpVectorTimesScalar", + "OpConvertFToU", "OpConvertFToS", "OpConvertSToF", "OpConvertUToF", + "OpUConvert", "OpSConvert", "OpFConvert", "OpQuantizeToF16", + "OpIAddCarry", "OpISubBorrow", "OpUMulExtended", "OpSMulExtended", +)) + +_COMMUTATIVE_OPS = frozenset(( + "OpIAdd", "OpIMul", "OpBitwiseOr", "OpBitwiseAnd", "OpBitwiseXor", + "OpIEqual", "OpINotEqual", "OpLogicalAnd", "OpLogicalOr", + "OpLogicalEqual", "OpLogicalNotEqual", +)) + +_PURE_GLSL_EXT = frozenset(( + "FAbs", "SAbs", "FSign", "SSign", "Floor", "Trunc", "Round", "RoundEven", + "Ceil", "Fract", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", + "Sinh", "Cosh", "Tanh", "Pow", "Exp", "Log", "Exp2", "Log2", + "Sqrt", "InverseSqrt", + "FMin", "UMin", "SMin", "FMax", "UMax", "SMax", + "FClamp", "UClamp", "SClamp", "NMin", "NMax", "NClamp", + "FMix", "Step", "SmoothStep", "Fma", + "PackHalf2x16", "UnpackHalf2x16", + "PackSnorm4x8", "PackUnorm4x8", "PackSnorm2x16", "PackUnorm2x16", + "UnpackSnorm4x8", "UnpackUnorm4x8", "UnpackSnorm2x16", "UnpackUnorm2x16", + "FindILsb", "FindSMsb", "FindUMsb", "Ldexp", "FrexpStruct", "ModfStruct", +)) + + +def _parse_line(line: str): + """Return (res_id_or_None, opname, args_list) for one SPIR-V assembly line, or None if blank/comment.""" + if '"' not in line: + semi = line.find(";") + toks = (line[:semi] if semi >= 0 else line).split() + else: + # Lines with quotes only appear in module header (OpExtension, OpEntryPoint, OpName, OpString). + return None + if not toks: + return None + if len(toks) >= 3 and toks[1] == "=": + return toks[0], toks[2], toks[3:] + return None, toks[0], toks[1:] + + +def _format_inst(res: str | None, op: str, args: list[str]) -> str: + if res is not None: + return f" {res} = {op} {' '.join(args)}" if args else f" {res} = {op}" + return f" {op} {' '.join(args)}" if args else f" {op}" + + +def _to_signed(uval: int, width: int) -> int: + sign_bit = 1 << (width - 1) + return uval - (1 << width) if uval >= sign_bit else uval + + +def _build_cfg_and_dom(insts: list[list]): + """Split function instructions into basic blocks and compute CFG + dominator tree.""" + blocks: list[list[int]] = [] # block_idx -> list of inst indices (starting with OpLabel) + label_to_block: dict[str, int] = {} + cur: list[int] | None = None + for idx, (res, op, _args, _raw) in enumerate(insts): + if op == "OpLabel" and res is not None: + b = len(blocks) + label_to_block[res] = b + cur = [idx] + blocks.append(cur) + elif cur is not None: + if op == "OpFunctionEnd": + cur = None + else: + cur.append(idx) + + n_blocks = len(blocks) + if n_blocks == 0: + return blocks, [], [], [], {}, [] + + succs: list[list[int]] = [[] for _ in range(n_blocks)] + all_preds: list[set[int]] = [set() for _ in range(n_blocks)] + + for b, b_insts in enumerate(blocks): + seen_s: set[int] = set() + for idx in b_insts: + _, op, args, _ = insts[idx] + targets = () + if op == "OpBranch" and args: + targets = (args[0],) + elif op == "OpBranchConditional" and len(args) >= 3: + targets = (args[1], args[2]) + elif op == "OpSwitch" and len(args) >= 2: + targets = tuple([args[1]] + [args[k] for k in range(3, len(args), 2)]) + for t in targets: + tb = label_to_block.get(t) + if tb is not None: + all_preds[tb].add(b) + if tb not in seen_s: + seen_s.add(tb) + succs[b].append(tb) + + # Iterative DFS from block 0 to compute reverse postorder (RPO) of reachable blocks. + visited = [False] * n_blocks + postorder: list[int] = [] + stack: list[tuple[int, int]] = [(0, 0)] + visited[0] = True + while stack: + b, si = stack[-1] + if si < len(succs[b]): + stack[-1] = (b, si + 1) + nb = succs[b][si] + if not visited[nb]: + visited[nb] = True + stack.append((nb, 0)) + else: + stack.pop() + postorder.append(b) + + rpo = list(reversed(postorder)) + rpo_num = {b: i for i, b in enumerate(rpo)} + + # Cooper-Harvey-Kennedy iterative dominator algorithm on reachable blocks. + idom: dict[int, int] = {0: 0} + + def intersect(b1: int, b2: int) -> int: + while b1 != b2: + while rpo_num[b1] > rpo_num[b2]: + b1 = idom[b1] + while rpo_num[b2] > rpo_num[b1]: + b2 = idom[b2] + return b1 + + dom_changed = True + while dom_changed: + dom_changed = False + for b in rpo[1:]: + new_idom = None + for p in all_preds[b]: + if p in idom: + new_idom = p if new_idom is None else intersect(p, new_idom) + if new_idom is not None and idom.get(b) != new_idom: + idom[b] = new_idom + dom_changed = True + + dom_children: list[list[int]] = [[] for _ in range(n_blocks)] + for b in rpo[1:]: + p = idom.get(b) + if p is not None and p != b: + dom_children[p].append(b) + + return blocks, succs, all_preds, rpo, idom, dom_children + + +def _fold_int_op(op: str, res_ty: str, args: list[str], + const_int_val: dict[str, tuple[str, int, int, int]], + int_const_by_val: dict[tuple[str, int], str], + int_type_info: dict[str, tuple[int, int]], + const_true_id: str | None, const_false_id: str | None) -> str | None: + """Fold constant/algebraic integer/bit operations into an existing SSA ID, or return None.""" + n = len(args) + if op == "OpNot" and n == 2: + c1 = const_int_val.get(args[1]) + if c1 is not None: + ty, v1, w, _ = c1 + mask = (1 << w) - 1 + return int_const_by_val.get((res_ty, (~v1) & mask)) + return None + + if op == "OpUConvert" and n == 2: + c1 = const_int_val.get(args[1]) + dst_info = int_type_info.get(res_ty) + if c1 is not None and dst_info is not None: + _, v1, _, _ = c1 + dw, _ = dst_info + return int_const_by_val.get((res_ty, v1 & ((1 << dw) - 1))) + return None + + if op == "OpBitFieldUExtract" and n == 4: + base, off_id, cnt_id = args[1], args[2], args[3] + co = const_int_val.get(off_id) + cc = const_int_val.get(cnt_id) + dst_info = int_type_info.get(res_ty) + if co is not None and cc is not None and dst_info is not None: + w, _ = dst_info + off = co[1] + cnt = cc[1] + if off == 0 and cnt == w: + return base + cb = const_int_val.get(base) + if cb is not None and off <= w and cnt <= w and off + cnt <= w: + val = 0 if cnt == 0 else ((cb[1] >> off) & ((1 << cnt) - 1)) + return int_const_by_val.get((res_ty, val)) + return None + + if n != 3: + return None + + a1, a2 = args[1], args[2] + c1 = const_int_val.get(a1) + c2 = const_int_val.get(a2) + + # Full constant folding when both operands are known integer constants. + if c1 is not None and c2 is not None: + _, v1, w1, _ = c1 + _, v2, w2, _ = c2 + mask = (1 << w1) - 1 + if op == "OpIAdd": + return int_const_by_val.get((res_ty, (v1 + v2) & mask)) + if op == "OpISub": + return int_const_by_val.get((res_ty, (v1 - v2) & mask)) + if op == "OpIMul": + return int_const_by_val.get((res_ty, (v1 * v2) & mask)) + if op == "OpUDiv" and v2 != 0: + return int_const_by_val.get((res_ty, (v1 // v2) & mask)) + if op == "OpUMod" and v2 != 0: + return int_const_by_val.get((res_ty, (v1 % v2) & mask)) + if op == "OpBitwiseAnd": + return int_const_by_val.get((res_ty, (v1 & v2) & mask)) + if op == "OpBitwiseOr": + return int_const_by_val.get((res_ty, (v1 | v2) & mask)) + if op == "OpBitwiseXor": + return int_const_by_val.get((res_ty, (v1 ^ v2) & mask)) + if op == "OpShiftLeftLogical" and v2 < w1: + return int_const_by_val.get((res_ty, (v1 << v2) & mask)) + if op == "OpShiftRightLogical" and v2 < w1: + return int_const_by_val.get((res_ty, (v1 >> v2) & mask)) + if op == "OpShiftRightArithmetic" and v2 < w1: + sv1 = _to_signed(v1, w1) + return int_const_by_val.get((res_ty, (sv1 >> v2) & mask)) + if const_true_id is not None and const_false_id is not None and w1 == w2: + if op == "OpIEqual": + return const_true_id if v1 == v2 else const_false_id + if op == "OpINotEqual": + return const_true_id if v1 != v2 else const_false_id + if op == "OpULessThan": + return const_true_id if v1 < v2 else const_false_id + if op == "OpULessThanEqual": + return const_true_id if v1 <= v2 else const_false_id + if op == "OpUGreaterThan": + return const_true_id if v1 > v2 else const_false_id + if op == "OpUGreaterThanEqual": + return const_true_id if v1 >= v2 else const_false_id + sv1, sv2 = _to_signed(v1, w1), _to_signed(v2, w2) + if op == "OpSLessThan": + return const_true_id if sv1 < sv2 else const_false_id + if op == "OpSLessThanEqual": + return const_true_id if sv1 <= sv2 else const_false_id + if op == "OpSGreaterThan": + return const_true_id if sv1 > sv2 else const_false_id + if op == "OpSGreaterThanEqual": + return const_true_id if sv1 >= sv2 else const_false_id + return None + + # Algebraic identities with one constant or identical operands (all bit-exact for SPIR-V ints). + dst_info = int_type_info.get(res_ty) + dst_mask = (1 << dst_info[0]) - 1 if dst_info is not None else None + + if op == "OpIAdd": + if c2 is not None and c2[1] == 0: + return a1 + if c1 is not None and c1[1] == 0: + return a2 + elif op == "OpISub": + if c2 is not None and c2[1] == 0: + return a1 + if a1 == a2: + return int_const_by_val.get((res_ty, 0)) + elif op == "OpIMul": + if c2 is not None: + if c2[1] == 1: + return a1 + if c2[1] == 0: + return a2 + if c1 is not None: + if c1[1] == 1: + return a2 + if c1[1] == 0: + return a1 + elif op == "OpBitwiseAnd": + if a1 == a2: + return a1 + if c2 is not None: + if c2[1] == 0: + return a2 + if dst_mask is not None and c2[1] == dst_mask: + return a1 + if c1 is not None: + if c1[1] == 0: + return a1 + if dst_mask is not None and c1[1] == dst_mask: + return a2 + elif op == "OpBitwiseOr": + if a1 == a2: + return a1 + if c2 is not None: + if c2[1] == 0: + return a1 + if dst_mask is not None and c2[1] == dst_mask: + return a2 + if c1 is not None: + if c1[1] == 0: + return a2 + if dst_mask is not None and c1[1] == dst_mask: + return a1 + elif op == "OpBitwiseXor": + if a1 == a2: + return int_const_by_val.get((res_ty, 0)) + if c2 is not None and c2[1] == 0: + return a1 + if c1 is not None and c1[1] == 0: + return a2 + elif op in ("OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic"): + if c2 is not None and c2[1] == 0: + return a1 + if op != "OpShiftRightArithmetic" and c1 is not None and c1[1] == 0: + return a1 + elif op == "OpIEqual" and a1 == a2: + return const_true_id + elif op == "OpINotEqual" and a1 == a2: + return const_false_id + return None + + +def _optimize_function(body_lines: list[str], const_ids: set[str], const_true: set[str], + const_false: set[str], const_null_elem_zero: dict[str, str], + const_type: dict[str, str], const_int_val: dict[str, tuple[str, int, int, int]], + int_const_by_val: dict[tuple[str, int], str], + int_type_info: dict[str, tuple[int, int]], + readonly_global_vars: set[str], glsl_sets: set[str], + decorated_ids: set[str], max_passes: int = 4) -> tuple[list[str], set[str]]: + """Optimize one OpFunction ... OpFunctionEnd slice. Returns (new_lines, deleted_ids).""" + insts: list[list] = [] + for raw in body_lines: + parsed = _parse_line(raw) + if parsed is None: + insts.append([None, None, None, raw]) + else: + res, op, args = parsed + insts.append([res, op, args, raw]) + + deleted_ids: set[str] = set() + const_true_id = next(iter(const_true)) if const_true else None + const_false_id = next(iter(const_false)) if const_false else None + + for _pass in range(max_passes): + changed = False + + # 1. Discover Function-scope variables, pointer-to-slot mappings, escapes, dynamic indices, + # result types, and which variables / static slots are ever stored to. + func_vars: dict[str, str | None] = {} # var_id -> initializer_id or None + ptr_root: dict[str, str] = {} # ptr_id -> root var_id (Function or readonly global) + ptr_slot: dict[str, tuple | None] = {} # ptr_id -> (var_id, *canonical_const_indices) or None + escaped: set[str] = set() + dyn_indexed: set[str] = set() + id_type: dict[str, str] = dict(const_type) + + for res, op, args, _ in insts: + if op is None: + continue + if res is not None and args and op != "OpLabel": + id_type[res] = args[0] + if op == "OpVariable" and len(args) >= 2 and args[1] == "Function" and res: + init = args[2] if len(args) >= 3 else None + func_vars[res] = init + ptr_root[res] = res + ptr_slot[res] = (res,) + elif op == "OpAccessChain" and res and len(args) >= 2: + base = args[1] + idxs = args[2:] + if base in ptr_root: + root = ptr_root[base] + ptr_root[res] = root + base_slot = ptr_slot.get(base) + if base_slot is not None and all(i in const_int_val for i in idxs): + # Canonicalize integer index constants by unsigned value so %uint_0 and %int_0 alias. + cidxs = tuple(const_int_val[i][1] for i in idxs) + ptr_slot[res] = base_slot + cidxs + else: + ptr_slot[res] = None + if root in func_vars: + dyn_indexed.add(root) + elif base in readonly_global_vars: + ptr_root[res] = base + + slot_depths: dict[str, set[int]] = {} + for res, op, args, _ in insts: + if op is None: + continue + if op == "OpLoad": + if len(args) >= 2 and args[1] in ptr_root and ptr_root[args[1]] in func_vars: + root = ptr_root[args[1]] + if any("Volatile" in m for m in args[2:]): + escaped.add(root) + sl = ptr_slot.get(args[1]) + if sl is not None: + slot_depths.setdefault(root, set()).add(len(sl)) + for tok in args[2:]: + if tok in ptr_root and ptr_root[tok] in func_vars: + escaped.add(ptr_root[tok]) + elif op == "OpStore": + if len(args) >= 2 and args[0] in ptr_root and ptr_root[args[0]] in func_vars: + root = ptr_root[args[0]] + if any("Volatile" in m for m in args[2:]): + escaped.add(root) + sl = ptr_slot.get(args[0]) + if sl is not None: + slot_depths.setdefault(root, set()).add(len(sl)) + for tok in args[1:]: + if tok in ptr_root and ptr_root[tok] in func_vars: + escaped.add(ptr_root[tok]) + elif op == "OpAccessChain": + for tok in args[2:]: + if tok in ptr_root and ptr_root[tok] in func_vars: + escaped.add(ptr_root[tok]) + elif op != "OpVariable": + for tok in args: + if tok in ptr_root and ptr_root[tok] in func_vars: + escaped.add(ptr_root[tok]) + + # Exclude variables accessed at mixed aggregate/subobject depths (e.g. whole array + element pointer). + for root, depths in slot_depths.items(): + if len(depths) > 1: + escaped.add(root) + + trackable = {v for v in func_vars if v not in escaped} + static_trackable = {v for v in trackable if v not in dyn_indexed} + + # Identify which trackable vars and static slots ever receive an OpStore in the function. + stored_vars: set[str] = set() + stored_slots: set[tuple] = set() + for _res, op, args, _ in insts: + if op == "OpStore" and len(args) >= 2: + ptr = args[0] + root = ptr_root.get(ptr) + if root in trackable: + stored_vars.add(root) + slot = ptr_slot.get(ptr) + if slot is not None: + stored_slots.add(slot) + + # Function-wide immutable facts for never-stored trackable variables (e.g. %active in non-divergent shaders). + readonly_slot_val: dict[tuple, str] = {} + readonly_null_zero: dict[str, str] = {} + for v in trackable: + if v in stored_vars: + continue + init = func_vars[v] + if init is None: + continue + if init in const_null_elem_zero: + readonly_null_zero[v] = const_null_elem_zero[init] + elif init in const_ids: + readonly_slot_val[(v,)] = init + + # Never-stored static zero-initialized array variables: individual slots with zero stores are always zero. + static_null_zero: dict[str, str] = {} + for v in static_trackable: + init = func_vars[v] + if init is not None and init in const_null_elem_zero and (v,) not in stored_slots: + static_null_zero[v] = const_null_elem_zero[init] + + # 2. Build CFG + dominator tree and run dominator-tree preorder optimization pass. + blocks, _succs, all_preds, rpo, idom, dom_children = _build_cfg_and_dom(insts) + alias: dict[str, str] = {} + + def resolve(tok: str) -> str: + cur = tok + while cur in alias: + cur = alias[cur] + if cur != tok: + alias[tok] = cur + return cur + + dead_idx: set[int] = set() + + # Scoped dominator-tree tables (maintained via undo logs during iterative DFS). + ac_cse: dict[tuple, str] = {} + val_cse: dict[tuple, str] = {} + ro_load_cse: dict[tuple, str] = {} # (res_ty, ptr_id) -> loaded_id for Input / PushConstant + bitcast_of: dict[str, tuple[str, str]] = {} # res_id -> (src_id, src_type_id) + bool_mask_of: dict[str, tuple[str, bool]] = {} # res_id -> (cond_id, True if cond->nz/!cond->0 else inverted) + ctor_elems: dict[str, list[str]] = {} # composite_id -> list of constituent IDs + logical_not_of: dict[str, str] = {} # res_id -> inner bool ID + + def process_block(b: int, slot_val: dict[tuple, str], entry_null_zero: dict[str, str], + reachable: bool): + nonlocal changed + last_store: dict[tuple, int] = {} + undo_ac: list[tuple] = [] + undo_val: list[tuple] = [] + undo_ro: list[tuple] = [] + undo_bc: list[str] = [] + undo_bm: list[str] = [] + undo_ce: list[str] = [] + undo_ln: list[str] = [] + + for idx in blocks[b]: + entry = insts[idx] + res, op, args, _ = entry + if op is None or op == "OpLabel": + continue + + if alias and args: + new_args = [resolve(t) if t.startswith("%") else t for t in args] + if new_args != args: + entry[2] = new_args + args = new_args + changed = True + + # Trivial OpPhi simplification (only in reachable blocks so dominance is guaranteed). + if op == "OpPhi" and reachable and res is not None and res not in decorated_ids and len(args) >= 3: + vals = [args[k] for k in range(1, len(args), 2)] + non_self = {v for v in vals if v != res} + if len(non_self) == 1: + alias[res] = next(iter(non_self)) + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + + # Algebraic / copy / constant-fold / round-trip bitcast simplifications + if res is not None and res not in decorated_ids: + if op == "OpCopyObject" and len(args) == 2: + alias[res] = args[1] + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if op == "OpBitcast" and len(args) == 2: + dst_ty, src = args[0], args[1] + prev_bc = bitcast_of.get(src) + if prev_bc is not None and prev_bc[1] == dst_ty: + alias[res] = prev_bc[0] + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + src_ty = id_type.get(src) + if src_ty is not None: + bitcast_of[res] = (src, src_ty) + undo_bc.append(res) + if op == "OpCompositeConstruct" and len(args) >= 2: + ctor_elems[res] = args[1:] + undo_ce.append(res) + if op == "OpCompositeExtract" and len(args) == 3 and args[2].isdigit(): + elems = ctor_elems.get(args[1]) + if elems is not None: + k = int(args[2]) + if k < len(elems) and all(id_type.get(e) == args[0] for e in elems): + alias[res] = elems[k] + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if op == "OpSelect" and len(args) == 4: + cond, x, y = args[1], args[2], args[3] + if cond in const_true or x == y: + alias[res] = x + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if cond in const_false: + alias[res] = y + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if x in const_true and y in const_false: + alias[res] = cond + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + cx = const_int_val.get(x) + cy = const_int_val.get(y) + if cx is not None and cy is not None: + if cx[1] != 0 and cy[1] == 0: + bool_mask_of[res] = (cond, True) + undo_bm.append(res) + elif cx[1] == 0 and cy[1] != 0: + bool_mask_of[res] = (cond, False) + undo_bm.append(res) + if op == "OpLogicalNot" and len(args) == 2: + inner = args[1] + if inner in const_true and const_false_id is not None: + alias[res] = const_false_id + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if inner in const_false and const_true_id is not None: + alias[res] = const_true_id + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + prev_not = logical_not_of.get(inner) + if prev_not is not None: + alias[res] = prev_not + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + logical_not_of[res] = inner + undo_ln.append(res) + if op == "OpLogicalAnd" and len(args) == 3: + a1, a2 = args[1], args[2] + if a1 == a2 or a2 in const_true: + alias[res] = a1 + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if a1 in const_true: + alias[res] = a2 + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if a1 in const_false: + alias[res] = a1 + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if a2 in const_false: + alias[res] = a2 + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if op == "OpLogicalOr" and len(args) == 3: + a1, a2 = args[1], args[2] + if a1 == a2 or a2 in const_false: + alias[res] = a1 + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if a1 in const_false: + alias[res] = a2 + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if a1 in const_true: + alias[res] = a1 + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if a2 in const_true: + alias[res] = a2 + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + if op in ("OpINotEqual", "OpIEqual") and len(args) == 3: + a1, a2 = args[1], args[2] + for cand, other in ((a1, a2), (a2, a1)): + bm = bool_mask_of.get(cand) + co = const_int_val.get(other) + if bm is not None and co is not None and co[1] == 0: + cond_id, normal = bm + if (op == "OpINotEqual" and normal) or (op == "OpIEqual" and not normal): + alias[res] = cond_id + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + break + if idx in dead_idx: + continue + + # Integer/bit constant folding & algebraic identities + folded = _fold_int_op( + op, args[0], args, const_int_val, int_const_by_val, + int_type_info, const_true_id, const_false_id, + ) + if folded is not None: + alias[res] = folded + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + + # Dominator-scoped OpAccessChain CSE + if op == "OpAccessChain" and res is not None and res not in decorated_ids: + key = tuple(args) + prev = ac_cse.get(key) + if prev is not None: + alias[res] = prev + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + ac_cse[key] = res + undo_ac.append(key) + continue + + # Dominator-scoped pure-value CSE (with commutative operand canonicalization) + if res is not None and res not in decorated_ids and ( + op in _PURE_OPS or (op == "OpExtInst" and len(args) >= 3 and args[1] in glsl_sets and args[2] in _PURE_GLSL_EXT) + ): + if op in _COMMUTATIVE_OPS and len(args) == 3 and args[1] > args[2]: + key = (op, (args[0], args[2], args[1])) + else: + key = (op, tuple(args)) + prev = val_cse.get(key) + if prev is not None: + alias[res] = prev + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + val_cse[key] = res + undo_val.append(key) + continue + + # OpLoad forwarding & CSE (Function-scope slots + immutable Input/PushConstant globals) + if op == "OpLoad" and res is not None and len(args) >= 2: + ptr = args[1] + volatile = any("Volatile" in m for m in args[2:]) + root = ptr_root.get(ptr) + if not volatile and root in trackable: + slot = ptr_slot.get(ptr) + if slot is not None: + cached = slot_val.get(slot) + if cached is None and len(slot) == 2: + if root in entry_null_zero: + cached = entry_null_zero[root] + elif root in static_null_zero and slot not in stored_slots: + cached = static_null_zero[root] + if cached is not None and res not in decorated_ids: + alias[res] = cached + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + slot_val[slot] = res + last_store.pop(slot, None) + else: + # Dynamic load from root: protect all pending intra-block stores to root. + for s in [k for k in last_store if k[0] == root]: + last_store.pop(s, None) + elif not volatile and (root in readonly_global_vars or ptr in readonly_global_vars) and res not in decorated_ids: + ro_key = (args[0], ptr) + prev = ro_load_cse.get(ro_key) + if prev is not None: + alias[res] = prev + dead_idx.add(idx) + deleted_ids.add(res) + changed = True + continue + ro_load_cse[ro_key] = res + undo_ro.append(ro_key) + continue + + # Function-scope OpStore tracking & redundant/overwritten store elimination + if op == "OpStore" and len(args) >= 2: + ptr, val = args[0], args[1] + volatile = any("Volatile" in m for m in args[2:]) + root = ptr_root.get(ptr) + if not volatile and root in trackable: + slot = ptr_slot.get(ptr) + if slot is not None: + cur_val = slot_val.get(slot) + if cur_val is None and root in entry_null_zero and len(slot) == 2: + cur_val = entry_null_zero[root] + if cur_val == val: + dead_idx.add(idx) + changed = True + continue + prev_st = last_store.get(slot) + if prev_st is not None: + dead_idx.add(prev_st) + changed = True + slot_val[slot] = val + last_store[slot] = idx + else: + entry_null_zero.pop(root, None) + for s in [k for k in slot_val if k[0] == root]: + slot_val.pop(s, None) + for s in [k for k in last_store if k[0] == root]: + last_store.pop(s, None) + continue + + return undo_ac, undo_val, undo_ro, undo_bc, undo_bm, undo_ce, undo_ln + + if blocks: + # Initial state for entry block 0. + entry_sv = dict(readonly_slot_val) + entry_nz = dict(readonly_null_zero) + if not all_preds[0]: + for v in trackable: + init = func_vars[v] + if init is None: + continue + if init in const_null_elem_zero: + entry_nz[v] = const_null_elem_zero[init] + elif init in const_ids: + entry_sv[(v,)] = init + + # Iterative dominator-tree preorder DFS. + dfs: list[tuple] = [("enter", 0, entry_sv, entry_nz)] + while dfs: + frame = dfs.pop() + if frame[0] == "enter": + _, b, sv, nz = frame + undos = process_block(b, sv, nz, reachable=True) + dfs.append(("exit", undos)) + for ch in reversed(dom_children[b]): + if all_preds[ch] == {b}: + dfs.append(("enter", ch, dict(sv), dict(nz))) + else: + dfs.append(("enter", ch, dict(readonly_slot_val), dict(readonly_null_zero))) + else: + undo_ac, undo_val, undo_ro, undo_bc, undo_bm, undo_ce, undo_ln = frame[1] + for k in undo_ac: + del ac_cse[k] + for k in undo_val: + del val_cse[k] + for k in undo_ro: + del ro_load_cse[k] + for k in undo_bc: + del bitcast_of[k] + for k in undo_bm: + del bool_mask_of[k] + for k in undo_ce: + del ctor_elems[k] + for k in undo_ln: + del logical_not_of[k] + + # Process any unreachable blocks (in case spirv-val inspects them) with fresh state. + reachable_set = set(rpo) + for b in range(len(blocks)): + if b not in reachable_set: + undos = process_block(b, dict(readonly_slot_val), dict(readonly_null_zero), reachable=False) + undo_ac, undo_val, undo_ro, undo_bc, undo_bm, undo_ce, undo_ln = undos + for k in undo_ac: + del ac_cse[k] + for k in undo_val: + del val_cse[k] + for k in undo_ro: + del ro_load_cse[k] + for k in undo_bc: + del bitcast_of[k] + for k in undo_bm: + del bool_mask_of[k] + for k in undo_ce: + del ctor_elems[k] + for k in undo_ln: + del logical_not_of[k] + + if dead_idx: + insts = [e for i, e in enumerate(insts) if i not in dead_idx] + + # Post-walk alias resolution sweep (updates backedge operands of OpPhi, etc.). + if alias: + for entry in insts: + _, op, args, _ = entry + if op is None or not args: + continue + new_args = [resolve(t) if t.startswith("%") else t for t in args] + if new_args != args: + entry[2] = new_args + changed = True + + # 3. Whole-function dead-slot store elimination for non-escaped, statically-indexed Function vars: + # if a slot (var, ...) has zero remaining OpLoads anywhere in the function, every OpStore to it is dead. + if static_trackable: + loaded_slots: set[tuple] = set() + for _res, op, args, _ in insts: + if op == "OpLoad" and len(args) >= 2: + slot = ptr_slot.get(args[1]) + if slot is not None and slot[0] in static_trackable: + loaded_slots.add(slot) + dead_stores: set[int] = set() + for idx, (_res, op, args, _) in enumerate(insts): + if op == "OpStore" and len(args) >= 2: + if any("Volatile" in m for m in args[2:]): + continue + slot = ptr_slot.get(args[0]) + if slot is not None and slot[0] in static_trackable and slot not in loaded_slots: + dead_stores.add(idx) + if dead_stores: + insts = [e for i, e in enumerate(insts) if i not in dead_stores] + changed = True + + # 4. Backward pure Dead-Code Elimination (DCE) + dead Function-scope OpVariable removal. + use_count: dict[str, int] = {} + for _res, op, args, _ in insts: + if op is None or not args: + continue + for tok in args: + if tok.startswith("%"): + use_count[tok] = use_count.get(tok, 0) + 1 + + def is_pure_dce_candidate(res: str, op: str, args: list[str]) -> bool: + if op in _PURE_OPS or op == "OpPhi": + return True + if op == "OpExtInst" and len(args) >= 3 and args[1] in glsl_sets and args[2] in _PURE_GLSL_EXT: + return True + if op == "OpLoad" and len(args) >= 2 and not any("Volatile" in m for m in args[2:]): + ptr = args[1] + root = ptr_root.get(ptr) + return root in trackable or root in readonly_global_vars or ptr in readonly_global_vars + if op == "OpVariable" and len(args) >= 2 and args[1] == "Function" and res in trackable: + return True + return False + + dce_dead: set[int] = set() + for idx in range(len(insts) - 1, -1, -1): + res, op, args, _ = insts[idx] + if res is None or op is None: + continue + if use_count.get(res, 0) == 0 and is_pure_dce_candidate(res, op, args): + dce_dead.add(idx) + deleted_ids.add(res) + for tok in args: + if tok.startswith("%"): + use_count[tok] = use_count.get(tok, 0) - 1 + + if dce_dead: + insts = [e for i, e in enumerate(insts) if i not in dce_dead] + changed = True + + if not changed: + break + + out_lines = [] + for res, op, args, raw in insts: + if op is None or op in ("OpFunction", "OpFunctionEnd", "OpLabel", "OpVariable"): + out_lines.append(raw) + else: + out_lines.append(_format_inst(res, op, args)) + return out_lines, deleted_ids + + +def optimize(spvasm: str, max_passes: int = 4) -> str: + """Apply sound dominator-tree SPIR-V optimizations to a SPIR-V assembly module.""" + lines = spvasm.splitlines() + + # Scan module header for constants, integer types, immutable globals, GLSL ext sets, decorations. + const_ids: set[str] = set() + const_true: set[str] = set() + const_false: set[str] = set() + const_type: dict[str, str] = {} + int_type_info: dict[str, tuple[int, int]] = {} # int_type_id -> (width, signedness) + const_int_val: dict[str, tuple[str, int, int, int]] = {} # const_id -> (type_id, uval, width, signedness) + int_const_by_val: dict[tuple[str, int], str] = {} # (type_id, uval) -> const_id + array_elem_type: dict[str, str] = {} # arr_type_id -> elem_type_id + zero_const_of_type: dict[str, str] = {} # scalar_type_id -> zero_const_id + const_null_type: dict[str, str] = {} # null_const_id -> array_type_id + readonly_global_vars: set[str] = set() # PushConstant and Input OpVariables + glsl_sets: set[str] = set() + decorated_ids: set[str] = set() + + func_ranges: list[tuple[int, int]] = [] + fn_start = None + for i, raw in enumerate(lines): + if fn_start is None: + if "OpExtInstImport" in raw and '"GLSL.std.450"' in raw: + lhs = raw.split("=", 1)[0].strip() + if lhs.startswith("%"): + glsl_sets.add(lhs) + continue + parsed = _parse_line(raw) + if parsed is None: + continue + res, op, args = parsed + if op == "OpFunction": + fn_start = i + continue + if op == "OpDecorate" and args: + decorated_ids.add(args[0]) + elif op == "OpTypeInt" and res and len(args) >= 2: + try: + w, s = int(args[0]), int(args[1]) + if w in (8, 16, 32, 64): + int_type_info[res] = (w, s) + except ValueError: + pass + elif op == "OpConstant" and res and len(args) >= 2: + const_ids.add(res) + const_type[res] = args[0] + if args[1] in ("0", "0x0", "0.0"): + zero_const_of_type.setdefault(args[0], res) + info = int_type_info.get(args[0]) + if info is not None: + try: + w, s = info + uval = int(args[1], 0) & ((1 << w) - 1) + const_int_val[res] = (args[0], uval, w, s) + int_const_by_val.setdefault((args[0], uval), res) + if uval == 0: + zero_const_of_type.setdefault(args[0], res) + except ValueError: + pass + elif op == "OpConstantTrue" and res and args: + const_ids.add(res) + const_true.add(res) + const_type[res] = args[0] + elif op == "OpConstantFalse" and res and args: + const_ids.add(res) + const_false.add(res) + const_type[res] = args[0] + elif op == "OpConstantComposite" and res and args: + const_ids.add(res) + const_type[res] = args[0] + elif op == "OpConstantNull" and res and args: + const_ids.add(res) + const_type[res] = args[0] + const_null_type[res] = args[0] + elif op == "OpTypeArray" and res and args: + array_elem_type[res] = args[0] + elif op == "OpVariable" and res and len(args) >= 2 and args[1] in ("PushConstant", "Input"): + readonly_global_vars.add(res) + else: + parsed = _parse_line(raw) + if parsed is not None and parsed[1] == "OpFunctionEnd": + func_ranges.append((fn_start, i + 1)) + fn_start = None + + if not func_ranges: + return spvasm + + const_null_elem_zero: dict[str, str] = {} + for null_id, arr_ty in const_null_type.items(): + elem_ty = array_elem_type.get(arr_ty) + if elem_ty and elem_ty in zero_const_of_type: + const_null_elem_zero[null_id] = zero_const_of_type[elem_ty] + + all_deleted: set[str] = set() + opt_funcs: dict[int, list[str]] = {} + for start, end in func_ranges: + new_body, deleted = _optimize_function( + lines[start:end], const_ids, const_true, const_false, + const_null_elem_zero, const_type, const_int_val, int_const_by_val, + int_type_info, readonly_global_vars, glsl_sets, decorated_ids, + max_passes=max_passes, + ) + opt_funcs[start] = new_body + all_deleted.update(deleted) + + # Reassemble module, dropping OpDecorate / OpName lines that target deleted SSA IDs. + out: list[str] = [] + func_map = {start: (end, opt_funcs[start]) for start, end in func_ranges} + i = 0 + n = len(lines) + while i < n: + if i in func_map: + end, new_body = func_map[i] + out.extend(new_body) + i = end + continue + raw = lines[i] + if all_deleted: + stripped = raw.lstrip() + if stripped.startswith(("OpDecorate ", "OpName ")): + toks = stripped.split(None, 2) + if len(toks) >= 2 and toks[1] in all_deleted: + i += 1 + continue + out.append(raw) + i += 1 + return "\n".join(out) + ("\n" if spvasm.endswith("\n") else "") + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description="Sound dominator-tree SPIR-V optimizer.") + ap.add_argument("src", help="input .spvasm file") + ap.add_argument("-o", "--out", required=True, help="output .spvasm file") + ap.add_argument("--passes", type=int, default=4, help="max optimization passes (default: 4)") + args = ap.parse_args(argv) + with open(args.src, encoding="utf-8") as f: + text = f.read() + opt = optimize(text, max_passes=args.passes) + with open(args.out, "w", encoding="utf-8", newline="\n") as f: + f.write(opt) + return 0 + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/swizzle_search.py b/tools/swizzle_search.py index 275cf9bda..f5e4c5757 100644 --- a/tools/swizzle_search.py +++ b/tools/swizzle_search.py @@ -9,11 +9,12 @@ Usage: """ import argparse import itertools +import os import sys import numpy as np -sys.path.insert(0, __import__("os").path.dirname(__file__)) +sys.path.insert(0, os.path.dirname(__file__)) from tile_probe import block_feature, score, same_report_path # noqa: E402 @@ -90,7 +91,28 @@ def render(data, bpe, tile_bytes, wpx, seq, out): Image.open(io.BytesIO(body + lin.tobytes())).convert("RGB").save(out) -def main(): +def validate_out_path(path): + """Return an error string if `path` cannot be used as a --out image file, or None.""" + if not path or not path.strip(): + return "--out path must not be empty" + if "\x00" in path: + return "--out path contains a NUL byte" + if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path): + return f"--out path is a directory: {path}" + cur = os.path.dirname(os.path.abspath(path)) + while cur: + if os.path.isdir(cur): + break + if os.path.lexists(cur): + return f"--out parent is not a directory: {cur}" + nxt = os.path.dirname(cur) + if nxt == cur: + break + cur = nxt + return None + + +def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument("blob") ap.add_argument("--bpe", type=int, default=8) @@ -98,11 +120,18 @@ def main(): ap.add_argument("--widths", default="1024,2048") ap.add_argument("--tiles", type=int, default=48, help="target number of tiles to score (default: 48)") ap.add_argument("--out") - a = ap.parse_args() - if a.out and same_report_path(a.out, a.blob): - ap.error("--out would overwrite the input blob") + a = ap.parse_args(argv) + if a.out is not None: + out_err = validate_out_path(a.out) + if out_err: + print(f"ERROR: {out_err}", file=sys.stderr) + return 2 + if same_report_path(a.out, a.blob): + ap.error("--out would overwrite the input blob") if a.bpe < 1: ap.error("--bpe must be at least 1") + if a.bpe not in (8, 16): + ap.error("--bpe must be 8 or 16") if a.tile < a.bpe or a.tile % a.bpe: ap.error("--tile must be a multiple of --bpe and at least --bpe") blocks = a.tile // a.bpe @@ -125,11 +154,19 @@ def main(): res = search(data, a.bpe, a.tile, widths, a.tiles) for s, w, seq in res[:8]: print(f"score {s:7.2f} width {w:5} bits(low->high) {seq}") - if a.out: + if a.out is not None: if not res: print("ERROR: no layout fits the input, tile size and requested widths", file=sys.stderr) return 1 - render(data, a.bpe, a.tile, res[0][1], res[0][2], a.out) + parent = os.path.dirname(os.path.abspath(a.out)) + try: + if parent: + os.makedirs(parent, exist_ok=True) + render(data, a.bpe, a.tile, res[0][1], res[0][2], a.out) + except (OSError, ValueError) as e: + detail = getattr(e, "strerror", None) or str(e) + print(f"ERROR: cannot write {a.out}: {detail}", file=sys.stderr) + return 2 print("preview ->", a.out) diff --git a/tools/tex_export.py b/tools/tex_export.py index 597b5a24e..bd8f76fdc 100644 --- a/tools/tex_export.py +++ b/tools/tex_export.py @@ -117,11 +117,12 @@ def export_one(t, carve, out, blob_cache, png=False): bpe, blk = FMT[fmt] w, h = t["w"], t["h"] we, he = (w + blk - 1) // blk, (h + blk - 1) // blk - key = (t["archive"], t["gpu"]) + chain_offs = tuple(off for off, _ in (t.get("gpu_chain") or ((t["gpu"], t["gpu_size"]),))) + key = (t["archive"], chain_offs) if key not in blob_cache: blob_cache.clear() parts = [] - for off, _ in t.get("gpu_chain") or [[t["gpu"], t["gpu_size"]]]: + for off in chain_offs: with open(os.path.join(carve, t["archive"], f"{off:012x}.bin"), "rb") as f: parts.append(f.read()) blob_cache[key] = b"".join(parts) diff --git a/tools/tex_headers.py b/tools/tex_headers.py index c1ffd57c4..9948d9782 100644 --- a/tools/tex_headers.py +++ b/tools/tex_headers.py @@ -18,6 +18,7 @@ import argparse import array import json import os +import stat import struct import sys from collections import Counter @@ -207,6 +208,116 @@ def gfx10_tile_bytes(mode): return COMPACT_TILE_64K if gfx10_tile_mode(mode) == 0 else COMPACT_TILE_4K +def joaat(s: str) -> int: + """Standard Jenkins One-at-a-Time 32-bit hash of lowercase ASCII string.""" + h = 0 + for c in s.lower().encode("latin-1", "replace"): + h = (h + c) & 0xFFFFFFFF + h = (h + (h << 10)) & 0xFFFFFFFF + h ^= h >> 6 + h = (h + (h << 3)) & 0xFFFFFFFF + h ^= h >> 11 + return (h + (h << 15)) & 0xFFFFFFFF + + +def is_system_pointer(val: int, max_len: int) -> bool: + """Validate that the pointer is strictly in the system page segment (0x50000000..0x5FFFFFFF).""" + if (val >> 28) != 5: + return False + offset = val & 0x0FFFFFFF + return 0 < offset + 8 <= max_len + + +def parse_texture_dict_page(data: bytes): + """Parse a small RAGE texture dictionary system page (e.g. the 400-byte stream in textures.rpf). + + Layout: + +0x20: 64-bit pointer to hash array (optional in synthetic tests) + +0x30: 64-bit pointer to grcTexture descriptor pointer array (optional in synthetic tests) + +0x38: u16 texture count (optional in synthetic tests) + +0x140..pointers_off: null-separated lower-case ASCII texture names + pointers_off (+0x170 or +0x178): array of 64-bit pointers to grcTexture descriptors (tagged 0x5...) + hashes_off (+0x180 or +0x188): array of 32-bit joaat32 name hashes + Within each grcTexture descriptor: + +0x10: dtype (0x980) + +0x18: data pointer (0x60000000 + GPU data offset) + +0x38: u16 width, u16 height, u16 depth, u8 b6, u8 DXGI format + +0x40: u64 flags (bits 16..23: mip count) + """ + if len(data) < 400: + raise ValueError(f"texture dictionary page truncated: expected >= 400 bytes, got {len(data)}") + + pointers_off = None + hashes_off = None + count = 2 + + # Check pgDictionary header at 0x20 / 0x30 + if len(data) >= 0x40: + h_cand = struct.unpack_from(" len(data): + break + raw_ptr = struct.unpack_from("> 28) != 5: + continue + ptr = raw_ptr & 0x0FFFFFFF + if ptr == 0 or ptr + 0x48 > len(data): + continue + dtype = struct.unpack_from("> 16) & 0xFF + name = names_by_hash.get(thash, f"tex_{thash:08x}") + textures.append({ + "name": name, + "hash": thash, + "width": w, + "height": height, + "depth": depth, + "b6": b6, + "mips": mips, + "flags": flags, + "format": fmt, + "format_name": DXGI.get(fmt, f"dxgi{fmt}"), + "data_offset": data_off, + "dtype": dtype, + }) + return textures + + def parse_etpf_texture_record(record): """Parse one 16-byte ETPF texture record (the RDS5 embedded descriptor). @@ -747,6 +858,33 @@ def input_files(carve, archs): yield "blob", entry.path +def report_needs_input_check(carve, archs, path): + """Whether a report path has to be compared with every scanned input. + + A report that already exists as a regular file, is not a symlink and has one link is reachable + only through its own name. When that name is not ``index.json`` or a ``*.bin`` stream, no input + can resolve to it, so the per-file realpath/samefile checks can be skipped. A missing report, + a link, or an input-like name is always compared; an input may also be a symlink to it. + """ + try: + st = os.lstat(path) + except OSError: + return True + if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1: + return True + name = os.path.basename(os.path.realpath(path)).lower() + if name == "index.json" or name.endswith(".bin"): + return True + for arch in archs: + with os.scandir(os.path.join(carve, arch)) as entries: + for entry in entries: + if entry.is_symlink(): + leaf = entry.name.lower() + if leaf == "index.json" or leaf.endswith(".bin"): + return True + return False + + def main(): ap = argparse.ArgumentParser() ap.add_argument("carve") @@ -765,9 +903,10 @@ def main(): path = a.out or os.path.join(a.carve, "textures_index.json") if os.path.isdir(path): ap.error(f"{path} is a directory, not a .json file") - for kind, source in input_files(a.carve, archs): - if same_output_path(source, path): - ap.error(f"output would overwrite an input {kind}: {path}") + if report_needs_input_check(a.carve, archs, path): + for kind, source in input_files(a.carve, archs): + if same_output_path(source, path): + ap.error(f"output would overwrite an input {kind}: {path}") allt = [] for arch in archs: try: diff --git a/tools/texoff_probe.py b/tools/texoff_probe.py index ae9350b47..e548bdc4c 100644 --- a/tools/texoff_probe.py +++ b/tools/texoff_probe.py @@ -119,10 +119,10 @@ def kernel(arch, dim, rows): return out + tsharp._longs(texture(dim)) -def main(): +def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--oracle", choices=("rule", "hw"), default="rule") - a = ap.parse_args() + a = ap.parse_args(argv) if a.oracle == "rule": for name, dim, start, off in ROWS: print(f"{name:16} offset 0x{off:06x} rule {expected(dim, start, off):.0f}") @@ -130,30 +130,33 @@ def main(): import asm import runner try: - oracle = runner.Oracle() + oracle = runner.open_oracle() except runner.Unavailable as e: print(f"hardware oracle unavailable: {e}") return 77 - print(f"device: {oracle.device}") - bad = 0 - for dim in ("2d", "3d"): - rows = [r for r in ROWS if r[1] == dim] - got = {} - for wave in (32, 64): - res = oracle.run([asm.Kernel(kernel(oracle.arch, dim, rows), wave=wave, threads=1, words=len(rows), - raw=True, vgprs=16, sgprs=24)])[0] - if isinstance(res, str): - print(f"{dim} wave{wave}: kernel rejected: {res}") - return 2 - got[wave] = [struct.unpack("AU_\\0