Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -15963,7 +15963,7 @@ Past the entry block of a program with branches, the read does not copy the VGPR

A lane that was inactive at the definition keeps an older VGPR value; the recomputed expression gives every lane the first active lane's value instead. `exec` need not be known at the definition. A conditional branch between the definition and the read is a fall-through, not a join, and is accepted. The one case where hardware can differ is a read with no active lane: it returns lane 0's VGPR, which the program cannot rely on. `tests/startup_gfx2hlsl_readfirstlane_recompute_check.py` checks the accepted forms (including one-path scalars and uniform loop counters both inside and after loops) and refuses each condition above, including a definition under a narrower `exec` than the read, a rewritten scalar input, a loop back edge, a divergent `else`-arm write before a join, a non-uniform loop back-edge and a join where two definitions reach.

A compute buffer load through a read-only descriptor and uniform address is also accepted past the entry block when the entry EXEC mask is still known. The lowering saves the uniform value in a function-scope temporary so the read uses the value held when the load ran, even if the offset scalar later changes. A narrowed mask may be empty. In that case RDNA 2 reads the previous lane-zero VGPR, which an unguarded reload cannot reproduce. Branch targets, EXEC writes and VGPR overwrites invalidate the proof between the load and read. The source-built controls cover scalar and vector addresses, the second dword, formatted loads, and a lane-zero sentinel followed by empty EXEC.
A compute buffer load through a read-only descriptor and uniform address is also accepted past the entry block when the entry EXEC mask is still known. The lowering saves the uniform value in a function-scope temporary so the read uses the value held when the load ran, even if the offset scalar later changes. A narrowed mask may be empty. In that case RDNA 2 reads the previous lane-zero VGPR, which an unguarded reload cannot reproduce. Branch targets, EXEC writes and VGPR overwrites invalidate the proof between the load and read. A loop may revisit the load after changing EXEC. The lowering follows control-flow edges from EXEC writers to catch this case, including detours outside the loop's instruction range. A loop that changes EXEC only after it exits still qualifies. The source-built controls cover scalar and vector addresses, the second dword, formatted loads, and a lane-zero sentinel followed by empty EXEC.

[`tests/startup_compute_readfirstlane_check.py`](../tests/startup_compute_readfirstlane_check.py) pairs that unit coverage with a source-built gfx1013 compute fixture (`(4, 1, 1)` local threads x `(2, 1, 1)` groups) containing both a one-path SGPR across a uniform forward branch join and a four-iteration uniform loop counter read via `v_readfirstlane_b32` inside the loop and after exit, machine-code refusal patches (non-uniform `s_cbranch_vccnz` back-edge, divergent `else`/`then` write before a join, lane-mask loop update) and 320-word GPU readback with pinned `dropped-one-path`, `dropped-loop-read` and `dropped-post-loop` negative controls. Verified with zero mismatches and zero D3D12 debug-layer errors or warnings on Windows 11 25H2 (build 26200.9974) across WARP 10.0.26100.9818 and an AMD Radeon RX 7900 XTX (driver 32.0.32029.2010).

Expand Down
33 changes: 15 additions & 18 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,12 @@ The translation is refused when:
- either header has another size;
- the code reads an attribute the table does not list.

The shader cache revision is `x2w-startup-shader-21`. Revision 21 refuses a compute lane-mask form that revision 20 translated (`s_and_b32 M, X, exec_lo` with X data, see docs/experiments.md), so its cached compute shaders are not reused. Revision 20 decodes MTBUF/MUBUF format 50 (`R10G10B10A2_UNORM`) in the run-time FORMAT switch, so cached shaders from revision 19 are not reused. Revision 19 folds `s_mov_b32` from a scalar register that
holds a plain constant, so later reads of the copy use the constant word. The matching compute
(`x2w-startup-shader-21cs`) key advances because that stage uses the shared lowering. The fixed slot 57 mesh
Graphics and compute use cache revisions `x2w-startup-shader-22` and `x2w-startup-shader-22cs`.
Revision 22 invalidates compute shaders that assumed the entry EXEC mask at a load reached on a later
loop iteration after an EXEC write. The two cache keys advance together.
Revision 21 refuses a compute lane-mask form that revision 20 translated (`s_and_b32 M, X, exec_lo` with X data).
Revision 20 decodes MTBUF/MUBUF format 50 (`R10G10B10A2_UNORM`) in the run-time FORMAT switch.
Revision 19 folds `s_mov_b32` from a scalar register that holds a plain constant, so later reads of the copy use the constant word. The fixed slot 57 mesh
(`x2w-startup-mesh-57-3`) key stays, because that shader is not translated from guest code.
Revisions before 19 read a register copied from a constant as a run-time value.
Revision 18 preserves the sign of zero in floating-point min, max, min3, max3 and med3.
Expand Down Expand Up @@ -2792,24 +2795,20 @@ hardware or driver glitch count.

## APU heap stand-in

With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` reserves
(`MEM_RESERVE`, 0 bytes committed up front). The heap is a first-fit free list in a static table of 4096
extents, guarded by one lock. `ApuAlloc` commits the 4 KiB page span covering the allocated block on demand
(`MEM_COMMIT`), rolling back the free-list change and returning `E_OUTOFMEMORY` if commit fails. `ApuFree`
gives a block back, merges it with free neighbours, and decommits strictly interior 4 KiB pages
(`[ceil_page(free_begin), floor_page(free_end))` via `MEM_DECOMMIT`) so partial boundary pages shared with
live neighbours stay committed and streaming code that allocates and frees repeatedly no longer exhausts the
heap or commit charge. While nothing has been freed the offsets are the ones a bump allocator hands out.
With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` commits. The
heap is a first-fit free list in a static table of 4096 extents, guarded by one lock. `ApuFree` gives a
block back and merges it with free neighbours, so streaming code that allocates and frees repeatedly no
longer exhausts the heap. While nothing has been freed the offsets are the ones a bump allocator hands out.

- A block is aligned in address (a power of two, 16 at least; 0, anything below 16 and a value that is not a power of two
all mean 16). Size and alignment are 32 bits. `ApuCreateHeap` creates and publishes the heap under one lock, so
competing first calls cannot reset a heap that already has live blocks. A heap whose 64 KiB-rounded size
exceeds 4 GiB is refused with `E_INVALIDARG` without reserving or committing memory, so every block fits the APU range.
exceeds 4 GiB is refused with `E_INVALIDARG` without committing memory, so every block fits the APU range.
- Null or non-writable output (`virtual_address` or optional `apu_address`) is `E_POINTER` without
allocating; size 0 is `E_INVALIDARG`; no room, an offset past 32 bits, a full extent table, or a failed
page commit is `E_OUTOFMEMORY`. A refused call leaves the heap and the optional APU-address output as they were,
allocating; size 0 is `E_INVALIDARG`; no room, an offset past 32 bits, or a full extent table is
`E_OUTOFMEMORY`. A refused call leaves the heap and the optional APU-address output as they were,
and writes null to the virtual-address output when writable.
- A block that is reused is zeroed, as fresh heap memory is (including still-committed shared boundary pages).
- A block that is reused is zeroed, as fresh heap memory is.
- `ApuFree(NULL)` is `S_OK`. An address that does not start a live block (never allocated, inside a block,
already freed) is `E_INVALIDARG` and changes nothing.
- `ApuIsVirtualAddressValid` and the two map calls read the published heap bounds under the heap lock and
Expand All @@ -2820,9 +2819,7 @@ The shape-context allocation (`AcpHalAllocateShapeContexts`, types other than 4)
rolling back any already allocated XMA block and zeroing its output pointer and APU address. The source-built
check loads the stub, checks non-permissive traps, cycles 64 MiB through a 2 MiB heap, checks reuse, alignment,
coalescing, every refused call, shape-context allocation and partial-failure rollback, `AcpHalCreate`, and the
address validity/mapping exports, runs 4 threads of 1000 rounds against an interval map of live blocks, and
verifies on-demand commit, interior-page decommit, shared-boundary-page preservation, and commit-failure
rollback against `GetProcessMemoryInfo().PagefileUsage` and `VirtualQuery` in a 64 MiB heap:
address validity/mapping exports, then runs 4 threads of 1000 rounds against an interval map of live blocks:

```
ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V
Expand Down
4 changes: 2 additions & 2 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void*
{
// Keep pre-fix desktop bytecode and manifests out of this ABI's cache.
// tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL.
constexpr char revision[] = "x2w-startup-shader-21";
constexpr char revision[] = "x2w-startup-shader-22";
const u64 seed = fnv_bytes(revision, sizeof(revision) - 1);
u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed)));
// A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key.
Expand Down Expand Up @@ -474,7 +474,7 @@ u64 publish_compute_request(const void* desc)
std::vector<unsigned char> fields(sizeof(words));
words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0;
std::memcpy(fields.data(), words, sizeof(words));
constexpr char compute_revision[] = "x2w-startup-shader-21cs"; // tools/startup/gfx2hlsl.py compute_key
constexpr char compute_revision[] = "x2w-startup-shader-22cs"; // tools/startup/gfx2hlsl.py compute_key
u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1);
const std::vector<unsigned char>* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b};
for (const auto* part : order) key = fnv_part(*part, key);
Expand Down
4 changes: 2 additions & 2 deletions tests/startup_compute_request_offline_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@
DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11)
STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003)
STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0)
KEY = 0x90041d02ef75b4e9 # framed key at revision 21cs
KEY = 0x5159f6a85d77858e # framed key at revision 22cs


def framed_key():
h = 1469598103934665603
for b in b'x2w-startup-shader-21cs':
for b in b'x2w-startup-shader-22cs':
h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff
for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B):
for b in struct.pack('<Q', len(part)) + part:
Expand Down
4 changes: 2 additions & 2 deletions tests/startup_gfx2hlsl_buffer_store_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ def main():
'%s %s' % (result, fail_reason(name)))

# 8. The cache revision moved, so a translation from before the store lowering is never loaded.
check('cache key uses revision 19', G.pipeline_key(b'a', b'b', ROOT) ==
G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-21')))))
check('cache key uses revision 22', G.pipeline_key(b'a', b'b', ROOT) ==
G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-22')))))

if failures:
print('FAILED: ' + ', '.join(failures))
Expand Down
26 changes: 26 additions & 0 deletions tests/startup_gfx2hlsl_compute_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,25 @@ def replace_store(*lines):
CASES['O-dword'] = (SOURCE_O_DWORD, WORDS_O_DWORD, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1))
CASES['O-shift'] = (SOURCE_O_SHIFT, WORDS_O_SHIFT, USER7 | TGID_X | tidig(1), (32, 1, 1), (4, 1, 1))

# Two groups reach the same load from different branch arms. Each of their lanes must read its group's word.
SOURCE_JOIN_LOAD = OFF_PROLOGUE + """\
s_cmp_eq_u32 s7, 0
s_cbranch_scc0 1
s_nop 0
s_lshl_b32 s3, s7, 2
buffer_load_dword v7, off, s[12:15], s3
s_waitcnt vmcnt(0)
v_readfirstlane_b32 s24, v7
v_mov_b32_e32 v7, s24
v_lshl_add_u32 v4, s7, 3, v0
v_lshlrev_b32_e32 v4, 2, v4
buffer_store_dword v7, v4, s[16:19], 0 offen
s_endpgm
"""
WORDS_JOIN_LOAD = bytes.fromhex(OFF_PROLOGUE_WORDS + '078006bf 010084bf 000080bf 0782038f 000030e000070303 '
'703f8cbf 0705307e 18020e7e 040046d707060104 82080834 001070e004070480 000081bf')
CASES['join-load'] = (SOURCE_JOIN_LOAD, WORDS_JOIN_LOAD, USER7 | TGID_X, (8, 1, 1), (2, 1, 1))


def root_blob(constants=2, table_range=False):
"""RTS0: param 0 = root constants (b0), param 1 = a descriptor table with no ranges.
Expand Down Expand Up @@ -782,6 +801,10 @@ def expected(name):
if name in ('I', 'I-raw'):
return expected('A')
out = [SENTINEL] * WORDS
if name == 'join-load':
for i in range(16):
out[i] = input_word(i // 8)
return out
if name == 'O-dword':
for group in range(4):
out[2 + group] = KEY ^ group
Expand Down Expand Up @@ -1866,6 +1889,7 @@ def check_binary(llvm_mc):
MBCNT_LANE = '(tid.x + 4u * (tid.y + 2u * tid.z))'
MBCNT_COUNT = f'countbits(0x85241249u & ((1u << {MBCNT_LANE}) - 1u))'
CONTROLS = {
'join-load-zero': ('join-load', 's24 = ul24_7;', 's24 = 0u;'),
'swapped-axes': ('A', ' s7 = gid.x;\n s8 = gid.y;\n', ' s7 = gid.y;\n s8 = gid.x;\n'),
'dropped-store': ('A', ' u0.Store(a, v5);\n', ''),
'b-offset': ('B', ' a = (v4 + 8) & 0xfffffffcu;\n', ' a = (v4 + 0) & 0xfffffffcu;\n'),
Expand Down Expand Up @@ -1903,6 +1927,7 @@ def check_binary(llvm_mc):

# First bad word for controls with a pinned mismatch.
CONTROL_MISMATCH = {
'join-load-zero': 'word=0 expected=8b02a7f1 actual=00000000',
'f-second-fill': 'word=1 expected=00000094 actual=00000000',
'd-mask': 'word=8 expected=00000008 actual=00000009',
'd-whole-mask': 'word=0 expected=00000007 actual=00000011',
Expand Down Expand Up @@ -1966,6 +1991,7 @@ def check_dispatch(dxc, runner, adapter, control=None):
runs = [(CONTROLS[control][0], control)]
else:
runs = [(name, None) for name in CASES]
runs.append(('join-load', 'join-load-zero'))
runs += [(case, mutation) for mutation, (case, _, _) in CONTROLS.items() if case in L_WORD3]
runs += [('masked-tid', 'mask-shift-dropped'), ('extracted-tid', 'extract-shift-dropped')]
for name, mutation in runs:
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_gfx2hlsl_const_copy_join_check.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""`s_mov_b32` copy of a plain constant SGPR in tools/startup/gfx2hlsl.py: run-time write and join.

The copy folds the constant into later reads (revision x2w-startup-shader-21), and these two cases pin what must
The copy folds the constant into later reads (revision x2w-startup-shader-22), and these two cases pin what must
stay true next to the fold:
- the copy still assigns its register at run time (`s12 = ...;` is emitted), so a reader the fold does not reach
(a branch target after a join) sees a real value;
Expand Down
4 changes: 2 additions & 2 deletions tests/startup_gfx2hlsl_fract_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,8 @@ def float_capped(word):
repr((seed and seed.group(1), literal and literal.group(1))))
check('the two literals are identical', seed and literal and seed.group(1) == literal.group(1),
repr((seed and seed.group(1), literal and literal.group(1))))
check('the revision is x2w-startup-shader-21, after the lane-mask-preserving execz forms joined the compute lowering',
bool(seed and seed.group(1) == 'x2w-startup-shader-21'), repr(seed and seed.group(1)))
check('the revision is x2w-startup-shader-22, after the compute loop entry-EXEC guard',
bool(seed and seed.group(1) == 'x2w-startup-shader-22'), repr(seed and seed.group(1)))


def key_from_seed(word):
Expand Down
8 changes: 8 additions & 0 deletions tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ def run(*instructions, kind='cs', descriptor_proven=False):
check('temporary declared', ' uint ulc_7 = 0;' in s.declarations(), repr(s.declarations()))

REFUSED = [
('loop carries a narrowed EXEC into the load', JOIN + (SCALAR, LOAD, READ, 's_add_u32 s3, s3, 4',
'v_cmp_lt_f32_e32 vcc_lo, v0, v1', 's_and_b32 exec_lo, exec_lo, vcc_lo', 's_cmp_lt_u32 s3, 64',
's_cbranch_scc1 label_000c', 's_endpgm')),
('EXEC write outside the textual back edge', JOIN + (SCALAR, LOAD, READ, 's_branch label_0020',
's_cbranch_scc1 label_000c', 's_endpgm', NARROW, 's_branch label_0018')),
# Two definitions reach the read at a join.
('join of a load and another definition', ('s_cbranch_scc0 label_0014', SCALAR, LOAD, 's_branch label_0014',
'v_mov_b32_e32 v7, 0', READ, 's_endpgm')),
Expand Down Expand Up @@ -125,6 +130,9 @@ def run(*instructions, kind='cs', descriptor_proven=False):
for label, instructions in REFUSED:
got = run(*instructions)
check(f'{label} refused', got == REFUSAL, repr(got))
got = run(*JOIN, SCALAR, LOAD, READ, 's_add_u32 s3, s3, 4', 's_cmp_lt_u32 s3, 64',
's_cbranch_scc1 label_000c', NARROW, 's_endpgm')
check('loop with unchanged EXEC accepts the load', isinstance(got, list) and 's9 = ulc_7;' in got, repr(got))
got = run(*JOIN, SCALAR, LOAD, READ, kind='ps')
check('graphics stage refused', got == REFUSAL, repr(got))

Expand Down
2 changes: 1 addition & 1 deletion tests/startup_indirect_draw_indexed.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ ComPtr<IUnknown> translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r
bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false)
{
// The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC.
constexpr char revision[] = "x2w-startup-shader-21";
constexpr char revision[] = "x2w-startup-shader-22";
static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103};
static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204};
auto& vertex_id = vertex_ids[indexed ? 2 : needs_start];
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_packed_position_provenance_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def refused(label, cache, key, reason):
cache = Path(tmp)
bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob())
check('without a description the key is unchanged',
bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-21')))))
bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-22')))))
keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)]
check('same stages, root and layout with three mask pairs: three request identities',
len(set(keys)) == 3 and bare not in keys
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_resource_retire_title.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target
constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel
constexpr int draw_seed = 77;
constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM
constexpr char draw_revision[] = "x2w-startup-shader-21"; // d3d12_draw.inl cached_translation
constexpr char draw_revision[] = "x2w-startup-shader-22"; // d3d12_draw.inl cached_translation

constexpr char draw_vertex_shader[] = R"(
struct Varying { float4 position : SV_Position; };
Expand Down
6 changes: 3 additions & 3 deletions tests/startup_shader_cache_key_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ def check_request(blobs, key, diagnostic=None, rtv_request=None, layout=None):

def main():
# Independently executed C++ runtime fnv_bytes/cached_translation known-answer vector.
# Revision x2w-startup-shader-21 excludes NUL. Stored order is a, b, root, then optional input layout.
# Revision x2w-startup-shader-22 excludes NUL. Stored order is a, b, root, then optional input layout.
vector = (b"\x00VS\xff", b"PS\x00\x80", b"RTS0\x00")
assert gfx2hlsl.pipeline_key(*vector) == 0x93a74e652d95daf6
assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0x1ff6b039237188d6
assert gfx2hlsl.pipeline_key(*vector) == 0x30009a5d8295d679
assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xdae7d34c534837e5
blobs = (VERTEX, PIXEL, ROOT)
canonical = gfx2hlsl.pipeline_key(*blobs)
check_request(blobs, canonical)
Expand Down
Loading
Loading