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
23 changes: 23 additions & 0 deletions docs/experiments/native-fixed-mesh57.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,29 @@ element yields (0,62,0,0) when reading element 1. A float SRV, absent slot
and out-of-range selector preserve the clear color. The guest source heap
and resource are released after recording and before submission.

Offline, a `.mslayout` can also name `heap_tokens` next to
`validate_uint_heap_reads`. The heap descriptor load may then use a byte
offset that GPU data chooses, such as a dword read from a buffer SRV in a root
descriptor table. The offset must be a value shifted left by 5 or more, so it
is a multiple of the 32-byte descriptor size. The translator does not trust
the title's value. It reads the view token at that byte address: word 0 the
magic `0x56573258` and word 1 the view id. The id's entry in a per-id kind
table must have bit 16 set (one-channel 32-bit typed buffer); other kind bits
on the same id, such as the raw-buffer bit 0x20, are allowed. When the magic, `id < count` and
the kind hold, the read uses `ResourceDescriptorHeap[base + id]` as a typed U32
buffer. Otherwise it uses the null slot, and the first lane of the wave adds
one to a miss counter. The runtime provides the token memory and the kind
table as raw SRVs, the miss counter as a raw UAV, and `base`, `count` and
`null` as words 0 to 2 of cbuffer `b1`. `compile_dxil` prints
`requires_heap_tokens srv=<token SRV> kinds_srv=<kind table SRV>
miss_uav=<UAV> words=b1 reads=<count>`. Native preparation does not set the
option yet and refuses such a program ("MS heap token reads are not bound
yet"). `tests/native_direct_mesh_check.py` checks the guard in the module, two
reads sharing one set of views, a wave32 entry and the unchanged root-constant
route. It also covers six refusals: no option, the option without validated
heap reads, a shift by 4, an offset without a shift, a raw read and an
overwritten descriptor word.

The version 6 mesh profile also binds pixel texture reads from the directly
indexed guest resource heap. An eight-DWORD descriptor load must select a
32-byte-aligned slot within a proven interval. At recording time, each slot
Expand Down
15 changes: 15 additions & 0 deletions src/gfx1013_compute_native.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,17 @@ struct GraphicsLinkage {
struct MeshHeapRead {
unsigned root_parameter, dword, mask; // R32_UINT SRV at (root constant & mask).
};
// Formatted mesh reads of heap buffers chosen by GPU data, checked through view tokens (MeshStageLayout::heap_tokens).
// The title keeps a 32-byte view token at the descriptor address of a registered view: word 0 heap_token_magic,
// word 1 the view id. Per read the shader loads those words from token_srv at the guest byte address, looks up the
// view kind of the id in kinds_srv (one uint per view id) and reads ResourceDescriptorHeap[base + id] when the magic
// matches, id < count and the kind has the heap_token_r32_uint_buffer bit; otherwise it reads the null slot and the first lane
// of the wave adds one to the uint at byte 0 of miss_uav. base, count and null are words 0-2 of cbuffer b1.
inline constexpr unsigned heap_token_magic = 0x56573258u;
inline constexpr unsigned heap_token_r32_uint_buffer = 16;
struct MeshHeapTokens {
unsigned token_srv, kinds_srv, miss_uav, reads;
};
struct NativeComputeShader {
std::vector<PixelHeapSpan> pixel_heap_spans;
std::vector<MeshHeapRead> mesh_heap_reads;
Expand All @@ -145,6 +156,7 @@ struct NativeComputeShader {
std::vector<unsigned> pixel_descriptor_word_tables;
// Pair of guest root parameter and byte offset of a numerically read image descriptor.
std::vector<std::pair<unsigned, unsigned>> pixel_descriptor_records;
std::optional<MeshHeapTokens> mesh_heap_tokens;
std::vector<GraphicsLinkage> inputs, outputs;
std::vector<ComputeConstants> constants;
// Additional b0 words, after root constants, read from these bound SRVs.
Expand Down Expand Up @@ -232,6 +244,9 @@ struct MeshStageLayout {
std::vector<MeshRootInput> root_inputs{};
std::optional<unsigned> resource_heap_sgpr{};
bool validate_uint_heap_reads{};
// With validate_uint_heap_reads: a heap descriptor at a GPU-computed byte offset (a proven multiple of 32) is
// read through its view token (MeshHeapTokens); the runtime then provides the token views and cbuffer b1.
bool heap_tokens{};
bool packed_parameters{};
bool texture_heap_slot_map{};
};
Expand Down
79 changes: 68 additions & 11 deletions src/gfx1013_direct_mesh.inl
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,50 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout
std::map<unsigned,RootBits> heap_fetches;
std::set<string> heap_entry_offsets;
std::map<unsigned,string> texture_heap_fetches;
// heap_tokens: the heap descriptor loads at a byte offset in heap_entry_offsets (a multiple of the 32-byte
// descriptor size), by pc, with that offset.
if (layout.heap_tokens && !layout.validate_uint_heap_reads)
refuse(0,"mesh heap tokens require validated heap reads");
std::map<unsigned,string> token_fetches;
// The heap slot of a token fetch at byte address `at` (MeshHeapTokens): base + id when the token holds the magic, an
// id below count and that id's kind has the one-channel 32-bit typed buffer bit, else the null slot, counting the
// miss once per wave. Every value is uniform (scalar address, full EXEC), so the slot is too.
auto heap_token_slot=[&](const string &at) {
auto &tokens=emitter.result.mesh_heap_tokens;
if (!tokens) tokens=MeshHeapTokens{emitter.srv++,emitter.srv++,emitter.uav++,0};
++tokens->reads;
// 16: the module reads raw buffers (the token memory and the kind table); 0x10000: a UAV (the miss counter)
// outside the compute and pixel stages; 0x40000000: ResourceDescriptorHeap. The validator checks all three.
ir.features|=16|0x10000|0x40000000;
const auto words=ir.handle({2,1,13,0,0,16});
const auto row=ir.invoke("%dx.types.CBufRet.i32","cbufferLoadLegacy.i32",59,
{{"%dx.types.Handle",words},{"i32","0"}},"nounwind readonly");
const auto word=[&](unsigned j) { return ir.value("extractvalue %dx.types.CBufRet.i32 "+row+", "+to_string(j)); };
const auto base=word(0), count=word(1), null=word(2);
const auto load_word=[&](const string &h,const string &address) {
return ir.value("extractvalue %dx.types.ResRet.i32 "+alu.load_buffer(h,address,true,1)+", 0");
};
const auto memory=ir.handle({0,tokens->token_srv,11}), kinds=ir.handle({0,tokens->kinds_srv,11});
const auto magic=load_word(memory,at), id=load_word(memory,ir.binary("add",at,"4"));
const auto in_range=alu.cmp("ult",id,count);
const auto clamped=alu.select(in_range,id,ir.binary("sub",count,"1"));
const auto kind=load_word(kinds,ir.binary("shl",clamped,"2"));
auto valid=ir.value("and i1 "+alu.cmp("eq",magic,to_string(heap_token_magic))+", "+in_range);
// A bit test, not equality: one view id may carry other kind bits as well (raw views, #3631).
const auto typed=ir.binary("and",kind,to_string(heap_token_r32_uint_buffer));
valid=ir.value("and i1 "+valid+", "+alu.cmp("ne",typed,"0"));
ir.uses_wave=true;
const auto first_lane=ir.invoke("i1","waveIsFirstLane",110,{},"nounwind");
const auto missed=ir.value("and i1 "+ir.value("xor i1 "+valid+", true")+", "+first_lane);
const auto tag=to_string(alu.label_number++);
ir.body<<" br i1 "<<missed<<", label %meshTokenMiss"<<tag<<", label %meshTokenMissEnd"<<tag<<"\nmeshTokenMiss"
<<tag<<":\n";
ir.invoke("i32","atomicBinOp.i32",78,
{{"%dx.types.Handle",ir.handle({1,tokens->miss_uav,11})},{"i32","0"},{"i32","0"},{"i32","undef"},
{"i32","undef"},{"i32","1"}},"nounwind");
ir.body<<" br label %meshTokenMissEnd"<<tag<<"\nmeshTokenMissEnd"<<tag<<":\n";
return alu.select(valid,ir.binary("add",base,id),null);
};
for (const auto &block : emitter.result.constants)
for (unsigned j=0;j<block.count;++j)
root_values.emplace(alu.read(block.first_sgpr+j),RootBits{block.root_parameter,j,~0u,0});
Expand Down Expand Up @@ -1054,9 +1098,14 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout
refuse(pc,"unsupported mesh heap descriptor address");
const auto bytes=alu.operand32(i,offset_reg);
const auto bits=root_values.find(bytes);
if (bits==root_values.end() || bits->second.shift!=5)
if (bits!=root_values.end() && bits->second.shift==5)
heap_fetches[pc]=bits->second;
else if (layout.heap_tokens && heap_entry_offsets.count(bytes))
token_fetches[pc]=bytes;
else if (layout.heap_tokens)
refuse(pc,"mesh heap token byte offset is not a proven multiple of 32");
else
refuse(pc,"mesh heap slot lacks masked root constant provenance");
heap_fetches[pc]=bits->second;
} else {
const auto offset=alu.graphics_registers.find(offset_reg);
const bool uniform_load=i.op>=8 && whole_wave_execution() && !branch && forward.empty() &&
Expand All @@ -1081,23 +1130,31 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout
} else if (i.name=="buffer_load_format" && i.op==0 && full_exec && (i.a&0x3ffff)==0x2000) {
const auto base=((i.b>>16)&31)*4;
const auto sym=state[base];
const auto token=token_fetches.find(sym.definition);
if (sym.type!=Symbol::Type::indexed_descriptor || sym.value!=compute_resource_heap ||
!heap_fetches.count(sym.definition) || sym.offset)
(!heap_fetches.count(sym.definition) && token==token_fetches.end()) || sym.offset)
refuse(pc,"formatted mesh load lacks an R32_UINT resource heap contract");
for (unsigned j=1;j<4;++j) {
auto expected=sym;
expected.offset=j*4;
if (!(expected==state[base+j])) refuse(pc,"overwritten mesh heap descriptor");
}
const auto guard=heap_fetches.at(sym.definition);
const auto entry=std::find_if(root_values.begin(),root_values.end(),[&](const auto &x) {
return x.second.param==guard.param && x.second.dword==guard.dword && !x.second.shift && x.second.mask==~0u;
});
if (entry==root_values.end()) refuse(pc,"missing mesh heap selector");
emitter.result.mesh_heap_reads.push_back({guard.param,guard.dword,guard.mask});
const auto descriptor=ir.binary("and",entry->first,to_string(guard.mask));
string descriptor;
bool uniform_slot=false;
if (token!=token_fetches.end()) {
descriptor=heap_token_slot(token->second);
uniform_slot=true;
} else {
const auto guard=heap_fetches.at(sym.definition);
const auto entry=std::find_if(root_values.begin(),root_values.end(),[&](const auto &x) {
return x.second.param==guard.param && x.second.dword==guard.dword && !x.second.shift && x.second.mask==~0u;
});
if (entry==root_values.end()) refuse(pc,"missing mesh heap selector");
emitter.result.mesh_heap_reads.push_back({guard.param,guard.dword,guard.mask});
descriptor=ir.binary("and",entry->first,to_string(guard.mask));
}
ir.features|=0x40000000;
const auto handle=ir.heap_handle(descriptor,10,261); // TypedBuffer, one U32 component.
const auto handle=ir.heap_handle(descriptor,10,261,false,!uniform_slot); // TypedBuffer, one U32 component.
const auto index=alu.read(256+(i.b&255));
const auto word=ir.value("extractvalue %dx.types.ResRet.i32 "+alu.load_buffer(handle,index,false,1)+", 0");
alu.write(256+i.dst,word);
Expand Down
3 changes: 3 additions & 0 deletions src/startup_stubs/native_mesh57.inl
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,9 @@ void prepare_native_mesh57(Wrapper* pipeline)
if ((mapped ? !mapped_constants : !native.constants.empty()) || (!buffers && !native.bindings.empty()) || !native.samplers.empty() || native.sampler_heap ||
(direct_heap ? native.mesh_heap_reads.empty() : !native.mesh_heap_reads.empty()))
throw std::runtime_error("MS needs root or heap bindings");
// MeshStageLayout::heap_tokens is off here: the token views and cbuffer b1 are not bound yet.
if (native.mesh_heap_tokens)
throw std::runtime_error("MS heap token reads are not bound yet");
UINT heap_word = UINT_MAX;
for (const auto& guard : native.mesh_heap_reads) {
if (guard.root_parameter != mapping.root_parameter || guard.dword >= mapping.count || guard.mask != 1023 ||
Expand Down
76 changes: 76 additions & 0 deletions tests/native_direct_mesh_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,82 @@ def run(name, words, expected=None):
'graphics register read includes undefined bits: 276')
run('mesh-full-read-of-partial-half',half_frontend+[0x7e340314]+program,
'graphics register read includes undefined bits: 276')
# GPU-selected slot through a view token: the heap byte offset is a dword read from a root-table buffer SRV,
# times 32. The token at that address names the view; the shader checks it before reading the heap.
select_word = [0xbe910380, # s_mov_b32 s17, 0 (table high word)
0xf4080808,0xfa000000, # s_load_dwordx4 s[32:35], s[16:17], 0 (table 1, slot 0)
0xf4200910,0xfa0007f8] # s_buffer_load_dword s36, s[32:35], 0x7f8
times_32 = [0x8f248524] # s_lshl_b32 s36, s36, 5
heap_base = [0xbe9e0317,0xbe9f0380] # s[30:31] = heap base s23, high word 0
selected_fetch = [0xf4080a0f,0x48000000] # s_load_dwordx4 s[40:43], s[30:31], s36
formatted = [0x7e020280,0xe0002000,0x800a0a01] # v1 = 0; buffer_load_format_x v10, v1, s[40:43] idxen
selected = select_word + times_32 + heap_base + selected_fetch + formatted
gpu_layout = 'mesh1 128 3 1 2 128 64\ntable 16 1\nresource_heap 23\nvalidate_uint_heap_reads'
layout.write_text(gpu_layout)
run('token-no-contract',selected+exported,'mesh heap slot lacks masked root constant provenance')
layout.write_text('mesh1 128 3 1 2 128 64\ntable 16 1\nresource_heap 23\nheap_tokens')
run('token-unvalidated',selected+exported,'mesh heap tokens require validated heap reads')
token_layout = gpu_layout + '\nheap_tokens'

def token_module(name, words, report):
result, out = compile_mesh(name, words)
assert result.returncode == 0, result.stderr
assert report in result.stdout, result.stdout
return subprocess.check_output([sdk/'dxc.exe','-dumpbin',out], text=True)

def assert_token_guard(text, reads):
# Token words (magic, id) and the kind word come from raw views; base, count and null from cbuffer b1.
assert re.search(rf'icmp eq i32 [^\n]*, {0x56573258}\n', text), text # heap_token_magic
# heap_token_r32_uint_buffer as a bit test: (kind & 16) != 0, so other kind bits on the id still pass.
typed = re.search(r'(%[\w.]+) = and i32 [^\n]*, 16\n', text)
assert typed and re.search(r'icmp ne i32 ' + re.escape(typed[1]) + r', 0\n', text), text
assert not re.search(r'icmp eq i32 [^\n]*, 16\n', text), text
assert re.search(r'icmp ult i32', text), text
assert 'waveIsFirstLane' in text and 'atomicBinOp.i32(i32 78' in text, text
assert 'cbufferLoadLegacy' in text, text
heaps = re.findall(r'createHandleFromHeap\(i32 218, i32 (%[\w.]+), i1 false, i1 (true|false)\)', text)
assert len(heaps) == reads and all(u == 'false' for _, u in heaps), heaps
for slot, _ in heaps: # the slot is base + id or the null word, never the title's dword
assert re.search(re.escape(slot) + r' = select i1 ', text), (slot, text)
assert 'i32 10, i32 261' in text and 'bufferLoad.i32' in text, text

layout.write_text(token_layout)
text = token_module('token', selected+exported,
'requires_heap_tokens srv=1 kinds_srv=2 miss_uav=0 words=b1 reads=1')
assert_token_guard(text, 1)
# The token is read at the computed byte address: the selector dword shifted left by 5.
loaded = re.search(r'(%[\w.]+) = call %dx\.types\.ResRet\.i32 @dx\.op\.rawBufferLoad\.i32\(i32 139, '
r'%dx\.types\.Handle %[\w.]+, i32 2040,', text)
assert loaded, text
selector = re.search(r'(%[\w.]+) = extractvalue %dx\.types\.ResRet\.i32 ' + re.escape(loaded[1]) + r', 0', text)
assert selector, text
shifted = re.search(r'(%[\w.]+) = shl i32 ' + re.escape(selector[1]) + r', ', text) # amount: 5 & 31
assert shifted, text
assert re.search(r'rawBufferLoad\.i32\(i32 139, %dx\.types\.Handle %[\w.]+, i32 ' + re.escape(shifted[1]) + ',',
text), text
# Two guarded reads share one set of token views and words.
second = [0xf4080b0f,0x48000000, 0xe0002000,0x800b0b01] # s[44:47] at the same offset; v11 from it
text = token_module('token-twice', selected+second+exported,
'requires_heap_tokens srv=1 kinds_srv=2 miss_uav=0 words=b1 reads=2')
assert_token_guard(text, 2)
# wave32: the same chain with 32-lane waves.
layout.write_text(token_layout.replace(' 128 64\n', ' 128 32\n', 1))
assert_token_guard(token_module('token-wave32', selected+exported,
'requires_heap_tokens srv=1 kinds_srv=2 miss_uav=0 words=b1 reads=1'), 1)
# The root-constant route is unchanged with heap_tokens on: no token views.
layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1\nresource_heap 23\nvalidate_uint_heap_reads\n'
'heap_tokens')
result, out = compile_mesh('token-root-route', typed+exported)
assert result.returncode == 0 and 'requires_heap_tokens' not in result.stdout, result.stdout + result.stderr
# Negative controls: another scale, no scale, a raw read and an overwritten descriptor word.
layout.write_text(token_layout)
unaligned = 'mesh heap token byte offset is not a proven multiple of 32'
run('token-shift4',select_word+[0x8f248424]+heap_base+selected_fetch+formatted+exported,unaligned)
run('token-unshifted',select_word+heap_base+selected_fetch+formatted+exported,unaligned)
run('token-raw-read',select_word+times_32+heap_base+selected_fetch+[0x7e020280,0xe0302000,0x800a0a01]+
exported,'indexed raw load needs a reflected table SRV')
run('token-overwritten',select_word+times_32+heap_base+selected_fetch+[0xbea90380]+formatted+exported,
'overwritten mesh heap descriptor')
layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1')
widen_only = [
0xbe96047e, # s_mov_b64 s[22:23], exec
Expand Down
Loading
Loading