diff --git a/docs/experiments/native-image-atomics.md b/docs/experiments/native-image-atomics.md index fffb013f57..0ded7913e9 100644 --- a/docs/experiments/native-image-atomics.md +++ b/docs/experiments/native-image-atomics.md @@ -1,9 +1,15 @@ # Direct Compute atomics on unsigned 2D textures The native Compute compiler lowers `image_atomic_add`, `image_atomic_umax`, -and `image_atomic_cmpswap` on a fixed table descriptor for a 2D `R32_UINT` -UAV. DXIL uses `RWTexture2D` with two integer coordinates and honours -the guest EXEC mask. GLC writes the pre-operation value to the data VGPR. +`image_atomic_cmpswap`, `image_atomic_swap`, `image_atomic_umin`, +`image_atomic_and`, `image_atomic_or` and `image_atomic_xor` on a fixed table +descriptor for a 2D `R32_UINT` UAV. Swap, umin, and, or and xor use DXIL +`AtomicBinOp` Exchange (8), UMin (6), And (1), Or (2) and Xor (3). Signed +`image_atomic_smin` and `_smax` are outside the verified scope and stay +refused, as do `sub`, `inc`, `dec` and the float atomics. + +DXIL uses `RWTexture2D` with two integer coordinates and honours the +guest EXEC mask. GLC writes the pre-operation value to the data VGPR. Compare-and-swap takes replacement from the first data VGPR and comparison from the next one. Atomic writes are included when translating memory waits and barriers. @@ -33,12 +39,20 @@ add with only 16 active lanes. Each returning operation also feeds its result to a second atomic. Clearing only the first operation's GLC bit changes the second readback and fails the comparison. +The [binary-operation fixture](../../tests/native_image_atomic_binops_check.py) +reuses that program for swap, umin, and, or and xor. Its controls check each +`AtomicBinOp` code, the operand refusals and the refused opcodes. Its readback +compares the same 336 words for distinct and contended texels, with GLC on and +off and 16 active lanes. + The runtime fixture publishes the native compiler's DXIL and manifest from a source-built device slot 67 request. A dispatch through the stand-in matches all 256 words, with the one target texel incremented by 32 across two groups. The same program with a float UAV is refused and leaves all 1,024 halfwords -unchanged. On Windows 11 build `26300.10075` both ran on the RTX 4070 with -driver `32.0.16.2124`. Direct DXIL requires wave32. Local WARP exposes four +unchanged. On Windows 11 build `26300.10075` the synthetic and runtime fixtures +ran on the RTX 4070 with driver `32.0.16.2124`. The binary-operation fixture +passed on an NVIDIA GeForce RTX 5080 (Windows 11, driver `32.0.16.2101`). +Direct DXIL requires wave32. Local WARP exposes four lanes, so the native execution test reports a capability skip there. ## References diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 78bd5dc4df..37f0fcdb2c 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -821,8 +821,21 @@ struct DirectCompute { vector_write(256 + i.dst + j, select(have_view, ir.value("bitcast float " + value + " to i32"), "0")); } } + static int image_atomic_binop(unsigned op) { + switch (op) { + case 0x0f: return 8; // Exchange + case 0x11: return 0; // IAdd + case 0x15: return 6; // UMin + case 0x17: return 7; // UMax + case 0x18: return 1; // And + case 0x19: return 2; // Or + case 0x1a: return 3; // Xor + // Signed min/max is not verified on this R32_UINT binding. + default: return -1; + } + } static bool is_image_atomic(const Inst &i) { - return i.enc == Encoding::Image && (i.op == 16 || i.op == 17 || i.op == 23); + return i.enc == Encoding::Image && (i.op == 0x10 || image_atomic_binop(i.op) >= 0); } void image_atomic(const Inst &i, const State &s) { const bool compare_exchange = i.op == 16; @@ -849,7 +862,7 @@ struct DirectCompute { << "\nimageAtomic" << label << ":\n"; std::vector> args{{"%dx.types.Handle", handle}}; if (!compare_exchange) - args.emplace_back("i32", i.op == 17 ? "0" : "7"); // AtomicBinOp IADD or UMAX. + args.emplace_back("i32", to_string(image_atomic_binop(i.op))); args.emplace_back("i32", read(256 + coord)); args.emplace_back("i32", read(257 + coord)); args.emplace_back("i32", "undef"); diff --git a/tests/cmake/native_image_atomic_binops.cmake b/tests/cmake/native_image_atomic_binops.cmake new file mode 100644 index 0000000000..ee4658b799 --- /dev/null +++ b/tests/cmake/native_image_atomic_binops.cmake @@ -0,0 +1,14 @@ +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_image_atomic_binops_check.py") + add_test(NAME native_image_atomic_binops_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$" "${DXC_BIN_DIR}") + set_tests_properties(native_image_atomic_binops_controls PROPERTIES TIMEOUT 120) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_image_atomic_binops_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" hardware "$" "${DXC_BIN_DIR}" + "$" ${adapter}) + set_tests_properties(native_image_atomic_binops_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/native_image_atomic_binops_check.py b/tests/native_image_atomic_binops_check.py new file mode 100644 index 0000000000..f8ce9f287b --- /dev/null +++ b/tests/native_image_atomic_binops_check.py @@ -0,0 +1,110 @@ +"""Check new direct DXIL integer atomics on the typed 2D uint UAV.""" +from pathlib import Path +import operator +import re +import subprocess +import sys +import tempfile + +from native_direct_container_check import compute, words +from native_image_atomic_check import ( + OPERAND, TEXELS, UINT_MASK, WIDTH, image_atomic, program_words, reference, render, +) + + +OPS = { + 'swap': (0x0f, 8, 1 << 28, lambda old, operand: operand), + 'umin': (0x15, 6, 1 << 27, min), + 'and': (0x18, 1, 1 << 25, operator.and_), + 'or': (0x19, 2, 1 << 25, operator.or_), + 'xor': (0x1a, 3, 1 << 25, operator.xor), +} +REFUSED = {'sub': 0x12, 'smin': 0x14, 'smax': 0x16, 'inc': 0x1b, 'dec': 0x1c, + 'fcmpswap': 0x1d, 'fmin': 0x1e, 'fmax': 0x1f} +OPERAND_DIAGNOSTIC = 'unsupported typed 2D image atomic operands' + + +def compile_shader(cli, sdk, work, opcode, *, glc=True, sparse=False, contend=False, **encoding): + # Retain the fixture's coordinates, EXEC mask, wait, and old-value probe. + # With GLC clear the probe observes the original data VGPR instead. + code = program_words('add', returning=True, drop_glc=not glc, sparse=sparse, + contend=contend, **encoding) + flags = encoding.get('flags', 0) | (0x2000 if glc else 0) + atomic_word, _ = image_atomic('add', flags=flags, mask=encoding.get('mask'), dim=encoding.get('dim', 1)) + index = code.index(atomic_word) + code[index] = (atomic_word & ~(0x7f << 18)) | (opcode << 18) + if contend: + # The original fixture uses 1 for contended add. Exercise the same + # high-bit operand as the distinct-texel case here. + code[code.index(0x7e1c02ff) + 1] = OPERAND + source = work / 'binop.cs' + shader = source.with_suffix('.cso') + shader.unlink(missing_ok=True) + source.write_bytes(compute(words(*code), table=True)) + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=30) + return shader, result + + +def controls(cli, sdk, work): + for name, (opcode, dxil, _, _) in OPS.items(): + shader, run = compile_shader(cli, sdk, work, opcode) + assert run.returncode == 0, ( + f'{name}: valid typed image atomic refused (operand diagnostic: {OPERAND_DIAGNOSTIC})', + run.stdout, run.stderr, + ) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', shader], + capture_output=True, text=True, timeout=30, check=True).stdout + # The second atomic is the existing add probe and must have code 0. + codes = re.findall(r'@dx\.op\.atomicBinOp\.i32\(i32 78, %dx\.types\.Handle [^,]+, i32 (\d+),', dump) + assert codes == [str(dxil), '0'] and '2d' in dump, (name, dump) + for encoding in ({'dim': 5}, {'mask': 15}, {'coord': 255}, {'flags': 0x80}, + {'addr_flags': 0x40000000}, {'addr_flags': 0x200000}): + _, run = compile_shader(cli, sdk, work, opcode, **encoding) + assert run.returncode and OPERAND_DIAGNOSTIC in run.stderr, (name, encoding, run.stdout, run.stderr) + for name, opcode in REFUSED.items(): + _, run = compile_shader(cli, sdk, work, opcode) + assert run.returncode and 'direct image opcode or descriptor modifiers' in run.stderr, ( + name, run.stdout, run.stderr, + ) + print('Typed image binary atomic DXIL codes and refusal diagnostics matched') + + +def expected_texels(update, *, glc, contend): + initial, _ = reference('add') + expected = initial.copy() + for lane in range(0, 32, 2): + x, y = (5, 6) if contend else (2 + lane % 8, 1 + lane // 8) + index = y * WIDTH + x + previous = expected[index] + expected[index] = update(previous, OPERAND) + # Contending lanes use the same operand, so the aggregate of returned + # values depends only on the number of updates, regardless of order. + probe = index + 12 + expected[probe] = (expected[probe] + (previous if glc else OPERAND)) & UINT_MASK + return initial, expected + + +def hardware(cli, sdk, work, renderer, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, (wave.stdout, wave.stderr) + print(wave.stdout, end='') + for name, (opcode, _, format_selector, update) in OPS.items(): + for contend in (False, True): + for glc in (False, True): + shader, run = compile_shader(cli, sdk, work, opcode, glc=glc, sparse=True, contend=contend) + assert run.returncode == 0, (name, glc, contend, run.stdout, run.stderr) + initial, expected = expected_texels(update, glc=glc, contend=contend) + payload = work / 'texture.bin' + payload.write_bytes(words(1 | format_selector, 0, *initial, *expected)) + run = render(renderer, adapter, '--compute-texture-store-case', shader, payload) + assert run.returncode == 0, (name, glc, contend, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'{name} GLC={glc} contended={contend}: {TEXELS} texture words matched') + + +if __name__ == '__main__': + mode, cli, sdk, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as temp: + {'controls': controls, 'hardware': hardware}[mode](cli, sdk, Path(temp), *args)