diff --git a/docs/experiments/native-mesh-heap-descriptor.md b/docs/experiments/native-mesh-heap-descriptor.md new file mode 100644 index 0000000000..a14e82f2e9 --- /dev/null +++ b/docs/experiments/native-mesh-heap-descriptor.md @@ -0,0 +1,66 @@ +# Slot 57 mesh heap descriptor load + +The stable slot 57 profile `9482ea4411e1e03f` (version 5, heap SGPR 23, +`validate_uint_heap_reads`, views s16..s19 for roots 0..3) reaches the mesh +frontend with `req_72e1909e13df6f66.m57`. The captured MS is the exact part +the profile carries, so `compile_dxil gfx1013-raw-ms` reproduces the run's +refusal byte for byte. + +## Decoded form + +At code offset `+0x614` the program issues + + s_load_dwordx8 s[56:63], s[12:13], s22 + +SMEM op 3 (eight dwords), immediate offset 0, SGPR offset s22, base s12:s13 +where s12 was copied from the heap SGPR s23 and s13 is the constant 0. The +preceding `s_lshl_b32 s22, s22, 5` proves the byte offset is a multiple of 32, +and the result feeds `image_load v[19:21], v11, s[56:63] dmask:0x7 +dim:SQ_RSRC_IMG_1D unorm` at `+0x700`. + +## Contract + +The mesh heap branch behind `validate_uint_heap_reads` accepted only +`i.op == 2` (one four-dword typed-buffer descriptor). It now also accepts +`i.op == 3`, the eight-dword texture descriptor, with the same address rules: +no immediate offset, an SGPR offset inside the SGPR range, a constant zero high +word and the destination range check. A root-provided selector still records +`heap_fetches`; a GPU-selected selector that is a proven multiple of 32 keeps +the fetch opaque and records only the heap slot: + +- the fetch records `bytes >> 5` by its pc for a consumer that brings its own + descriptor contract. The eight destination words stay symbolic; none of + their field bits are available, so a numeric read keeps refusing (for + example `unbound numeric SGPR s33` for word 1 and `s37` for word 5); +- with `texture_heap_slot_map` the texture branch keeps priority and words 1..3 + stay the guest descriptor metadata from the remap record; +- the consumers still need their own proof: a buffer load needs + `heap_fetches`/`token_fetches` and an image needs + `texture_heap_fetches`, so an unmapped selection still refuses. + +## Observed + +Before this change the request refused at `+0x614: unsupported mesh heap +descriptor address`. After accepting the eight-dword form it refused at +`+0x69c: unbound numeric SGPR s57` because the eight words stayed +`indexed_descriptor`. That refusal is the correct one here: the fetch has +recorded the slot, but the image still needs a consumer that can name the V# +fields. The slot-57 image change supplies that consumer separately; it must +use the recorded slot and keep the words symbolic. + +## Fixture + +[tests/native_direct_mesh_check.py](../../tests/native_direct_mesh_check.py) +adds the eight-dword heap fetch feeding a typed load (`typed-heap-descriptor-x8`), +a sixteen-dword refusal (`typed-heap-descriptor-x16`) and an unaligned-offset +refusal (`typed-heap-descriptor-unproven`). The GPU-selected form is covered by +`gpu-heap-descriptor-x8-typed`, `-x8-image`, `-word-1` and `-word-5`, all of +which keep refusing. `mesh-table-wide-load` and `mesh-heap-wide-load` cover a +sixteen-dword write loop against the eight-word record. The texture fixture has +a masked and an unmasked selector; only the slot-map form reads descriptor +word 1 (`s33`) numerically. + +**Reproduce** with +`ctest --preset release --no-tests=error -R '^native_direct'` and +`ctest --preset release --no-tests=error -R '^native_fixed_mesh57_warp$'`. + diff --git a/docs/experiments/native-mesh-image-load.md b/docs/experiments/native-mesh-image-load.md new file mode 100644 index 0000000000..d714cc5ade --- /dev/null +++ b/docs/experiments/native-mesh-image-load.md @@ -0,0 +1,65 @@ +# Mesh image_load through a full table descriptor + +The slot 57 capture `req_72e1909e13df6f66.m57` reaches `+0x700` after the +eight-dword heap descriptor load of +[native-mesh-heap-descriptor.md](native-mesh-heap-descriptor.md): + + image_load v[19:21], v11, s[56:63] dmask:0x7 dim:SQ_RSRC_IMG_1D unorm + +The descriptor is a complete guest V# read from the resource heap, not a +texture heap slot-map record, so the existing image branch (which requires +`layout.texture_heap_slot_map`) refused it. + +## Lowering + +A mesh image branch now handles the full-V# form when +`!layout.texture_heap_slot_map`: + +- the instruction must be an `image_load` (op 0) with `dim 1D` (0), + `dmask 0x7`, `unorm` set, no LWE/TFE/R128/reserved bits, no cache-policy + or descriptor base bits in word 1, a destination inside the VGPR range and + eight descriptor words in range; +- the descriptor symbol must be an `indexed_descriptor` of the resource heap at + offset 0 whose eight words share its fetch pc and offsets 0, 4, ..., 28. The + fetch must be recorded by `heap_fetches` or `heap_descriptor_slots`; the + words stay symbolic and an overwritten word keeps refusing; +- the slot comes from the fetch: a root-proven selector uses the same + `heap_fetches` guard as the typed path, records a + `mesh_heap_reads` entry and takes `and(root, mask)`; a GPU-selected fetch + uses the `bytes >> 5` slot recorded by the eight-dword load; +- the load binds `createHandleFromHeap(slot)` as a Texture1D + (`annotateHandle { 1, 1033 }`) and issues `textureLoad.f32` at mip 0 with + the VGPR coordinate, writing the three integer channels. + +Four-channel loads, other dimensions, missing UNORM, a mismatched coordinate or +an unmatched descriptor still refuse with `unsupported mesh image load or +descriptor`. + +## Observed + +With #3754's corrected head the capture refuses at `+0x69c: unbound numeric +SGPR s57`: `s_bfe_u32 s22, s57, 0x2001e` reads descriptor word 1 to build the +image coordinate. The full-V# branch is covered by source-built fixtures with +a constant coordinate; reaching `+0x700` needs a contract that supplies the +real V# field bits. + +## Fixture + +[tests/native_direct_mesh_check.py](../../tests/native_direct_mesh_check.py) +adds `mesh-image-full-descriptor`: an eight-dword heap fetch behind a masked +root selector drives the 1D UNORM load, and the IR must hold +`createHandleFromHeap`, one `textureLoad.f32` at mip 0 and the three +extracted channels exported through POS0.x. `mesh-image-full-descriptor-root` +and `-gpu` cover the root-proven and GPU-selected fetch paths without a slot +map. `mesh-image-unsupported-dimension` flips the dimension to 2D and must +refuse; `mesh-image-four-channel-without-map` is the dmask-15 control. + +Observed on the captured MS with the v5 profile layout: the `+0x700` +`image_load` refusal is gone. The next refusal is +`+0x7c0: unproven mesh entry register 287`, the full `v31` read after the +`v_fma_mixlo_f16` / `v_fma_mixhi_f16` pair. + +**Reproduce** with +`ctest --preset release --no-tests=error -R '^native_direct'` and +`ctest --preset release --no-tests=error -R '^native_fixed_mesh57_warp$'`. + diff --git a/src/dxil_module.h b/src/dxil_module.h index d826ce1823..72abf12224 100644 --- a/src/dxil_module.h +++ b/src/dxil_module.h @@ -143,7 +143,9 @@ class DxilModule { resources.push_back(r); if (offset.empty() && !static_handles.insert(h).second) return h; - Text index = reg; + // A root SRV in space 2 is one descriptor, not an array starting at its register number: + // createHandleFromBinding takes the descriptor index inside the binding, which is zero. + Text index = r.space == 2 ? "0" : reg; auto &out = offset.empty() ? setup : body; if (!offset.empty()) { index = r.reg ? binary("add", reg, offset) : offset; diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index b478740524..1defd3a60b 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -159,6 +159,9 @@ struct NativeComputeShader { std::vector pixel_descriptor_word_tables; // Pair of guest root parameter and byte offset of a numerically read image descriptor. std::vector> pixel_descriptor_records; + // A mesh stage reads guest V# words numerically. The runtime binds a 1024-entry table of eight-dword + // descriptors as a root SRV at this guest root parameter's register number in space 2. + unsigned mesh_descriptor_word_table = ~0u; std::optional mesh_heap_tokens; std::vector inputs, outputs; std::vector constants; diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl index abc97056b8..643bbfa6ca 100644 --- a/src/gfx1013_direct_mesh.inl +++ b/src/gfx1013_direct_mesh.inl @@ -96,6 +96,24 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout std::map heap_fetches; std::set heap_entry_offsets; std::map texture_heap_fetches; + // The heap slot an eight-dword descriptor fetch read, by the pc of that fetch. + std::map heap_descriptor_slots; + // The same slot when the fetch offset was a compile-time constant. + std::map heap_descriptor_slot_values; + // The fetch's byte index when it was a compile-time constant; a fixed s_load folds it into + // each destination symbol's offset, so the word index is relative to this base. + std::map heap_descriptor_slot_offsets; + // Values known to be constants, keyed by the SSA text an SGPR holds. + std::map known_words; + const auto constant_word=[&](const string &text)->std::optional { + if (const auto known=known_words.find(text); known!=known_words.end()) return known->second; + if (text.empty() || text.find_first_not_of("0123456789")!=string::npos) return {}; + try { + const auto value=std::stoull(text); + if (value<=UINT32_MAX) return static_cast(value); + } catch (const std::exception&) {} + return {}; + }; // 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) @@ -140,6 +158,106 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout ir.body<<" br label %meshTokenMissEnd"<=root.NumParameters || + root.pParameters[input.root_parameter].ParameterType!=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE)) + continue; + descriptor_word_root=input.root_parameter; + return descriptor_word_root; + } + refuse(alu.graphics_pc,"mesh descriptor word table requires a guest descriptor table"); + return 0u; + }; + std::map,string> descriptor_word_values; + const auto descriptor_word=[&](const Inst &op,unsigned reg)->std::optional { + if (reg>=106) return {}; + const auto &sym=state[reg]; + if (sym.type!=Symbol::Type::indexed_descriptor || sym.value!=compute_resource_heap || (sym.offset&3)) return {}; + unsigned word=sym.offset/4; + if (const auto base=heap_descriptor_slot_offsets.find(sym.definition); base!=heap_descriptor_slot_offsets.end()) { + if (sym.offsetsecond || sym.offset-base->second>=32) return {}; + word=(sym.offset-base->second)/4; + } else if (sym.offset>=32) return {}; + string slot; + if (const auto fetch=heap_descriptor_slots.find(sym.definition); fetch!=heap_descriptor_slots.end()) + slot=fetch->second; + else return {}; + const auto key=std::make_pair(sym.definition,word); + if (const auto hit=descriptor_word_values.find(key); hit!=descriptor_word_values.end()) return hit->second; + const auto root=descriptor_table_root(); + emitter.result.mesh_descriptor_word_table=root; + const auto fixed=heap_descriptor_slot_values.find(sym.definition); + if (fixed!=heap_descriptor_slot_values.end() && fixed->second>=1024) + refuse(op.pc,"mesh descriptor word slot outside 1024"); + const auto index=ir.binary("add",ir.binary("shl",slot,"3"),to_string(word)); + const auto in_range=alu.cmp("ult",index,"8192"); + const auto safe=alu.select(in_range,index,"0"); + const auto table=ir.handle({0,0,10,5,1,0,1,false,2}); + const auto raw=ir.value("extractvalue %dx.types.ResRet.i32 "+alu.load_buffer(table,safe,false,1)+", 0"); + const auto value=alu.select(in_range,raw,"0"); + descriptor_word_values.emplace(key,value); + return value; + }; + // The scalar operations that consume a V# word as data. A raw descriptor word is never + // numeric: only these named reads may leave the table. + const auto descriptor_numeric=[&](const Inst &op)->bool { + const bool compare=op.name.rfind("s_cmp_",0)==0; + if (!compare && op.dst>=106) return false; + if (op.name!="s_bfe_u32" && op.name!="s_and_b32" && op.name!="s_or_b32" && + op.name!="s_xor_b32" && op.name!="s_lshr_b32" && op.name!="s_lshl_b32" && !compare) + return false; + auto first=descriptor_word(op,op.src[0]); + auto second=descriptor_word(op,op.src[1]); + if (!first && !second) return false; + if (compare) { + if (!first) first=alu.operand32(op,op.src[0]); + if (!second) second=alu.operand32(op,op.src[1]); + const auto suffix=op.name.substr(6); + string predicate; + if (suffix=="eq_i32" || suffix=="eq_u32") predicate="eq"; + else if (suffix=="lg_i32" || suffix=="lg_u32") predicate="ne"; + else if (suffix=="lt_i32") predicate="slt"; + else if (suffix=="le_i32") predicate="sle"; + else if (suffix=="gt_i32") predicate="sgt"; + else if (suffix=="ge_i32") predicate="sge"; + else if (suffix=="lt_u32") predicate="ult"; + else if (suffix=="le_u32") predicate="ule"; + else if (suffix=="gt_u32") predicate="ugt"; + else if (suffix=="ge_u32") predicate="uge"; + else refuse(op.pc,"unsupported mesh descriptor word comparison"); + const auto result=alu.cmp(predicate,*first,*second); + alu.write(128,ir.value("zext i1 "+result+" to i32")); + return true; + } + if (!first) first=alu.operand32(op,op.src[0]); + if (!second) second=alu.operand32(op,op.src[1]); + string value, scc; + if (op.name=="s_bfe_u32") { + const auto field=constant32(op,op.src[1]); + if (!field) refuse(op.pc,"mesh descriptor word bitfield requires a constant field"); + const unsigned offset=*field&31, width=(*field>>16)&127; + if (!width || offset+width>32) refuse(op.pc,"invalid mesh descriptor word bitfield"); + value=ir.binary("lshr",*first,to_string(offset)); + if (width<32) value=ir.binary("and",value,to_string((Word{1}<=106 || (i.b&0xfffff) || + // A typed-buffer descriptor is one s_load_dwordx4 (op 2) and a + // texture descriptor is one s_load_dwordx8 (op 3); both take + // the same resource-heap address. + if ((i.op!=2 && i.op!=3) || offset_reg>=106 || (i.b&0xfffff) || !(state[i.src[0]+1]==Symbol{Symbol::Type::constant,0})) refuse(pc,"unsupported mesh heap descriptor address"); const auto bytes=alu.operand32(i,offset_reg); + bool heap_descriptor=false; 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; + heap_descriptor=true; + } 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 if (i.op==3 && heap_entry_offsets.count(bytes)) + // A 32-byte-aligned eight-dword fetch whose slot comes from GPU data + // stays opaque. It records only the slot for a consumer that brings its + // own descriptor contract; it adds no heap_fetches, token_fetches or + // mesh_heap_reads entry and leaves the eight words symbolic. + heap_descriptor=true; else refuse(pc,"mesh heap slot lacks masked root constant provenance"); + if (i.op==3 && heap_descriptor) { + // The eight words are a whole guest V# whose field bits are not + // available here. Record only the heap slot; a consumer that can + // name the fields supplies its own contract, and a numeric read + // keeps refusing until then. + heap_descriptor_slots[pc]=ir.binary("lshr",bytes,"5"); + if (const auto fixed=constant_word(bytes)) { + heap_descriptor_slot_values[pc]=*fixed>>5; + heap_descriptor_slot_offsets[pc]=*fixed; + } + } } else { const auto offset=alu.graphics_registers.find(offset_reg); const bool uniform_load=i.op>=8 && whole_wave_execution() && !branch && forward.empty() && @@ -1545,6 +1686,55 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout alu.write(dst,ir.value("bitcast float "+value+" to i32")); if (!full_exec) partial_writes.insert(dst); } + } else if (i.enc==Encoding::Image && i.op==0 && !layout.texture_heap_slot_map && + (full_exec || exec_skip)) { + // A full V# fetched from the resource heap drives one 1D UNORM load + // of three channels at a VGPR coordinate. The runtime descriptor + // heap slot holds the guest texture descriptor, so this needs no + // slot map; the eight-dword fetch above recorded the slot. + const unsigned dim=(i.a>>3)&7, mask=(i.a>>8)&15; + const auto base=((i.b>>16)&31)*4; + const auto sym=state[base]; + if (dim!=0 || mask!=7 || !(i.a&0x1000) || (i.a&0x3c040) || (i.b&0xffe00000u) || + (i.b&0x3c000000u) || base+8>106 || i.dst>252 || + sym.type!=Symbol::Type::indexed_descriptor || sym.value!=compute_resource_heap || + sym.offset || + (!heap_fetches.count(sym.definition) && !heap_descriptor_slots.count(sym.definition))) + refuse(pc,"unsupported mesh image load or descriptor"); + for (unsigned j=1;j<8;++j) { + auto expected=sym; + expected.offset=4*j; + if (!(expected==state[base+j])) refuse(pc,"overwritten mesh texture descriptor"); + } + string slot; + const auto fetch=heap_fetches.find(sym.definition); + if (fetch!=heap_fetches.end()) { + const auto &guard=fetch->second; + 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}); + slot=ir.binary("and",entry->first,to_string(guard.mask)); + } else { + const auto stored=heap_descriptor_slots.find(sym.definition); + if (stored==heap_descriptor_slots.end()) + refuse(pc,"mesh image load lacks a heap descriptor fetch"); + slot=stored->second; + } + ir.features|=0x40000000; + const auto handle=ir.heap_handle(slot,1,1033); + const auto x=alu.read(256+(i.b&255)); + const auto load=ir.invoke("%dx.types.ResRet.f32","textureLoad.f32",66, + {{"%dx.types.Handle",handle},{"i32","0"},{"i32",x},{"i32","undef"},{"i32","undef"}, + {"i32","undef"},{"i32","undef"},{"i32","undef"}},"nounwind readonly"); + for (unsigned j=0;j<3;++j) { + const auto value=ir.value("extractvalue %dx.types.ResRet.f32 "+load+", "+to_string(j)); + const auto dst=256+i.dst+j; + alu.write(dst,ir.value("bitcast float "+value+" to i32")); + if (!full_exec) partial_writes.insert(dst); + } } else if (op.form==gfx1013::Form::mtbuf && (full_exec || exec_skip)) { const auto base=((i.b>>16)&31)*4; const auto low=state[base]; @@ -1885,6 +2075,8 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout const auto old=alu.operand32(i,i.dst); alu.write(i.dst,i.name=="s_bitset0_b32" ? ir.binary("and",old,ir.binary("xor",bit,"4294967295")) : ir.binary("or",old,bit)); + } else if (descriptor_numeric(i)) { + // The descriptor word was materialized from the runtime table. } else if (i.name=="s_bitcmp0_b32" || i.name=="s_bitcmp1_b32" || i.name=="s_cmp_lt_u32" || i.name=="s_mulk_i32" || i.name=="s_addk_i32" || i.name=="s_mul_i32" || i.name=="s_add_u32" || i.name=="s_add_i32" || i.name=="s_max_u32" || i.name=="s_sub_i32" || i.name=="s_mul_hi_u32" || i.name=="s_lshl2_add_u32" || i.name=="s_cmpk_lg_i32" || @@ -1989,9 +2181,13 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout } else if (i.name=="s_movk_i32" && i.dst<106) { alu.arithmetic(i,state); state=transfer(i, state, !layout.wave32, true, false, true); + known_words[alu.read(i.dst)]=static_cast(static_cast(i.a)); } else if (i.name=="s_mov_b32" && i.dst<106) { const auto provenance=source(i,i.src[0],state); - if (auto value=constant32(i,i.src[0])) alu.write(i.dst,to_string(*value)); + if (auto value=constant32(i,i.src[0])) { + alu.write(i.dst,to_string(*value)); + known_words[alu.read(i.dst)]=*value; + } else if (i.src[0]<=107) { const auto source=alu.graphics_registers.find(i.src[0]<106 ? i.src[0] : vcc_words+i.src[0]-106); alu.write(i.dst,source==alu.graphics_registers.end() ? string{} : source->second); @@ -2038,6 +2234,15 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout const auto value=ir.binary(i.name=="s_lshl_b32" ? "shl" : i.name=="s_lshr_b32" ? "lshr" : i.name=="s_or_b32" ? "or" : i.name=="s_xor_b32" ? "xor" : "and", a,shift ? ir.binary("and",b,"31") : b); + const auto av=constant_word(a); + const auto bv=constant_word(b); + if (av && bv) { + if (i.name=="s_and_b32") known_words[value]=*av & *bv; + if (i.name=="s_or_b32") known_words[value]=*av | *bv; + if (i.name=="s_xor_b32") known_words[value]=*av ^ *bv; + if (i.name=="s_lshl_b32") known_words[value]=*av << (*bv & 31); + if (i.name=="s_lshr_b32") known_words[value]=*av >> (*bv & 31); + } if (i.name=="s_lshl_b32" && a==wave_number && constant32(i,i.src[1])==(layout.wave32 ? 5u : 6u)) wave_bases.insert(value); const auto bits=root_values.find(a); diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp index b2d6e338e2..9403b22420 100644 --- a/src/shader_compute_request.cpp +++ b/src/shader_compute_request.cpp @@ -200,7 +200,7 @@ uint64_t x2w::compute_request_key(std::string_view code, std::string_view data, } uint64_t x2w::mesh57_request_key(std::string_view code, std::string_view ps57, std::string_view root) { - constexpr char revision[] = "x2w-startup-mesh-57-4"; + constexpr char revision[] = "x2w-startup-mesh-57-5"; uint64_t key = fnv1a_64(std::string_view(revision, sizeof(revision) - 1)); for (const auto part_view : {code, ps57, root}) { const uint64_t size = part_view.size(); diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 9e181eb612..3ed1a897d7 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -48,6 +48,7 @@ struct PipelineInfo { mutable std::vector mesh57_pixel_spans; mutable UINT mesh57_heap_word = UINT_MAX; // R32_UINT at guest root constant[heap_word] & 1023. mutable std::vector mesh57_reads; // Host SRV register order. + mutable UINT mesh57_descriptor_word_table = UINT_MAX; // Guest root parameter, bound as t,space2. u64 guest_stream_key = 0; // content hash of the copied descriptor, recorded at creation }; struct ViewRecord { diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2b012ca84d..5c7287e45b 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -533,7 +533,7 @@ bool append_pso_recipe(const wchar_t* path, const x2w_startup::PsoRecipe& recipe namespace shader_cache { constexpr char revision[] = "x2w-startup-shader-29"; constexpr char compute_revision[] = "x2w-startup-shader-29cs"; // tools/startup/gfx2hlsl.py compute_key -constexpr char mesh57_revision[] = "x2w-startup-mesh-57-4"; +constexpr char mesh57_revision[] = "x2w-startup-mesh-57-5"; } // namespace shader_cache // Once per process, before its first request: \revision.txt names this runtime's revisions, so diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a3ddf5832..44840f54a5 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -195,6 +195,9 @@ struct IndirectGraphicsPipeline { const std::vector* guest_root_params{}; UINT cached_srv_root = UINT_MAX; UINT constant_guest = UINT_MAX; // Single MS b0 mapped from this guest root under a deferred signature. + // Slot 57 descriptor-word table: host root parameter and guest root parameter (its shader register in space 2). + UINT mesh57_descriptor_word_parameter = UINT_MAX; + UINT mesh57_descriptor_word_guest = UINT_MAX; // Slot 86 heap-buffer profile: the resource-heap slots [first, first + count) the desktop stages may index // (mesh86_cache.inl), and the type they read every slot as ('f', 'u' or 'i'). A count of 0 means the root // indexes no heap. @@ -1929,6 +1932,8 @@ struct DesktopAllocator { x2w_startup::UniqueRecordingHolds> retained_resources; // Immutable raw SRV table slices live until the allocator's last queue fence retires. std::vector> mesh_view_pages; + // Slot 57 descriptor-word SRV pages; one R32_UINT SRV at index 0 per page. + std::vector> mesh57_word_pages; std::vector, x2w_startup::ComPtr>> mesh86_texture_pages; UINT mesh_view_cursor = 0; diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index 3cb399a6e7..b117563ea5 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -1,4 +1,50 @@ // Included after both the native graphics compiler and the desktop stream validator. +// Materialize the guest V# words a mesh stage reads numerically. A token names a desktop SRV: its +// captured description and resource supply the dimensional fields the guest reads. Raw title bytes +// are already a guest descriptor and enter the table unchanged. +bool mesh57_descriptor_entry(const UINT (&slot)[8], std::array& words) +{ + words = {}; + if (slot[0] != view_token_magic) { + std::memcpy(words.data(), slot, sizeof(slot)); + return true; + } + ViewRecord record{}; + if (!token_view(slot, record) || record.slot != 18 || + record.desc_bytes < sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) + return true; // not a texture SRV: the table entry stays zero + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + std::memcpy(&view, record.desc, sizeof(view)); + const bool one = view.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1D; + const bool two = view.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D; + const bool array = view.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + if (!one && !two && !array) return true; + Wrapper* owner = record.resource ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; + ID3D12Resource* resource = owner ? sampled_address_texture(owner) : nullptr; + if (!resource) return true; + const auto desc = resource->GetDesc(); + if (desc.Dimension != (one ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D)) + return true; + const UINT base = one ? view.Texture1D.MostDetailedMip : array ? view.Texture2DArray.MostDetailedMip : + view.Texture2D.MostDetailedMip; + const UINT levels = one ? view.Texture1D.MipLevels : array ? view.Texture2DArray.MipLevels : + view.Texture2D.MipLevels; + if (base >= desc.MipLevels || !levels) return true; + const UINT width = static_cast((std::max)(UINT64{1}, desc.Width >> base)) - 1; + const UINT height = (std::max)(1u, desc.Height >> base) - 1; + const UINT last = (std::min)(levels, UINT{desc.MipLevels} - base) - 1; + words[1] = (width & 3) << 30; + words[2] = (width >> 2) | (height << 14); + words[3] = (last & 15) << 16; + // Guest base address words. The desktop resource is resolved through its title-memory address; + // the numeric consumer only reads the dimensional words today, but the table keeps the pair so + // a word-5 read observes the same nonzero descriptor the title wrote. + const auto address = reinterpret_cast(owner->own().title_memory); + words[4] = static_cast(address); + words[5] = static_cast(address >> 32); + return true; +} + // Resolve every SRV before recording barriers or a descriptor table. A guest root address // has no descriptor length; use the remaining proven GPU allocation, including for indexed reads. const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommandList* list, ID3D12Resource* arguments) @@ -7,10 +53,46 @@ const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommand if (!info) return "missing MS creation metadata"; const auto& reads = info->mesh57_reads; const auto& spans = info->mesh57_pixel_spans; - if (reads.empty() && spans.empty()) { + const bool descriptor_words = info->mesh57_descriptor_word_table != UINT_MAX; + if (descriptor_words != (pass.indirect_graphics.mesh57_descriptor_word_parameter != UINT_MAX) || + (descriptor_words && pass.indirect_graphics.mesh57_descriptor_word_guest != info->mesh57_descriptor_word_table)) + return "MS descriptor word root binding is missing or stale"; + if (reads.empty() && spans.empty() && !descriptor_words) { list->SetGraphicsRootSignature(pass.indirect_graphics.root); return nullptr; } + const UINT descriptor_word_parameter = pass.indirect_graphics.mesh57_descriptor_word_parameter; + DrawSamplerHeap word_heap; + D3D12_GPU_DESCRIPTOR_HANDLE word_gpu{}; + if (descriptor_words) { + constexpr UINT entries = 1024, words_per_entry = 8; + constexpr UINT bytes = entries * words_per_entry * sizeof(UINT); + auto* data = static_cast(list_allocate_upload(self, bytes, D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)); + if (!data) return "MS descriptor word table allocation failed"; + std::memset(data, 0, bytes); + for (UINT slot_index = 0; slot_index < entries; ++slot_index) { + const auto at = pass.title_view_heap.record(UINT64{slot_index} * 32, 32); + if (!at || !x2w_local::readable(reinterpret_cast(at), 32)) continue; + UINT slot[8]{}; + if (!copy_title_bytes(slot, reinterpret_cast(at), sizeof(slot))) + return "MS descriptor word table slot is unreadable"; + std::array words{}; + if (!mesh57_descriptor_entry(slot, words)) return "MS descriptor word table slot is not a descriptor"; + std::memcpy(data + slot_index * words_per_entry, words.data(), sizeof(words)); + } + const auto range = list_upload_range(self, reinterpret_cast(data), bytes); + if (!range.resource || !range.gpu) return "MS descriptor word table has no GPU-backed upload"; + auto* device = device_of(self->own().list_device); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + if (FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&word_heap)))) + return "MS descriptor word SRV heap allocation failed"; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer = {range.offset / 4, entries * words_per_entry, 0, D3D12_BUFFER_SRV_FLAG_NONE}; + device->CreateShaderResourceView(range.resource, &srv, word_heap->GetCPUDescriptorHandleForHeapStart()); + word_gpu = word_heap->GetGPUDescriptorHandleForHeapStart(); + } std::array views{}; if (reads.size() > views.size()) return "too many MS buffer reads"; for (size_t i = 0; i < reads.size(); ++i) { @@ -147,17 +229,22 @@ const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommand constexpr UINT capacity = 256; const auto increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); DrawSamplerHeap heap; - UINT start; + UINT start = 0; { x2w_startup::ExclusiveNoteLock guard(allocator_lock); const auto recording = list_recordings.find(self); if (!self->own().list_open || recording == list_recordings.end() || !recording->second) return "MS descriptor table requires an open recording"; auto& allocator = *recording->second; + if (word_heap) { + try { allocator.mesh57_word_pages.push_back(word_heap); } + catch (const std::bad_alloc&) { return "MS descriptor word SRV page could not be retained"; } + } + const bool need_heap = !reads.empty() || !spans.empty(); const bool changed = index != allocator.mesh_heap_index || (typed.resource && (allocator.mesh_heap_buffer != typed.resource || allocator.mesh_heap_begin != typed.offset || allocator.mesh_heap_size != typed.bytes)); - if (!spans.empty() || allocator.mesh_view_pages.empty() || changed || reads.size() > capacity - allocator.mesh_view_cursor) { + if (need_heap && (!spans.empty() || allocator.mesh_view_pages.empty() || changed || reads.size() > capacity - allocator.mesh_view_cursor)) { const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, capacity + prefix, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap)))) return "MS descriptor heap allocation failed"; @@ -177,21 +264,23 @@ const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommand selected.ptr += SIZE_T{index} * increment; device->CreateShaderResourceView(typed.resource,&srv,selected); } - } else { + } else if (need_heap) { heap = allocator.mesh_view_pages.back(); } - start = allocator.mesh_view_cursor + prefix; - allocator.mesh_view_cursor = spans.empty() ? allocator.mesh_view_cursor + static_cast(reads.size()) : capacity; + if (need_heap) { + start = allocator.mesh_view_cursor + prefix; + allocator.mesh_view_cursor = spans.empty() ? allocator.mesh_view_cursor + static_cast(reads.size()) : capacity; + } } - for (auto& texture : textures) { + if (heap) for (auto& texture : textures) { auto dst=heap->GetCPUDescriptorHandleForHeapStart(); dst.ptr+=SIZE_T{texture.slot}*increment; device->CreateShaderResourceView(texture.resource.Get(),&texture.view,dst); if (texture.resource) require_state(self, texture.resource.Get(), sampled_state(self, texture.resource.Get())); } - auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + auto handle = heap ? heap->GetCPUDescriptorHandleForHeapStart() : D3D12_CPU_DESCRIPTOR_HANDLE{}; handle.ptr += SIZE_T{start} * increment; - for (size_t i = 0; i < reads.size(); ++i) { + if (heap) for (size_t i = 0; i < reads.size(); ++i) { const auto& view = views[i]; if (!retain_with_recording(self, x2w_startup::ComPtr(view.resource))) return "MS buffer could not be retained with its recording"; @@ -204,12 +293,18 @@ const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommand for (size_t i = 0; i < reads.size(); ++i) if (!views[i].upload) require_state(self, views[i].resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); if (typed.resource && !typed.upload) require_state(self, typed.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - auto* native_heap = heap.Get(); - list->SetDescriptorHeaps(1, &native_heap); + std::array heaps{}; + UINT heap_count = 0; + if (heap) heaps[heap_count++] = heap.Get(); + if (word_heap) heaps[heap_count++] = word_heap.Get(); + if (heap_count) list->SetDescriptorHeaps(heap_count, heaps.data()); list->SetGraphicsRootSignature(pass.indirect_graphics.root); - auto gpu = heap->GetGPUDescriptorHandleForHeapStart(); - gpu.ptr += UINT64{start} * increment; - if (!reads.empty()) list->SetGraphicsRootDescriptorTable(1, gpu); + if (heap) { + auto gpu = heap->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += UINT64{start} * increment; + if (!reads.empty()) list->SetGraphicsRootDescriptorTable(1, gpu); + } + if (descriptor_word_parameter != UINT_MAX) list->SetGraphicsRootDescriptorTable(descriptor_word_parameter, word_gpu); return nullptr; } // Slot-57 profile lookups that reached the cache, and the ones that opened the file (fixtures read both). @@ -430,7 +525,7 @@ void prepare_native_mesh57(Wrapper* pipeline) return note_mesh57_outcome(Mesh57Outcome::missing_creation_root_or_state); root_blob = it->second; } - constexpr char revision[] = "x2w-startup-mesh-57-4"; + constexpr char revision[] = "x2w-startup-mesh-57-5"; const u64 key = fnv_part(root_blob, fnv_part(ps_bytes, fnv_part(ms_bytes, fnv_bytes(revision, sizeof(revision) - 1)))); const auto normalized = x2w_startup::normalize_mesh57_descriptor(info->desc); const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(normalized, key))); @@ -538,15 +633,27 @@ void prepare_native_mesh57(Wrapper* pipeline) std::vector spans; std::vector samplers; UINT heap_word = UINT_MAX; + UINT descriptor_word_table = UINT_MAX; std::vector ms_code, ps_code; const auto prepare_native = [&] { auto native = mapped ? x2w::translate_mesh_program(ms, mesh_layout, guest_desc->Desc_1_1) : x2w::translate_mesh_program(ms, mesh_layout); + descriptor_word_table = native.mesh_descriptor_word_table; const bool mapped_constants = mapped && native.constants.size() == 1 && native.constants[0].root_parameter == mapping.root_parameter && native.constants[0].count == mapping.count && native.constants[0].first_sgpr == mapping.sgpr; - 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())) + const bool descriptor_words = native.mesh_descriptor_word_table != ~0u; + if (descriptor_words) { + if (!mapped || !direct_heap) + throw std::runtime_error("MS descriptor words require a directly indexed reviewed heap"); + if (native.mesh_descriptor_word_table >= guest_desc->Desc_1_1.NumParameters || + guest_desc->Desc_1_1.pParameters[native.mesh_descriptor_word_table].ParameterType != + D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + throw std::runtime_error("MS descriptor word table is not a guest descriptor table"); + } + if ((mapped ? !mapped_constants : !native.constants.empty()) || (!buffers && !native.bindings.empty()) || + (buffers && native.bindings.empty() && !descriptor_words) || !native.samplers.empty() || native.sampler_heap || + (direct_heap ? native.mesh_heap_reads.empty() && !descriptor_words : !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) @@ -557,7 +664,7 @@ void prepare_native_mesh57(Wrapper* pipeline) throw std::runtime_error("unsupported MS resource heap index contract"); heap_word = guard.dword; } - if (buffers) { + if (buffers && !native.bindings.empty()) { if (native.bindings.empty() || native.bindings.size() > 32) throw std::runtime_error("unsupported MS buffer binding count"); for (auto b : native.bindings) { @@ -635,7 +742,7 @@ void prepare_native_mesh57(Wrapper* pipeline) prepare_native(); } catch (const x2w::UnsupportedComputeShader& error) { if (!is_mesh57_group_index_refusal(error) || !allow_published_mesh57_pair()) throw; - if (!buffers || direct_heap) + if (!buffers || direct_heap || descriptor_word_table != UINT_MAX) throw std::runtime_error("published MS57 pair does not describe this profile"); native_refusal = error.what(); published = true; @@ -683,18 +790,37 @@ void prepare_native_mesh57(Wrapper* pipeline) char why[256]{}; auto& state = pipeline->own(); x2w_startup::ComPtr host; + UINT descriptor_word_parameter = UINT_MAX; if (mapped) { - D3D12_ROOT_PARAMETER params[2]{}; + D3D12_ROOT_PARAMETER1 params[3]{}; auto& block = params[0]; block.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - block.Constants.Num32BitValues = (mapping.count + 3) & ~3u; - D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, static_cast(reads.size())}; - params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - params[1].DescriptorTable = {1, &range}; - D3D12_ROOT_SIGNATURE_DESC host_desc{reads.empty() ? 1u : 2u, params, static_cast(samplers.size()), samplers.data()}; - if (direct_heap) host_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + block.Constants = {0, 0, (mapping.count + 3) & ~3u}; + D3D12_DESCRIPTOR_RANGE1 range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, static_cast(reads.size()), 0, 0, + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_STATIC_KEEPING_BUFFER_BOUNDS_CHECKS, 0}; + D3D12_DESCRIPTOR_RANGE1 word_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 2, + D3D12_DESCRIPTOR_RANGE_FLAG_NONE, 0}; + UINT count = 1; + if (!reads.empty()) { + params[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[count++].DescriptorTable = {1, &range}; + } + if (descriptor_word_table != ~0u) { + params[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[count].DescriptorTable = {1, &word_range}; + descriptor_word_parameter = count; + ++count; + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC host_desc{}; + host_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + // A descriptor-word-only stage reads the table through its descriptor table; the + // resource-heap flag would then be declared but unused and DXIL validation refuses it. + const bool host_heap = direct_heap && (heap_word != UINT_MAX || descriptor_word_table == UINT_MAX); + host_desc.Desc_1_1 = {count, params, static_cast(samplers.size()), samplers.data(), + host_heap ? D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED : + D3D12_ROOT_SIGNATURE_FLAG_NONE}; x2w_startup::ComPtr blob; - if (FAILED(D3D12SerializeRootSignature(&host_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + if (FAILED(D3D12SerializeVersionedRootSignature(&host_desc, &blob, nullptr)) || !blob || FAILED(device_of(the_device)->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&host)))) throw std::runtime_error("failed to create MS b0 constant root"); @@ -713,9 +839,12 @@ void prepare_native_mesh57(Wrapper* pipeline) throw std::runtime_error("could not retain MS constant root"); } state.indirect_graphics.constant_guest = mapping.root_parameter; + state.indirect_graphics.mesh57_descriptor_word_parameter = descriptor_word_parameter; + state.indirect_graphics.mesh57_descriptor_word_guest = descriptor_word_table; info->mesh57_pixel_spans = std::move(spans); info->mesh57_reads = std::move(reads); info->mesh57_heap_word = heap_word; + info->mesh57_descriptor_word_table = descriptor_word_table; } note_mesh57_outcome(Mesh57Outcome::ready); log("x2w-render native slot57 mesh %016llx ready", key); diff --git a/tests/native_compile_dxil_rekey_check.py b/tests/native_compile_dxil_rekey_check.py index 02f15b4764..ed95deffc6 100644 --- a/tests/native_compile_dxil_rekey_check.py +++ b/tests/native_compile_dxil_rekey_check.py @@ -88,7 +88,7 @@ def check_revision_strings(): cpp_req = (ROOT / 'src' / 'shader_compute_request.cpp').read_text(encoding='utf-8') draw_inl = (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_text(encoding='utf-8') py_text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') - for token in ('x2w-startup-shader-29', 'x2w-startup-shader-29cs', 'x2w-startup-mesh-57-4'): + for token in ('x2w-startup-shader-29', 'x2w-startup-shader-29cs', 'x2w-startup-mesh-57-5'): ok = (token in cpp_req) and (token in draw_inl) and (token in py_text) check('revision string %s matches across C++ and Python' % token, ok) diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index 0816a19356..1bc6f73291 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -642,7 +642,7 @@ def run(name, words, expected=None): 0x7e020280,0xe0002000,0x80080a01] # v10 = formatted element v1 (index zero) exported = program.copy() exported[7] = 0x7e020d0a # v_cvt_f32_u32 v1,v10 - layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1\nresource_heap 23') + layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1\ntable 16 1\nresource_heap 23') run('unknown-heap-view',typed+exported,'selected GPU slot') with layout.open('a') as meta: meta.write('\nvalidate_uint_heap_reads') @@ -651,6 +651,19 @@ def run(name, words, expected=None): assert marker in text, marker overwritten = typed[:7] + [0xbea10380] + typed[7:] run('overwritten-heap-word',overwritten+exported,'overwritten mesh heap descriptor') + # The slot 57 descriptor load may be eight dwords wide: the same heap + # address and proven selector fetch one 32-byte descriptor, and the + # first four words stay the V# a typed load consumes. + x8_fetch = [0xf40c080f, 0x2a000000] # s_load_dwordx8 s[32:39], s[30:31], s21 + x8_load = [0x7e020280,0xe0002000,0x80080a01] # v1 = 0; buffer_load_format_x v10, v1, s[32:35] idxen + text = run('typed-heap-descriptor-x8', typed[:5] + x8_fetch + x8_load + exported) + for marker in ('createHandleFromHeap', 'bufferLoad.i32', 'i32 261'): + assert marker in text, marker + run('typed-heap-descriptor-x16', typed[:5] + [0xf410080f, 0x2a000000] + x8_load + exported, + '+0x14: unsupported mesh heap descriptor address') + run('typed-heap-descriptor-unproven', + [0xbe9e0317,0xbe9f0380,0x8f148415] + [0xf40c080f, 0x28000000] + x8_load + exported, + '+0xc: mesh heap slot lacks masked root constant provenance') # Unindexed buffer_load_format_x reads element 0 without touching vaddr, and its result is uniform under full EXEC. heap_setup = typed[:7] load_idxen = [0xe0002000, 0x80080a01] # buffer_load_format_x v10, v1, s[32:35], 0 idxen @@ -710,29 +723,108 @@ def skip_load(body, seed=True): ] text = run('typed-heap-saveexec-then', skip_load(saveexec_load)) assert 'bufferLoad.i32' in text and 'mesh_then' in text and 'phi i32' in text, text - texture = [ + texture_fetch = [ 0xbe9e0317, 0xbe9f0380, # heap base and zero high word - 0x8f148515, # s20 = s21 << 5 + 0x8715ff15, 31, # mask the root selector + 0x8f148515, # s20 = s21 << 5 0xf40c080f, 0x28000000, # s_load_dwordx8 s[32:39], s[30:31], s20 - 0x9394ff23, 0x4000c, 0x7e020214, # v1 = base mip from descriptor word 3 - 0xf0001f00, 0x00080a01, # image_load 1D v[10:13] at v1 ] + texture_zero = [0x7e020280] # v1 = 0 + texture_load = [0xf0001f00, 0x00080a01] # image_load 1D v[10:13] at v1 + texture_numeric = [0x9394ff21, 0x4000c, 0x7e020214] # v1 = field from word 1 texture_export = program.copy() - texture_export[7] = 0x7e02030a # pass the red float to POS0.x - run('mesh-texture-heap-without-map',texture+texture_export,'unsupported mesh heap descriptor address') + texture_export[7] = 0x7e020214 # v1 = s20; POS0.x exports the numeric descriptor word + texture_gpu = [ + 0xbe9e0317, 0xbe9f0380, + 0x8f148515, + 0xf40c080f, 0x28000000, + ] + # The runtime table supplies guest V# words to numeric scalar reads. + result, out = compile_mesh('mesh-descriptor-word-1', texture_fetch + texture_numeric + texture_export) + assert result.returncode == 0, result.stderr + assert 'requires_mesh_descriptor_words root=1 t0,space2 entries=1024 words=8' in result.stdout, result.stdout + text = subprocess.check_output([sdk/'dxc.exe','-dumpbin',out], text=True) + for marker in ('bufferLoad.i32', 'createHandleFromBinding', 'icmp ult i32'): + assert marker in text, marker + text = run('mesh-descriptor-word-5', + texture_fetch + [0x9394ff25, 0x4000c, 0x7e020214] + texture_export) + assert 'bufferLoad.i32' in text, text + # A typed four-word heap fetch is not a V# table entry: its words keep refusing as numbers. + typed_fetch = [0xbe9e0317, 0xbe9f0380, 0x8715ff15, 31, 0x8f158515, 0xf408080f, 0x2a000000] + run('mesh-descriptor-non-descriptor', + typed_fetch + [0x9394ff21, 0x4000c, 0x7e020214] + texture_export, + 'unbound numeric SGPR s33') + # A 1D UNORM three-channel image uses the full V# consumer, with a root + # or GPU-selected fetch, without the slot map. Four channels stay out. + texture_load3 = [0xf0001700, 0x00080a01] # image_load 1D v[10:13] at v1, dmask 0x7 + text = run('mesh-image-full-descriptor-root', + texture_fetch + texture_zero + texture_load3 + texture_export) + assert 'createHandleFromHeap' in text and 'textureLoad.f32' in text, text + text = run('mesh-image-full-descriptor-gpu', + texture_gpu + texture_zero + texture_load3 + texture_export) + assert 'createHandleFromHeap' in text and 'textureLoad.f32' in text, text + run('mesh-image-four-channel-without-map', + texture_fetch + texture_zero + texture_load + texture_export, + 'unsupported mesh image load or descriptor') + # The unmasked selector reaches the GPU-selected branch through the + # proven 32-byte shift; its four-channel load stays outside the full-V# + # consumer and still needs the remapped view. + run('mesh-texture-heap-gpu-without-map', + texture_gpu + texture_zero + texture_load + texture_export, + 'unsupported mesh image load or descriptor') with layout.open('a') as meta: meta.write('\ntexture_heap_slot_map') - text = run('mesh-texture-heap-slot-map',texture+texture_export) + texture_mapped = texture_fetch + texture_numeric + texture_load + text = run('mesh-texture-heap-slot-map', texture_mapped + texture_export) for marker in ('t0,space1', 'RawBuffer', 'createHandleFromHeap', 'textureLoad.f32', 'texture1d'): assert marker.lower() in text.lower(), marker - bad_shift = texture.copy() - bad_shift[2] = 0x8f148415 - run('mesh-texture-heap-unaligned',bad_shift+texture_export,'32-byte alignment proof') - bad_dim = texture.copy() + text = run('mesh-texture-heap-gpu-slot-map', + texture_gpu + texture_zero + texture_load + texture_export) + assert 'textureLoad.f32' in text and 'createHandleFromHeap' in text, text + bad_shift = texture_mapped.copy() + bad_shift[4] = 0x8f148415 + run('mesh-texture-heap-unaligned', bad_shift + texture_export, '32-byte alignment proof') + bad_dim = texture_mapped.copy() bad_dim[-2] |= 8 - run('mesh-texture-heap-wrong-dimension',bad_dim+texture_export,'remapped Texture1D heap contract') - run('mesh-texture-heap-overwritten',texture[:5]+[0xbea70380]+texture[5:]+texture_export, + run('mesh-texture-heap-wrong-dimension', bad_dim + texture_export, + 'remapped Texture1D heap contract') + run('mesh-texture-heap-overwritten', + texture_mapped[:7] + [0xbea70380] + texture_mapped[7:] + texture_export, 'overwritten mesh texture heap descriptor') + # A full V# fetched from the resource heap drives a 1D UNORM load of + # three channels without the slot map: createHandleFromHeap selects the + # guest descriptor and textureLoad reads it at the VGPR coordinate. + saved_layout = layout.read_text() + layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1\nresource_heap 23\nvalidate_uint_heap_reads') + full_image = [ + 0xbe9e0317, 0xbe9f0380, # heap base and zero high word + 0x8715ff15, 31, # mask the root selector + 0x8f158515, # s21 = s21 << 5 + 0xf40c080f, 0x2a000000, # s_load_dwordx8 s[32:39], s[30:31], s21 + 0x7e160280, # v11 = 0 + 0xf0001700, 0x0008130b, # image_load v[19:21], v11, s[32:39] dmask:0x7 1D unorm + ] + image_export = program.copy() + image_export[5] = 0x7e020313 # v_mov_b32 v1, v19 + image_export[6] = 0x7e040314 # v_mov_b32 v2, v20 + text = run('mesh-image-full-descriptor', full_image + image_export) + assert 'createHandleFromHeap' in text, text + loaded = re.search(r'(?P%[\w.]+) = call %dx\.types\.ResRet\.f32 @dx\.op\.textureLoad\.f32' + r'\(i32 66, %dx\.types\.Handle %[\w.]+, i32 0, i32 (?:%[\w.]+|-?\d+)', text) + assert loaded, text + first = re.search(rf'(?P%[\w.]+) = extractvalue %dx\.types\.ResRet\.f32 ' + rf'{re.escape(loaded["load"])}, 0\n\s*' + rf'(?P%[\w.]+) = bitcast float (?P=value) to i32\n', text) + assert first, text + assert_position_x(text, rf'bitcast float {re.escape(first["value"])} to i32') + for channel in (1, 2): + assert re.search(rf'= extractvalue %dx\.types\.ResRet\.f32 ' + rf'{re.escape(loaded["load"])}, {channel}\n', text), text + unsupported_dim = full_image.copy() + unsupported_dim[-2] = 0xf0001708 # dim 2D stays refused + run('mesh-image-unsupported-dimension', unsupported_dim + image_export, + 'unsupported mesh image load or descriptor') + layout.write_text(saved_layout) half_frontend = [0xcc210014, 242 | (242 << 9) | (242 << 18)] # v_fma_mixlo_f16 v20, 1, 1, 1 half_pack = [0xd711001a, 276 | (276 << 9)] # pack the defined low half of v20 twice text = run('mesh-pack-from-defined-half',half_frontend+half_pack+program) @@ -754,6 +846,39 @@ def skip_load(body, seed=True): 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') + # A GPU-selected eight-dword descriptor fetch records its slot. The typed + # consumer has no heap or token fetch and an image needs the slot map; + # numeric reads take the runtime descriptor-word table. + selected_x8 = select_word + times_32 + heap_base + [0xf40c080f, 0x48000000] + run('gpu-heap-descriptor-x8-typed', selected_x8 + formatted + exported, + 'formatted mesh load lacks an R32_UINT resource heap contract') + run('gpu-heap-descriptor-x8-image', + selected_x8 + [0x7e020280, 0xf0001f00, 0x00080a01] + texture_export, + 'unsupported mesh image load or descriptor') + text = run('gpu-heap-descriptor-word-1', + selected_x8 + [0x9394ff21, 0x4000c, 0x7e020214] + texture_export) + assert 'bufferLoad.i32' in text, text + text = run('gpu-heap-descriptor-word-5', + selected_x8 + [0x9394ff25, 0x4000c, 0x7e020214] + texture_export) + assert 'bufferLoad.i32' in text, text + # Without a guest descriptor-table root there is no register or space to bind the table. + layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1\nresource_heap 23\nvalidate_uint_heap_reads') + run('gpu-heap-descriptor-word-no-table', + heap_base + [0x8f158515, 0xf40c080f, 0x2a000000, + 0x9394ff21, 0x4000c, 0x7e020214] + texture_export, + 'mesh descriptor word table requires a guest descriptor table') + layout.write_text(gpu_layout) + # A sixteen-dword table fetch is refused by the shared table bounds; + # a sixteen-dword heap fetch without the validated branch still reaches + # the write loop, which must stay inside the eight-word record. + wide_table = [0xf4100808, 0xfa000000] + run('mesh-table-wide-load', program[:5] + wide_table + [0x7e020220] + program[6:], + 'direct descriptor address outside bound table') + layout.write_text('mesh1 128 3 1 2 128 64\nresource_heap 23') + run('mesh-heap-wide-load', + program[:5] + [0xbe9e0317, 0xbe9f0380, 0xf410080f, 0xfa000000] + + [0x7e020220] + program[6:], + 'direct resource-heap load requires the selected GPU slot and its view type') 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' diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index a7326db931..164d94d4ff 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -225,8 +225,8 @@ def test_shader_patches(self): ok + shader_patch(revision="x2w-startup-shader-12"), "s002 revision 'x2w-startup-shader-12cs' is not a graphics key revision (x2w-startup-shader-)": ok + shader_patch("s002", pipeline="graphics", revision="x2w-startup-shader-12cs"), - "revision 'x2w-startup-mesh-57-4' is not a mesh86 key revision (x2w-startup-mesh-86-)": - ok + shader_patch(pipeline="mesh86", revision="x2w-startup-mesh-57-4"), + "revision 'x2w-startup-mesh-57-5' is not a mesh86 key revision (x2w-startup-mesh-86-)": + ok + shader_patch(pipeline="mesh86", revision="x2w-startup-mesh-57-5"), "revision 'x2w-startup-shader-cs' is not a compute": ok + shader_patch(revision="x2w-startup-shader-cs"), "revision 'x2w-startup-shader-012cs' is not a compute": ok + shader_patch(revision="x2w-startup-shader-012cs"), diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 02b7c56c32..1a873ba6a4 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2667,7 +2667,7 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, key = (key ^ p[i]) * 1099511628211ull; return key; }; - const char revision[] = "x2w-startup-mesh-57-4"; + const char revision[] = "x2w-startup-mesh-57-5"; auto key = fold(1469598103934665603ull, revision, sizeof(revision) - 1); const auto extend = [&](UINT64 base, const void* data, UINT64 n) { return fold(fold(base, &n, sizeof(n)), data, n); }; const auto part = [&](const void* data, UINT64 n) { key = extend(key,data,n); }; diff --git a/tests/startup_mesh57_runtime.inl b/tests/startup_mesh57_runtime.inl index cf0d3533d6..65a4144012 100644 --- a/tests/startup_mesh57_runtime.inl +++ b/tests/startup_mesh57_runtime.inl @@ -23,12 +23,13 @@ std::uint64_t mesh57_extend(std::uint64_t key, const void* data, std::uint64_t b // Write the reviewed source-built profile the runtime loader needs beside the request. The // fixture has no state blocks and one table at s16 (root parameter 1). void write_mesh57_profile(const std::filesystem::path& cache, const std::array& fields, - const std::vector& root_blob, const std::vector& ms, const std::vector& ps) + const std::vector& root_blob, const std::vector& ms, const std::vector& ps, + bool heap_profile = false) { std::vector raw(reinterpret_cast(fields.data()), reinterpret_cast(fields.data()) + sizeof(fields)); auto normalized = x2w_startup::normalize_mesh57_descriptor(std::move(raw)); - const char revision[] = "x2w-startup-mesh-57-4"; + const char revision[] = "x2w-startup-mesh-57-5"; std::uint64_t key = mesh57_fold(1469598103934665603ull, revision, sizeof(revision) - 1); key = mesh57_extend(key, ms.data(), ms.size()); key = mesh57_extend(key, ps.data(), ps.size()); @@ -38,7 +39,7 @@ void write_mesh57_profile(const std::filesystem::path& cache, const std::array(normalized.size()); profile.lengths[1] = 0; profile.lengths[2] = 0; @@ -80,6 +81,10 @@ void write_mesh57_profile(const std::filesystem::path& cache, const std::array(&view_count), sizeof(view_count)); out.write(reinterpret_cast(&view), sizeof(view)); + if (heap_profile) { + const UINT heap_sgpr = 23; + out.write(reinterpret_cast(&heap_sgpr), sizeof(heap_sgpr)); + } out.write(reinterpret_cast(normalized.data()), static_cast(normalized.size())); out.write(reinterpret_cast(root_blob.data()), static_cast(root_blob.size())); out.write(ms.data(), static_cast(ms.size())); @@ -93,6 +98,7 @@ bool run_mesh57_runtime(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSig const char* scenario = std::getenv("X2W_TEST_MESH57_SCENARIO"); const bool two_views = scenario && !std::strcmp(scenario, "two-views"); const bool short_view = scenario && !std::strcmp(scenario, "short-view"); + const bool descriptor_words = scenario && !std::strcmp(scenario, "descriptor-words"); const auto read = [&](const char* name) { std::ifstream file(exchange / name, std::ios::binary); return std::vector(std::istreambuf_iterator(file), {}); @@ -114,7 +120,7 @@ bool run_mesh57_runtime(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSig fields[13] = reinterpret_cast(ms.data()); fields[14] = ms.size(); std::vector root_bytes(root_blob.begin(), root_blob.end()); - write_mesh57_profile(cache, fields, root_bytes, ms, ps); + write_mesh57_profile(cache, fields, root_bytes, ms, ps, descriptor_words); using Create = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); ComPtr pso; check(slot(guest, 57)(guest, fields.data(), __uuidof(ID3D12PipelineState), @@ -165,7 +171,8 @@ bool run_mesh57_runtime(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSig const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 backing, bytes; - } table_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, two_views ? 2u : 1u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + } table_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + two_views || descriptor_words ? 2u : 1u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; using CreateHeap = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); ComPtr table; check(slot(guest, 14)(guest, &table_desc, __uuidof(ID3D12DescriptorHeap), @@ -182,6 +189,19 @@ bool run_mesh57_runtime(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSig slot(guest, 18)(guest, vertex_guest.Get(), &srv, cpu, 0); if (two_views) slot(guest, 18)(guest, colour_guest.Get(), &srv, cpu + 32, 0); + ComPtr texture_guest; + if (descriptor_words) { + const D3D12_RESOURCE_DESC texture{D3D12_RESOURCE_DIMENSION_TEXTURE1D, 0, 768, 1, 1, 1, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); + check(slot(guest, 133)(guest, reinterpret_cast(0x100000000ull), &texture, + D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), + reinterpret_cast(texture_guest.GetAddressOf())), "create descriptor-word Texture1D"); + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE1D, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Texture1D.MipLevels = 1; + slot(guest, 18)(guest, texture_guest.Get(), &view, cpu + 32, 0); + } const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; diff --git a/tests/startup_mesh57_runtime_check.py b/tests/startup_mesh57_runtime_check.py index d7b1f60195..ad389f3ec1 100644 --- a/tests/startup_mesh57_runtime_check.py +++ b/tests/startup_mesh57_runtime_check.py @@ -51,14 +51,15 @@ def run_case(directory, consumer, adapter, label, expected, forwarded, scenario= return 0 -def publish(directory, consumer, adapter, mesh=fixture.MESH_R1): +def publish(directory, consumer, adapter, mesh=fixture.MESH_R1, verify=True): directory.mkdir(parents=True, exist_ok=True) status, published = fixture.publish_request(directory, consumer, adapter, mesh=mesh) if status: return status, None cache, key, _ = published - result = fixture.G.translate_request(str(cache), key) - assert result == "ok", result + if verify: + result = fixture.G.translate_request(str(cache), key) + assert result == "ok", result (directory / "root.bin").write_bytes((cache / f"req_{key:016x}.root").read_bytes()) (directory / "ms.bin").write_bytes(fixture.code(mesh)) (directory / "ps.bin").write_bytes(fixture.code(fixture.PIXEL)) @@ -113,6 +114,20 @@ def check(directory, consumer, adapter): if status: return status + # Source-built descriptor-word table: title heap slot 1 is a Texture1D SRV. Red exports the + # projected width bits from V# word 1 and green is 64 only when V# word 5 is nonzero. + words_case = directory / "descriptor-words" + status, published = publish(words_case, consumer, adapter, mesh=fixture.MESH_DESCRIPTOR, verify=False) + if status: + return status + (words_case / "geometry.bin").write_bytes(fixture.buffer(points, colours, words)) + descriptor_pixels = b"".join(bytes(pixel) for pixel in fixture.rasterise( + points, [(192, 64, 0, 255)] * len(points), indices, 12, 4)) + status = run_case(words_case, consumer, adapter, "descriptor words", descriptor_pixels, 1, + "descriptor-words") + if status: + return status + # Without a published pair the native R1 refusal remains the result. absent = directory / "absent" status, published = publish(absent, consumer, adapter) diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index cfa21a4423..8acb632af7 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -76,6 +76,15 @@ # mesh_skeleton still accepts the shape. This is the fallback case the runtime must handle. MESH_R1 = MESH[:1] + ['befe04c1', '7e0a0280'] + MESH[1:] MESH_TWO_BUFFERS_R1 = MESH_TWO_BUFFERS[:1] + ['befe04c1', '7e0a0280'] + MESH_TWO_BUFFERS[1:] +# Source-built mesh for the runtime descriptor-word table. It keeps one table-buffer read (root 1) +# so the buffers profile has a manifest, then reads heap slot 1's V# words 1 and 5. Red is the +# projected width low bits; green is 64 when word 5 is nonzero, which proves the table kept the +# guest address word instead of zeroing it. +MESH_DESCRIPTOR = ( + 'befc03ff 1003 bf900009 d7650000 100c1 36020081 2c040081 7e020d01 7e040d02 7e0602f0 7e0802f2' + ' be9e0317 be9f0380 be950381 8f158515 f40c080f 2a000000 9394ff21 2001e 8f148614' + ' bf078025 851580c0 7e0a0214 7e0c0215 7e0e0280 7e1002f2 f800020f 08070605' + ' f80008cf 04030201 f8000941 80808005 bf810000').split() # A depth-only pixel stage: no colour output, only the null-target export (done, vm, no channel). Lanes whose flat # attribute 0 red is not above 0.5 leave EXEC, so the vm export kills them and they write no depth. DEPTH_PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_cmpx_lt_f32_e32 0.5, v0\n' diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp index 93a4214344..0e8ec510cc 100644 --- a/tools/startup/compile_dxil.cpp +++ b/tools/startup/compile_dxil.cpp @@ -294,6 +294,9 @@ static std::optional compile_one(x2w::ShaderDxilCompiler& compiler, report<<"requires_heap_r32_uint root="<