From 7582c01d97e2c26e47ac084fdd13c28e335dfbdc Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Fri, 27 Nov 2026 08:24:07 +0100 Subject: [PATCH 1/2] native: read the byte-address rewrite of a GPU-selected heap descriptor Under the raw_buffer heap view contract the direct compute path now tracks the byte-address rewrite (stride, max 1, byte count, stride cleared, raw out-of-bounds mode) of a descriptor loaded from the GPU-selected heap slot, as byte_descriptor_field already does for table descriptors, and reads a raw load through it as the same ResourceDescriptorHeap[slot] raw view. The words must come from one heap load; a program with a backward branch refuses the window as a precaution. Without a contract nothing changes. Refs #3023, part of #2935. Co-Authored-By: Claude Opus 5.5 --- .../native-global-srv-heap-replay.md | 39 +++++++-- src/gfx1013_compute_native.cpp | 23 +++-- src/gfx1013_compute_native.h | 5 ++ src/gfx1013_direct_compute.inl | 24 +++++- tests/native_global_srv_heap_replay_check.py | 83 +++++++++++++++++-- 5 files changed, 153 insertions(+), 21 deletions(-) diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index 7d4a486387..4076ce668a 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -9,8 +9,17 @@ Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ D `none`, `raw_buffer`, `other`). An SMEM descriptor load from the resource heap is refused unless the contract is `raw_buffer`; without a contract the existing text stays: "direct resource-heap load requires the selected GPU slot and its view type". A scalar buffer load from the heap base, a heap descriptor load with an immediate offset or a constant - index (both could address another slot than the captured selection), and a stride read of a GPU-selected slot in the - direct path are refused with their own texts. The contract is part of the frontend cache key when it is not `none`. + index (both could address another slot than the captured selection), and a numeric use of a GPU-selected slot's + stride in the direct path are refused with their own texts. The contract is part of the frontend cache key when it is + not `none`. +- Byte-address rewrite (#3023): under `raw_buffer` the direct path tracks the rewrite of the loaded heap descriptor that + `byte_descriptor_field` already models for table descriptors (`s_bfe_u32 ... 0xe0010` stride, `s_max_u32 ... 1`, + `s_mul_i32` byte count, `s_and_b32 ... 0xc000ffff`, `s_and_b32 ... 0xcfffffff`, `s_or_b32 ... 0x30000000`, word 0 + copied). A raw load through the rewritten descriptor reads the same `ResourceDescriptorHeap[slot]` raw view. The words + must all come from one heap load (same pc); a program with a backward branch anywhere refuses the window, as a + precaution, because a loop would run that load again for another selection. The caller's contract: every slot the + program can select is a raw view of exactly `num_records * max(stride, 1)` bytes; the translator does not check that, + nor the swizzle bits or the other word 3 fields. Without the contract the first refusal stays as before. - Modules that read `ResourceDescriptorHeap` now also set shader flag `0x40000000`, as DXC does for the HLSL reference. Without it the validator refuses the module ("Flags must match usage. Validation failed."), measured by removing the flag and running the hardware test. @@ -70,7 +79,14 @@ The check runs, in order: line, no line for the selected slot, `select 7`, and (replay) a missing `.views` file. Each gives an explicit diagnostic, no `.cso`, and intact sentinels. 8. Shader shapes refused by `compile_dxil` even with valid metadata: a constant heap index, a heap descriptor load with - an immediate offset, and a stride read of the selected slot. + an immediate offset, a stride read used as a number (`unbound numeric SGPR s24`), and four byte-address rewrites the + raw slot view cannot stand for: a wrong stride mask (`unbound numeric SGPR s21`), word 0 from a second heap load + (`non-contiguous resource descriptor`), a store through the rewritten descriptor (`a GPU-selected heap slot is read + as a raw buffer SRV only`) and a never-taken backward branch before the rewrite (`heap byte window in a program with + a backward branch`). +9. The byte-address rewrite: a stride read that nothing uses compiles; the program with the full rewrite is recorded + for selections 0 and 1 (output equals the slot's data), compiled by `compile_dxil --requests`, replayed with the + same result, and replaying selection 0 against the slot 1 reference reports a mismatch. ## Result @@ -88,6 +104,14 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha (one known failure, `native_wave_request_hardware`, #2915, addressed by #2928). - Revert control: with the heap refusal restored for every contract, `record` for selection 0 exits 4 with "direct resource-heap load requires the selected GPU slot and its view type". +- Byte-address rewrite (#3023): `native_global_srv_heap_replay_hardware` passed, 83 assertions, on the same machine and + driver. The check run against `compile_dxil` and the fixture built at `999e17cd` (before the change) fails at + `stride_read` (old text "a GPU-selected heap slot stride read is not translated with a view contract") and, with the + shapes skipped, at "an unused stride read compiles" (the run stops there, so the full-rewrite record step was not + reached on that build). `ctest --preset dev --no-tests=error -R + "native_|startup_compute_dispatch|compute_heap" -j 6`: 147 tests, 142 passed, 4 skipped (77, WARP), 1 failed + (`native_cvt_pk_u8_hardware`, failing before the change as well). `compile_dxil --refusals` on a local start-up + capture gives the same output as before (it translates without a contract). ## Limits @@ -96,7 +120,12 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha out of bounds. No static index bound is checked. - Replay regenerates the slot contents deterministically from the slot index; `.views` captures type, stride and size, not contents. -- In the direct DXIL path a stride read of a GPU-selected heap slot is refused. The HLSL path's `heap_stride_srv` - (`src/gfx1013_compute_native.cpp`, used by `tests/native_compute_grid.cpp`) is unchanged. +- In the direct DXIL path a GPU-selected slot's stride is never a number: it is tracked symbolically and only the + byte-address rewrite consumes it. The fixture's descriptor words are never evaluated, so a stride above 1 and the + size rule of the contract are not exercised. The HLSL path's `heap_stride_srv` (`src/gfx1013_compute_native.cpp`, + used by `tests/native_compute_grid.cpp`) is unchanged. +- Typed loads (`buffer_load_format_*`) through a heap descriptor and scalar loads through the rewritten descriptor stay + refused. The startup runtime + does not pass a contract yet, so none of this reaches a title run (#3023). - The captured `select` must be the slot index the dispatch addresses; producing it from a title capture is outside this fixture. diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 60270f869d..d37bf75178 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -437,12 +437,15 @@ Symbol source(const Inst &i, unsigned code, const State &s) { unsigned memory_count(const Inst &i) { return 1u << (i.op & 7); } // Derive the rewritten byte-address V# symbolically. Each field carries its // source table/slot identity. Numeric consumption still requires real bits. -static std::optional byte_descriptor_field(const Inst &i, const State &s) { +// heap_window: the direct path under HeapViewContract::raw_buffer also rewrites a +// descriptor loaded from the GPU-selected heap slot (its words keep the load pc). +static std::optional byte_descriptor_field(const Inst &i, const State &s, bool heap_window = false) { using T = Symbol::Type; if (i.enc != Encoding::Sop2 || i.dst > 105) return {}; auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); - auto component = [](const Symbol &v, unsigned ch) { - return v.type == T::descriptor && v.offset % 32 == ch*4 && v.value != compute_resource_heap; + auto component = [heap_window](const Symbol &v, unsigned ch) { + return v.offset % 32 == ch*4 && ((v.type == T::descriptor && v.value != compute_resource_heap) || + (heap_window && v.type == T::indexed_descriptor && v.value == compute_resource_heap)); }; auto field = [](Symbol v, T kind) { v.type = kind; @@ -464,7 +467,7 @@ static std::optional byte_descriptor_field(const Inst &i, const State &s return field(a,T::byte_oob); return {}; } -State transfer(const Inst &i, State s, bool wave64, bool graphics) { +State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_window = false) { auto set = [&](unsigned n, Symbol v) { if (n >= s.size()) refuse(i.pc, "invalid SGPR"); @@ -483,7 +486,7 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics) { (i.src[0] == 193 || i.src[0] == 128) && (i.src[1] == 193 || i.src[1] == 128)) { set(i.dst,{Symbol::Type::uniform_mask,i.pc,0}); set(i.dst+1,{Symbol::Type::uniform_mask,i.pc,1}); - } else if (auto field = byte_descriptor_field(i,s)) { + } else if (auto field = byte_descriptor_field(i,s,heap_window)) { set(i.dst,*field); } else if (i.enc == Encoding::FixedSetup) { for (unsigned r = i.dst; r < i.dst + i.op && r < s.size(); ++r) s[r] = {}; @@ -621,7 +624,8 @@ std::map fixed_vertex_loads(const string &code) { } return found ? result : std::map{}; } -Program parse(const string &code, unsigned entry, const State &initial, bool graph, bool graphics=false, bool wave64=false, bool fixed_vertex=false) { +Program parse(const string &code, unsigned entry, const State &initial, bool graph, bool graphics=false, bool wave64=false, bool fixed_vertex=false, + bool heap_window=false) { Program p; p.graphics_wave64 = graphics && wave64; if ((entry & 3) || entry >= code.size() || code.size() > 1u << 20) @@ -670,7 +674,7 @@ Program parse(const string &code, unsigned entry, const State &initial, bool gra auto k = work.front(); work.pop_front(); auto &i = p.code[k]; - auto after = transfer(i, p.before[k], wave64, graphics); + auto after = transfer(i, p.before[k], wave64, graphics, heap_window); auto merge = [&](size_t t) { bool changed = !p.reached[t]; auto &in = p.before[t]; @@ -1502,7 +1506,9 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi if (!stage && (UINT(layout->Desc_1_1.Flags) & 0xc00u) == 0xc00u && next + 2 == user) initial[next] = {Symbol::Type::table, compute_resource_heap}; const bool wave64 = stage && !stage->wave32; - auto program = parse(request.code, entry, initial, direct_dxil, false, wave64); + // The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer contract. + const bool heap_window = direct_dxil && heap_view == HeapViewContract::raw_buffer; + auto program = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window); Emit emit{{}, program,layout->Desc_1_1}; emit.result.constants = constants; if (!lds) @@ -1513,6 +1519,7 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi DirectCompute compiler{emit}; compiler.wave64 = wave64; compiler.heap_view = heap_view; + compiler.heap_window = heap_window; if (threads % (wave64 ? 64 : 32)) for (const auto &i : program.code) if (i.name == "v_readlane_b32" || i.name == "v_writelane_b32") diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 9824e1f37c..03dc53cec8 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -112,6 +112,11 @@ struct NativeComputeShader { // The view class a GPU-selected descriptor heap slot is read as. none: the slot and its view type are not known, so a // heap read is refused. raw_buffer: the capture says the selected slot is a raw buffer SRV. other: the capture names a // view type that is not translated (refused when the shader reads the heap). +// Under raw_buffer the direct path also reads the byte-address rewrite of the selected descriptor (stride read, +// max(stride, 1), byte count, stride cleared, raw out-of-bounds mode) as the same raw view. The caller guarantees that +// every slot the program can select is a raw view whose size is the guest range num_records * max(stride, 1); the +// translator does not check that, nor the swizzle bits (word 1 bits 31:30) or the other word 3 fields, and a program +// with two heap loads from different selectors is outside what one captured selection covers. enum class HeapViewContract : unsigned { none, raw_buffer, other }; NativeComputeShader translate_compute(const ComputeRequest &request, unsigned entry_byte_offset, bool direct_dxil = false); diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 3ad5cd714a..192efe4afd 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -26,6 +26,8 @@ struct DirectCompute { bool wave64 = false; // The view class a GPU-selected heap slot is read as; see HeapViewContract. HeapViewContract heap_view = HeapViewContract::none; + // heap_view is raw_buffer and the path is direct: the byte-address rewrite of a heap descriptor is tracked. + bool heap_window = false; // Binary16 add, sub, subrev and mul are lowered only while MODE stays at // the contract this path implements: round-to-nearest-even, f16 denormals // kept on input and output, and FP16_OVFL clear. mode_bits holds the @@ -279,16 +281,30 @@ struct DirectCompute { // A raw buffer SRV chosen by a GPU value in the whole descriptor heap: ResourceDescriptorHeap[slot]. The view class the // shader reads is the one this handle is annotated with (raw buffer); a slot holding another class is refused by the // dispatch before the shader runs. The binding names the heap (no table register); the pipeline indexes it directly. + // A byte window is the byte-address rewrite of that descriptor (word 0 copied, word 1 without stride, word 2 the + // byte count, word 3 with the raw out-of-bounds mode; see byte_descriptor_field): read as the same raw slot view. string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { const auto &symbol = s.at(base); refuse_heap_contract(i.pc); - if (kind != ComputeViewKind::raw_vector_srv && kind != ComputeViewKind::buffer_srv) + const bool window = kind == ComputeViewKind::byte_window_srv; + if (kind != ComputeViewKind::raw_vector_srv && kind != ComputeViewKind::buffer_srv && !window) refuse(i.pc, "a GPU-selected heap slot is read as a raw buffer SRV only"); if (symbol.offset % 32 || s[base].type != Symbol::Type::indexed_descriptor) refuse(i.pc, "unaligned heap descriptor"); + // Precaution: the rewritten words are compared by the pc of their heap load, which a loop executes again for + // another selection. + if (window) + for (const auto &inst : analysis.program.code) + if (inst.branch() && inst.target() <= inst.pc) + refuse(i.pc, "heap byte window in a program with a backward branch"); + constexpr Symbol::Type window_words[] = {Symbol::Type::indexed_descriptor, Symbol::Type::zero_stride_word, + Symbol::Type::byte_count, Symbol::Type::byte_oob}; for (unsigned j = 1; j < 4; ++j) { Symbol expected = symbol; - expected.offset += 4 * j; + if (window) + expected.type = window_words[j]; // field() already cleared the word offset + else + expected.offset += 4 * j; if (!(s.at(base + j) == expected)) refuse(i.pc, "non-contiguous resource descriptor"); } @@ -1472,7 +1488,7 @@ struct DirectCompute { } else write_ballot(*dst, carry); return; } - if (auto field = byte_descriptor_field(i,state)) { + if (auto field = byte_descriptor_field(i,state,heap_window)) { // Keep derived words symbolic, including the status bit until a // later instruction overwrites it. Never let a numeric branch // observe a placeholder for this field or its SCC. @@ -1640,6 +1656,8 @@ struct DirectCompute { descriptor.offset % 32 == 4 && field.type == Symbol::Type::constant && field.value == 0xe0010) { // Reachable only through a heap descriptor load, which needs the raw_buffer contract. A raw buffer view // has no stride to read, so the stride of a GPU-selected slot stays untranslated in the direct path. + // With the raw_buffer contract a stride read into s0-s105 is tracked symbolically + // (byte_descriptor_field) and does not reach here. refuse_heap_contract(i.pc); refuse(i.pc, "a GPU-selected heap slot stride read is not translated with a view contract"); } diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py index b75844a15a..15a5c6a5e6 100644 --- a/tests/native_global_srv_heap_replay_check.py +++ b/tests/native_global_srv_heap_replay_check.py @@ -223,11 +223,36 @@ def without(prefix): variant("no_slot_line", without("slot 0 "), "global SRV slot 0 has no captured view type") variant("select_7", good.replace("select 0", "select 7"), "global SRV slot 7 has no captured view type") - # 8. Shader shapes whose heap read could address another slot than the captured selection, or read the slot's - # stride: refused by compile_dxil even with valid metadata, no .cso. + # 8. Shader shapes whose heap read could address another slot than the captured selection, use the slot's stride + # as a number, or rewrite the heap descriptor in a way the raw slot view cannot stand for: refused by + # compile_dxil even with valid metadata, no .cso. words_list = list(struct.unpack(f"<{len(PROGRAM) // 4}I", PROGRAM)) lshl = words_list.index(0x8f118510) heap_load = words_list.index(0xf4080501) + after_wait = heap_load + 3 # the s_waitcnt after the heap descriptor load + # The byte-address rewrite of the heap descriptor s[20:23] into s[24:27] (LLVM 15 encodings, as above). + rewrite = [ + 0x939cff15, 0x000e0010, # s_bfe_u32 s28, s21, 0xe0010 (stride) + 0x849c811c, # s_max_u32 s28, s28, 1 + 0x931a1c16, # s_mul_i32 s26, s22, s28 (byte count) + 0x8719ff15, 0xc000ffff, # s_and_b32 s25, s21, 0xc000ffff (stride cleared) + 0x871bff17, 0xcfffffff, # s_and_b32 s27, s23, 0xcfffffff + 0x881bff1b, 0x30000000, # s_or_b32 s27, s27, 0x30000000 (raw out-of-bounds mode) + 0xbe980314, # s_mov_b32 s24, s20 + ] + load = words_list.index(0xe0301000) # buffer_load_dword v2, v1, s[20:23], 0 offen + store = words_list.index(0xe0701000) # buffer_store_dword v2, v1, s[12:15], 0 offen + + def window(rewritten=rewrite, prefix=(), store_word=0x80030201): + """PROGRAM with the rewrite after the heap load and the load through s[24:27].""" + program = list(words_list) + program[load + 1] = 0x80060201 # buffer_load_dword v2, v1, s[24:27], 0 offen + program[store + 1] = store_word + return program[:after_wait] + list(prefix) + list(rewritten) + program[after_wait:] + + WINDOW = window() + second_load = window([0xbe980320 if w == 0xbe980314 else w for w in rewrite]) + second_load[after_wait - 1:after_wait - 1] = [0xf4080801, 0x22000000] # before the s_waitcnt shapes = { # s_mov_b32 s17, 64 instead of the GPU-derived s_lshl_b32 s17, s16, 5 "constant_index": (words_list[:lshl] + [0xbe9103c0] + words_list[lshl + 1:], @@ -235,9 +260,18 @@ def without(prefix): # s_load_dwordx4 s[20:23], s[2:3], s17 offset:0x20 "immediate_offset": (words_list[:heap_load] + [0xf4080501, 0x22000020] + words_list[heap_load + 2:], "heap descriptor load with an immediate offset addresses another slot than the captured selection"), - # s_bfe_u32 s24, s21, 0xe0010 after the heap descriptor load (stride field of the selected slot) - "stride_read": (words_list[:heap_load + 3] + [0x9398ff15, 0x000e0010] + words_list[heap_load + 3:], - "a GPU-selected heap slot stride read is not translated with a view contract"), + # s_bfe_u32 s24, s21, 0xe0010 after the heap descriptor load (stride field of the selected slot), then + # v_mov_b32 v3, s24: the stride is used as a number + "stride_read": (words_list[:after_wait] + [0x9398ff15, 0x000e0010, 0x7e060218] + words_list[after_wait:], + "unbound numeric SGPR s24"), + # s_and_b32 s25, s21, 0xc000fffe: not the mask that clears the stride + "window_wrong_mask": (window([0xc000fffe if w == 0xc000ffff else w for w in rewrite]), "unbound numeric SGPR s21"), + # a second heap load s_load_dwordx4 s[32:35], s[2:3], s17 and word 0 from it (s_mov_b32 s24, s32) + "window_second_load": (second_load, "non-contiguous resource descriptor"), + # buffer_store_dword v2, v1, s[24:27], 0 offen: a store through the window + "window_store": (window(store_word=0x80060201), "a GPU-selected heap slot is read as a raw buffer SRV only"), + # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 -2 (back to the compare, never taken) before the rewrite + "window_loop": (window(prefix=(0xbf071010, 0xbf85fffe)), "heap byte window in a program with a backward branch"), } for name, (program, expected) in shapes.items(): directory = base / ("shape_" + name) @@ -252,6 +286,45 @@ def without(prefix): require(code == 1 and expected in err, f"compile_dxil shape '{name}': refused with '{expected}'") require(not any(out_dir.glob("*.cso")), f"compile_dxil shape '{name}': no .cso") + # 9. The byte-address rewrite of the selected heap descriptor (stride, max 1, byte count, stride cleared, raw + # out-of-bounds mode) reads the selected raw slot: recorded, compiled offline and replayed like PROGRAM. A stride + # read that nothing uses compiles too. The descriptor words stay symbolic, so a stride > 1 is not exercised. + def window_request(name, program): + directory = base / name + directory.mkdir() + cdx_bytes = compute_two_inputs(words(*program)) + window_stem = "req_%016x" % key_of(root, cdx_bytes) + (directory / (window_stem + ".cdx")).write_bytes(cdx_bytes) + (directory / (window_stem + ".root")).write_bytes(root) + return directory, window_stem + + directory, window_stem = window_request("stride_unused", words_list[:after_wait] + [0x9398ff15, 0x000e0010] + + words_list[after_wait:]) + (directory / (window_stem + ".views")).write_text(good, newline="\n") + out_dir = base / "stride_unused_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 0 and "requests=1 compiled=1 refused=0" in out and (out_dir / (window_stem[len("req_"):] + ".cs.cso")).exists(), + "compile_dxil: an unused stride read compiles and publishes a .cso") + window_outputs = {} + for n in (0, 1): + directory, window_stem = window_request(f"window{n}", WINDOW) + code, out, err = run([fixture, "record", sdk, cache, directory / (window_stem + ".cdx"), adapter, n, "ok"]) + require(code == 0 and "output matches slot %d data" % n in out, + f"record window select {n}: u0 equals the slot {n} data read through the rewritten descriptor") + out_dir = base / f"window{n}_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + cso = out_dir / (window_stem[len("req_"):] + ".cs.cso") + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil window select {n}: compiled and published a .cso") + window_outputs[n] = (directory, window_stem, cso) + code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, + directory / (window_stem + ".views"), adapter, "ok", n]) + require(code == 0 and "output matches slot %d data" % n in out, f"replay window select {n}: output equals slot {n} data") + directory, window_stem, cso = window_outputs[0] + code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, + directory / (window_stem + ".views"), adapter, "ok", 1]) + require(code == 1 and "mismatch word 0" in out, "replay window select 0 compared with slot 1 data reports a mismatch") + missing = base / "missing" / (stem + ".views") code, out, err = replay(selections[0], outputs[0], missing, "refused", 0) require(code == 0 and "global SRV view metadata file missing: " + str(missing) in out and "sentinels intact" in out, From 837728ddfa9f612ca4c73817055b5ba72fdbd318 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Fri, 27 Nov 2026 09:04:11 +0100 Subject: [PATCH 2/2] native: refuse a heap byte window only for a loop around its heap load The first guard refused the window for any backward branch in the program. On a local start-up capture (contract forced locally) that refused 921 of 2,689 requests, although their loops do not contain the heap descriptor load. Only a loop around that load runs it again for another selection, so the guard now checks whether a backward branch's range contains the load pc (symbol.definition). The test refuses a loop back to the load and compiles a loop after it. Refs #3023. Co-Authored-By: Claude Opus 5.5 --- .../native-global-srv-heap-replay.md | 18 ++++++++---- src/gfx1013_direct_compute.inl | 9 +++--- tests/native_global_srv_heap_replay_check.py | 29 +++++++++++++------ 3 files changed, 38 insertions(+), 18 deletions(-) diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index 4076ce668a..9d89103578 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -16,8 +16,9 @@ Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ D `byte_descriptor_field` already models for table descriptors (`s_bfe_u32 ... 0xe0010` stride, `s_max_u32 ... 1`, `s_mul_i32` byte count, `s_and_b32 ... 0xc000ffff`, `s_and_b32 ... 0xcfffffff`, `s_or_b32 ... 0x30000000`, word 0 copied). A raw load through the rewritten descriptor reads the same `ResourceDescriptorHeap[slot]` raw view. The words - must all come from one heap load (same pc); a program with a backward branch anywhere refuses the window, as a - precaution, because a loop would run that load again for another selection. The caller's contract: every slot the + must all come from one heap load (same pc). As a precaution, a backward branch whose loop contains that heap load + refuses the window, because the loop would run the load again for another selection. Loops elsewhere in the program + do not refuse it. The caller's contract: every slot the program can select is a raw view of exactly `num_records * max(stride, 1)` bytes; the translator does not check that, nor the swizzle bits or the other word 3 fields. Without the contract the first refusal stays as before. - Modules that read `ResourceDescriptorHeap` now also set shader flag `0x40000000`, as DXC does for the HLSL reference. @@ -82,9 +83,10 @@ The check runs, in order: an immediate offset, a stride read used as a number (`unbound numeric SGPR s24`), and four byte-address rewrites the raw slot view cannot stand for: a wrong stride mask (`unbound numeric SGPR s21`), word 0 from a second heap load (`non-contiguous resource descriptor`), a store through the rewritten descriptor (`a GPU-selected heap slot is read - as a raw buffer SRV only`) and a never-taken backward branch before the rewrite (`heap byte window in a program with - a backward branch`). -9. The byte-address rewrite: a stride read that nothing uses compiles; the program with the full rewrite is recorded + as a raw buffer SRV only`) and a never-taken backward branch to (or before) the heap load (`heap byte window loaded + inside a loop`). +9. The byte-address rewrite: a stride read that nothing uses compiles, a never-taken backward branch after the heap + load (the loop does not contain the load) compiles, and the program with the full rewrite is recorded for selections 0 and 1 (output equals the slot's data), compiled by `compile_dxil --requests`, replayed with the same result, and replaying selection 0 against the slot 1 reference reports a mismatch. @@ -112,6 +114,12 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha "native_|startup_compute_dispatch|compute_heap" -j 6`: 147 tests, 142 passed, 4 skipped (77, WARP), 1 failed (`native_cvt_pk_u8_hardware`, failing before the change as well). `compile_dxil --refusals` on a local start-up capture gives the same output as before (it translates without a contract). +- Loop guard narrowed: the first version of the guard refused the window for any backward branch in the program. + With the contract forced locally (an uncommitted switch), it refused 921 of the 2,689 requests of the same capture. + With the guard limited to loops around the heap load, none of these is refused for a loop; 906 then stop at a typed + load (`buffer_load_format_*`) through the heap descriptor. After the change, the test passes with 84 assertions. The + run against the earlier commit `7582c01d` fails at the `window_loop` shape (old text "heap byte window in a program + with a backward branch"). The run stops there. ## Limits diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 192efe4afd..b83d57ac73 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -291,12 +291,13 @@ struct DirectCompute { refuse(i.pc, "a GPU-selected heap slot is read as a raw buffer SRV only"); if (symbol.offset % 32 || s[base].type != Symbol::Type::indexed_descriptor) refuse(i.pc, "unaligned heap descriptor"); - // Precaution: the rewritten words are compared by the pc of their heap load, which a loop executes again for - // another selection. + // Precaution: the rewritten words are compared by the pc of their heap load (symbol.definition), which a loop + // around that load executes again for another selection. A loop that does not contain the load runs it once. + // The scan also sees unreached code up to s_endpgm, which can only refuse more. if (window) for (const auto &inst : analysis.program.code) - if (inst.branch() && inst.target() <= inst.pc) - refuse(i.pc, "heap byte window in a program with a backward branch"); + if (inst.branch() && inst.target() <= symbol.definition && symbol.definition <= inst.pc) + refuse(i.pc, "heap byte window loaded inside a loop"); constexpr Symbol::Type window_words[] = {Symbol::Type::indexed_descriptor, Symbol::Type::zero_stride_word, Symbol::Type::byte_count, Symbol::Type::byte_oob}; for (unsigned j = 1; j < 4; ++j) { diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py index 15a5c6a5e6..d679b3cfb4 100644 --- a/tests/native_global_srv_heap_replay_check.py +++ b/tests/native_global_srv_heap_replay_check.py @@ -253,6 +253,8 @@ def window(rewritten=rewrite, prefix=(), store_word=0x80030201): WINDOW = window() second_load = window([0xbe980320 if w == 0xbe980314 else w for w in rewrite]) second_load[after_wait - 1:after_wait - 1] = [0xf4080801, 0x22000000] # before the s_waitcnt + # The branch word sits at after_wait + 1; its target is next pc + 4 * simm16, here the s_lshl_b32 at word lshl. + loop_around_load = window(prefix=(0xbf071010, 0xbf850000 | ((lshl - (after_wait + 2)) & 0xFFFF))) shapes = { # s_mov_b32 s17, 64 instead of the GPU-derived s_lshl_b32 s17, s16, 5 "constant_index": (words_list[:lshl] + [0xbe9103c0] + words_list[lshl + 1:], @@ -270,8 +272,9 @@ def window(rewritten=rewrite, prefix=(), store_word=0x80030201): "window_second_load": (second_load, "non-contiguous resource descriptor"), # buffer_store_dword v2, v1, s[24:27], 0 offen: a store through the window "window_store": (window(store_word=0x80060201), "a GPU-selected heap slot is read as a raw buffer SRV only"), - # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 -2 (back to the compare, never taken) before the rewrite - "window_loop": (window(prefix=(0xbf071010, 0xbf85fffe)), "heap byte window in a program with a backward branch"), + # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 back to the s_lshl_b32 before the heap load (never taken): the + # loop contains the heap load, which would run again for another selection + "window_loop": (loop_around_load, "heap byte window loaded inside a loop"), } for name, (program, expected) in shapes.items(): directory = base / ("shape_" + name) @@ -298,13 +301,21 @@ def window_request(name, program): (directory / (window_stem + ".root")).write_bytes(root) return directory, window_stem - directory, window_stem = window_request("stride_unused", words_list[:after_wait] + [0x9398ff15, 0x000e0010] + - words_list[after_wait:]) - (directory / (window_stem + ".views")).write_text(good, newline="\n") - out_dir = base / "stride_unused_out" - code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) - require(code == 0 and "requests=1 compiled=1 refused=0" in out and (out_dir / (window_stem[len("req_"):] + ".cs.cso")).exists(), - "compile_dxil: an unused stride read compiles and publishes a .cso") + compiled_shapes = { + "stride_unused": (words_list[:after_wait] + [0x9398ff15, 0x000e0010] + words_list[after_wait:], + "an unused stride read compiles and publishes a .cso"), + # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 -2 (back to the compare, never taken) after the heap load: the loop + # does not contain the load, which runs once + "window_loop_after_load": (window(prefix=(0xbf071010, 0xbf85fffe)), + "a loop after the heap load does not refuse the window, a .cso is published"), + } + for name, (program, message) in compiled_shapes.items(): + directory, window_stem = window_request(name, program) + (directory / (window_stem + ".views")).write_text(good, newline="\n") + out_dir = base / (name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 0 and "requests=1 compiled=1 refused=0" in out and + (out_dir / (window_stem[len("req_"):] + ".cs.cso")).exists(), "compile_dxil: " + message) window_outputs = {} for n in (0, 1): directory, window_stem = window_request(f"window{n}", WINDOW)