From dd9a9082dc0e5007a20dcb9e4127fd98bc88335a Mon Sep 17 00:00:00 2001 From: JohnVonWells <3764276+JohnVonWells@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:30:03 +0100 Subject: [PATCH] xshader: lower masked and quad byte SADs Add v_msad_u8 to the 32-bit integer forms and v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8 and v_mqsad_u32_u8 in a new quad_sad module. Window k of the S0 pair is bits [8k+31:8k]; each window's SAD against S1 goes into the matching 16- or 32-bit accumulator field of S2. Every result word is computed before any is written, so a destination may overlap S0 or S2. Plain VGPR operands without clamp, op_sel or negation, compute only. The live-in analysis knows the extra source words and wider results. Native RDNA2 execution (tools/native_rdna2/check_sad.py) settled what the ISA text leaves open: the masked forms skip a byte whose S1 byte is zero, the 16-bit fields wrap without clamp, and MODE changes nothing. 81,920 comparisons, no mismatches. tools/check_byte_sad_gpu.py runs the translated shaders on a D3D12 GPU against the same model, with dynamic operands and overlapping destinations: 384 inputs, 6,528 results, zero mismatches. Masking on S0 or a 17-bit field fails it. It joins the translator's GPU checks, and the sad-mad64 negative control now uses a clamped v_msad_u8, which stays refused. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NhDbTJdTcjebsL5u7pwFoY --- evidence/byte-sad-control.json | 354 ++++++++++++++++++ evidence/native-rdna2-byte-sad.json | 61 +++ tests/test_byte_sad_gpu.py | 32 ++ tools/check_byte_sad_gpu.py | 209 +++++++++++ tools/check_sad_mad64_gpu.py | 2 +- tools/check_translator_gpu.py | 1 + tools/native_rdna2/README.md | 8 + tools/native_rdna2/check_model.py | 4 +- tools/native_rdna2/check_sad.py | 91 +++++ tools/native_rdna2/sad.hip | 26 ++ tools/shader-compiler/src/hlsl.rs | 1 + .../src/hlsl/emitter/analysis.rs | 3 +- .../src/hlsl/emitter/vector.rs | 2 +- tools/shader-compiler/src/hlsl/int32.rs | 6 +- tools/shader-compiler/src/hlsl/quad_sad.rs | 111 ++++++ tools/shader-compiler/src/tests/hlsl/int32.rs | 5 +- .../src/tests/hlsl/quad_sad.rs | 64 ++++ 17 files changed, 971 insertions(+), 9 deletions(-) create mode 100644 evidence/byte-sad-control.json create mode 100644 evidence/native-rdna2-byte-sad.json create mode 100644 tests/test_byte_sad_gpu.py create mode 100644 tools/check_byte_sad_gpu.py create mode 100644 tools/native_rdna2/check_sad.py create mode 100644 tools/native_rdna2/sad.hip create mode 100644 tools/shader-compiler/src/hlsl/quad_sad.rs create mode 100644 tools/shader-compiler/src/tests/hlsl/quad_sad.rs diff --git a/evidence/byte-sad-control.json b/evidence/byte-sad-control.json new file mode 100644 index 00000000..dbffd663 --- /dev/null +++ b/evidence/byte-sad-control.json @@ -0,0 +1,354 @@ +{ + "scope": "Synthetic LLVM-assembled v_msad_u8, v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8 and v_mqsad_u32_u8 instructions; dynamic instrumented inputs and observed outputs", + "adapter": "1002:73a5", + "proton": "1794497090 experimental-11.0-20261112-x86_64", + "seed": 1364410692, + "assembly": [ + "v_mov_b32_e32 v20, 0x13572468", + "v_mov_b32_e32 v21, 0x14582569", + "v_mov_b32_e32 v22, 0x1559266a", + "v_mov_b32_e32 v24, 0x165a276b", + "v_mov_b32_e32 v25, 0x175b286c", + "v_mov_b32_e32 v26, 0x185c296d", + "v_mov_b32_e32 v27, 0x195d2a6e", + "v_msad_u8 v30, v20, v22, v24", + "v_qsad_pk_u16_u8 v[32:33], v[20:21], v22, v[24:25]", + "v_mqsad_pk_u16_u8 v[34:35], v[20:21], v22, v[26:27]", + "v_mqsad_u32_u8 v[36:39], v[20:21], v22, v[24:27]", + "v_mov_b32_e32 v40, v24", + "v_mov_b32_e32 v41, v25", + "v_qsad_pk_u16_u8 v[40:41], v[20:21], v22, v[40:41]", + "v_mov_b32_e32 v44, v24", + "v_mov_b32_e32 v45, v25", + "v_mov_b32_e32 v46, v26", + "v_mov_b32_e32 v47, v27", + "v_mqsad_u32_u8 v[44:47], v[20:21], v22, v[44:47]", + "v_mov_b32_e32 v48, v20", + "v_mov_b32_e32 v49, v21", + "v_mqsad_pk_u16_u8 v[48:49], v[48:49], v22, v[24:25]", + "s_endpgm" + ], + "native_words": [ + "7e2802ff", + "13572468", + "7e2a02ff", + "14582569", + "7e2c02ff", + "1559266a", + "7e3002ff", + "165a276b", + "7e3202ff", + "175b286c", + "7e3402ff", + "185c296d", + "7e3602ff", + "195d2a6e", + "d571001e", + "04622d14", + "d5720020", + "04622d14", + "d5730022", + "046a2d14", + "d5750024", + "04622d14", + "7e500318", + "7e520319", + "d5720028", + "04a22d14", + "7e580318", + "7e5a0319", + "7e5c031a", + "7e5e031b", + "d575002c", + "04b22d14", + "7e600314", + "7e620315", + "d5730030", + "04622d30", + "bf810000" + ], + "emitted_sha256": "7c93d32daeed40f01c4b641f54190cb08d5b1906f028344311dc3998130f2ef9", + "shader_cases": 48, + "inputs": 384, + "result_words": 6528, + "compared_words": 18432, + "mismatches": 0, + "failures": [], + "baseline_refused": true, + "negative_controls": [ + { + "kind": "clamp", + "assembly": [ + "v_qsad_pk_u16_u8 v[0:1], v[2:3], v4, v[6:7] clamp", + "s_endpgm" + ], + "refusal": "unsupported quad SAD encoding or modifiers [v_qsad_pk_u16_u8 @ 0x0]" + }, + { + "kind": "scalar_source", + "assembly": [ + "v_mqsad_u32_u8 v[0:3], s[2:3], v4, v[8:11]", + "s_endpgm" + ], + "refusal": "unsupported quad SAD operand [v_mqsad_u32_u8 @ 0x0]" + }, + { + "kind": "inline_accumulator", + "assembly": [ + "v_msad_u8 v0, v1, v2, 0", + "s_endpgm" + ], + "refusal": "unsupported ordinary 32-bit integer source or encoding [v_msad_u8 @ 0x0]" + } + ], + "tool_sha256": { + "emitter": "4d193cdb69d73d8eb4569128d234ee0fed5d82e2054d6fc4253332717e9d74e9", + "dxc": "3dfc856b76291ffc7e45e21fd37ab80e85b34101de76a03253df6608785c92a0", + "dxv": "33778294d67143d9f81526f4759c66d5a67a95ea9873448ef3595650a643cbd3", + "provider": "e52c8a378ed0edf777a4aabe8cf6236d6133b0aeac9084bfd7e574c7978d3870", + "baseline": "2d64f7b32e6994020d17338cb280490b6e82412987410c3c4d677ccf5aa711ac" + }, + "guest_sha256": "d421d70a6e422742017743290472c9a1454bf6d64d976d4175264145713405f7", + "rows": [ + { + "case": "byte_sad_00", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "5a71e211ea7d33d4e6062d819f6beaf20d7f99914fb3363c93949241abe6753a" + }, + { + "case": "byte_sad_01", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "bbbf7c678161cac3218667a57afe83bc66916919462b6ea447f62df4c51c79bb" + }, + { + "case": "byte_sad_02", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "77aa8d0637d8c9ed478fd367be43d1b7d144ed332336920b686fd33cd5ab8209" + }, + { + "case": "byte_sad_03", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "c902a84c6fe01a9dcadd8ff5c29df647da4334ab8ed87aad0f99d271d07b4b50" + }, + { + "case": "byte_sad_04", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "d00ce8ea09f8ac8c3efa7b5a84e5075ad54f089e1bd220b76fa9d0e3cc76d8af" + }, + { + "case": "byte_sad_05", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "7d333bffcb44fe8eec31409209d118c98458ca12b1280fbbe0e929de2c4a99b1" + }, + { + "case": "byte_sad_06", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "fad532005f7d70ea8dcc8546c13d45718e0e28592ea3fedd946a058d4239c41b" + }, + { + "case": "byte_sad_07", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "c08eecb75b121ba905ea47b932e10c654938c8486ec455ffb6b1e142a35d1cc3" + }, + { + "case": "byte_sad_08", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "09edfd99f6ca674944f823e906f03edef9f90c76ceebcacb437313131b1bc97f" + }, + { + "case": "byte_sad_09", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "e6ef5f32b968ae836605264847529eea58496d7d690bf84bea355968ea991e16" + }, + { + "case": "byte_sad_10", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "74389ef1ac371ea2a66d9666e33f15f0cc1bcba5855a2cdcd30ea6839fb70924" + }, + { + "case": "byte_sad_11", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "2ab9dde0cf899177c87e031c7f5e2056f899bc29942bb43ddb445d99654411a2" + }, + { + "case": "byte_sad_12", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "0f2a0f50d0334edbe4939da72eb7d1b6fb961e29a509c67d1e637986cb0d2823" + }, + { + "case": "byte_sad_13", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "33fea544220bd5b33acf8b41855ca4bf7ece125458fbb1fae8e22f5efdcfc551" + }, + { + "case": "byte_sad_14", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "7900428f0da0ea2f86ac5ff275c2311989beadb71b240674a790a01a8fb62b64" + }, + { + "case": "byte_sad_15", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "ae474dcb9ffa9670bcd6338b606ddf9a14c335c34f8808381f3e5808cee10119" + }, + { + "case": "byte_sad_16", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "b84bdb5f71bc2b1982487dcf245da1875602e69cc9ec2756ae53494e04d4b595" + }, + { + "case": "byte_sad_17", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "34aff66101beeb5ecde52c8944286ec6abcb35a53cba1a7df61219b2409cb9e8" + }, + { + "case": "byte_sad_18", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "70b0a39acbdc8d56035fc9ab196db5559f54007f8d9a6dfdc706936332d55527" + }, + { + "case": "byte_sad_19", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "037be5ba7d78c2550c286abaa2828e0ce85cfc5fb35392056a2e871851639105" + }, + { + "case": "byte_sad_20", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "0b7d82d5b009d91749b3ec5ad1ad02ff7eedd90ab9554ea5eaf5519956f8a99a" + }, + { + "case": "byte_sad_21", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "d6f39261cfe10e7dd4c1b41035d35224415854e0f6f6fe7f8f911cd73d6e617a" + }, + { + "case": "byte_sad_22", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "155e90cc452c60b2b3d6cf37e5ad9ad1557cf6bf0719aae3db61b21faa912034" + }, + { + "case": "byte_sad_23", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "818f2d8ac2a26298366df027b9612674b99f31df64ddf1ce77ff3cbc85310b1b" + }, + { + "case": "byte_sad_24", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "6d63d84d0f8d305c1e2010022dba29ea58fe760be3f4c7ea3eacb2d1b5ed48e8" + }, + { + "case": "byte_sad_25", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "37efe903fcca27e34c176c5173da09c725ba2188eab1cd6eb2ae6674da7ec374" + }, + { + "case": "byte_sad_26", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "9cfb15744592bab7d69407104ca6113ac61ad5b485a4831c20ab293ae918cb32" + }, + { + "case": "byte_sad_27", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "211dfdb69a75fc6f785ad9557cefc170139afc3308f4c99bb83d6dde2361d1c6" + }, + { + "case": "byte_sad_28", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "80893ff84520c944c5464ef082c58364493ce96ae062de9304448f0634ee872f" + }, + { + "case": "byte_sad_29", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "9b193cdf69814985364d4c9d784edd39689ccf050e5fc43b5f2555ca8c952f5c" + }, + { + "case": "byte_sad_30", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "57f692587d17865a70706a9966490aa77cbe4ee85bd8c7f83b7ae9403842afd5" + }, + { + "case": "byte_sad_31", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "4514edc2dc18cbd9611e901d10abde038627ea1e17a74854151a3aeb074f3378" + }, + { + "case": "byte_sad_32", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "5ffd85623581e7fdaf04c5095a62c4fda57ba16190b32b149a34cc811494e871" + }, + { + "case": "byte_sad_33", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "8d13ccf58115816ef3e1892580efa9602f395a4b1f1bc811ffe256a0f23c5d12" + }, + { + "case": "byte_sad_34", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "dc3d24946a7b74bd0dd4fa85b210ad9d62027c98fc7070ccfb9f91162e2f36d3" + }, + { + "case": "byte_sad_35", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "6e296d9db5eb2fb2d26b30a5316e005db9e35040221d92e24d57648d99c38b99" + }, + { + "case": "byte_sad_36", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "0a600ba1ba5eb8108a9ad40c60aaae3b0b928971dc023fe7e5bd14d46e989ecf" + }, + { + "case": "byte_sad_37", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "971ac7b5ada8e229b23aa676f5fde158cf45ed6da6315e99d895a254890fef0c" + }, + { + "case": "byte_sad_38", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "38156bfec5ea4c55d9584764d6335785f01239e1eebb4fc0fd6767fb6b77da50" + }, + { + "case": "byte_sad_39", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "60172b9b7140513b84554f9e9b9372d11c6aada4be520f0c374b63309826549b" + }, + { + "case": "byte_sad_40", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "0e26770201164f6734b18d75c0294482379b3c003b5404a9f87c887e47e0ea3b" + }, + { + "case": "byte_sad_41", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "0bab48b964b58e713dfb5a6096fecc402a0eec1f891e1cde66e73bf755986e77" + }, + { + "case": "byte_sad_42", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "2bd201f6e2a5b460560e948495670accd64c543fa28abddf207af4bb6c0e266b" + }, + { + "case": "byte_sad_43", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "4bc5c4cf90fcf2bc419244cefd0feba5d827d0e93827ccfc0610362f889bdb8a" + }, + { + "case": "byte_sad_44", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "d38fae8b3b4abd077b3a860c4c343d4a3a6fbd6c4eac2aab79403b2862df007d" + }, + { + "case": "byte_sad_45", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "3fda9ea13aedc21bc67376ea0ced1b316a88b924de1343af2efce8ff63cec706" + }, + { + "case": "byte_sad_46", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "8d31bc9d635c09a2179b953a09fdaabe214c060c689c5acc51e9792fab20cd24" + }, + { + "case": "byte_sad_47", + "dxil_sha256": "822cd74d7eccd370f8ffacb9dcb5197ca4c4412489db2a51caac7a4df3ccfe42", + "readback_sha256": "a73a1b8c94a4f44e1bfa62c8a908b6f763c2518bc070f339ea7f0adc29c13dca" + } + ] +} diff --git a/evidence/native-rdna2-byte-sad.json b/evidence/native-rdna2-byte-sad.json new file mode 100644 index 00000000..bac5aede --- /dev/null +++ b/evidence/native-rdna2-byte-sad.json @@ -0,0 +1,61 @@ +{ + "scope": "Native RDNA2 execution of synthetic byte SAD inputs under MODE 0 and 0x3ff, compared with the byte SAD reference model", + "device": "AMD Radeon RX 6950 XT", + "seed": 521278738, + "records": 16384, + "modes": [ + "0x000", + "0x3ff" + ], + "inputs_sha256": "082f92bf44d3897d9c1371840505ff4b3fae0761698e34739af6f001c66e3c05", + "kernels_sha256": "ee7e1d28fee2c817b353f0d6c9f6c7bd41c5464ac7b6054c85b4baea030b211f", + "model_comparisons": 81920, + "mismatches": 0, + "kernels": [ + { + "kernel": "v_msad_u8", + "instruction": "v_msad_u8", + "comparisons": 16384, + "mismatches": 0, + "mode_independent": true, + "examples": [], + "native_results_sha256": "01da72816c8d7ffb270056fd965db61f2e42c52e5f10f278b552004f89ad5c0d" + }, + { + "kernel": "v_qsad_pk_u16_u8", + "instruction": "v_qsad_pk_u16_u8", + "comparisons": 16384, + "mismatches": 0, + "mode_independent": true, + "examples": [], + "native_results_sha256": "aadbaba86804fcd79a391bfe0758321a37961b3d2c6d44a4a991f86a2971d57a" + }, + { + "kernel": "v_mqsad_pk_u16_u8", + "instruction": "v_mqsad_pk_u16_u8", + "comparisons": 16384, + "mismatches": 0, + "mode_independent": true, + "examples": [], + "native_results_sha256": "8dc0c6d150008fbaadc3702e657d3632cfd01cd37a6ddcc66b5bc989eec3a995" + }, + { + "kernel": "v_mqsad_u32_u8_0", + "instruction": "v_mqsad_u32_u8", + "comparisons": 16384, + "mismatches": 0, + "mode_independent": true, + "examples": [], + "native_results_sha256": "d1e64377f9652dea016d0c3b04de03a13f076f6b180f804a75a9293f0c032b09" + }, + { + "kernel": "v_mqsad_u32_u8_1", + "instruction": "v_mqsad_u32_u8", + "comparisons": 16384, + "mismatches": 0, + "mode_independent": true, + "examples": [], + "native_results_sha256": "4cabf87fee4e835785997ddc87e531d670a64b0cf64cd1277b979239bc67c03c" + } + ] +} diff --git a/tests/test_byte_sad_gpu.py b/tests/test_byte_sad_gpu.py new file mode 100644 index 00000000..9d0d3214 --- /dev/null +++ b/tests/test_byte_sad_gpu.py @@ -0,0 +1,32 @@ +import unittest + +from tools.check_byte_sad_gpu import reference + + +class ByteSadReferenceTests(unittest.TestCase): + # Hand-computed results for the behaviour native RDNA2 execution settled. + def test_masked_sad_skips_zero_reference_bytes(self): + # |0x10 - 0x01| + |0x20 - 0x00| skipped + |0x30 - 0x05| + |0x40 - 0x00| skipped + self.assertEqual(reference("v_msad_u8", 0x4030_2010, 0x0005_0001, [7]), [7 + 0x0F + 0x2B]) + # A zero S0 byte still counts when the S1 byte is set. + self.assertEqual(reference("v_msad_u8", 0, 0xFF00_0000, [0]), [0xFF]) + self.assertEqual(reference("v_msad_u8", 1, 1, [0xFFFF_FFFF]), [0xFFFF_FFFF]) + + def test_quad_windows_slide_by_one_byte(self): + s0 = 0x0706_0504_0302_0100 + out = reference("v_qsad_pk_u16_u8", s0, 0x0302_0100, [0, 0]) + # Window k is bytes k..k+3, so each byte differs by k. + self.assertEqual(out, [0 | 4 << 16, 8 | 12 << 16]) + + def test_sixteen_bit_fields_wrap(self): + out = reference("v_qsad_pk_u16_u8", 0xFF, 0, [0xFFFF_FFF0, 0]) + self.assertEqual(out[0], 0xFFFF_00EF) # 0xfff0 + 0xff wraps to 0xef + self.assertEqual(reference("v_mqsad_pk_u16_u8", 0xFF, 0, [0xFFF0, 0]), [0xFFF0, 0]) + + def test_mqsad_u32_uses_one_accumulator_word_per_window(self): + out = reference("v_mqsad_u32_u8", 0x0000_0000_0000_00FF, 0x0000_0001, [1, 2, 3, 4]) + self.assertEqual(out, [1 + 0xFE, 2 + 1, 3 + 1, 4 + 1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/check_byte_sad_gpu.py b/tools/check_byte_sad_gpu.py new file mode 100644 index 00000000..42bdde37 --- /dev/null +++ b/tools/check_byte_sad_gpu.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""LLVM-assembled byte SAD controls on a D3D12 GPU. + +v_msad_u8, v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8 and v_mqsad_u32_u8 with +dynamic VGPR operands, including destinations that overlap the accumulator +or the S0 pair. The reference was checked against native RDNA2 execution +(tools/native_rdna2/check_sad.py): the masked forms skip a byte whose S1 +byte is zero, and the 16-bit fields wrap. +""" +import argparse +import hashlib +import json +from pathlib import Path +import random +import re +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +from check_packed_integer_gpu import assemble, digest, translate +from frosty_gpu_guest import run_gpu_guest + +M32 = 0xFFFFFFFF +SEED = 0x51534144 +# v20:v21 is S0, v22 S1 and v24..v27 the accumulators. +INPUTS = [20, 21, 22, 24, 25, 26, 27] +INIT = [0x13572468 + 0x01010101 * k for k in range(len(INPUTS))] +# The guest's guarded view covers words 96..288: eight groups of 24 words. +GROUPS, STRIDE, START = 8, 24, 96 + + +def sad(x, y, masked): + total = 0 + for i in range(4): + p, q = x >> 8 * i & 255, y >> 8 * i & 255 + if not (masked and q == 0): + total += abs(p - q) + return total + + +def reference(name, s0, s1, acc): + """Result words for a 64-bit S0, a 32-bit S1 and accumulator words.""" + if name == "v_msad_u8": + return [(sad(s0 & M32, s1, True) + acc[0]) & M32] + masked = name.startswith("v_mqsad") + sums = [sad(s0 >> 8 * k & M32, s1, masked) for k in range(4)] + if name == "v_mqsad_u32_u8": + return [(sums[k] + acc[k]) & M32 for k in range(4)] + fields = [(sums[k] + (acc[k // 2] >> 16 * (k % 2) & 0xFFFF)) & 0xFFFF for k in range(4)] + return [fields[0] | fields[1] << 16, fields[2] | fields[3] << 16] + + +def program(): + """The program and, per result, its instruction, first register and first accumulator.""" + lines = [f"v_mov_b32_e32 v{reg}, 0x{v:x}" for reg, v in zip(INPUTS, INIT)] + lines += ["v_msad_u8 v30, v20, v22, v24", + "v_qsad_pk_u16_u8 v[32:33], v[20:21], v22, v[24:25]", + "v_mqsad_pk_u16_u8 v[34:35], v[20:21], v22, v[26:27]", + "v_mqsad_u32_u8 v[36:39], v[20:21], v22, v[24:27]", + # The destination is the accumulator. + "v_mov_b32_e32 v40, v24", "v_mov_b32_e32 v41, v25", + "v_qsad_pk_u16_u8 v[40:41], v[20:21], v22, v[40:41]", + "v_mov_b32_e32 v44, v24", "v_mov_b32_e32 v45, v25", "v_mov_b32_e32 v46, v26", "v_mov_b32_e32 v47, v27", + "v_mqsad_u32_u8 v[44:47], v[20:21], v22, v[44:47]", + # The destination is the S0 pair. + "v_mov_b32_e32 v48, v20", "v_mov_b32_e32 v49, v21", + "v_mqsad_pk_u16_u8 v[48:49], v[48:49], v22, v[24:25]", + "s_endpgm"] + plan = [("v_msad_u8", 30, 0), ("v_qsad_pk_u16_u8", 32, 0), ("v_mqsad_pk_u16_u8", 34, 2), + ("v_mqsad_u32_u8", 36, 0), ("v_qsad_pk_u16_u8", 40, 0), ("v_mqsad_u32_u8", 44, 0), + ("v_mqsad_pk_u16_u8", 48, 0)] + return lines, plan + + +def stored(plan): + return [f"v{base + k}" for name, base, _ in plan for k in range(len(reference(name, 0, 0, [0] * 4)))] + + +def expected_outputs(vals, plan): + s0, s1, acc = vals[0] | vals[1] << 32, vals[2], vals[3:] + return [w for name, _, first in plan for w in reference(name, s0, s1, acc[first:])] + + +def instrument(text, names): + marker = "[numthreads(1, 1, 1)]" + if text.count(marker) != 1 or not text.rstrip().endswith("}"): + raise ValueError("unexpected compute entry") + text = text.replace(marker, "RWStructuredBuffer output : register(u0);\n" + marker) + for j, (reg, v) in enumerate(zip(INPUTS, INIT)): + text, found = re.subn(rf"\b(v{reg} = )0x{v:x}u;", rf"\g<1>output[{STRIDE}u * gid.x + {j}u];", text) + if found != 1: + raise ValueError(f"expected one initial literal for v{reg}, found {found}") + stores = "".join(f" output[{STRIDE}u * gid.x + {len(INIT) + i}u] = {name};\n" for i, name in enumerate(names)) + return text.rstrip()[:-1] + stores + "}\n" + + +def byte_word(rng, count): + """Bytes that are often zero, equal, or at the extremes.""" + return sum(rng.choice([0, 0, 1, 0xFF, rng.getrandbits(8), rng.getrandbits(8)]) << 8 * i for i in range(count)) + + +def inputs(rng, index): + s0, s1 = byte_word(rng, 8), byte_word(rng, 4) + if index % 5 == 0: + s1 = s0 & M32 # the first window matches + acc = [rng.choice([rng.getrandbits(32), 0xFFFFFFFF, 0xFFFEFFFD, 0xFC00FFF0, 0]) for _ in range(4)] + return [s0 & M32, s0 >> 32, s1] + acc + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + for n in ("emitter", "llvm-mc", "dxc", "dxv", "provider", "proton", "prefix", "compiler-dir", "work", "output"): + ap.add_argument("--" + n, type=Path, required=True) + ap.add_argument("--baseline", type=Path, help="earlier emitter that must refuse the program") + ap.add_argument("--adapter", required=True) + ap.add_argument("--dispatches", type=int, default=48) + a = ap.parse_args() + if a.output.exists(): + ap.error("choose a fresh receipt") + a.work.mkdir(parents=True, exist_ok=False) + rng = random.Random(SEED) + tool_hashes = {n: digest(getattr(a, n)) for n in ("emitter", "dxc", "dxv", "provider")} + if a.baseline: + tool_hashes["baseline"] = digest(a.baseline) + lines, plan = program() + names = stored(plan) + if len(INIT) + len(names) != STRIDE: + raise ValueError("stride does not match the outputs") + words = assemble(lines, a.llvm_mc) + if a.baseline: + before = translate(a.baseline, words) + if before.returncode != 65: + raise ValueError(f"baseline did not refuse: {before.returncode} {before.stderr}") + got = translate(a.emitter, words) + got.check_returncode() + source = instrument(got.stdout, names) + rows, expected, negatives = [], {}, [] + with TemporaryDirectory(dir=a.work) as td: + trial = Path(td) + guest = ROOT / "tools/reference/independent-shaders/compute.cpp" + (trial / "guest.cpp").write_text(guest.read_text()) + (trial / "context.h").write_text((guest.parent / "context.h").read_text().replace( + '"../compute_buffers.h"', '"' + str(ROOT / "tools/reference/compute_buffers.h") + '"')) + for k in range(a.dispatches): + label = f"byte_sad_{k:02}" + shader = trial / (label + ".hlsl") + shader.write_text(source) + blob = shader.with_suffix(".cso") + subprocess.run([a.dxc, "-T", "cs_6_0", "-E", "main", "-O3", "-Fo", blob, shader], + check=True, capture_output=True, timeout=60) + subprocess.run([a.dxv, blob], check=True, capture_output=True, timeout=15) + seed = [rng.getrandbits(32) for _ in range(384)] + want = seed.copy() + for lane in range(GROUPS): + index = k * GROUPS + lane + vals = inputs(rng, index) + offset = START + STRIDE * lane + seed[offset:offset + len(INIT)] = vals + want[offset:offset + len(INIT)] = vals + want[offset + len(INIT):offset + STRIDE] = expected_outputs(vals, plan) + (trial / (label + ".seed")).write_bytes(struct.pack("<384I", *seed)) + expected[label] = struct.pack("<384I", *want) + rows.append({"case": label, "dxil_sha256": digest(blob)}) + for kind, inst in [("clamp", ["v_qsad_pk_u16_u8 v[0:1], v[2:3], v4, v[6:7] clamp", "s_endpgm"]), + ("scalar_source", ["v_mqsad_u32_u8 v[0:3], s[2:3], v4, v[8:11]", "s_endpgm"]), + ("inline_accumulator", ["v_msad_u8 v0, v1, v2, 0", "s_endpgm"])]: + bad = translate(a.emitter, assemble(inst, a.llvm_mc)) + if bad.returncode != 65: + raise ValueError(f"unexpected acceptance {inst}") + negatives.append({"kind": kind, "assembly": inst, "refusal": bad.stderr.strip()}) + (trial / "cases.txt").write_text("".join(f"{n} 4 structured {GROUPS}\n" for n in expected)) + exe, status, fields = run_gpu_guest(trial / "guest.cpp", "bytesad.exe", trial, a.work, a.proton, + a.prefix, a.provider, a.compiler_dir) + if status or fields.get("adapter") != a.adapter: + raise RuntimeError(f"guest failed: {status} {fields}") + failures = [] + for row in rows: + actual = trial / (row["case"] + ".bin") + observed = actual.read_bytes() if actual.is_file() else b"" + if observed != expected[row["case"]]: + lhs = struct.unpack(f"<{len(observed) // 4}I", observed) + rhs = struct.unpack("<384I", expected[row["case"]]) + failures.append({"case": row["case"], "different_words": [ + (i, f"{x:08x}", f"{y:08x}") for i, (x, y) in enumerate(zip(lhs, rhs)) if x != y][:16]}) + else: + row["readback_sha256"] = digest(actual) + receipt = {"scope": "Synthetic LLVM-assembled v_msad_u8, v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8 and v_mqsad_u32_u8 instructions; dynamic instrumented inputs and observed outputs", + "adapter": fields["adapter"], "proton": (a.proton / "version").read_text().strip(), + "seed": SEED, "assembly": lines, "native_words": [f"{v:08x}" for v in words], + "emitted_sha256": hashlib.sha256(got.stdout.encode()).hexdigest(), + "shader_cases": len(rows), "inputs": len(rows) * GROUPS, + "result_words": len(rows) * GROUPS * (STRIDE - len(INIT)), "compared_words": 384 * len(rows), + "mismatches": len(failures), "failures": failures, + "baseline_refused": bool(a.baseline), "negative_controls": negatives, + "tool_sha256": tool_hashes, "guest_sha256": digest(exe), "rows": rows} + with a.output.open("x") as f: + json.dump(receipt, f, indent=2) + f.write("\n") + if failures: + print(f"FAIL {len(failures)} of {len(rows)} dispatches; first: {failures[0]}") + raise SystemExit(1) + print(f"PASS {receipt['inputs']} inputs, {receipt['result_words']} results, {receipt['compared_words']} GPU words; zero mismatches") + + +if __name__ == "__main__": + main() diff --git a/tools/check_sad_mad64_gpu.py b/tools/check_sad_mad64_gpu.py index f0208d9a..f387c137 100644 --- a/tools/check_sad_mad64_gpu.py +++ b/tools/check_sad_mad64_gpu.py @@ -132,7 +132,7 @@ def main(): for kind, inst in [("clamp", "v_sad_u8 v10, v4, v5, v6 clamp"), ("scalar_source", "v_sad_u32 v10, s4, v5, v6"), ("carry_destination", "v_mad_i64_i32 v[14:15], vcc_lo, v4, v5, v[6:7]"), - ("masked_sad", "v_msad_u8 v10, v4, v5, v6")]: + ("masked_sad_clamp", "v_msad_u8 v10, v4, v5, v6 clamp")]: bad = translate(a.emitter, assemble([inst, "s_endpgm"], a.llvm_mc)) if bad.returncode != 65: raise ValueError(f"unexpected acceptance {inst}") diff --git a/tools/check_translator_gpu.py b/tools/check_translator_gpu.py index 4baf336d..e8ccdfd6 100644 --- a/tools/check_translator_gpu.py +++ b/tools/check_translator_gpu.py @@ -45,6 +45,7 @@ def assembled(tool, *extra): "packed-chain-saturate": assembled("check_packed_chain_gpu", "--include-saturate"), "packed-chain-unoptimized": assembled("check_packed_chain_gpu", "--optimization", "O0"), "sad-mad64": assembled("check_sad_mad64_gpu"), + "byte-sad": assembled("check_byte_sad_gpu"), "f64": assembled("check_f64_exact_gpu"), "swizzle": Check("check_compute_swizzle", emitter="compute_swizzle"), "readlane": Check("check_readlane_gpu", emitter="readlane_probe", dxc=True), diff --git a/tools/native_rdna2/README.md b/tools/native_rdna2/README.md index 5f79edd5..c3887d05 100644 --- a/tools/native_rdna2/README.md +++ b/tools/native_rdna2/README.md @@ -11,3 +11,11 @@ python tools/native_rdna2/check_model.py --work build/native-rdna2 --output buil ``` It needs ROCm (`hipcc`, `clang-offload-bundler` and `libhsa-runtime64`), by default under `/opt/rocm`. [Example receipt](../../evidence/native-rdna2-f64-modes.json) + +`sad.hip` and `check_sad.py` do the same for the byte SAD forms (`v_msad_u8`, `v_qsad_pk_u16_u8`, `v_mqsad_pk_u16_u8`, `v_mqsad_u32_u8`). They compare the model of `tools/check_byte_sad_gpu.py` under MODE 0 and 0x3ff: + +``` +python tools/native_rdna2/check_sad.py --work build/native-rdna2-sad --output build/native-rdna2-sad.json +``` + +[Example receipt](../../evidence/native-rdna2-byte-sad.json) diff --git a/tools/native_rdna2/check_model.py b/tools/native_rdna2/check_model.py index d737ddb5..29ae1d08 100644 --- a/tools/native_rdna2/check_model.py +++ b/tools/native_rdna2/check_model.py @@ -26,9 +26,9 @@ ALL_MODES = range(1024) -def build(rocm, work): +def build(rocm, work, source=HERE / "kernels.hip"): bundle, code, host = work / "kernels.hsaco", work / "kernels.co", work / "host" - subprocess.run([rocm / "bin/hipcc", "--offload-arch=gfx1030", "-O2", "--genco", HERE / "kernels.hip", "-o", bundle], + subprocess.run([rocm / "bin/hipcc", "--offload-arch=gfx1030", "-O2", "--genco", source, "-o", bundle], check=True, capture_output=True) subprocess.run([rocm / "llvm/bin/clang-offload-bundler", "--unbundle", "--type=o", f"--input={bundle}", "--targets=hipv4-amdgcn-amd-amdhsa--gfx1030", f"--output={code}"], check=True) diff --git a/tools/native_rdna2/check_sad.py b/tools/native_rdna2/check_sad.py new file mode 100644 index 00000000..13cfca69 --- /dev/null +++ b/tools/native_rdna2/check_sad.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Compare the byte SAD reference model with native RDNA2 execution. + +Runs v_msad_u8, v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8 and v_mqsad_u32_u8 +natively on a gfx1030 GPU and compares the reference of +tools/check_byte_sad_gpu.py. Each kernel runs under MODE 0 and 0x3ff to +show that MODE does not change these integer results. Needs ROCm. +""" +import argparse +import hashlib +import json +from pathlib import Path +import random +import struct +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent)) +sys.path.insert(0, str(HERE)) +from check_byte_sad_gpu import SEED, inputs, reference +from check_model import build + +M32 = 0xFFFFFFFF +# Kernel name, instruction, and the result words the kernel stores. +KERNELS = [("v_msad_u8", "v_msad_u8", slice(0, 1)), ("v_qsad_pk_u16_u8", "v_qsad_pk_u16_u8", slice(0, 2)), + ("v_mqsad_pk_u16_u8", "v_mqsad_pk_u16_u8", slice(0, 2)), + ("v_mqsad_u32_u8_0", "v_mqsad_u32_u8", slice(0, 2)), ("v_mqsad_u32_u8_1", "v_mqsad_u32_u8", slice(2, 4))] +MODES = [0, 0x3FF] + + +def record(vals): + """kernels.hip reads S0 = a, S1 = c, accumulators (b, f, low ^ high word of b).""" + s0, s1, acc = vals[0] | vals[1] << 32, vals[2], vals[3:6] + acc = acc + [acc[0] ^ acc[1]] + return (s0, acc[0] | acc[1] << 32, s1, acc[2]), (s0, s1, acc) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--rocm", type=Path, default=Path("/opt/rocm")) + ap.add_argument("--work", type=Path, required=True) + ap.add_argument("--output", type=Path, required=True) + ap.add_argument("--records", type=int, default=16384, help="input records, a multiple of 64") + a = ap.parse_args() + if a.output.exists(): + ap.error("choose a fresh receipt") + a.work.mkdir(parents=True, exist_ok=False) + code, host = build(a.rocm, a.work, HERE / "sad.hip") + rng = random.Random(SEED ^ 0x4e415456) + rows = [record(inputs(rng, i)) for i in range(a.records)] + records = a.work / "inputs.bin" + records.write_bytes(b"".join(struct.pack(" 1 else 0) + if hw != want: + mismatches += 1 + if len(examples) < 8: + examples.append({"s0": f"{native[0]:016x}", "s1": f"{native[2]:08x}", + "acc": [f"{w:08x}" for w in model[2]], "native": f"{hw:016x}", "model": f"{want:016x}"}) + report.append({"kernel": kernel, "instruction": name, "comparisons": n, "mismatches": mismatches, + "mode_independent": mode_independent, "examples": examples, + "native_results_sha256": hashlib.sha256(raw).hexdigest()}) + print(f"{kernel}: {mismatches} mismatches, MODE-independent {mode_independent}", flush=True) + failed = sum(r["mismatches"] for r in report) or not all(r["mode_independent"] for r in report) + receipt = {"scope": "Native RDNA2 execution of synthetic byte SAD inputs under MODE 0 and 0x3ff, compared with the byte SAD reference model", + "device": device, "seed": SEED ^ 0x4e415456, "records": n, "modes": [f"{m:#05x}" for m in MODES], + "inputs_sha256": hashlib.sha256(records.read_bytes()).hexdigest(), + "kernels_sha256": hashlib.sha256((HERE / "sad.hip").read_bytes()).hexdigest(), + "model_comparisons": n * len(KERNELS), "mismatches": sum(r["mismatches"] for r in report), + "kernels": report} + with a.output.open("x") as f: + json.dump(receipt, f, indent=2) + f.write("\n") + print(f"{'FAIL' if failed else 'PASS'} {receipt['model_comparisons']} model comparisons, {receipt['mismatches']} mismatches") + raise SystemExit(1 if failed else 0) + + +if __name__ == "__main__": + main() diff --git a/tools/native_rdna2/sad.hip b/tools/native_rdna2/sad.hip new file mode 100644 index 00000000..834b2c0b --- /dev/null +++ b/tools/native_rdna2/sad.hip @@ -0,0 +1,26 @@ +// Byte SAD instructions, one per lane, for tools/native_rdna2/check_sad.py. +// Same record layout and host interface as kernels.hip. +#include +#include + +struct In { uint64_t a, b; uint32_t c, f; }; + +#define SET "s_setreg_b32 hwreg(HW_REG_MODE, 0, 10), %[m]\n s_nop 7\n" +#define K(op, body) extern "C" __global__ void k_##op(const In* in, uint64_t* out, uint32_t mode) { \ + int i = blockIdx.x * 64 + threadIdx.x; In x = in[i]; uint64_t r = 0; uint32_t r32 = 0; (void)r32; body; out[i] = r; } + +// Byte SAD forms. MODE does not apply; S0 is a, S1 is c, S2 is b. The +// 128-bit accumulator of v_mqsad_u32_u8 is (b, f, low ^ high word of b), +// and its result is stored in two halves. +typedef uint32_t u32x4 __attribute__((ext_vector_type(4))); +K(v_msad_u8, { asm volatile(SET "v_msad_u8 %0, %1, %2, %3" : "=&v"(r32) : "v"((uint32_t)x.a), "v"(x.c), "v"((uint32_t)x.b), [m]"s"(mode)); r = r32; }) +K(v_qsad_pk_u16_u8, { asm volatile(SET "v_qsad_pk_u16_u8 %0, %1, %2, %3" : "=&v"(r) : "v"(x.a), "v"(x.c), "v"(x.b), [m]"s"(mode)); }) +K(v_mqsad_pk_u16_u8, { asm volatile(SET "v_mqsad_pk_u16_u8 %0, %1, %2, %3" : "=&v"(r) : "v"(x.a), "v"(x.c), "v"(x.b), [m]"s"(mode)); }) +__device__ uint64_t mqsad(const In& x, int half, uint32_t mode) { + u32x4 acc = {(uint32_t)x.b, (uint32_t)(x.b >> 32), x.f, (uint32_t)x.b ^ (uint32_t)(x.b >> 32)}; + u32x4 d; + asm volatile(SET "v_mqsad_u32_u8 %0, %1, %2, %3" : "=&v"(d) : "v"(x.a), "v"(x.c), "v"(acc), [m]"s"(mode)); + return (uint64_t)d[2 * half] | (uint64_t)d[2 * half + 1] << 32; +} +K(v_mqsad_u32_u8_0, { r = mqsad(x, 0, mode); }) +K(v_mqsad_u32_u8_1, { r = mqsad(x, 1, mode); }) diff --git a/tools/shader-compiler/src/hlsl.rs b/tools/shader-compiler/src/hlsl.rs index 99db25a8..2a5aa9ec 100644 --- a/tools/shader-compiler/src/hlsl.rs +++ b/tools/shader-compiler/src/hlsl.rs @@ -77,6 +77,7 @@ mod classify_materials; mod int16; mod int32; mod float64; +mod quad_sad; mod indexed_lane; mod particle_sort; mod persistent; diff --git a/tools/shader-compiler/src/hlsl/emitter/analysis.rs b/tools/shader-compiler/src/hlsl/emitter/analysis.rs index f79cedea..d8465838 100644 --- a/tools/shader-compiler/src/hlsl/emitter/analysis.rs +++ b/tools/shader-compiler/src/hlsl/emitter/analysis.rs @@ -519,7 +519,7 @@ impl<'a> Emitter<'a> { if setreg { continue; } - for high in float64::pair_source_highs(ins) { + for high in float64::pair_source_highs(ins).into_iter().chain(quad_sad::source_highs(ins)) { if !written.contains(&format!("v{high}")) { live.insert((1, high)); } @@ -546,6 +546,7 @@ impl<'a> Emitter<'a> { Self::mubuf_dwords(&ins.mnemonic).unwrap_or(1) - 1, _ if wide_bit_result(&ins.mnemonic) => 1, _ if float64::pair_result(&ins.mnemonic) => 1, + _ if quad_sad::handles(&ins.mnemonic) => quad_sad::result_extra(&ins.mnemonic), _ => 0, }; for o in &ins.dst { diff --git a/tools/shader-compiler/src/hlsl/emitter/vector.rs b/tools/shader-compiler/src/hlsl/emitter/vector.rs index 24bd9e39..b6a3fbf4 100644 --- a/tools/shader-compiler/src/hlsl/emitter/vector.rs +++ b/tools/shader-compiler/src/hlsl/emitter/vector.rs @@ -289,7 +289,7 @@ impl<'a> Emitter<'a> { if let Some(result) = int16::expression(ins)? { return self.wv(&d, &result); } - if self.lower_f64(ins)? { + if self.lower_f64(ins)? || self.lower_quad_sad(ins)? { return Ok(()); } if int32::handles(ins) && self.ex.stage != Stage::Compute { diff --git a/tools/shader-compiler/src/hlsl/int32.rs b/tools/shader-compiler/src/hlsl/int32.rs index 5edae7ce..0913a77b 100644 --- a/tools/shader-compiler/src/hlsl/int32.rs +++ b/tools/shader-compiler/src/hlsl/int32.rs @@ -1,6 +1,6 @@ //! Ordinary VOP3 integer forms with a 32-bit result: the signed no-carry //! add/subtract, 16x16+32 multiply-add, saturating integer packs and sums of -//! absolute differences over bytes, halves and words. Add/subtract and unsigned MAD +//! absolute differences over bytes, halves and words, and the masked byte SAD. Add/subtract and unsigned MAD //! accept integer immediates, and byte SAD accepts an inline zero accumulator. //! Signed add/subtract also support saturating arithmetic with clamp. use super::{int16::half, r, signed_add_overflow, Enc, Insn, Opnd}; @@ -9,7 +9,7 @@ pub(super) fn handles(ins: &Insn) -> bool { ins.enc == Enc::Vop3 && matches!(ins.mnemonic.as_str(), "v_add_nc_i32" | "v_sub_nc_i32" | "v_mad_u32_u16" | "v_mad_i32_i16" | "v_cvt_pk_u16_u32" | "v_cvt_pk_i16_i32" - | "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32") + | "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32" | "v_msad_u8") } pub(super) fn expression(ins: &Insn) -> Result, String> { @@ -73,6 +73,8 @@ pub(super) fn expression(ins: &Insn) -> Result, String> { "v_sad_hi_u8" => format!("((({}) << 16) + {})", sad(8), r(&ins.src[2])?), "v_sad_u16" => format!("({} + {})", sad(16), r(&ins.src[2])?), "v_sad_u32" => format!("((max({a}, {b}) - min({a}, {b})) + {})", r(&ins.src[2])?), + // MSAD_U8 skips each byte whose S1 byte is zero (measured natively). + "v_msad_u8" => format!("({} + {})", super::quad_sad::sad(&a, &b, true), r(&ins.src[2])?), // Without clamp these wrap exactly like the unsigned forms. "v_add_nc_i32" => format!("({a} + {b})"), "v_sub_nc_i32" => format!("({a} - {b})"), diff --git a/tools/shader-compiler/src/hlsl/quad_sad.rs b/tools/shader-compiler/src/hlsl/quad_sad.rs new file mode 100644 index 00000000..e0ef6005 --- /dev/null +++ b/tools/shader-compiler/src/hlsl/quad_sad.rs @@ -0,0 +1,111 @@ +//! Byte SADs over four sliding windows: V_QSAD_PK_U16_U8, V_MQSAD_PK_U16_U8 +//! and V_MQSAD_U32_U8. S0 is a VGPR pair whose window k is bits [8k+31:8k], +//! S1 the reference word, and S2 the accumulators: four 16-bit fields in a +//! pair, or four words for V_MQSAD_U32_U8. The masked forms skip a byte whose +//! S1 byte is zero, and without clamp the 16-bit fields wrap. Native RDNA2 +//! execution settled both (tools/native_rdna2/check_sad.py). Plain VGPR +//! operands without modifiers, in compute shaders only. +use super::{r, Emitter, Enc, Insn, Opnd}; +use crate::Stage; + +pub(super) fn handles(m: &str) -> bool { + matches!(m, "v_qsad_pk_u16_u8" | "v_mqsad_pk_u16_u8" | "v_mqsad_u32_u8") +} + +/// Extra registers after the first of the S2 accumulator and the result. +fn words(m: &str) -> u32 { + if m == "v_mqsad_u32_u8" { 3 } else { 1 } +} + +pub(super) fn result_extra(m: &str) -> u32 { + if handles(m) { words(m) } else { 0 } +} + +/// High source registers read beyond the decoded operands. +pub(super) fn source_highs(ins: &Insn) -> Vec { + if !handles(&ins.mnemonic) { + return Vec::new(); + } + let mut highs = Vec::new(); + if let Some(Opnd::Vgpr(a)) = ins.src.first() { + highs.push(u32::from(*a) + 1); + } + if let Some(Opnd::Vgpr(c)) = ins.src.get(2) { + highs.extend((1..=words(&ins.mnemonic)).map(|k| u32::from(*c) + k)); + } + highs +} + +/// Sum of byte differences between `x` and `y`, skipping zero bytes of `y` when masked. +pub(super) fn sad(x: &str, y: &str, masked: bool) -> String { + (0..4).map(|i| { + let p = format!("(({x} >> {}u) & 0xffu)", 8 * i); + let q = format!("(({y} >> {}u) & 0xffu)", 8 * i); + let diff = format!("(max({p}, {q}) - min({p}, {q}))"); + if masked { format!("({q} != 0u ? {diff} : 0u)") } else { diff } + }).collect::>().join(" + ") +} + +impl Emitter<'_> { + pub(in crate::hlsl) fn lower_quad_sad(&mut self, ins: &Insn) -> Result { + let m = ins.mnemonic.as_str(); + if !handles(m) { + return Ok(false); + } + let extra = words(m) as u8; + let (Some(Opnd::Vgpr(dst)), [Opnd::Vgpr(a), Opnd::Vgpr(b), Opnd::Vgpr(c), ..]) = (ins.dst.first(), &ins.src[..]) else { + return Err("unsupported quad SAD operand".into()); + }; + let (dst, a, b, c) = (*dst, *a, *b, *c); + // VOP3 without clamp, op_sel or negation. + if ins.enc != Enc::Vop3 || !ins.is_complete() || ins.raw[0] & 0xff00 != 0 || ins.raw[1] >> 27 != 0 { + return Err("unsupported quad SAD encoding or modifiers".into()); + } + if self.ex.stage != Stage::Compute { + return Err("unverified quad SAD shader stage".into()); + } + if dst.checked_add(extra).is_none() || a == u8::MAX || c.checked_add(extra).is_none() { + return Err("VGPR range overflows".into()); + } + let reg = |n: u8| Opnd::Vgpr(n); + for n in [a + 1].into_iter().chain((1..=extra).map(|k| c + k)) { + self.touch(®(n)); + } + let (lo, hi, y) = (r(®(a))?, r(®(a + 1))?, r(®(b))?); + let t = self.tmp; + self.tmp += 1; + let masked = m.starts_with("v_mqsad"); + let mut sums = Vec::new(); + for k in 0..4u8 { + let window = if k == 0 { lo.clone() } else { format!("(({lo} >> {}u) | ({hi} << {}u))", 8 * k, 32 - 8 * k) }; + self.line(&format!("uint t{t}w{k} = {window};")); + sums.push(sad(&format!("t{t}w{k}"), &y, masked)); + } + let mut results = Vec::new(); + if m == "v_mqsad_u32_u8" { + for (k, sum) in sums.iter().enumerate() { + results.push(format!("{sum} + {}", r(®(c + k as u8))?)); + } + } else { + let (acc_lo, acc_hi) = (r(®(c))?, r(®(c + 1))?); + let field = |k: usize| { + let acc = if k < 2 { &acc_lo } else { &acc_hi }; + format!("((({}) + (({acc} >> {}u) & 0xffffu)) & 0xffffu)", sums[k], 16 * (k % 2)) + }; + results.push(format!("{} | ({} << 16u)", field(0), field(1))); + results.push(format!("{} | ({} << 16u)", field(2), field(3))); + } + // Every result word is computed before any destination word is written. + for (k, value) in results.iter().enumerate() { + self.line(&format!("uint t{t}r{k} = {value};")); + } + for k in 0..results.len() { + self.wv(®(dst + k as u8), &format!("t{t}r{k}"))?; + } + Ok(true) + } +} + +#[cfg(test)] +#[path = "../tests/hlsl/quad_sad.rs"] +mod tests; diff --git a/tools/shader-compiler/src/tests/hlsl/int32.rs b/tools/shader-compiler/src/tests/hlsl/int32.rs index 38bacd22..7dfc8a0c 100644 --- a/tools/shader-compiler/src/tests/hlsl/int32.rs +++ b/tools/shader-compiler/src/tests/hlsl/int32.rs @@ -126,8 +126,9 @@ fn sums_of_absolute_differences_accumulate_into_source_2() { assert!(expression(&native(first | 0x0800, 0x041a_0b04)).is_err(), "{name} op_sel"); assert!(expression(&native(first, 0x041a_0b04 & !511 | 4)).is_err(), "{name} sgpr"); } - // Masked and quad SADs remain refused. - assert!(!handles(&native(0xd571_0007, 0x041a_0b04))); + // The masked byte SAD is handled here; quad SADs have their own module. + assert!(handles(&native(0xd571_0007, 0x041a_0b04))); + assert!(!handles(&native(0xd572_0006, 0x041a_0b04))); } #[test] diff --git a/tools/shader-compiler/src/tests/hlsl/quad_sad.rs b/tools/shader-compiler/src/tests/hlsl/quad_sad.rs new file mode 100644 index 00000000..63c6b4b5 --- /dev/null +++ b/tools/shader-compiler/src/tests/hlsl/quad_sad.rs @@ -0,0 +1,64 @@ +use crate::hlsl::float64::tests::translate; +use crate::Stage; + +// LLVM gfx1030 encodings. +const QSAD: [u32; 2] = [0xd572_0000, 0x041a_0902]; // v_qsad_pk_u16_u8 v[0:1], v[2:3], v4, v[6:7] +const MQSAD_PK_ON_S0: [u32; 2] = [0xd573_0000, 0x041a_0900]; // v_mqsad_pk_u16_u8 v[0:1], v[0:1], v4, v[6:7] +const MQSAD_ON_ACC: [u32; 2] = [0xd575_0008, 0x0422_0902]; // v_mqsad_u32_u8 v[8:11], v[2:3], v4, v[8:11] + +fn entry_live(hlsl: &str) -> &str { + hlsl.lines().find(|l| l.starts_with("// entry-live registers")).unwrap() +} + +#[test] +fn quad_sads_read_every_source_word_and_write_every_result_word() { + let hlsl = translate(Stage::Compute, &QSAD).unwrap(); + assert!(hlsl.contains("((v2 >> 24u) | (v3 << 8u))"), "{hlsl}"); + assert!(entry_live(&hlsl).ends_with(" v2 v3 v6 v7"), "{hlsl}"); + assert!(hlsl.contains("v0 = t0r0;") && hlsl.contains("v1 = t0r1;"), "{hlsl}"); + // Unmasked: no byte of S1 is tested against zero. + assert!(!hlsl.contains("!= 0u ?"), "{hlsl}"); + + let hlsl = translate(Stage::Compute, &MQSAD_ON_ACC).unwrap(); + // The test prologue writes v4 and v5. + assert!(entry_live(&hlsl).ends_with(" v2 v3 v8 v9 v10 v11"), "{hlsl}"); + assert_eq!(hlsl.matches("((v4 >> 24u) & 0xffu) != 0u ?").count(), 4, "{hlsl}"); + // All four sums use the old accumulator before any destination word is written. + let first_write = hlsl.find("v8 = t0r0;").unwrap(); + assert!(hlsl.find("uint t0r3 = ").unwrap() < first_write, "{hlsl}"); + assert!(hlsl.contains("v11 = t0r3;"), "{hlsl}"); +} + +#[test] +fn quad_sad_windows_are_taken_before_s0_is_overwritten() { + let hlsl = translate(Stage::Compute, &MQSAD_PK_ON_S0).unwrap(); + let first_write = hlsl.find("v0 = t0r0;").unwrap(); + assert!(hlsl.find("uint t0w3 = ((v0 >> 24u) | (v1 << 8u));").unwrap() < first_write, "{hlsl}"); + assert!(hlsl.find("uint t0r1 = ").unwrap() < first_write, "{hlsl}"); +} + +#[test] +fn quad_sads_refuse_modifiers_scalars_overflow_and_other_stages() { + for body in [ + [QSAD[0] | 0x8000, QSAD[1]], // clamp + [QSAD[0] | 0x0800, QSAD[1]], // op_sel + [QSAD[0], QSAD[1] | 1 << 29], // neg + [0xd575_0000, 0x0422_0802], // v_mqsad_u32_u8 v[0:3], s[2:3], v4, v[8:11] + [0xd572_00ff, 0x041a_0902], // destination pair from v255 + [0xd575_0000, 0x07f6_0902], // accumulator from v253 + ] { + assert!(translate(Stage::Compute, &body).is_err(), "{body:x?}"); + } + assert!(translate(Stage::Pixel, &QSAD).is_err()); +} + +#[test] +fn masked_byte_sad_skips_zero_reference_bytes() { + // v_msad_u8 v0, v1, v2, v3 + let hlsl = translate(Stage::Compute, &[0xd571_0000, 0x040e_0501]).unwrap(); + assert_eq!(hlsl.matches("((v2 >> 16u) & 0xffu) != 0u ?").count(), 1, "{hlsl}"); + assert!(!hlsl.contains("((v1 >> 16u) & 0xffu) != 0u"), "{hlsl}"); + // v_msad_u8 v0, v1, v2, 0: an inline accumulator is not accepted. + assert!(translate(Stage::Compute, &[0xd571_0000, 0x0202_0501]).is_err()); + assert!(translate(Stage::Pixel, &[0xd571_0000, 0x040e_0501]).is_err()); +}