diff --git a/CMakeLists.txt b/CMakeLists.txt index df3f0e36b..1e37bf69c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,8 +13,8 @@ if(WIN32) set(native_shader_revision "") foreach(source gfx1013_compute_native.cpp gfx1013_compute_native.h gfx1013_compute_opcodes.inl gfx1013_graphics_wqm.inl gfx1013_isa_tables.inl gfx1013_isa.cpp gfx1013_isa.h gfx1013_compute_alu.inl gfx1013_direct_compute.inl gfx1013_compute_ir.cpp gfx1013_compute_ir.h - gfx1013_compute_mtbuf.inl gfx1013_direct_graphics.inl gfx1013_rect_geometry.cpp guest_shader_container.cpp guest_shader_container.h - dxil_module.h direct_compute_cache.cpp direct_compute_cache.h + gfx1013_compute_mtbuf.inl gfx1013_direct_graphics.inl gfx1013_direct_mesh.inl gfx1013_pixel_waterfall.inl gfx1013_rect_geometry.cpp guest_shader_container.cpp guest_shader_container.h + dxil_module.h mesh_pixel_heap.h direct_compute_cache.cpp direct_compute_cache.h shader_compute_request.cpp shader_compute_request.h startup_stubs/inflate.h) set(native_shader_file "${CMAKE_CURRENT_SOURCE_DIR}/src/${source}") set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${native_shader_file}") @@ -1951,6 +1951,10 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_sampled_replay COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_sampled_replay_check.py" "$" "$" "${DXC_BIN_DIR}") foreach(backend IN ITEMS warp hardware) + add_test(NAME native_indexed_pixel_texture_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_indexed_pixel_texture_check.py" "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_indexed_pixel_texture_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) add_test(NAME native_buffered_vertex_${backend} COMMAND native_buffered_vertex_gpu ${backend} "${DXC_BIN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/native-buffered-${backend}") set_tests_properties(native_buffered_vertex_${backend} PROPERTIES SKIP_RETURN_CODE 77) @@ -1986,6 +1990,23 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_direct_container COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" "$" "${DXC_BIN_DIR}") + add_test(NAME native_direct_mesh + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_direct_mesh_check.py" + "$" "${DXC_BIN_DIR}") + add_executable(native_frozen_request_check tests/native_frozen_request_check.cpp) + target_include_directories(native_frozen_request_check PRIVATE src) + target_compile_features(native_frozen_request_check PRIVATE cxx_std_17) + target_link_libraries(native_frozen_request_check PRIVATE x2w_shader_compiler) + set_property(TARGET native_frozen_request_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_frozen_request COMMAND native_frozen_request_check) + add_executable(native_compute_pack_check tests/native_compute_pack_check.cpp) + target_link_libraries(native_compute_pack_check PRIVATE x2w_shader_compiler) + target_include_directories(native_compute_pack_check PRIVATE src) + target_compile_features(native_compute_pack_check PRIVATE cxx_std_17) + set_property(TARGET native_compute_pack_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_compute_pack COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_pack_check.py" "$" + "$" "${DXC_BIN_DIR}") foreach(adapter IN ITEMS warp hardware) foreach(case IN ITEMS r rg rgb array volume rgba sparse) add_test(NAME native_image_store_exact_width_${adapter}_${case} @@ -2002,6 +2023,12 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ "${CMAKE_SOURCE_DIR}/tests/native_graphics_wqm_check.py" "$" "$" "${DXC_BIN_DIR}") set_tests_properties(native_graphics_wqm_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + foreach(adapter warp hardware) + add_test(NAME native_graphics_sampler_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_graphics_sampler_heap_check.py" "$" + "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_graphics_sampler_heap_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() add_test(NAME native_graphics_interface_library COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_graphics_interface_library_check.py" "$" "${DXC_BIN_DIR}") diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index 29a346550..b677f0353 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -36,20 +36,23 @@ bool embedded_graphics_id(std::string_view raw) { } return true; } -GuestShaderStage match_graphics_stage(std::string_view raw, const Bytes &blob, bool &exact) { +GuestShaderStage match_graphics_stage(std::string_view raw, const Bytes &blob, bool &exact, + std::optional required = {}) { auto stages = read_guest_shader_container(blob); int best = 0; size_t selected = 0; bool tie = false; for (size_t i = 0; i < stages.size(); ++i) { const auto &stage = stages[i]; - if (stage.stage != GpuStage::vs && stage.stage != GpuStage::ps) continue; + if (required ? stage.stage != *required : (stage.stage != GpuStage::vs && stage.stage != GpuStage::ps)) + continue; // A pixel container can carry materialized export instructions in a // patch table. The running PS already contains the selected export. int rank = 0; if (raw == stage.code) rank = stage.exports.empty() ? 3 : 2; if (!stage.exports.empty() && raw == stage.full_precision_code()) rank = 3; - if (!rank && raw.substr(0,24) == std::string_view(stage.code).substr(0,24) && embedded_graphics_id(raw)) + if (!rank && raw.substr(0,24) == std::string_view(stage.code).substr(0,24) && embedded_graphics_id(raw) && + (!required || (stage.container_identifier && native_shader_identifier(raw) == stage.container_identifier))) rank = 1; if (rank > best) { best = rank; selected = i; tie = false; } else if (rank && rank == best) tie = true; @@ -97,6 +100,7 @@ Bytes encode(const NativeComputeShader &program) { for (const auto &c : program.constants) for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) word(out, n); + word(out, program.sampler_heap); word(out, static_cast(program.stride_srvs.size())); for (unsigned srv : program.stride_srvs) word(out, srv); @@ -131,7 +135,7 @@ NativeComputeShader decode(std::string_view bytes) { unsigned n = in.count(1000000); shader.bindings.reserve(n); for (unsigned j = 0; j < n; ++j) { - auto kind = static_cast(in.count(static_cast(ComputeViewKind::float3_texture_uav))); + auto kind = static_cast(in.count(static_cast(ComputeViewKind::indexed_raw_srv))); ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; b.scalar_table = static_cast(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); const bool sampler_heap = kind == ComputeViewKind::heap_sampler; @@ -148,6 +152,7 @@ NativeComputeShader decode(std::string_view bytes) { throw std::runtime_error("invalid cached constants"); shader.constants.push_back(c); } + shader.sampler_heap = in.count(1) != 0; n = in.count(32); for (unsigned j = 0; j < n; ++j) shader.stride_srvs.push_back(in.count(31)); @@ -261,7 +266,7 @@ std::shared_ptr load_interfaces(const fs::path &dir) { Reader reader{index}; while (!reader.remaining.empty()) { auto key = reader.take(65), value = reader.take(64); - if ((key.front() != 'F' && key.front() != 'I') || !digest_text(key.substr(1)) || + if (std::string_view("FIMN").find(key.front()) == std::string_view::npos || !digest_text(key.substr(1)) || (!digest_text(value) && value != Bytes(64,'-')) || !entries->emplace(key,value).second) throw std::runtime_error("invalid graphics interface catalog entry"); } @@ -269,10 +274,10 @@ std::shared_ptr load_interfaces(const fs::path &dir) { resident = entries; return resident; } -Bytes indexed_interface(const fs::path &dir, const InterfaceMap &entries, std::string_view raw, const Bytes &hash) { - auto it = entries.find("F" + hash); +Bytes indexed_interface(const fs::path &dir, const InterfaceMap &entries, std::string_view raw, const Bytes &hash, bool mesh = false) { + auto it = entries.find((mesh ? "M" : "F") + hash); if (it == entries.end() && embedded_graphics_id(raw)) - it = entries.find("I" + shader_digest(raw.substr(0,24))); + it = entries.find((mesh ? "N" : "I") + shader_digest(raw.substr(0,24))); if (it == entries.end()) return {}; if (it->second.front() == '-') throw UnsupportedComputeShader("ambiguous reviewed graphics interfaces"); Bytes container; @@ -282,6 +287,15 @@ Bytes indexed_interface(const fs::path &dir, const InterfaceMap &entries, std::s } } // namespace +GuestShaderStage reviewed_graphics_stage(std::string_view raw, GpuStage kind, const fs::path &cache, bool &exact) { + const auto dir = cache / "interfaces" / "library"; + const auto entries = load_interfaces(dir); + if (!entries) throw UnsupportedComputeShader("missing reviewed graphics interfaces"); + const auto blob = indexed_interface(dir, *entries, raw, shader_digest(raw), kind == GpuStage::ms); + if (blob.empty()) throw UnsupportedComputeShader("stage absent from reviewed graphics interfaces"); + return match_graphics_stage(raw, blob, exact, kind); +} + size_t index_graphics_interfaces(const fs::path &source, const fs::path &cache) { const auto dir = cache / "interfaces" / "library"; InterfaceMap index; @@ -297,11 +311,13 @@ size_t index_graphics_interfaces(const fs::path &source, const fs::path &cache) }; bool graphics = false; for (const auto &stage : stages) { - if (stage.stage != GpuStage::vs && stage.stage != GpuStage::ps) continue; + const bool mesh = stage.stage == GpuStage::ms; + if (!mesh && stage.stage != GpuStage::vs && stage.stage != GpuStage::ps) continue; graphics = true; - add("F" + shader_digest(stage.code)); + add((mesh ? "M" : "F") + shader_digest(stage.code)); if (!stage.exports.empty()) add("F" + shader_digest(stage.full_precision_code())); - if (embedded_graphics_id(stage.code)) add("I" + shader_digest(std::string_view(stage.code).substr(0,24))); + if (embedded_graphics_id(stage.code)) + add((mesh ? "N" : "I") + shader_digest(std::string_view(stage.code).substr(0,24))); } if (!graphics) continue; publish(dir / (id + ".stage"), id, blob); @@ -315,43 +331,136 @@ size_t index_graphics_interfaces(const fs::path &source, const fs::path &cache) publish(dir / "catalog", catalog_version(), generation); return count; } -NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, unsigned entry, bool container, - const std::filesystem::path &cache, bool &cache_hit, - HeapViewContract heap_view) { - if (!container && heap_view != HeapViewContract::none) - throw std::runtime_error("a heap view contract needs a container request"); - ComputeRequest request{}; - ComputeContainer packed; - Bytes identity = X2W_NATIVE_SHADER_REVISION; - identity += container ? "/container/cs_6_6" : "/slot67/cs_6_6"; - word(identity, container ? 0 : entry); - if (heap_view != HeapViewContract::none) - identity += heap_view == HeapViewContract::raw_buffer ? "/heap-view/raw_buffer" : "/heap-view/other"; - if (container) { - packed = read_compute_container(input); - identity += shader_digest(packed.bytes) + shader_digest(packed.root); - } else { - request = read_compute_request(input); - for (auto *part : {&request.code, &request.data, &request.root, &request.description, &request.sa, &request.sb}) - identity += shader_digest(*part); - } - const auto key = shader_digest(identity); +namespace { +Bytes slot67_digest(const ComputeRequest &request, unsigned entry) { + Bytes identity = X2W_NATIVE_SHADER_REVISION "/slot67/cs_6_6"; + word(identity, entry); + for (const auto *part : {&request.code, &request.data, &request.root, &request.description, &request.sa, &request.sb}) + identity += shader_digest(*part); + return shader_digest(identity); +} +template +NativeComputeShader cached_compute_ir(const fs::path &cache, const Bytes &key, bool &hit, Translate translate) { const auto path = cache / (key + ".csir"); - NativeComputeShader program{}; Bytes payload; - cache_hit = lookup(path, key, payload); - if (cache_hit) { + hit = lookup(path, key, payload); + if (hit) { + try { return decode(payload); } + catch (const std::runtime_error &) { hit = false; } + } + auto program = translate(); + publish(path, key, encode(program)); + return program; +} +Bytes pack_version(unsigned entry) { + Bytes version = X2W_NATIVE_SHADER_REVISION "/slot67/cs_6_6/prepared-1"; + word(version, entry); + return shader_digest(version); +} +} +NativeComputeShader prepare_direct_compute(const fs::path &input, unsigned entry, bool container, + const fs::path &cache, bool &cache_hit, HeapViewContract heap_view) { + if (!container) { + if (heap_view != HeapViewContract::none) + throw std::runtime_error("a heap view contract needs a container request"); + const auto request = read_compute_request(input); + return cached_compute_ir(cache, slot67_digest(request, entry), cache_hit, + [&] { return translate_compute(request, entry, true); }); + } + auto packed = read_compute_container(input); + Bytes identity = X2W_NATIVE_SHADER_REVISION "/container/cs_6_6"; + word(identity, 0); + if (heap_view != HeapViewContract::none) + identity += heap_view == HeapViewContract::raw_buffer ? "/heap-view/raw_buffer" : "/heap-view/other"; + identity += shader_digest(packed.bytes) + shader_digest(packed.root); + return cached_compute_ir(cache, shader_digest(identity), cache_hit, + [&] { return translate_compute_container(std::move(packed), heap_view); }); +} + +ComputePackCounts build_compute_frontend_pack(const fs::path &requests, const fs::path &cache, unsigned entry) { + std::vector markers; + for (const auto &file : fs::directory_iterator(requests)) + if (file.is_regular_file() && file.path().extension() == ".c67" && file.path().stem().wstring().rfind(L"req_",0) == 0) + markers.push_back(file.path()); + if (markers.empty() || markers.size() > 100000) + throw std::runtime_error("invalid compute pack request count"); + std::sort(markers.begin(), markers.end()); + Bytes pack; + word(pack, 0); + ComputePackCounts counts; + for (const auto &marker : markers) { try { - program = decode(payload); - } catch (const std::runtime_error &) { - cache_hit = false; + const auto request = read_compute_request(marker); + const auto digest = slot67_digest(request, entry); + Bytes payload; + bool unsupported = false, hit = false; + try { + auto program = cached_compute_ir(cache, digest, hit, [&] { return translate_compute(request, entry, true); }); + payload = encode(program); + + } catch (const UnsupportedComputeShader &error) { + payload = error.what(); + unsupported = true; + + } + constexpr size_t limit = (256u << 20) - 128; + if (payload.empty() || payload.size() > limit || pack.size() + 80 + payload.size() > limit) + throw std::runtime_error("invalid compute pack size"); + word(pack, static_cast(request.key)); + word(pack, static_cast(request.key >> 32)); + pack += digest; + word(pack, unsupported); + word(pack, static_cast(payload.size())); + pack += payload; + if (unsupported) ++counts.unsupported; + else ++counts.prepared; + } catch (const std::runtime_error &e) { + counts.errors.push_back(marker.filename().string() + ": " + e.what()); } } - if (!cache_hit) { - program = container ? translate_compute_container(std::move(packed), heap_view) : translate_compute(request, entry, true); - publish(path, key, encode(program)); + const uint32_t total = static_cast(counts.prepared + counts.unsupported); + if (!total) throw std::runtime_error(counts.errors.at(0)); + std::memcpy(pack.data(), &total, sizeof(total)); + publish(cache / ("compute-" + std::to_string(entry) + ".pack"), pack_version(entry), pack); + return counts; +} + +ComputeFrontendPack ComputeFrontendPack::load(const fs::path &file, unsigned entry) { + Bytes bytes; + if (!x2w::lookup(file, pack_version(entry), bytes)) + throw std::runtime_error("missing, stale or damaged compute pack"); + Reader in{bytes}; + ComputeFrontendPack pack; + pack.entry_ = entry; + auto count = in.count(100000); + if (!count) throw std::runtime_error("empty compute pack"); + pack.records_.reserve(count); + for (unsigned j = 0; j < count; ++j) { + uint64_t key = in.word(); + key |= uint64_t(in.word()) << 32; + auto digest = in.take(64); + bool unsupported = in.count(1) != 0; + auto payload = in.take(in.word()); + if (!digest_text(digest) || payload.empty() || (unsupported && payload.size() > 4096) || + !pack.records_.emplace(key, Record{Bytes(digest), Bytes(payload), unsupported}).second) + throw std::runtime_error("invalid compute pack record"); + } + if (!in.remaining.empty()) throw std::runtime_error("trailing compute pack data"); + return pack; +} + +ComputePackResult ComputeFrontendPack::lookup(const ComputeRequest &request, unsigned entry, + NativeComputeShader &program, Bytes &diagnostic) const { + auto it = records_.find(request.key); + if (it == records_.end() || entry != entry_ || it->second.digest != slot67_digest(request, entry)) + return ComputePackResult::miss; + if (it->second.unsupported) { + diagnostic = it->second.payload; + return ComputePackResult::unsupported; } - return program; + try { program = decode(it->second.payload); } + catch (const std::runtime_error &) { return ComputePackResult::miss; } + return ComputePackResult::prepared; } unsigned dxil_io_component(unsigned format) { @@ -539,14 +648,18 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view Bytes payload; cache_hit = write_cache && !cache.empty() && lookup(path, key, payload); auto effective_layout = [&](const NativeComputeShader &vs) { - if (!input_layout.empty() || (pixel_entry.empty() && !reflected) || !vs.vertex_fetch) return std::string(input_layout); + if (!input_layout.empty() || !vs.vertex_fetch) return std::string(input_layout); unsigned count = 0; std::ostringstream elements; for (const auto &r : vs.inputs) { if (r.name != "X2W_RAW_VERTEX") continue; unsigned format = 0; + if (r.component == 5 && r.width == 1) format = DXGI_FORMAT_R8_UINT; if (r.component == 5 && r.width == 2) format = DXGI_FORMAT_R32G32_UINT; if (r.component == 5 && r.width == 3) format = DXGI_FORMAT_R32G32B32_UINT; + if (r.component == 5 && r.width == 4) format = DXGI_FORMAT_R32G32B32A32_UINT; + if (r.component == 9 && r.width == 1) format = DXGI_FORMAT_R8_UNORM; + if (r.component == 9 && r.width == 2) format = DXGI_FORMAT_R8G8_UNORM; if (r.component == 9 && r.width == 4) format = DXGI_FORMAT_R8G8B8A8_UNORM; if (!format) throw UnsupportedComputeShader("unsupported fixed vertex format"); elements << " X2W_RAW_VERTEX " << r.index << ' ' << format << " 0 " << r.index << " 0 0"; @@ -579,6 +692,12 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view std::optional first_stage; bool exact_pair = reflected; Bytes entry; + const bool fixed_entry = pixel_entry.size() == 12 && pixel_entry.substr(0,4) == "PSI1"; + if (fixed_entry && !reflected) + throw UnsupportedComputeShader("fixed graphics entry requires matching stage interfaces"); + bool packed_xy = false; + std::optional captured_interp_count; + std::optional> stage_wave32; if (reflected) { for (size_t i = 0; i < companions.size(); ++i) { bool exact = false; @@ -591,6 +710,28 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view } if (!interfaces.count(GpuStage::vs) || !interfaces.count(GpuStage::ps)) throw UnsupportedComputeShader("missing vertex or pixel interface"); + const auto &pixel_defaults = interfaces.at(GpuStage::ps); + stage_wave32 = {{interfaces.at(GpuStage::vs).wave32, pixel_defaults.wave32}}; + if (fixed_entry) { + // Fixed slot 57 supplies ADDR and NUM_INTERP, not ENA. Intersect + // the observed ABI with the reviewed stage and the raw consumers. + uint32_t address, interpolants; + std::memcpy(&address, pixel_entry.data() + 4, 4); + std::memcpy(&interpolants, pixel_entry.data() + 8, 4); + if (!interpolants || interpolants > 7 || interpolants > pixel_defaults.attributes.size()) + throw UnsupportedComputeShader("captured interpolation count disagrees with pixel interface"); + captured_interp_count = interpolants; + packed_xy = address == 0x8002 && pixel_defaults.pixel_input_address == 0x302; + if (!(address == 2 && pixel_defaults.pixel_input_address == 2) && !packed_xy) + throw UnsupportedComputeShader("unsupported fixed pixel entry layout"); + // Center I/J and, in the specialized position variant, packed XY + // are the only allocated inputs. The raw frontend checks each + // register use; the interpolants are checked below after linking. + entry = "psin1"; + word(entry, address); + word(entry, address); + pixel_entry = entry; + } if (exact_pair && !pixel_entry.empty()) { auto &ps = interfaces.at(GpuStage::ps); uint32_t enable_mask = 0, address_mask = 0; @@ -624,24 +765,37 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view } interfaces.at(GpuStage::ps).target_components = targets; pair = translate_reflected_graphics(interfaces.at(GpuStage::vs),interfaces.at(GpuStage::ps),layout); - } else pair = translate_graphics_pair(a, b, layout, pixel_entry, first_stage, targets); + } else pair = translate_graphics_pair(a, b, layout, pixel_entry, first_stage, targets, stage_wave32); pair.target_components = targets; if (!entry.empty()) { const auto &attrs = interfaces.at(GpuStage::ps).attributes; std::vector channels(attrs.size()); for (const auto &r : pair.pixel.inputs) { if (r.kind == 28 && r.interpolation == 2) continue; - if (r.name != "TEXCOORD" || r.index / 4 >= channels.size() || r.interpolation != 2 || + if (packed_xy && r.kind == 3 && r.name == "SV_Position" && r.first == 0 && + r.index == 0 && r.width == 4 && r.interpolation == 4) continue; + // Fixed pipelines may specialize individual components from + // P1/P2 to VINTRP_MOV P0. The raw front end links each observed + // component to a VS PARAM channel and emits flat mode only for + // that P0 instruction. It may drop unused reflected rows, too. + if (r.name != "TEXCOORD" || r.index / 4 >= channels.size() || + (captured_interp_count && r.index / 4 >= *captured_interp_count) || + (r.interpolation != 2 && !(fixed_entry && r.interpolation == 1)) || r.width != 1 || r.first != r.index % 4) throw UnsupportedComputeShader("raw and reflected interpolation inputs disagree"); channels[r.index / 4] |= 1u << r.first; } for (const auto &attr : attrs) { if (attr.usage != 6 || attr.location >= channels.size() || attr.flags != 2 || - attr.mask != channels[attr.location] || !attr.mask) - throw UnsupportedComputeShader("raw and reflected interpolation channels disagree"); + (channels[attr.location] & ~attr.mask) || !attr.mask) + throw UnsupportedComputeShader("raw and reflected interpolation channels disagree at location " + + std::to_string(attr.location) + " (usage " + std::to_string(attr.usage) + ", flags " + + std::to_string(attr.flags) + ", reflected mask " + std::to_string(attr.mask) + + ", raw mask " + std::to_string(attr.location < channels.size() ? channels[attr.location] : 0) + ")"); channels[attr.location] = 0; } + if (std::any_of(channels.begin(), channels.end(), [](unsigned bits) { return bits != 0; })) + throw UnsupportedComputeShader("raw interpolation has no reflected attribute"); } pair.input_layout = vertex_layout(effective_layout(pair.vertex), pair.vertex); if (!root.empty()) { @@ -688,7 +842,7 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view // Scalar buffer loads also consume CBV table records. The // resolver supplies a raw SRV over the recorded CBV window. if (first <= slot && slot < next && (kind == range.RangeType || - (binding.kind == ComputeViewKind::buffer_srv && range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV))) + (accepts_cbv_window(binding.kind) && range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV))) found = true; } if (reflected && binding.array_count == 1) { @@ -701,11 +855,11 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view } const bool used = apply_reflected_table_use(binding, iface, exact_pair ? std::optional{} : std::optional{sgpr}); - const bool needs_record = !found || (!exact_pair && (binding.kind == ComputeViewKind::buffer_srv || + const bool needs_record = !found || (!exact_pair && (accepts_cbv_window(binding.kind) || binding.kind == ComputeViewKind::texture_srv || binding.kind == ComputeViewKind::d16_sample_srv)); if (!used && needs_record && binding.kind != ComputeViewKind::heap_stride_srv) - throw UnsupportedComputeShader("raw load disagrees with reflected table record"); + throw UnsupportedComputeShader(std::string("missing reflected resource: ") + (vertex ? "VS" : "PS") + " root " + std::to_string(binding.root_parameter) + " offset " + std::to_string(binding.byte_offset) + " kind " + std::to_string(static_cast(binding.kind)) + " user SGPR " + std::to_string(sgpr)); found |= used; } apply_scalar_table_layout(binding, p.DescriptorTable); @@ -870,10 +1024,18 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh } std::optional format_graphics_runtime_manifest(const DirectGraphicsPair &pair, std::string_view rtv_request) { - if (pair.vertex.vertex_fetch || !pair.input_layout.empty()) + const bool fixed_stream = pair.vertex.vertex_fetch && !pair.input_layout.empty(); + if (pair.vertex.vertex_fetch != !pair.input_layout.empty()) return std::nullopt; + for (const auto &e : pair.input_layout) + if (e.semantic != "X2W_RAW_VERTEX" || e.slot || e.offset != e.index || e.classification || e.step_rate || + !e.used || (e.format != DXGI_FORMAT_R8_UNORM && e.format != DXGI_FORMAT_R8G8_UNORM && + e.format != DXGI_FORMAT_R8G8B8A8_UNORM && e.format != DXGI_FORMAT_R32G32_UINT && + e.format != DXGI_FORMAT_R32G32B32_UINT && e.format != DXGI_FORMAT_R32G32B32A32_UINT && + e.format != DXGI_FORMAT_R8_UINT)) + return std::nullopt; for (const auto &in : pair.vertex.inputs) - if (in.name != "SV_VertexID" && in.name != "SV_InstanceID") + if (in.name != "SV_VertexID" && in.name != "SV_InstanceID" && !(fixed_stream && in.name == "X2W_RAW_VERTEX")) return std::nullopt; // An integer target is published only for the RTV variant whose format asked for that type. for (const auto &out : pair.pixel.outputs) @@ -908,10 +1070,12 @@ std::optional format_graphics_runtime_manifest(const DirectGraphics if (b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv || b.kind == ComputeViewKind::byte_window_srv) { srv_lines << "srv " << i << " buf table " << b.root_parameter << ' ' << b.byte_offset << '\n'; + } else if (b.kind == ComputeViewKind::indexed_raw_srv && b.array_count == 1 && + b.required_bytes && !(b.required_bytes % 4) && b.required_bytes <= 2048) { + srv_lines << "srv " << i << " idxbuf table " << b.root_parameter << ' ' << b.byte_offset << ' ' << b.required_bytes << '\n'; } else if (b.kind == ComputeViewKind::root_buffer_srv && b.byte_offset == 0 && b.array_count == 1) { srv_lines << "srv " << i << " buf root " << b.root_parameter << '\n'; - } else if ((b.kind == ComputeViewKind::texture_srv || b.kind == ComputeViewKind::comparison_texture_srv) && - b.array_count == 1) { + } else if (b.kind == ComputeViewKind::texture_srv || b.kind == ComputeViewKind::comparison_texture_srv) { const char *tex = b.image_dimension == 0 ? "tex1d" : b.image_dimension == 1 ? "tex2d" : b.image_dimension == 2 ? "tex3d" @@ -943,6 +1107,7 @@ std::optional format_graphics_runtime_manifest(const DirectGraphics uav_lines << "uav " << j << (b.image_dimension == 5 ? " tex2da table " : " tex2d table ") << b.root_parameter << ' ' << b.byte_offset << '\n'; } + if (bindings.samplers.heap) sampler_lines << "smpheap 2048 1 fallback 2047\n"; for (size_t i = 0; i < bindings.samplers.statics.size(); ++i) { const auto &w = bindings.samplers.statics[i]; const bool cmp = i < bindings.samplers.comparison.size() && bindings.samplers.comparison[i]; @@ -959,7 +1124,9 @@ std::optional format_graphics_runtime_manifest(const DirectGraphics params = (std::max)(params, out.index / 4 + 1); std::ostringstream out; - out << "x2w-manifest " << (uav_count ? 2 : 1) << "\nud " << (total_constants ? total_constants : 1u) << '\n'; + out << "x2w-manifest " << (fixed_stream ? 3 : uav_count ? 2 : 1) << "\nud " << (total_constants ? total_constants : 1u) << '\n'; + for (const auto &e : pair.input_layout) + out << "fixedvb " << e.offset << ' ' << e.format << '\n'; if (!total_constants) { out << "udsrc 0 rect\n"; } else { diff --git a/src/direct_compute_cache.h b/src/direct_compute_cache.h index efe29a989..ec388dc54 100644 --- a/src/direct_compute_cache.h +++ b/src/direct_compute_cache.h @@ -1,10 +1,29 @@ #pragma once #include "gfx1013_compute_native.h" +#include // The result includes the emitted DXIL module and its exact desktop/guest binding layout. namespace x2w { +enum class ComputePackResult { miss, prepared, unsupported }; +struct ComputePackCounts { size_t prepared{}, unsupported{}; std::vector errors; }; +class ComputeFrontendPack { + struct Record { std::string digest, payload; bool unsupported; }; + std::unordered_map records_; + unsigned entry_{}; +public: + static ComputeFrontendPack load(const std::filesystem::path &file, unsigned entry); + ComputePackResult lookup(const ComputeRequest &request, unsigned entry, NativeComputeShader &program, + std::string &diagnostic) const; + size_t size() const { return records_.size(); } +}; +ComputePackCounts build_compute_frontend_pack(const std::filesystem::path &requests, const std::filesystem::path &cache, + unsigned entry); size_t index_graphics_interfaces(const std::filesystem::path &source, const std::filesystem::path &cache); +// A logical match identifies the source shader. Only exact matches establish +// the compiled entry ABI, instruction offsets, and resource register layout. +GuestShaderStage reviewed_graphics_stage(std::string_view raw, GpuStage kind, + const std::filesystem::path &cache, bool &exact); // Signature component (f32/u32/i32) for supported typed IA and RTV formats. unsigned dxil_io_component(unsigned dxgi_format); NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, unsigned entry, bool container, diff --git a/src/dxil_module.h b/src/dxil_module.h index 512ebc9d2..ee6423729 100644 --- a/src/dxil_module.h +++ b/src/dxil_module.h @@ -9,6 +9,7 @@ #include #include #include +#include #include namespace x2w { @@ -21,10 +22,12 @@ class DxilModule { unsigned cls, reg, kind, component, width, bytes; unsigned count = 1; bool comparison = false; + unsigned space = 0; }; std::ostringstream body, setup, globals; bool uses_wave = false; bool heap_used = false; + unsigned mesh_vertices = 0, mesh_primitives = 0; unsigned features = 0; struct Signature { Text name; @@ -110,9 +113,10 @@ class DxilModule { Text handle(Resource r, const Text &offset = {}) { const Text reg = std::to_string(r.reg), cls = std::to_string(r.cls); const auto found = std::find_if(resources.begin(), resources.end(), [&](const Resource &other) { - return other.cls == r.cls && other.reg == r.reg; + return other.cls == r.cls && other.reg == r.reg && other.space == r.space; }); Text h = "%h" + cls + "_" + reg; + if (r.space) h += "_s" + std::to_string(r.space); if (found != resources.end()) { if (found->kind != r.kind || found->width != r.width || found->component != r.component || found->bytes != r.bytes || found->count != r.count || found->comparison != r.comparison) @@ -135,7 +139,7 @@ class DxilModule { } const unsigned props = r.cls == 2 ? r.bytes : r.component + r.width * 256; out << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 " - << reg << ", i32 " << r.reg + r.count - 1 << ", i32 0, i8 " << cls << " }, i32 " << index << ", i1 " + << reg << ", i32 " << r.reg + r.count - 1 << ", i32 " << r.space << ", i8 " << cls << " }, i32 " << index << ", i1 " << (offset.empty() ? "false" : "true") << ")\n" << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h << "b, %dx.types.ResourceProperties { i32 " << (r.kind + (r.cls == 1 ? 4096 : 0) + (r.comparison ? 32768 : 0)) << ", i32 " << props @@ -145,11 +149,15 @@ class DxilModule { // A handle taken from the descriptor heap at a run-time index (SM 6.6 ResourceDescriptorHeap[index]), annotated with // the view class the shader reads: `kind` is the DXIL resource kind (11 raw buffer, 2 Texture2D) and `props` the // second ResourceProperties word. No resource record is declared: the binding is the whole heap. - Text heap_handle(const Text &index, unsigned kind, unsigned props, bool uav = false) { + Text heap_handle(const Text &index, unsigned kind, unsigned props, bool uav = false, bool nonuniform = true) { heap_used = true; const Text h = "%heap" + std::to_string(sequence++); + if (track_inputs) { + if (auto it = dependencies.find(index); it != dependencies.end()) dependencies[h] = it->second; + if (loop_dependencies) consumers[index].push_back(h); + } body << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 " << index - << ", i1 false, i1 true)\n" + << ", i1 false, i1 " << (nonuniform ? "true" : "false") << ")\n" << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h << "b, %dx.types.ResourceProperties { i32 " << (kind + (uav ? 4096 : 0)) << ", i32 " << props << " })\n"; return h; @@ -197,16 +205,20 @@ class DxilModule { }; std::vector groups[4]; std::sort(resources.begin(), resources.end(), - [](const auto &a, const auto &b) { return std::pair{a.cls, a.reg} < std::pair{b.cls, b.reg}; }); + [](const auto &a, const auto &b) { + return std::tie(a.cls, a.space, a.reg) < std::tie(b.cls, b.space, b.reg); + }); for (auto &r : resources) { - const Text type = "%res" + std::to_string(r.cls) + "_" + std::to_string(r.reg); + const Text type = "%res" + std::to_string(r.cls) + "_" + std::to_string(r.reg) + + (r.space ? "_s" + std::to_string(r.space) : ""); Text scalar = r.component == 9 ? "float" : "i32"; Text member = r.cls == 2 ? "[" + std::to_string(r.bytes / 16) + " x <4 x i32>]" : r.width > 1 ? "<" + std::to_string(r.width) + " x " + scalar + ">" : scalar; out << type << " = type { " << member << " }\n"; const Text symbol = r.count == 1 ? type : "[" + std::to_string(r.count) + " x " + type + "]"; - Text md = "i32 " + std::to_string(groups[r.cls].size()) + ", " + symbol + "* undef, !\"\", i32 0, i32 " + + Text md = "i32 " + std::to_string(groups[r.cls].size()) + ", " + symbol + "* undef, !\"\", i32 " + + std::to_string(r.space) + ", i32 " + std::to_string(r.reg) + ", i32 " + std::to_string(r.count) + ", i32 " + std::to_string(r.cls == 2 ? r.bytes : r.cls == 3 ? unsigned(r.comparison) @@ -243,6 +255,13 @@ class DxilModule { properties = node("i32 0, i64 " + std::to_string(flags)); if (stage == "gs") properties = node("i32 1, " + node("i32 3, i32 6, i32 1, i32 5, i32 1")); + if (stage == "ms") { + const auto size = node("i32 " + std::to_string(x) + ", i32 " + std::to_string(y) + + ", i32 " + std::to_string(z)); + const auto mesh = node(size + ", i32 " + std::to_string(mesh_vertices) + ", i32 " + + std::to_string(mesh_primitives) + ", i32 2, i32 0"); + properties = node((flags ? "i32 0, i64 " + std::to_string(flags) + ", " : "") + "i32 9, " + mesh); + } auto signature_list = [&](const std::vector &rows, unsigned &scalars) { std::vector ids; for (const auto &r : rows) { @@ -276,6 +295,8 @@ class DxilModule { matrix.at(2 + i * stride + output / 32) |= 1u << (output % 32); if (stage == "gs") matrix.resize(matrix.size() + 3); // no outputs on streams 1 to 3 + if (stage == "ms") + matrix.push_back(0); // no per-primitive signature elements Text values; for (auto word : matrix) { if (!values.empty()) diff --git a/src/frozen_compute_requests.h b/src/frozen_compute_requests.h new file mode 100644 index 000000000..c938e2c51 --- /dev/null +++ b/src/frozen_compute_requests.h @@ -0,0 +1,74 @@ +#pragma once + +#include "shader_compute_request.h" +#include +#include +#include +#include + +namespace x2w { +// Slot 67 publishes requests before their first dispatch. Keep recent captures +// until dispatch takes ownership; eviction leaves the normal file replay intact. +class FrozenComputeRequests { + const size_t max_bytes_, max_entries_; + size_t bytes_{}; + std::mutex lock_; + std::list requests_; + std::unordered_map index_; + uint64_t hits_{}, misses_{}, evicted_{}; + + static size_t size(const ComputeRequest &r) { + return r.code.capacity() + r.data.capacity() + r.root.capacity() + + r.description.capacity() + r.sa.capacity() + r.sb.capacity(); + } + +public: + struct Stats { uint64_t hits, misses, evicted; size_t bytes, entries; }; + FrozenComputeRequests(size_t max_bytes = 32u << 20, size_t max_entries = 4096) + : max_bytes_(max_bytes), max_entries_(max_entries) {} + bool enabled() const { return max_entries_ && max_bytes_; } + Stats stats() { + std::lock_guard guard(lock_); + return {hits_, misses_, evicted_, bytes_, requests_.size()}; + } + + void put(ComputeRequest request) { + const auto bytes = size(request); + if (!max_entries_ || bytes > max_bytes_) return; + std::lock_guard guard(lock_); + if (index_.count(request.key)) return; + while (requests_.size() >= max_entries_ || bytes_ > max_bytes_ - bytes) { + const auto &old = requests_.front(); + bytes_ -= size(old); + index_.erase(old.key); + requests_.pop_front(); + ++evicted_; + } + requests_.push_back(std::move(request)); + auto node = std::prev(requests_.end()); + try { + index_.emplace(node->key, node); + } catch (...) { + requests_.pop_back(); + throw; + } + bytes_ += bytes; + } + + std::optional take(uint64_t key) { + std::lock_guard guard(lock_); + const auto found = index_.find(key); + if (found == index_.end()) { + ++misses_; + return {}; + } + ++hits_; + const auto node = found->second; + bytes_ -= size(*node); + auto request = std::move(*node); + requests_.erase(node); + index_.erase(found); + return request; + } +}; +} diff --git a/src/gfx1013_compute_ir.cpp b/src/gfx1013_compute_ir.cpp index a5c7d795b..8edda418d 100644 --- a/src/gfx1013_compute_ir.cpp +++ b/src/gfx1013_compute_ir.cpp @@ -1,4 +1,5 @@ #include "gfx1013_compute_ir.h" +#include "gfx1013_compute_native.h" #include #include #include @@ -25,6 +26,7 @@ LocalDataAccess decode_local_data(uint32_t instruction, uint32_t operands) { case 0x0a: case 0x2a: access.atomic_ir = "or"; access.atomic_hlsl = "Or"; break; case 0x0b: case 0x2b: access.atomic_ir = "xor"; access.atomic_hlsl = "Xor"; break; case 0x2d: access.atomic_ir = "xchg"; access.atomic_hlsl = "Exchange"; break; + case 0x30: access.compare_exchange = true; break; case 0x36: access.read = true; break; // read_b32 case 0x76: access.read = true; access.count = 2; break; case 0xfe: access.read = true; access.count = 3; break; @@ -41,12 +43,12 @@ LocalDataAccess decode_local_data(uint32_t instruction, uint32_t operands) { access.stride64 = (op & 0x3f) == 0x0f || (op & 0x3f) == 0x38; break; default: - throw std::runtime_error("unsupported local DS opcode " + std::to_string(op)); + throw UnsupportedComputeShader("unsupported local DS opcode " + std::to_string(op)); } - access.return_old = access.atomic_ir && op >= 0x20; + access.return_old = access.compare_exchange || (access.atomic_ir && op >= 0x20); const unsigned first_width = access.pair_words ? access.pair_words : access.count; if (access.read ? data0 || data1 || dst + access.count > 256 : - (!access.return_old && dst) || (!access.pair_words && data1) || + (!access.return_old && dst) || (!access.compare_exchange && !access.pair_words && data1) || data0 + first_width > 256 || data1 + access.pair_words > 256) throw std::runtime_error("invalid local DS register tuple"); return access; @@ -59,7 +61,10 @@ static std::string lower_lds(uint32_t instruction, uint32_t operands) { for (unsigned i = 0; i < access.count; ++i) { auto location = "lds[(ds_addr + " + std::to_string(access.byte_offset(i)) + "u) >> 2]"; auto reg = "v" + std::to_string(access.read ? access.destination + i : access.data_register(i)); - if (access.atomic_ir) { + if (access.compare_exchange) { + out += "InterlockedCompareExchange(" + location + ", " + reg + ", v" + std::to_string(access.data1) + + ", v" + std::to_string(access.destination) + "); "; + } else if (access.atomic_ir) { auto value = access.subtract ? "(0u - " + reg + ")" : reg; out += std::string("Interlocked") + access.atomic_hlsl + "(" + location + ", " + value; if (access.return_old) diff --git a/src/gfx1013_compute_ir.h b/src/gfx1013_compute_ir.h index eab66f7d9..d141faa94 100644 --- a/src/gfx1013_compute_ir.h +++ b/src/gfx1013_compute_ir.h @@ -8,7 +8,7 @@ struct LocalDataAccess { unsigned pair_words; // Width of each independently offset element; zero for a single address. bool read, stride64, return_old; const char *atomic_ir, *atomic_hlsl; - bool subtract; + bool subtract, compare_exchange; unsigned byte_offset(unsigned element) const { if (!pair_words) return offset + 4 * element; unsigned encoded = (offset >> (8 * (element / pair_words))) & 255; diff --git a/src/gfx1013_compute_mtbuf.inl b/src/gfx1013_compute_mtbuf.inl index 9c8ff1312..96b94552a 100644 --- a/src/gfx1013_compute_mtbuf.inl +++ b/src/gfx1013_compute_mtbuf.inl @@ -35,11 +35,12 @@ string normalized_channel(const string &field, unsigned width, bool snorm) { auto magnitude = select(cmp("eq", p, "0"), "0", ir.binary("add", base, rounded)); return snorm ? ir.binary("or", magnitude, sign) : magnitude; } -void formatted_byte_load(const Inst &i, const State &s) { +void formatted_byte_load(const Inst &i, const State &s, const string &byte_window = {}) { constexpr MtbufFamily families[] = { {1, 6, 8, 1, ChannelNumber::unorm}, {7, 13, 16, 1, ChannelNumber::unorm}, {14, 19, 8, 2, ChannelNumber::unorm}, {20, 22, 32, 1, ChannelNumber::uint_}, - {23, 29, 16, 2, ChannelNumber::unorm}, {56, 61, 8, 4, ChannelNumber::unorm}, + {23, 29, 16, 2, ChannelNumber::unorm}, {44, 49, 0, 4, ChannelNumber::unorm}, + {50, 55, 0, 4, ChannelNumber::unorm}, {56, 61, 8, 4, ChannelNumber::unorm}, {62, 64, 32, 2, ChannelNumber::uint_}, {65, 71, 16, 4, ChannelNumber::unorm}, {72, 74, 32, 3, ChannelNumber::uint_}, {75, 77, 32, 4, ChannelNumber::uint_} }; @@ -51,9 +52,15 @@ void formatted_byte_load(const Inst &i, const State &s) { refuse(i.pc, "unsupported MTBUF format or absent component"); if (i.dst + count > 256) refuse(i.pc, "MTBUF destination tuple overflow"); - const unsigned width = family->bits; + const auto component_width=[&](unsigned j) { + // The name lists the most significant field first; logical X is + // the low field. See Victory lower.rs format_layout. + return family->bits ? family->bits : j==(family->first==44 ? 0u : 3u) ? 2u : 10u; + }; + unsigned requested_bits=0; + for (unsigned j=0;j(unsigned(family->first_number) + format - family->first); - const auto handle = resource(i, s, (i.b >> 16 & 31) * 4, ComputeViewKind::raw_vector_srv, 4); + const auto handle = byte_window.empty() ? resource(i, s, (i.b >> 16 & 31) * 4, ComputeViewKind::raw_vector_srv, 4) : byte_window; const unsigned scalar_offset = i.b >> 24; auto addr = to_string(i.a & 4095); if (scalar_offset != 125 && scalar_offset != 128) @@ -65,17 +72,17 @@ void formatted_byte_load(const Inst &i, const State &s) { auto dimensions = ir.invoke("%dx.types.Dimensions", "getDimensions", 72, {{"%dx.types.Handle", handle}, {"i32", "undef"}}, "nounwind readonly"); auto bytes = ir.value("extractvalue %dx.types.Dimensions " + dimensions + ", 0"); - auto size = to_string(width * family->components / 8); + auto size = to_string(family->bits ? family->bits * family->components / 8 : 4u); auto valid = ir.value("and i1 " + cmp("uge", bytes, size) + ", " + cmp("ule", addr, ir.binary("sub", bytes, size))); const auto aligned = ir.binary("and", addr, "4294967292"); const auto shift_bits = ir.binary("shl", ir.binary("and", addr, "3"), "3"); - const unsigned word_count = (count * width + 31) / 32; + const unsigned word_count = (requested_bits + 31) / 32; const auto chunk = load_buffer(handle, aligned, true, word_count); std::array words; for (unsigned j = 0; j < word_count; ++j) words[j] = ir.value("extractvalue %dx.types.ResRet.i32 " + chunk + ", " + to_string(j)); - if (count * width > 8) { + if (requested_bits > 8) { const auto next = ir.binary("add", aligned, to_string(word_count * 4)); const auto high = load_buffer(handle, next, true, 1); words[word_count] = select(cmp("ult", next, aligned), "0", @@ -90,12 +97,15 @@ void formatted_byte_load(const Inst &i, const State &s) { words[j] = words[j + 1].empty() ? low : ir.binary("or", low, select(aligned_access, "0", ir.binary("shl", words[j + 1], inverse))); } + unsigned bit_offset=0; for (unsigned j = 0; j < count; ++j) { - auto field = words[j * width / 32]; + const auto width=component_width(j); + auto field = words[bit_offset / 32]; if (width < 32) { - field = ir.binary("lshr", field, to_string(j * width % 32)); + field = ir.binary("lshr", field, to_string(bit_offset % 32)); field = ir.binary("and", field, to_string((1u << width) - 1)); } + bit_offset+=width; const bool signed_field = numeric == ChannelNumber::sint || numeric == ChannelNumber::snorm || numeric == ChannelNumber::sscaled; if (signed_field && width < 32) { diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index a97377dc2..5e5c51d23 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -51,7 +51,7 @@ string hexword(Word n) { snprintf(s, sizeof(s), "0x%08xu", n); return s; } -enum class Encoding { Sopp, Sop1, Sop2, Sopc, Sopk, Vop1, Vop2, Vopc, Vop3, Mix, Smem, Image, Mubuf, Lds, Export, Interp, Fetch, FixedSetup, FixedFetch }; +enum class Encoding { Sopp, Sop1, Sop2, Sopc, Sopk, Vop1, Vop2, Vopc, QuadCompare, Vop3, Mix, Smem, Image, Mubuf, Lds, Export, Interp, Fetch, FixedSetup, FixedFetch }; #include "gfx1013_compute_opcodes.inl" struct Inst { unsigned pc = 0, next = 0, op = 0, dst = 0; @@ -226,7 +226,13 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa const unsigned soffset = i.b >> 24; if (soffset > 105 && !(soffset >= 128 && soffset <= 208)) refuse(pc, "raw buffer load scalar offset needs an SGPR or inline integer"); - } else if ((a & 0x0203f000u) != 0x1000u || (i.b & 0xffe00000u) != 0x80000000u) { + } else if (direct && graphics && !(a & 0x2000u)) { + const unsigned soffset = i.b >> 24; + if ((a & 0x02032000u) || (i.b & 0x00a00000u) || (soffset > 105 && soffset != 128)) + refuse(pc, "raw graphics load requires linear addressing without LDS or TFE"); + } else if (!(direct && (a & 0x0203f000u) == 0x2000u && + (i.b & 0xffe00000u) == 0x80000000u) && + ((a & 0x0203f000u) != 0x1000u || (i.b & 0xffe00000u) != 0x80000000u)) { refuse(pc, "raw buffer load needs offen with zero scalar offset and no modifiers"); } i.name = "buffer_load_dword"; @@ -302,7 +308,7 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa if (direct && half_alu && (dpp8 || (i.enc == Encoding::Vop1 && i.src[0] == 250))) refuse(pc, "unsupported " + string(encoded.name) + " DPP form"); const bool sdwa_logic = i.enc == Encoding::Vop2 && i.op == 0x1d; - const bool sdwa_class = i.enc == Encoding::Vopc && i.op == 0x88; + const bool sdwa_class = i.enc == Encoding::Vopc && (i.op == 0x88 || (direct && i.op == 0x8f)); const bool sdwa_compare = i.enc == Encoding::Vopc && !sdwa_class; const unsigned sdwa_mask_limit = direct && !graphics && !wave64 ? 107 : 106; if (direct && i.src[0] == 249 && (sdwa_compare || i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2)) { @@ -396,7 +402,7 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa i.src_select[0] = (ext >> 16) & 7u; i.src[0] = 256 + (ext & 255); lit = false; - } else if (direct && i.src[0]==250 && i.enc!=Encoding::Vopc && !lit) { + } else if (direct && i.src[0]==250 && (graphics || i.enc!=Encoding::Vopc) && !lit) { auto control=take(); // DPP_CTRL[8] selects patterns outside a quad; bit 17 is // reserved. FI and BOUND_CTRL are independent of the pattern. @@ -453,6 +459,13 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa refuse(pc, "invalid scalar lane read destination"); } } + // Keep permuted VCC compares separate from unpermuted compare/EXEC proofs. + if (i.enc == Encoding::Vopc && i.dpp_control) { + if (i.dst != 106 || i.name.substr(0,6) != "v_cmp_" || i.name.substr(i.name.size()-4) != "_f32" || + i.name.find("_class_") != Name::npos || *i.dpp_control > 255) + refuse(pc,"unsupported DPP pixel compare"); + i.enc = Encoding::QuadCompare; + } if(i.next-pc!=encoded.size)refuse(pc,"instruction extent mismatch for "+string(encoded.name)); return i; } @@ -466,7 +479,7 @@ static std::optional carry_destination(const Inst &i) { return {}; } struct Symbol { - enum class Type { unknown, constant, masked, table, descriptor, indexed_descriptor, root_address, primitive_mask, + enum class Type { unknown, constant, masked, table, descriptor, indexed_descriptor, sampler_heap, sampler_word, root_address, root_stride_one_high, primitive_mask, stride, byte_stride, zero_stride_word, byte_count, clear_oob, byte_oob, lane_mask, uniform_mask, heap_offset, heap_carry, unbound } type{}; Word value = 0, offset = 0; @@ -623,6 +636,12 @@ static std::optional byte_descriptor_field(const Inst &i, const State &s } if (a.type == T::constant) std::swap(a,b); if (b.type != T::constant) return {}; + // Address bits occupy the low halfword. Setting bit 16 in the high + // address word constructs a buffer descriptor with byte stride one. + if (i.name == "s_or_b32" && a.type == T::root_address && a.offset == 1 && b.value == 0x10000) { + a.type = T::root_stride_one_high; + return a; + } if (i.name == "s_max_u32" && a.type == T::stride && b.value == 1) return field(a, T::byte_stride); if (i.name == "s_and_b32" && b.value == 0xc000ffff && component(a,1)) return field(a,T::zero_stride_word); if (i.name == "s_and_b32" && b.value == 0xcfffffff && component(a,3)) return field(a,T::clear_oob); @@ -631,7 +650,7 @@ static std::optional byte_descriptor_field(const Inst &i, const State &s return {}; } State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_window, bool direct, - bool narrow_wave64) { + bool narrow_wave64 = false) { auto set = [&](unsigned n, Symbol v) { if (n >= s.size()) refuse(i.pc, "invalid SGPR"); @@ -698,7 +717,14 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win Symbol v{}; if (heap_address) { v = {Symbol::Type::indexed_descriptor, compute_resource_heap, (i.b & 0xfffff) + 4 * j, base.index_mask, i.pc}; - } else if (i.op == 2 && i.b >> 25 != 125 && base.type == Symbol::Type::table) { + } else if (graphics && i.op == 3 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { + const bool fixed = offset_reg == 125 || index.type == Symbol::Type::constant; + const Word offset = (i.b & 0xfffff) + (offset_reg != 125 && fixed ? index.value : 0); + v = {Symbol::Type::indexed_descriptor, base.value, offset + 4*j, + fixed ? 0u : index.type == Symbol::Type::masked ? index.value : ~0u, i.pc}; + } else if (i.op == 2 && base.type == Symbol::Type::sampler_heap) { + v = {Symbol::Type::sampler_word, i.dst, j, 0, i.pc}; + } else if ((i.op == 2 || (graphics && i.op == 3)) && offset_reg != 125 && base.type == Symbol::Type::table) { v = {Symbol::Type::indexed_descriptor, base.value, (i.b & 0xfffff) + 4*j, index.type == Symbol::Type::masked || index.type == Symbol::Type::constant ? index.value : ~0u, i.pc}; } else if (i.op < 8 && base.type == Symbol::Type::table) @@ -756,13 +782,14 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win set(i.dst, v); } else if (i.name == "s_movk_i32") { set(i.dst, {Symbol::Type::constant, Word(int16_t(i.a))}); - } else if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Vopc || + } else if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Vopc || i.enc == Encoding::QuadCompare || i.name == "s_mulk_i32" || i.name == "s_addk_i32" || i.name == "s_cmovk_i32" || i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32") { set(i.dst, {}); - if (((wave64 || (narrow_wave64 && i.dst == 126)) && i.enc == Encoding::Vopc) || - ((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2) && + const bool compare_pair = (wave64 && (i.enc == Encoding::Vopc || i.enc == Encoding::QuadCompare)) || + (narrow_wave64 && i.enc == Encoding::Vopc && i.dst == 126); + if (compare_pair || ((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2) && i.name.size() >= 4 && (i.name.substr(i.name.size() - 4) == "_b64" || i.name.substr(i.name.size() - 4) == "_i64" || i.name.substr(i.name.size() - 4) == "_u64") && @@ -828,14 +855,26 @@ std::map fixed_vertex_loads(const string &code) { while (pc + 8 <= code.size()) { const Word a = word(code,pc), b = word(code,pc+4); const Word form = a & ~4095u; - if (form != 0xe0342000u && form != 0xe03c2000u && form != 0xe9c32000u) break; + unsigned width, alignment; + bool normalized; + switch (form) { + case 0xe0342000u: width = 2; alignment = 4; normalized = false; break; + case 0xe0382000u: width = 4; alignment = 4; normalized = false; break; // buffer_load_dwordx4 idxen + case 0xe03c2000u: width = 3; alignment = 4; normalized = false; break; + case 0xe8282000u: width = 1; alignment = 1; normalized = false; break; // BUF_FMT_8_UINT + case 0xe8082000u: width = 1; alignment = 1; normalized = true; break; // BUF_FMT_8_UNORM + case 0xe8712000u: width = 2; alignment = 2; normalized = true; break; // BUF_FMT_8_8_UNORM + case 0xe9c32000u: width = 4; alignment = 4; normalized = true; break; // BUF_FMT_8_8_8_8_UNORM + default: return found ? result : std::map{}; + } if (overwrote_index || (b & 0xffff00ffu) != (0x80000000u | ((desc / 4) << 16))) return {}; Inst i{}; i.pc = pc; i.next = pc + 8; i.enc = Encoding::FixedFetch; i.name = "fixed_vertex_fetch"; i.dst = 256 + ((b >> 8) & 255); - i.op = form == 0xe0342000u ? 2 : form == 0xe03c2000u ? 3 : 4; + i.op = width; + i.a = normalized; i.literal = a & 4095u; - if (i.literal % 4 || i.literal >= 2048 || i.dst+i.op > 512) return {}; + if (i.literal % alignment || i.literal >= 2048 || i.dst+i.op > 512) return {}; result.emplace(pc, i); found = true; overwrote_index = i.dst == 256; pc += 8; } @@ -991,7 +1030,7 @@ struct Emit { if (sym.value == compute_resource_heap) refuse(i.pc, "whole-heap buffer access needs a matching descriptor at the GPU-selected index"); if (indexed) { - if (width != 4 || compute_uav(kind) || (sym.index_mask & 31)) + if ((width != 4 && width != 8) || compute_uav(kind) || (sym.index_mask & 31)) refuse(i.pc, "indexed descriptor requires a bounded 32-byte-aligned SRV offset"); const unsigned first = sym.offset / 32, count = 1 + sym.index_mask / 32; if (sym.value >= layout.NumParameters || layout.pParameters[sym.value].ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) @@ -1025,12 +1064,12 @@ struct Emit { refuse(i.pc, "indexed SRV span exceeds its declared root range"); auto span = std::find_if(list.begin(), list.end(), [&](const auto &b) { return b.kind == kind && b.root_parameter == sym.value && b.byte_offset == sym.offset && - b.array_count == count && !b.array_position; + b.array_count == count && b.image_dimension == dimension && !b.array_position; }); unsigned first_reg = srv; if (span == list.end()) { for (unsigned j = 0; j < count; ++j) - list.push_back({kind, sym.value, sym.offset + j * 32, srv++, bytes, count, j}); + list.push_back({kind, sym.value, sym.offset + j * 32, srv++, bytes, count, j, dimension}); } else { first_reg = span->shader_register; for (unsigned j = 0; j < count; ++j) @@ -1665,6 +1704,7 @@ void lower_blocks(Emit &e) { } #include "gfx1013_direct_compute.inl" #include "gfx1013_direct_graphics.inl" +#include "gfx1013_direct_mesh.inl" } // namespace static NativeComputeShader translate_program(const ComputeRequest &request, unsigned entry, bool direct_dxil, const GuestShaderStage *stage, HeapViewContract heap_view) { @@ -1697,11 +1737,14 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi Microsoft::WRL::ComPtr sig; D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty{}; const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *layout = ∅ - if ((!stage || !request.root.empty()) && (FAILED(D3D12CreateVersionedRootSignatureDeserializer(request.root.data(), request.root.size(), - IID_PPV_ARGS(&sig))) || - FAILED(sig->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &layout)) || - layout->Desc_1_1.NumParameters > 16)) - refuse(entry, "invalid root layout"); + if (!stage || !request.root.empty()) { + HRESULT hr = D3D12CreateVersionedRootSignatureDeserializer(request.root.data(), request.root.size(), + IID_PPV_ARGS(&sig)); + if (SUCCEEDED(hr)) hr = sig->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &layout); + if (hr == E_INVALIDARG) refuse(entry, "invalid root layout"); + if (FAILED(hr)) throw std::runtime_error("invalid root layout: deserializer HRESULT " + std::to_string(hr)); + if (layout->Desc_1_1.NumParameters > 16) refuse(entry, "invalid root layout"); + } unsigned next = 4; State initial{}; for (unsigned k = 0; k <= 105; ++k) @@ -1776,6 +1819,8 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi // group has at most 32 threads stays on the wave32 model, as before the wave size was read: its one guest wave // has lanes 0..31 only, so EXEC's high word is zero and v_mbcnt_hi adds nothing for its lanes. The model // does not write the zero high word that a wave64 compare or carry-out stores in an SGPR pair destination. + const bool packed_state = !stage && direct_dxil && word(request.sa,0)==0x4005cf00 && + word(request.sa,4)==0x6c090102; const bool wave64 = stage ? !stage->wave32 : direct_dxil && !request.wave32 && threads > 32; const bool narrow_wave64 = !stage && direct_dxil && !request.wave32 && !wave64; // The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer contract. @@ -1825,7 +1870,10 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi return i.enc == Encoding::Vopc || i.enc == Encoding::Lds || carry_destination(i) || i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32" || i.name == "s_barrier"; }); - if (branches && synchronizes) refuse(entry, "multi-wave64 exchange requires converged group control flow"); + if (branches && synchronizes) { + if (!packed_state) refuse(entry, "multi-wave64 exchange requires converged group control flow"); + compiler.virtual_waves = static_cast(threads / 64); + } } auto translated = compiler.lower(entry,user,rsrc2,x,y,z); for (auto &binding : translated.bindings) { @@ -1956,12 +2004,13 @@ bool x2w::apply_reflected_table_use(ComputeViewBinding &binding, const GuestShad match = &use; } if (!match) return false; - const bool scalar = binding.kind == ComputeViewKind::buffer_srv; + const bool scalar = accepts_cbv_window(binding.kind); const bool buffer = scalar || compute_buffer_uav(binding.kind) || binding.kind == ComputeViewKind::raw_vector_srv || - binding.kind == ComputeViewKind::typed_buffer_srv || binding.kind == ComputeViewKind::byte_window_srv; + binding.kind == ComputeViewKind::typed_buffer_srv || binding.kind == ComputeViewKind::byte_window_srv || + binding.kind == ComputeViewKind::indexed_raw_srv; if (match->dwords != (buffer ? 4u : 8u) || (match->type != (compute_uav(binding.kind) ? 3u : 0u) && !(scalar && match->type == 2))) - throw UnsupportedComputeShader("raw load disagrees with reflected table record"); + throw UnsupportedComputeShader("raw load disagrees with reflected table record at root " + std::to_string(binding.root_parameter) + " offset " + std::to_string(binding.byte_offset) + " kind " + std::to_string(static_cast(binding.kind)) + " reflected type " + std::to_string(match->type) + " width " + std::to_string(match->dwords)); if (scalar) binding.scalar_table = match->type == 2 ? ComputeViewBinding::ScalarTable::reflected_cbv : ComputeViewBinding::ScalarTable::srv; @@ -1970,7 +2019,7 @@ bool x2w::apply_reflected_table_use(ComputeViewBinding &binding, const GuestShad void x2w::apply_scalar_table_layout(ComputeViewBinding &binding, const D3D12_ROOT_DESCRIPTOR_TABLE1 &table) { using Table = ComputeViewBinding::ScalarTable; - if (binding.kind != ComputeViewKind::buffer_srv || binding.scalar_table != Table::unknown || binding.byte_offset % 32) + if (!accepts_cbv_window(binding.kind) || binding.scalar_table != Table::unknown || binding.byte_offset % 32) return; uint64_t end = 0; const auto slot = binding.byte_offset / 32; @@ -2018,6 +2067,29 @@ x2w::NativeComputeShader x2w::translate_graphics_container(const std::string &by return lower_graphics(*selected); } +x2w::NativeComputeShader x2w::translate_mesh_program(const std::string &code, const MeshStageLayout &layout) { + return lower_mesh(code,layout); +} + +x2w::NativeComputeShader x2w::translate_mesh_program(const std::string &code, const MeshStageLayout &layout, + const D3D12_ROOT_SIGNATURE_DESC1 &root) { + return lower_mesh(code,layout,nullptr,root); +} + +x2w::NativeComputeShader x2w::translate_mesh_container(const std::string &bytes, bool validate_uint_heap_reads) { + const auto stages=read_guest_shader_container(bytes); + const GuestShaderStage *mesh=nullptr; + for (const auto &s : stages) if (s.stage==GpuStage::ms) { + if (mesh) refuse(0,"ambiguous mesh stage"); + mesh=&s; + } + if (!mesh) refuse(0,"missing mesh stage"); + MeshStageLayout layout{mesh->threads[0],mesh->max_vertices,mesh->max_primitives, + mesh->topology,mesh->mesh_group_stride,mesh->wave32}; + layout.validate_uint_heap_reads=validate_uint_heap_reads; + return lower_mesh(mesh->code,layout,mesh); +} + x2w::DirectGraphicsPair x2w::translate_graphics_pair(std::string_view a,std::string_view b) { return translate_graphics_pair(a, b, {}); } @@ -2033,15 +2105,15 @@ static bool raw_center_inputs(unsigned enable_mask) { return (enable_mask & ~position_inputs) == 2; } static GuestShaderStage read_raw_graphics(std::string_view bytes, const D3D12_ROOT_SIGNATURE_DESC1 &layout, - unsigned enable_mask, unsigned address_mask) { + unsigned enable_mask, unsigned address_mask, bool mesh_pixel = false) { if (bytes.empty() || bytes.size() % 4 || bytes.size() > (1u << 20)) throw UnsupportedComputeShader("invalid raw graphics extent"); GuestShaderStage stage{}; unsigned extent = 0; bool position = false, color = false, ended = false; struct Parameter { unsigned exported = 0, smooth = 0, flat = 0; }; - std::array params{}; - const bool has_params = raw_center_inputs(enable_mask); + std::vector params(mesh_pixel ? 31 : 7); + const bool has_params = raw_center_inputs(enable_mask) || mesh_pixel; std::map visited; std::deque pending{0}; while (!pending.empty()) { @@ -2102,12 +2174,14 @@ static GuestShaderStage read_raw_graphics(std::string_view bytes, const D3D12_RO const auto &p = params[attr]; if ((position && (p.smooth || p.flat)) || (color && p.exported) || (p.smooth & p.flat)) refuse(0, "ambiguous raw varying interface"); + if (mesh_pixel && p.smooth && p.flat) + refuse(0, "mixed interpolation modes in one packed mesh PARAM"); // A PARAM may mix smooth channels and provoking-vertex fetches. for (unsigned ch = 0; ch < 4; ++ch) { const uint8_t bit = uint8_t(1u << ch); if (!((p.exported | p.smooth | p.flat) & bit)) continue; const unsigned index = 4 * attr + ch; - const uint8_t row = uint8_t(index + 1); + const uint8_t row = uint8_t(1 + (mesh_pixel ? attr : index)); (position ? stage.outputs : stage.attributes).push_back({6,row,bit,attr,0,uint8_t(bool(p.flat & bit))}); (position ? stage.output_signature : stage.input_signature).push_back({"TEXCOORD",index,0,3,row,bit,bit}); } @@ -2125,13 +2199,33 @@ static GuestShaderStage read_raw_graphics(std::string_view bytes, const D3D12_RO stage.inputs.push_back({table ? 3u : constants ? 0u : 1u,0,count,0,uint8_t(sgpr),uint8_t(j)}); sgpr+=count; } + if (layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { + if (sgpr >= 106) refuse(0, "resource heap outside graphics user data"); + stage.inputs.push_back({5,0,1,0,uint8_t(sgpr++),0}); + } + if (layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { + if (sgpr >= 106) refuse(0, "sampler heap outside graphics user data"); + stage.inputs.push_back({6,0,1,0,uint8_t(sgpr),0}); + } return stage; } +x2w::NativeComputeShader x2w::translate_mesh_pixel_program(std::string_view code, unsigned enable, unsigned address, + unsigned wave_size, const D3D12_ROOT_SIGNATURE_DESC1 *root) { + if (address > 0xffff || (enable & ~address) || (wave_size != 32 && wave_size != 64)) + refuse(0,"invalid fixed mesh pixel entry"); + const D3D12_ROOT_SIGNATURE_DESC1 layout = root ? *root : D3D12_ROOT_SIGNATURE_DESC1{}; + auto ps = read_raw_graphics(code, layout, enable, address, true); + if (ps.stage != GpuStage::ps) refuse(0,"mesh pixel program has no color export"); + ps.wave32 = wave_size == 32; + return lower_graphics(ps, 0, 0, nullptr, layout, 0, root != nullptr); +} + x2w::DirectGraphicsPair x2w::translate_graphics_pair(std::string_view a,std::string_view b, const D3D12_ROOT_SIGNATURE_DESC1 &layout, std::string_view pixel_entry, std::optional first_stage, - const std::array &target_components) { + const std::array &target_components, + std::optional> stage_wave32) { const bool raw = a.substr(0,4)!="DXBC" && b.substr(0,4)!="DXBC"; unsigned enable_mask=0, address_mask=0; if (!pixel_entry.empty()) { @@ -2153,6 +2247,10 @@ x2w::DirectGraphicsPair x2w::translate_graphics_pair(std::string_view a,std::str if(vs->stage==GpuStage::ps)std::swap(vs,ps); if(vs->stage!=GpuStage::vs || ps->stage!=GpuStage::ps)refuse(0,"expected vertex and pixel stages"); ps->target_components=target_components; + if (raw && stage_wave32) { + vs->wave32 = (*stage_wave32)[0]; + ps->wave32 = (*stage_wave32)[1]; + } return translate_reflected_graphics(*vs,*ps,layout); } x2w::DirectGraphicsPair x2w::translate_reflected_graphics(GuestShaderStage &vs, GuestShaderStage &ps, @@ -2168,6 +2266,10 @@ x2w::DirectGraphicsPair x2w::translate_reflected_graphics(GuestShaderStage &vs, static_cast(vertex.samplers.size()), &constants, layout, vertex_uavs); for (auto &binding : vertex.bindings) apply_reflected_table_use(binding, vs); for (auto &binding : pixel.bindings) apply_reflected_table_use(binding, ps); + validate_raster_link(vertex, pixel); + return {std::move(vertex),std::move(pixel)}; +} +void x2w::validate_raster_link(const NativeComputeShader &vertex, const NativeComputeShader &pixel) { for(const auto &input:pixel.inputs){ if(input.name=="SV_IsFrontFace" || input.kind==28) continue; auto producer=std::find_if(vertex.outputs.begin(),vertex.outputs.end(),[&](auto &out){ @@ -2176,5 +2278,4 @@ x2w::DirectGraphicsPair x2w::translate_reflected_graphics(GuestShaderStage &vs, }); if(producer==vertex.outputs.end())refuse(0,"graphics stages disagree on "+input.name+to_string(input.index)); } - return {std::move(vertex),std::move(pixel)}; } diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h index 1ba36eaaa..d7ccd7f90 100644 --- a/src/gfx1013_compute_native.h +++ b/src/gfx1013_compute_native.h @@ -1,4 +1,5 @@ #pragma once +#include "mesh_pixel_heap.h" #include "shader_compute_request.h" #include #include @@ -43,7 +44,9 @@ enum class ComputeViewKind { uint_texture_uav, float_texture_uav, float2_texture_uav, - float3_texture_uav + float3_texture_uav, + packed_d16_x_uav, // Single low-halfword payload; desktop buffer view determines the element size. + indexed_raw_srv // Fixed-stride record read. required_bytes is one complete record and its checked stride. }; inline unsigned exact_texture_uav_channels(ComputeViewKind kind) { switch (kind) { @@ -53,6 +56,9 @@ inline unsigned exact_texture_uav_channels(ComputeViewKind kind) { default: return 0; } } +inline bool accepts_cbv_window(ComputeViewKind kind) { + return kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::byte_window_srv; +} inline constexpr unsigned compute_resource_heap = ~0u; // the directly indexed sampler heap; entry n is title byte offset 16 * n inline constexpr unsigned compute_sampler_heap = ~0u - 1; @@ -60,7 +66,8 @@ inline constexpr unsigned compute_sampler_heap = ~0u - 1; inline bool compute_heap_binding(ComputeViewKind kind) { return kind == ComputeViewKind::heap_buffer_srv; } inline bool compute_buffer_uav(ComputeViewKind kind) { return kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::typed_buffer_uav || - kind == ComputeViewKind::half_buffer_uav || kind == ComputeViewKind::indexed_atomic_uav; + kind == ComputeViewKind::half_buffer_uav || kind == ComputeViewKind::packed_d16_x_uav || + kind == ComputeViewKind::indexed_atomic_uav; } struct IndexedAtomicView { unsigned stride = 0, count = 0; // Bytes per guest index and number of valid indices. @@ -117,7 +124,12 @@ struct GraphicsLinkage { std::string name; unsigned index, row, first, width, component, used, kind, interpolation; }; +struct MeshHeapRead { + unsigned root_parameter, dword, mask; // R32_UINT SRV at (root constant & mask). +}; struct NativeComputeShader { + std::vector pixel_heap_spans; + std::vector mesh_heap_reads; std::vector inputs, outputs; std::vector constants; // Additional b0 words, after root constants, read from these bound SRVs. @@ -125,6 +137,7 @@ struct NativeComputeShader { std::string hlsl, dxil_ir; std::vector bindings; std::vector samplers; + bool sampler_heap = false; unsigned instruction_count{}; std::array group{}; bool vertex_fetch = false; @@ -164,11 +177,31 @@ struct DirectGraphicsPair { DirectGraphicsPair translate_graphics_pair(std::string_view a, std::string_view b, const D3D12_ROOT_SIGNATURE_DESC1 &layout, std::string_view pixel_entry = {}, std::optional first_stage = {}, - const std::array &target_components = {}); + const std::array &target_components = {}, + std::optional> stage_wave32 = {}); DirectGraphicsPair translate_graphics_pair(std::string_view a, std::string_view b); +void validate_raster_link(const NativeComputeShader &producer, const NativeComputeShader &pixel); DirectGraphicsPair translate_reflected_graphics(GuestShaderStage &vs, GuestShaderStage &ps, const D3D12_ROOT_SIGNATURE_DESC1 &layout); std::string native_rectangle_geometry(const std::vector& vertex_outputs, const std::vector& pixel_inputs); NativeComputeShader translate_graphics_container(const std::string &bytes, bool pixel); +struct MeshRootInput { + unsigned sgpr, root_parameter, constant_count; // Zero words denotes a table unless root_address is set. + bool root_address{}; +}; +struct MeshStageLayout { + unsigned threads, max_vertices, max_primitives, topology, group_stride; + bool wave32; + std::vector root_inputs{}; + std::optional resource_heap_sgpr{}; + bool validate_uint_heap_reads{}; + bool packed_parameters{}; +}; +NativeComputeShader translate_mesh_pixel_program(std::string_view code, unsigned enable, unsigned address, + unsigned wave_size, const D3D12_ROOT_SIGNATURE_DESC1 *root = nullptr); +NativeComputeShader translate_mesh_program(const std::string &code, const MeshStageLayout &layout); +NativeComputeShader translate_mesh_program(const std::string &code, const MeshStageLayout &layout, + const D3D12_ROOT_SIGNATURE_DESC1 &root); +NativeComputeShader translate_mesh_container(const std::string &container, bool validate_uint_heap_reads = false); } // namespace x2w diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 3140d2d7c..1eb5815dd 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -36,10 +36,12 @@ struct DirectCompute { refuse(i.pc, "lane read/write needs full waves"); } Emit &analysis; + const GuestShaderStage *graphics_interface = nullptr; DxilModule ir; std::set allocated; string lane, lane_bit, half_index, upper_half, exchange_base; unsigned exchange_words = 0; + unsigned virtual_waves = 0; bool uses_exchange = false; bool wave64 = false; bool narrow_wave64 = false; @@ -60,6 +62,8 @@ struct DirectCompute { std::map,string> descriptor_strides; unsigned label_number = 0; bool pixel_stage = false; + bool pixel_heap_enabled = false; + struct PixelHeapIndex { string index; unsigned first, last; bool nonuniform; }; bool complete_compute_quads = false; bool compute_derivatives = false; // Straight-line graphics stages keep exact SSA definitions; a missing @@ -89,6 +93,11 @@ struct DirectCompute { } string address(unsigned r) { const auto name = "%r" + to_string(r); + if (virtual_waves) { + const auto type = "[" + to_string(virtual_waves) + " x i32]"; + if (allocated.insert(r).second) ir.setup << " " << name << " = alloca " << type << ", align 4\n"; + return ir.value("getelementptr " + type + ", " + type + "* " + name + ", i32 0, i32 %virtualWave"); + } if (allocated.insert(r).second) ir.setup << " " << name << " = alloca i32, align 4\n"; return name; @@ -141,7 +150,7 @@ struct DirectCompute { return "true"; return cmp("ne", ir.binary("and", wave64 ? select(upper_half, read(127), read(126)) : read(126), lane_bit), "0"); } - void vector_write(unsigned r, const string &value) { + void vector_write(unsigned r, const string &value, const string &sampled_float = {}) { if (graphics_input && graphics_predicate.empty()) write(r, value); else if (perspective_center_pair && (r == 256 || r == 257) && @@ -153,6 +162,13 @@ struct DirectCompute { // Only covered lanes can observe this result. In particular no // subsequent implicit LOD or quad operation can inspect helpers. write(r, value); + } else if (exact_pixel_entry && !graphics_predicate.empty() && !sampled_float.empty()) { + // Keep the floating sample and the incoming register live on the + // corresponding sides of the exact/helper predicate. Select has + // no floating-point arithmetic and preserves the old register bits. + auto previous = ir.value("bitcast i32 " + read(r) + " to float"); + auto result = ir.value("select i1 " + graphics_predicate + ", float " + sampled_float + ", float " + previous); + write(r, ir.value("bitcast float " + result + " to i32")); } else write(r, select(graphics_input ? graphics_predicate : active(), value, read_storage(r))); } @@ -234,8 +250,10 @@ struct DirectCompute { void initialize(unsigned user, unsigned flags, unsigned x, unsigned y, unsigned z) { unsigned threads = x * y * z; complete_compute_quads = threads % 4 == 0; - lane = ir.invoke("i32", "waveGetLaneIndex", 111, {}, "nounwind readnone"); - lane_bit = ir.binary("shl", "1", lane); + if (!virtual_waves) { + lane = ir.invoke("i32", "waveGetLaneIndex", 111, {}, "nounwind readnone"); + lane_bit = ir.binary("shl", "1", lane); + } write(126, ballot("true")); if (!wave64) { write(127, "0"); @@ -243,7 +261,9 @@ struct DirectCompute { write(107, "0"); } string wave = "0"; - if (threads > 32) { + if (virtual_waves) { + wave = ir.binary("add",ir.binary("shl","%virtualWave","1"),half_index); + } else if (threads > 32) { auto flat = ir.invoke("i32", "flattenedThreadIdInGroup.i32", 96, {}, "nounwind readnone"); auto first = ir.invoke("i32", "waveActiveOp.i32", 119, {{"i32", flat}, {"i8", "2"}, {"i8", "1"}}, "nounwind"); @@ -267,10 +287,12 @@ struct DirectCompute { } } if (wave64) { - exchange_words = threads / 32; - half_index = wave; - exchange_base = ir.binary("and", wave, "4294967294"); - upper_half = cmp("ne", ir.binary("and", wave, "1"), "0"); + if (!virtual_waves) { + exchange_words = threads / 32; + half_index = wave; + exchange_base = ir.binary("and", wave, "4294967294"); + upper_half = cmp("ne", ir.binary("and", wave, "1"), "0"); + } write(127, "4294967295"); } auto logical = ir.binary("add", ir.binary("mul", wave, "32"), lane); @@ -393,9 +415,10 @@ struct DirectCompute { if (bound_register) *bound_register = it->shader_register; const bool raw = kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::raw_vector_srv || kind == ComputeViewKind::byte_window_srv || - kind == ComputeViewKind::indexed_atomic_uav; + kind == ComputeViewKind::indexed_atomic_uav || kind == ComputeViewKind::indexed_raw_srv; const bool half = kind == ComputeViewKind::half_buffer_uav; - const unsigned width = kind == ComputeViewKind::typed_buffer_srv ? 4 : bytes / (half ? 2 : 4); + const unsigned width = kind == ComputeViewKind::typed_buffer_srv ? 4 : + kind == ComputeViewKind::packed_d16_x_uav ? 1 : bytes / (half ? 2 : 4); if (raw) ir.features |= 16; return ir.handle({unsigned(compute_uav(kind)), it->shader_register, raw ? 11u : 10u, @@ -502,6 +525,20 @@ struct DirectCompute { } #include "gfx1013_compute_mtbuf.inl" + string root_buffer_handle(unsigned parameter, unsigned span) { + auto &bindings = analysis.result.bindings; + auto binding = std::find_if(bindings.begin(), bindings.end(), [&](const auto &b) { + return b.kind == ComputeViewKind::root_buffer_srv && b.root_parameter == parameter; + }); + if (binding == bindings.end()) { + bindings.push_back({ComputeViewKind::root_buffer_srv, parameter, 0, analysis.srv++, span}); + binding = std::prev(bindings.end()); + } else + binding->required_bytes = (std::max)(binding->required_bytes, span); + ir.features |= 16; + return ir.handle({0, binding->shader_register, 11}); + } + // Global DWORD loads in the saddr form: ADDR = SADDR + zext(VADDR) + sext(OFFSET[11:0]) (RDNA 2 ISA, // FLAT/GLOBAL addressing), with SADDR the unadvanced root address of a root SRV, as for the scalar root loads. // Guard the first and last DWORD offsets against 32-bit wrap. The low two address bits are dropped, @@ -524,17 +561,7 @@ struct DirectCompute { if (offset % 4) refuse(i.pc, "global load at an unaligned immediate offset"); const unsigned span = static_cast((std::max)(offset, 0)) + count * 4; - auto &bindings = analysis.result.bindings; - auto binding = std::find_if(bindings.begin(), bindings.end(), [&](const auto &b) { - return b.kind == ComputeViewKind::root_buffer_srv && b.root_parameter == low.value; - }); - if (binding == bindings.end()) { - bindings.push_back({ComputeViewKind::root_buffer_srv, low.value, 0, analysis.srv++, span}); - binding = std::prev(bindings.end()); - } else - binding->required_bytes = (std::max)(binding->required_bytes, span); - ir.features |= 16; - const auto h = ir.handle({0, binding->shader_register, 11}); + const auto h = root_buffer_handle(low.value, span); const auto vaddr = read(256 + (i.b & 255)); string in_range; if (offset < 0) @@ -570,6 +597,38 @@ struct DirectCompute { unsigned so = i.b >> 25; const unsigned limit = smem_sgpr_limit(!graphics_input); const auto &low = s.at(i.src[0]); + if (low.type == Symbol::Type::sampler_heap) { + if (i.op != 2 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant, 0})) + refuse(i.pc, "sampler heap requires a four-word load with zero high address"); + if (so == 125 || s.at(so).type == Symbol::Type::constant) + refuse(i.pc, "constant sampler heap offset has no validated sampler-table contract"); + auto bytes = ir.binary("add", operand32(i, so), to_string(i.b & 0xfffff)); + // gfx2hlsl.x2w_sampler_entry: slot 2047 is reserved by the runtime. + auto aligned = cmp("eq", ir.binary("and", bytes, "15"), "0"); + auto in_range = cmp("ult", bytes, "32752"); + auto valid = ir.value("and i1 " + aligned + ", " + in_range); + auto index = select(valid, ir.binary("lshr", bytes, "4"), "2047"); + for (unsigned j = 0; j < 4; ++j) + write(i.dst + j, index); + return; + } + if (pixel_heap_enabled && low.type == Symbol::Type::table && low.value == compute_resource_heap && i.op == 3) { + if (i.dst + 8 > 106 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant,0})) + refuse(i.pc, "invalid pixel heap texture descriptor address"); + const Word offset = i.b & 0xfffff; + if (offset & 31) refuse(i.pc, "unaligned pixel heap immediate byte offset"); + string index = to_string(offset / 32); + if (so != 125) { + const auto value = s.at(so); + if ((value.type != Symbol::Type::masked && value.type != Symbol::Type::constant) || + (value.value & 31) || value.value > UINT_MAX - offset) + refuse(i.pc,"pixel heap byte offset has no proven aligned range"); + auto address = ir.binary("add", operand32(i,so), to_string(offset)); + index = ir.binary("lshr",address,"5"); + } + for (unsigned j=0;j<8;++j) write(i.dst+j,index); + return; + } const bool root = low.type == Symbol::Type::root_address; // Table and heap-offset descriptor lowering track identities and slot indices instead of // loading payload bits. @@ -626,10 +685,11 @@ struct DirectCompute { s.at(i.src[0] + 1).type != Symbol::Type::constant || s.at(i.src[0] + 1).value != 0) refuse(i.pc, "direct descriptor address outside bound table"); if (so != 125) { - if (i.op != 2 || so >= limit) + const bool pixel_texture = pixel_stage && i.op == 3 && low.value != compute_resource_heap; + if ((!pixel_texture && i.op != 2) || so >= limit || (pixel_texture && i.dst + 8 > limit)) refuse(i.pc, "direct indexed descriptor load shape"); auto index = ir.binary("lshr", operand32(i, so, limit), "5"); - for (unsigned j = 0; j < 4; ++j) + for (unsigned j = 0; j < memory_count(i); ++j) write(i.dst + j, index); } return; // The CFG transfer already associated every destination word with its table slot. @@ -638,7 +698,9 @@ struct DirectCompute { string h; if (root) { const Symbol high{Symbol::Type::root_address, low.value, 1}; - if (low.offset || !(s.at(i.src[0] + 1) == high)) + const bool stride_one = i.op >= 8 && s.at(i.src[0] + 1) == + Symbol{Symbol::Type::root_stride_one_high, low.value, 1}; + if (low.offset || (!(s.at(i.src[0] + 1) == high) && !stride_one)) refuse(i.pc, "mismatched root address high half"); // Like Victory's Source::Built, retain the root identity through // SGPR copies. Scalar buffer loads read dwords at byte offsets. @@ -646,7 +708,7 @@ struct DirectCompute { // only for this verified zero-stride, byte-address V# layout. const bool built = i.op >= 8; if (built && (s.at(i.src[0] + 2).type != Symbol::Type::constant || - !(s.at(i.src[0] + 3) == Symbol{Symbol::Type::constant, 0x31016fac}))) + !(s.at(i.src[0] + 3) == Symbol{Symbol::Type::constant, stride_one ? 0x11014facu : 0x31016facu}))) refuse(i.pc, "unsupported synthesized scalar buffer descriptor fields"); unsigned span = off + 4 * n; if (off % 4 || span > 65536 || i.dst + n > limit) @@ -660,17 +722,7 @@ struct DirectCompute { } if (built && span > s.at(i.src[0] + 2).value) refuse(i.pc, "scalar load exceeds synthesized descriptor byte bound"); - auto &bindings = analysis.result.bindings; - auto binding = std::find_if(bindings.begin(), bindings.end(), [&](const auto &b) { - return b.kind == ComputeViewKind::root_buffer_srv && b.root_parameter == low.value; - }); - if (binding == bindings.end()) { - bindings.push_back({ComputeViewKind::root_buffer_srv, low.value, 0, analysis.srv++, span}); - binding = std::prev(bindings.end()); - } else - binding->required_bytes = (std::max)(binding->required_bytes, span); - ir.features |= 16; - h = ir.handle({0, binding->shader_register, 11}); + h = root_buffer_handle(low.value, span); } else h = resource(i, s, i.src[0], ComputeViewKind::buffer_srv, so == 125 ? off + 4 * n : 4); auto addr = so == 125 ? to_string(off) @@ -692,14 +744,64 @@ struct DirectCompute { unsigned n = raw ? widths[i.op & 3] : (i.op & 3) + 1, data = 256 + i.dst; if (i.dst + (half ? (n + 1) / 2 : n) > 256) refuse(i.pc, "direct buffer data overflow"); + const bool packed_x = half && n == 1 && !graphics_input; auto kind = store ? (raw ? ComputeViewKind::raw_buffer_uav + : packed_x ? ComputeViewKind::packed_d16_x_uav : half ? ComputeViewKind::half_buffer_uav : ComputeViewKind::typed_buffer_uav) : raw && s.at(((i.b >> 16) & 31) * 4 + 1).type == Symbol::Type::zero_stride_word ? ComputeViewKind::byte_window_srv : raw ? ComputeViewKind::raw_vector_srv : ComputeViewKind::typed_buffer_srv; - auto h = resource(i, s, ((i.b >> 16) & 31) * 4, kind, raw ? 4 : n * (half ? 2 : 4)); + const unsigned base = ((i.b >> 16) & 31) * 4; + string h; + if (!store && raw && (i.a & 0x2000)) { + const auto &descriptor = s.at(base); + const unsigned offset = i.a & 4095; + if (!graphics_interface || descriptor.type != Symbol::Type::descriptor) + refuse(i.pc, "indexed raw load needs a reflected table SRV"); + std::optional record_stride; + for (const auto &use : graphics_interface->resources) { + if (use.type || use.root_type != 3 || use.dwords != 4 || + use.root_parameter != descriptor.value || uint64_t(use.offset_dwords)*4 != descriptor.offset) continue; + if (record_stride && *record_stride != use.stride) refuse(i.pc, "ambiguous indexed SRV record stride"); + record_stride = use.stride; + } + const unsigned stride = record_stride.value_or(0); + if (!stride || stride > 2048 || (stride | offset) % 4 || offset + 4*n > stride) + refuse(i.pc, "indexed raw load outside a verified dword-aligned record"); + h = resource(i, s, base, ComputeViewKind::indexed_raw_srv, stride); + auto index = read(256 + (i.b & 255)); + auto dimensions = ir.invoke("%dx.types.Dimensions", "getDimensions", 72, + {{"%dx.types.Handle", h}, {"i32", "undef"}}, "nounwind readonly"); + auto size = ir.value("extractvalue %dx.types.Dimensions " + dimensions + ", 0"); + auto valid = cmp("ult", index, ir.binary("udiv", size, to_string(stride))); + auto start = ir.binary("add", ir.binary("mul", index, to_string(stride)), to_string(offset)); + auto result = load_buffer(h, start, true, n); + for (unsigned j=0; j> 24) != 128) + refuse(i.pc, "unsupported raw root buffer descriptor or offset"); + h = root_buffer_handle(low.value, 4*n); + } else { + h = resource(i, s, base, kind, raw ? 4 : n * (half ? 2 : 4)); + } auto addr = (i.a & (raw ? 0x1000 : 0x2000)) ? read(256 + (i.b & 255)) : "0"; if (raw) { addr = ir.binary("add", addr, to_string(i.a & 4095)); @@ -721,20 +823,22 @@ struct DirectCompute { if (j < n || !raw) { const unsigned component = (std::min)(j, n - 1); value = read(data + (half ? component / 2 : component)); - if (half) { + if (packed_x) { + value = ir.binary("and", value, "65535"); + } else if (half) { if (component % 2) value = ir.binary("lshr", value, "16"); value = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", value}}, "nounwind readnone"); } } - args.emplace_back(half ? "float" : "i32", value); + args.emplace_back(half && !packed_x ? "float" : "i32", value); } args.emplace_back("i8", to_string(raw ? (1u << n) - 1 : 15)); if (raw) args.emplace_back("i32", "4"); ir.invoke("void", raw ? "rawBufferStore.i32" - : half ? "bufferStore.f32" + : half && !packed_x ? "bufferStore.f32" : "bufferStore.i32", raw ? 140 : 69, args, "nounwind"); if (!graphics_input) @@ -755,6 +859,40 @@ struct DirectCompute { select_float(is_y, major, nv), select_float(is_x, select_float(negative, u, nu), select_float(is_y, select_float(negative, nv, v), major))}; } + string pixel_heap_texture(const Inst &i, const State &s, unsigned base, unsigned dim, + std::optional selected) { + const auto sym = s.at(base); + if (!pixel_heap_enabled || sym.type != Symbol::Type::indexed_descriptor || + sym.value != compute_resource_heap || base+8>106 || (sym.offset & 31) || (dim != 1 && dim != 5)) + refuse(i.pc, "unproven pixel heap Texture2D descriptor"); + for (unsigned j=1;j<8;++j) { + auto expected = sym; + expected.offset += 4*j; + if (!(s.at(base+j)==expected)) refuse(i.pc,"mixed pixel heap texture descriptor words"); + } + if (!selected) { + if ((sym.index_mask & 31) || sym.index_mask > UINT_MAX - sym.offset) + refuse(i.pc,"pixel texture heap requires a proven slot domain"); + selected = PixelHeapIndex{read(base),sym.offset/32,(sym.offset+sym.index_mask)/32,false}; + } + auto &spans = analysis.result.pixel_heap_spans; + const auto &key=*selected; + if (key.first>key.last || key.last>UINT_MAX/32) refuse(i.pc,"invalid pixel texture heap range"); + auto it=std::find_if(spans.begin(),spans.end(),[&](const auto &v){ + return v.first==key.first && v.last==key.last && v.dimension==dim; + }); + if (it==spans.end()) { + const unsigned first=spans.empty()? first_pixel_heap_slot : + spans.back().host_first+(spans.back().last-spans.back().first+1); + if (uint64_t(first)+key.last-key.first+1 > D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1-256) + refuse(i.pc,"pixel texture heap domain exceeds desktop descriptor capacity"); + spans.push_back({key.first,key.last,dim,first}); + it=std::prev(spans.end()); + } + auto physical=ir.binary("add",key.index,to_string(it->host_first-key.first)); + ir.features |= 0x40000000; + return ir.heap_handle(physical,dim==1?2u:7u,1033,false,key.nonuniform); + } string texture_dimensions(const string &handle, const string &mip) { return ir.invoke("%dx.types.Dimensions", "getDimensions", 72, {{"%dx.types.Handle", handle}, {"i32", mip}}, "nounwind readonly"); @@ -887,12 +1025,18 @@ struct DirectCompute { write(256 + i.dst, previous); ir.body << " br label %imageAtomicEnd" << label << "\nimageAtomicEnd" << label << ":\n"; } - void image_io(const Inst &i, const State &s) { + void image_io(const Inst &i, const State &s, std::optional selected = {}) { if (is_image_atomic(i)) { image_atomic(i, s); return; } const bool bias = i.op == 37, gradient = i.op == 34, query = i.op == 96, dimensions = i.op == 14; + // With a different texture in neighboring lanes, compute the quad's + // derivatives on the original coordinates, independently of the + // descriptor selected by each iteration of the guest waterfall. + const bool quad_gradient = selected && selected->nonuniform && i.op==32; + if (quad_gradient && (i.a & 0x1000u)) + refuse(i.pc,"nonuniform implicit sampling requires normalized coordinates"); // image_gather4_c_lz (79) is the comparison gather at the view's first mip (#2969): DXIL textureGatherCmp. const bool compare_gather = i.op == 79; const bool compare = i.op == 40 || i.op == 47 || compare_gather; @@ -900,6 +1044,8 @@ struct DirectCompute { if (implicit && !pixel_stage) { if (!complete_compute_quads) refuse(i.pc, "implicit derivatives require a pixel stage"); + if (virtual_waves) + refuse(i.pc, "implicit derivatives with virtual wave64 groups"); compute_derivatives = true; } const bool gather = i.op == 64 || i.op == 71 || compare_gather; @@ -912,6 +1058,7 @@ struct DirectCompute { constexpr unsigned dx_kind[]{1, 2, 4, 5, 6, 7, 3, 8}; constexpr unsigned coord_count[]{1, 2, 3, 3, 2, 3, 2, 3}; const unsigned coords = coord_count[dim]; + const bool indexed = pixel_stage && !store && s.at(base).type == Symbol::Type::indexed_descriptor; const bool exact_store = store && !half && !graphics_input && (dim == 1 || dim == 2 || dim == 5) && (mask == 1 || mask == 3 || mask == 7); // Read-only image ops ignore GLC (bit 13, 0x2000) and DLC (bit 7, 0x0080) cache hints; @@ -925,7 +1072,7 @@ struct DirectCompute { ((sample || gather) && (i.a & 0x1000u) && gradient) || (dimensions && (dim == 4 || dim >= 6 || (i.b & 0x40000000u))) || (store && !half && mask != 15 && !exact_store) || (half && mask != 1 && mask != 3 && mask != 15) || - s.at(base).type != Symbol::Type::descriptor) + (!indexed && s.at(base).type != Symbol::Type::descriptor)) refuse(i.pc, "direct image opcode or descriptor modifiers"); if (gather_lod && (dim != 1 || (mask & (mask - 1)) || (i.a & 0x1006u) || (i.b & 0xc0000000u) || i.dst > 252)) refuse(i.pc, "unsupported explicit 2D gather operands"); @@ -945,15 +1092,23 @@ struct DirectCompute { : d16_sample ? ComputeViewKind::d16_sample_srv : compare ? ComputeViewKind::comparison_texture_srv : ComputeViewKind::texture_srv; - analysis.binding(i, s, base, 8, kind, 0, dim); - const auto &bs = analysis.result.bindings; - auto it = std::find_if(bs.begin(), bs.end(), [&](const auto &b) { - return !b.array_position && b.image_dimension == dim && b.kind == kind && - b.root_parameter == s[base].value && b.byte_offset == s[base].offset; - }); - if (it == bs.end()) - throw std::logic_error("missing image binding"); - auto h = ir.handle({unsigned(store), it->shader_register, cube_sample ? 9u : dx_kind[dim], 9, compare ? 1u : channels, 0}); + string h; + if (selected || (indexed && s[base].value==compute_resource_heap)) { + if (kind != ComputeViewKind::texture_srv) refuse(i.pc,"unsupported pixel heap texture view class"); + h=pixel_heap_texture(i,s,base,dim,selected); + } else { + analysis.binding(i, s, base, 8, kind, 0, dim); + const auto &bs = analysis.result.bindings; + const unsigned count = indexed ? 1 + s[base].index_mask / 32 : 1; + auto it = std::find_if(bs.begin(), bs.end(), [&](const auto &b) { + return !b.array_position && b.array_count == count && b.image_dimension == dim && b.kind == kind && + b.root_parameter == s[base].value && b.byte_offset == s[base].offset; + }); + if (it == bs.end()) + throw std::logic_error("missing image binding"); + h = ir.handle({unsigned(store), it->shader_register, cube_sample ? 9u : dx_kind[dim], 9, compare ? 1u : channels, 0, count}, + indexed && count > 1 ? read(base) : ""); + } auto coordinate = [&](unsigned j) { unsigned r = addr + j; if (j && (i.a & 6)) { @@ -1002,17 +1157,29 @@ struct DirectCompute { if (!store) { string r; if (sample || gather) { - const auto sampler_ref = analysis.sampler_index(i, s, sample || implicit, i.op == 71 || compare_gather, - implicit || gradient, compare); - if (i.op == 64 && !sampler_ref.heap && - (analysis.result.samplers.at(sampler_ref.index - analysis.first_sampler).words[1] & 0xffffff)) - refuse(i.pc, "implicit gather requires a sampler fixed to mip zero"); string sampler; - if (sampler_ref.heap) { - ir.features |= 0x80000000; - sampler = ir.sampler_heap_handle(to_string(sampler_ref.index)); - } else - sampler = ir.handle({3, sampler_ref.index, 14, 0, 0, 0, 1, compare}); + const unsigned sampler_base = ((i.b >> 21) & 31) * 4; + const auto &first = s.at(sampler_base); + if (first.type == Symbol::Type::sampler_word) { + if (compare || gather) + refuse(i.pc, "unsupported heap sampler operation or destination"); + for (unsigned j = 0; j < 4; ++j) + if (!(s.at(sampler_base+j) == Symbol{Symbol::Type::sampler_word,first.value,j,0,first.definition})) + refuse(i.pc, "mixed sampler heap descriptor words"); + analysis.result.sampler_heap = true; + sampler = ir.handle({3, 0, 14, 0, 0, 0, 2048, false, 1}, read(sampler_base)); + } else { + const auto sampler_ref = analysis.sampler_index(i, s, sample || implicit, i.op == 71 || compare_gather, + implicit || gradient, compare); + if (i.op == 64 && !sampler_ref.heap && + (analysis.result.samplers.at(sampler_ref.index - analysis.first_sampler).words[1] & 0xffffff)) + refuse(i.pc, "implicit gather requires a sampler fixed to mip zero"); + if (sampler_ref.heap) { + ir.features |= 0x80000000; + sampler = ir.sampler_heap_handle(to_string(sampler_ref.index)); + } else + sampler = ir.handle({3, sampler_ref.index, 14, 0, 0, 0, 1, compare}); + } using Arg = std::pair; std::vector args{{"%dx.types.Handle", h}, {"%dx.types.Handle", sampler}}; const auto size = (i.a & 0x1000u) ? texture_dimensions(h, "0") : string{}; @@ -1067,13 +1234,14 @@ struct DirectCompute { args.emplace_back("float", ir.value("bitcast i32 " + level + " to float")); if (implicit) args.emplace_back("float", "undef"); - } else if (gradient) { + } else if (gradient || quad_gradient) { // Victory emit/lower.rs: d/dx and then d/dy of spatial // coordinates precede the coordinates, excluding array slices. for (unsigned axis = 0; axis < 2; ++axis) { std::array d{"undef", "undef", "undef"}; for (unsigned j = 0; j < spatial; ++j) - d[j] = ir.value("bitcast i32 " + coordinate(axis * spatial + j) + " to float"); + d[j] = quad_gradient ? ir.invoke("float","unary.f32",83+axis,{{"float",c[j]}},"nounwind readnone") : + ir.value("bitcast i32 " + coordinate(axis * spatial + j) + " to float"); if (dim == 3) d = cube_axes(face, ir.value("fmul float " + d[0] + ", 2.0"), ir.value("fmul float " + d[1] + ", 2.0"), true); @@ -1088,10 +1256,10 @@ struct DirectCompute { args.emplace_back("float", lod ? ir.value("bitcast i32 " + level + " to float") : "0.0"); const char *method = compare_gather ? "textureGatherCmp.f32" : compare ? (implicit ? "sampleCmp.f32" : "sampleCmpLevelZero.f32") : - gather ? "textureGather.f32" : gradient ? "sampleGrad.f32" : + gather ? "textureGather.f32" : (gradient || quad_gradient) ? "sampleGrad.f32" : bias ? "sampleBias.f32" : implicit ? "sample.f32" : "sampleLevel.f32"; const unsigned opcode = compare_gather ? 74 : compare ? (implicit ? 64 : 65) : gather ? 73 : - gradient ? 63 : bias ? 61 : implicit ? 60 : 62; + (gradient || quad_gradient) ? 63 : bias ? 61 : implicit ? 60 : 62; r = ir.invoke("%dx.types.ResRet.f32", method, opcode, args, "nounwind readonly"); } else r = ir.invoke("%dx.types.ResRet.f32", "textureLoad.f32", 66, @@ -1121,7 +1289,7 @@ struct DirectCompute { bits = ir.binary("or", pending_half, ir.binary("shl", bits, "16")); pending_half.clear(); } - vector_write(256 + dst++, bits); + vector_write(256 + dst++, bits, !d16_sample && (sample || gather) ? value : string{}); } if (!pending_half.empty()) vector_write(256 + dst, pending_half); } else { @@ -1153,6 +1321,28 @@ struct DirectCompute { } } void local_memory(const Inst &i, unsigned words) { + if (((i.a >> 18) & 255) == 0x3e && virtual_waves) { + const unsigned offset = i.a & 65535; + if ((i.a & 0x30000) || (i.b & 0xffffff) || offset % 4 || offset / 4 >= words) + refuse(i.pc, "invalid local append counter"); + const auto count_bits = [&](unsigned reg) { + return ir.invoke("i32", "unaryBits.i32", 31, {{"i32", read(reg)}}, "nounwind readnone"); + }; + const auto count = ir.binary("add", count_bits(126), count_bits(127)); + const auto leader = ir.value("and i1 " + cmp("eq", half_index, "0") + ", " + cmp("eq", lane, "0")); + auto take = ir.value("and i1 " + leader + ", " + cmp("ne", count, "0")); + const auto tag = to_string(label_number++); + barrier(); + ir.body << " br i1 " << take << ", label %append" << tag << ", label %skipAppend" << tag + << "\nappend" << tag << ":\n"; + auto ptr = shared_address("lds", words, to_string(offset / 4)); + auto old = ir.value("atomicrmw add i32 addrspace(3)* " + ptr + ", i32 " + count + " monotonic"); + ir.body << " br label %afterAppend" << tag << "\nskipAppend" << tag << ":\n br label %afterAppend" + << tag << "\nafterAppend" << tag << ":\n"; + const auto result = ir.value("phi i32 [ " + old + ", %append" + tag + " ], [ 0, %skipAppend" + tag + " ]"); + vector_write(256 + (i.b >> 24), exchange_halves(result)[0]); + return; + } const auto op = decode_local_data(i.a, i.b); // The host executes a guest wave64 on two wave32s. Meet before // each operation, outside its lane predicate, as in Victory split_lds. @@ -1170,7 +1360,11 @@ struct DirectCompute { write(256 + op.destination + j, ir.value("load i32, i32 addrspace(3)* " + ptr + ", align 4")); else { auto data = read(256 + op.data_register(j)); - if (op.atomic_ir) { + if (op.compare_exchange) { + auto result = ir.value("cmpxchg i32 addrspace(3)* " + ptr + ", i32 " + data + ", i32 " + + read(256 + op.data1) + " monotonic monotonic"); + write(256 + op.destination, ir.value("extractvalue { i32, i1 } " + result + ", 0")); + } else if (op.atomic_ir) { if (op.subtract) data = ir.binary("sub", "0", data); auto old = ir.value(string("atomicrmw ") + op.atomic_ir + " i32 addrspace(3)* " + ptr + @@ -2438,7 +2632,7 @@ struct DirectCompute { }; if (op == "class" && fp) { if ((i.abs | i.neg) & 2 || - (i.subword && (half || i.src_select[0] != 6 || i.src_sext[0])) || + (i.subword && (i.src_select[0] != 6 || i.src_sext[0])) || (i.wide && (i.a & 0x7800))) refuse(i.pc, "unsupported floating class operand selection"); // The class mask is integer data. Testing raw bits keeps sNaNs, @@ -2912,7 +3106,7 @@ struct DirectCompute { // observe a placeholder for this field or its SCC. // The byte-address OOB selector ORs in two nonzero bits. // Its SCC is known for every source descriptor. - if (field->type == Symbol::Type::byte_oob) + if (field->type == Symbol::Type::byte_oob || field->type == Symbol::Type::root_stride_one_high) write(128, "1"); else if (n != "s_mul_i32" && uses_scc_after(i)) { const auto stride = descriptor_strides.find({field->value,field->offset}); @@ -3063,9 +3257,12 @@ struct DirectCompute { refuse(i.pc, "descriptor used as mask"); if (n == "s_mov_b64" && ((i.dst | i.src[0]) & 1)) refuse(i.pc, "unaligned scalar pair"); - if (state[i.src[0]].type == Symbol::Type::indexed_descriptor) + auto indexed = [](const Symbol &v) { + return v.type == Symbol::Type::indexed_descriptor || v.type == Symbol::Type::sampler_word; + }; + if (indexed(state[i.src[0]])) write(i.dst, read(i.src[0])); - if (n == "s_mov_b64" && state.at(i.src[0] + 1).type == Symbol::Type::indexed_descriptor) + if (n == "s_mov_b64" && indexed(state.at(i.src[0] + 1))) write(i.dst + 1, read(i.src[0] + 1)); // Transfer tracks symbolic low words; preserve numeric high words of a pair independently. if (n == "s_mov_b64" && state.at(i.src[0] + 1).numeric()) @@ -3551,6 +3748,15 @@ struct DirectCompute { write(128, ir.value("zext i1 " + carry + " to i32")); return; } + if (compute && n == "s_bcnt1_i32_b64") { + const auto count = [&](const string &word) { + return ir.invoke("i32", "unaryBits.i32", 31, {{"i32", word}}, "nounwind readnone"); + }; + auto total = ir.binary("add", count(a), count(pair_high(i, i.src[0]))); + write(i.dst, total); + write(128, ir.value("zext i1 " + cmp("ne", total, "0") + " to i32")); + return; + } auto combine_scalar_mask = [&](Name op, const string &left, const string &right) -> string { if (op == "and" || op == "or" || op == "xor") return ir.binary(string(op), left, right); @@ -3628,6 +3834,10 @@ struct DirectCompute { write(128, ir.value("zext i1 " + ir.value("or i1 " + flag + ", " + carry2) + " to i32")); return; } + if (n == "s_ff1_i32_b32") { + write(i.dst, ir.invoke("i32", "unaryBits.i32", 32, {{"i32", a}}, "nounwind readnone")); + return; + } if (n == "s_brev_b32" || n == "v_bfrev_b32" || n == "v_bcnt_u32_b32") { bool count = n == "v_bcnt_u32_b32"; auto value = ir.invoke("i32", count ? "unaryBits.i32" : "unary.i32", count ? 31 : 30, {{"i32", a}}, @@ -4214,6 +4424,54 @@ struct DirectCompute { const unsigned updated = (mode_bits & ~mask) | ((i.literal << offset) & mask); return accept(updated); } + // A 64-thread desktop group executes one guest wave at a time. Register + // banks and resume PCs are private to each virtual wave; guest LDS is + // shared. Yield at branches for fairness and park at guest barriers. + void start_virtual_group(const std::set& labels) { + constexpr auto initial = "4294967294"; + const auto type = "[" + to_string(virtual_waves) + " x i32]"; + ir.setup << " %vpc = alloca " << type << ", align 4\n %cursor = alloca i32, align 4\n"; + std::vector positions; + for (unsigned j=0; j> 15) & 511) * 128; const bool uses_lds = std::any_of(analysis.program.code.begin(), analysis.program.code.end(), @@ -4221,7 +4479,6 @@ struct DirectCompute { if (uses_lds) ir.globals << "@lds = internal addrspace(3) global [" << lds_words << " x i32] undef, align 4\n"; prepare_descriptor_strides(); - initialize(user, flags, x, y, z); const auto &p = analysis.program; mode_bits = 0xf0; bool mode_write = false, conditional = false; @@ -4259,19 +4516,24 @@ struct DirectCompute { (i.enc == Encoding::Image && i.op == 8) || is_image_atomic(i); }); std::set labels{entry}; - ir.body << " br label %pc" << entry << "\n"; for (auto &i : p.code) if (i.branch()) { labels.insert(i.target()); if (i.op != 2) labels.insert(i.next); } + if (virtual_waves) for (const auto &i : p.code) + if (i.name == "s_barrier") labels.insert(i.next); + if (virtual_waves) start_virtual_group(labels); + initialize(user, flags, x, y, z); + ir.body << " br label %pc" << entry << "\n"; for (size_t k = 0; k < p.code.size(); ++k) { const auto &i = p.code[k]; compute_pc = i.pc; compute_state = &p.before[k]; if (labels.count(i.pc)) { - if (k && p.code[k - 1].name != "s_endpgm" && !p.code[k - 1].branch()) + if (k && p.code[k - 1].name != "s_endpgm" && !p.code[k - 1].branch() && + !(virtual_waves && p.code[k-1].name=="s_barrier")) ir.body << " br label %pc" << i.pc << "\n"; ir.body << "pc" << i.pc << ":\n"; } @@ -4282,20 +4544,25 @@ struct DirectCompute { continue; } if (i.branch()) { - if (i.op == 2) - ir.body << " br label %pc" << i.target() << "\n"; + if (i.op == 2) { + if (virtual_waves) yield_virtual_wave(to_string(i.target())); + else ir.body << " br label %pc" << i.target() << "\n"; + } else { unsigned r = i.op == 4 || i.op == 5 ? 128 : i.op == 6 || i.op == 7 ? 106 : 126; auto mask = wave64 && r != 128 ? ir.binary("or", read(r), read(r + 1)) : read(r); auto pred = cmp((i.op & 1) ? "ne" : "eq", mask, "0"); - ir.body << " br i1 " << pred << ", label %pc" << i.target() << ", label %pc" << i.next << "\n"; + if (virtual_waves) yield_virtual_wave(select(pred,to_string(i.target()),to_string(i.next))); + else ir.body << " br i1 " << pred << ", label %pc" << i.target() << ", label %pc" << i.next << "\n"; } } else if (i.dpp_control || i.dpp8_selectors) lower_dpp(i, p.before[k], x*y*z); else if (i.name == "v_permlane16_b32" || i.name == "v_permlanex16_b32") lower_permlane(i, x*y*z); - else if (i.name == "s_endpgm") - ir.body << " ret void\n"; + else if (i.name == "s_endpgm") { + if (virtual_waves) yield_virtual_wave("4294967295"); + else ir.body << " ret void\n"; + } // Hardware scheduling and register-dependency waits have no SGPR // operands. SSA dependencies carry these constraints into DXIL. else if (i.name == "v_nop" || i.name == "s_inst_prefetch" || i.name == "s_clause" || i.name == "s_nop" || @@ -4305,8 +4572,10 @@ struct DirectCompute { memory(i, p.before[k]); else if (i.enc == Encoding::Lds) local_memory(i, lds_words); - else if (i.name == "s_barrier") - barrier(writes_uavs ? 11 : 9); // group rendezvous, LDS and, when used, UAV memory + else if (i.name == "s_barrier") { + if (virtual_waves) yield_virtual_wave(to_string(i.next | 0x80000000u)); + else barrier(writes_uavs ? 11 : 9); + } else if (i.name == "s_waitcnt_vscnt" || i.name == "s_waitcnt_vmcnt" || i.name == "s_waitcnt_lgkmcnt" || i.name == "s_waitcnt_expcnt") { // null,0 drains this wave's counter. Memory-only barriers @@ -4329,7 +4598,7 @@ struct DirectCompute { } auto &r = analysis.result; r.instruction_count = unsigned(p.code.size()); - const unsigned rank_words = x * y * z > 64 ? x * y * z : 0; + const unsigned rank_words = !virtual_waves && x * y * z > 64 ? x * y * z : 0; if ((uses_lds ? lds_words : 0) + rank_words + (uses_exchange ? exchange_words : 0) > 8192) refuse(entry, "combined shared storage exceeds 32 KiB"); // SM 6.6 forms consecutive linear quads for 1D groups. In 2D it forms @@ -4338,7 +4607,9 @@ struct DirectCompute { // The wave64 split occurs at lane 32, a quad boundary. if (compute_derivatives) ir.validator_minor = 8; - r.dxil_ir = compute_derivatives ? ir.finish_compute(x * y * z, 1, 1) : ir.finish_compute(x, y, z); + r.dxil_ir = virtual_waves ? ir.finish_compute(64, 1, 1) + : compute_derivatives ? ir.finish_compute(x * y * z, 1, 1) + : ir.finish_compute(x, y, z); return std::move(r); } }; diff --git a/src/gfx1013_direct_graphics.inl b/src/gfx1013_direct_graphics.inl index a9422b0b0..01d465034 100644 --- a/src/gfx1013_direct_graphics.inl +++ b/src/gfx1013_direct_graphics.inl @@ -467,6 +467,7 @@ struct GraphicsMaskRegions { std::map captures; std::set vertex_anchors, vertex_partitions; std::map mask_inputs; + std::map inverted_compare; std::set vertex_mask_compares, uniform_mask_tests; std::set scalar_mask_selects; std::map then_fallthroughs; @@ -524,6 +525,57 @@ struct GraphicsMaskRegions { skip.op = 0; skip.name = "s_nop"; // VGPR writes use the corresponding lane predicate. } + // A material flag is tested with a CLASS mask, then the compare bits + // are complemented before selecting an optional read. All active lanes + // take exactly one arm. Require a reaching save of the enclosing EXEC, + // side-effect-free bodies and a join that restores precisely that mask. + void pixel_class_arms(const Program &p,const std::multimap &entries) { + const auto &code=p.code; + for (size_t k=0;k+5104 || (cmp.dst&1) || + invert.name!="s_not_b64" || invert.dst!=cmp.dst || invert.src[0]!=cmp.dst || + narrow.name!="s_and_b64" || narrow.dst!=126 || narrow.src[0]!=cmp.dst || narrow.src[1]!=126 || + !skip.branch() || skip.op!=8 || skip.target()<=skip.next) continue; + const size_t middle=p.at.at(skip.target()); + const auto &otherwise=code[middle]; + const auto parent=otherwise.src[0]; + if (otherwise.name!="s_andn2_b64" || otherwise.dst!=126 || parent>104 || (parent&1) || + parent==cmp.dst || otherwise.src[1]!=126) continue; + auto pure=[](const Inst &i) { + return (local_alu(i) && !carry_destination(i)) || i.name=="s_waitcnt" || i.name=="s_nop" || + (i.enc==Encoding::Mubuf && i.name=="buffer_load_dword"); + }; + size_t end=middle+1; + while (endfirst<=code[end].pc;++it) + if (it->second!=skip.pc) external=true; + if (external) continue; + bool saved=false; + for (size_t j=k;j && !entries.count(code[j].pc);) { + const auto &prev=code[--j]; + if (prev.name=="s_mov_b64" && ((prev.dst==126 && prev.src[0]==parent) || + (prev.dst==parent && prev.src[0]==126))) {saved=true; break;} + const auto w=scalar_width(prev); + if (prev.branch() || prev.name.find("exec")!=Name::npos || carry_destination(prev) || + (w && ((prev.dst126))) break; + } + if (!saved) continue; + inverted_compare[invert.pc]=1024+cmp.pc; + mask_inputs[narrow.pc]=1024+invert.pc; + const unsigned predicate=1024+narrow.pc; + branch_saves[narrow.pc]=predicate; + lane_branches.emplace(skip.pc,std::make_pair(predicate,false)); + branch_merges[otherwise.pc]=branch_merges[code[end].pc]=predicate; + then_fallthroughs[code[middle-1].pc]=code[end].pc; + expired[otherwise.pc].insert(128); + expired[code[end].pc].insert(128); + } + } void vertex_scalar_tails(const Program &p, const std::multimap &entries) { const auto &code = p.code; for (size_t k=0; k+2narrow.next) { + // A material lookup can reuse an earlier saved EXEC across + // independent arithmetic, including reads of other SGPRs. + const auto &other=program.code[program.at.at(narrow.target())]; + if (other.name==(wave32 ? "s_andn2_b32" : "s_andn2_b64") && other.dst==126 && other.src[1]==126 && + other.src[0]<=(wave32 ? 105u : 104u) && (wave32 || !(other.src[0]&1))) { + const unsigned parent=other.src[0]; + for (size_t j=k; j && !entries.count(program.code[j].pc);) { + const auto &prev=program.code[--j]; + if (prev.name==mov && ((prev.dst==126 && prev.src[0]==parent) || + (prev.dst==parent && prev.src[0]==126))) { + save.dst=parent; + refilter=true; + break; + } + const auto n=scalar_width(prev); + auto changes=[&](unsigned r) {return n && prev.dst> 4) & 63) < 8) || + i.name == "s_waitcnt" || i.name == "s_endpgm"; + })) + continue; + } const bool captured = cmpx && capture.name == "s_and_b64" && capture.dst <= 104 && !(capture.dst & 1) && ((capture.src[0] == 106 && capture.src[1] == 126) || (capture.src[0] == 126 && capture.src[1] == 106)); const auto middle = join + captured; @@ -713,8 +812,24 @@ struct GraphicsMaskRegions { // gfx2hlsl.py's EXECZ analysis both require that scalar effects // of a skipped arm cannot escape. Here the branch guards reads // and the merge invalidates scalar definitions from either arm. - const bool branched = cmpx || from_mask || saved_mask || (vertex && std::any_of(program.code.begin()+begin,program.code.begin()+end, + // A pixel material selection can load different scalar records on the + // two sides of SAVEEXEC. The loads are read-only, and each invocation + // needs only the VGPR values selected by its own bit after reconvergence. + bool pixel_records = !vertex && two_arms && !cmpx && !from_mask && !saved_mask && !split; + bool has_scalar_load = false; + for (size_t j=begin; pixel_records && j=8 && v.dst+memory_count(v)<=106; + has_scalar_load |= load; + pixel_records = load || local_alu(v) || v.name=="s_waitcnt" || v.name=="s_nop" || v.name=="s_clause" || + (v.name=="s_add_u32" && v.dst<=105) || + (v.enc==Encoding::Vopc && v.dst<=106 && !(v.dst&1) && v.name.substr(0,6)=="v_cmp_" && + !v.subword && !v.scale && !v.clamp && !v.dpp_control); + } + const bool branched = (pixel_records && has_scalar_load) || cmpx || from_mask || saved_mask || (vertex && std::any_of(program.code.begin()+begin,program.code.begin()+end, [&](const Inst &i) {return i.branch() && (!two_arms || i.pc != else_skip.pc);})); + if (refilter && !(pixel_records && has_scalar_load)) continue; if (branched) { for (auto it = entries.upper_bound(save.pc); it != entries.end() && it->first <= restore.pc; ++it) { const unsigned dst = it->first, src = it->second; @@ -724,7 +839,9 @@ struct GraphicsMaskRegions { if (src < start || src >= limit || dst < start || dst > limit || dst <= src) refuse(dst, "branch enters or crosses a masked vertex arm"); } - std::set first_writes{106,107,128}, second_writes{106,107,128}; + const std::set implicit_writes = pixel_records && has_scalar_load ? + std::set{128} : std::set{106,107,128}; + auto first_writes = implicit_writes, second_writes = implicit_writes; for (size_t j=begin; j graphics_blocks(const Program &program, const GraphicsMaskRegions ®ions) { @@ -1286,10 +1412,11 @@ struct GraphicsFullWave { }; #include "gfx1013_graphics_wqm.inl" +#include "gfx1013_pixel_waterfall.inl" NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = 0, unsigned first_sampler = 0, const GraphicsConstantLayout *linked_constants = nullptr, - const D3D12_ROOT_SIGNATURE_DESC1 &layout = {}, unsigned first_uav = 0) { + const D3D12_ROOT_SIGNATURE_DESC1 &layout = {}, unsigned first_uav = 0, bool pixel_heap = false) { Program program; Emit emitter{{}, program, layout}; emitter.srv = first_srv; @@ -1297,7 +1424,9 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = emitter.first_sampler = first_sampler; DirectCompute alu{emitter}; const bool pixel = stage.stage == GpuStage::ps; + alu.graphics_interface = &stage; alu.pixel_stage = pixel; + alu.pixel_heap_enabled = pixel_heap && pixel; alu.perspective_center_pair = pixel && (stage.pixel_input_address & 3) == 2 && (stage.pixel_input_enable & 2) != 0; if (pixel && !(stage.pixel_input_address >> 16)) for (unsigned b = 0; b < 16; ++b) @@ -1313,6 +1442,23 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = std::set assigned; for (const auto &input : stage.inputs) { unsigned at = input.user_data; + if (input.type == 5 && alu.pixel_heap_enabled) { + if (!(layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) || + at >= 106 || input.sgpr_count != 1 || input.offset_dwords || !assigned.insert(at).second) + refuse(0, "invalid graphics resource heap input"); + initial[at] = {Symbol::Type::table, compute_resource_heap}; + continue; + } + if (input.type == 6) { + // Offline single-stage jobs may omit the root signature. An unused + // heap does not require a binding; any actual load stays unbound. + if (!(layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED)) + continue; + if (at >= 106 || input.sgpr_count != 1 || input.offset_dwords || !assigned.insert(at).second) + refuse(0, "invalid graphics sampler heap input"); + initial[at].type = Symbol::Type::sampler_heap; + continue; + } if (input.type == 1) { bind_root_address(initial, input, 106); assigned.insert(at); @@ -1406,6 +1552,8 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = } } } + PixelWaterfalls waterfalls; + if (pixel) waterfalls.find(program,stage.wave32); PixelWqm wqm; if (pixel) { wqm.raster_guard(program,stage.wave32); @@ -1450,7 +1598,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = auto terminal_mask = std::find_if_not(program.code.rbegin(),program.code.rend(),color_tail); auto lane_local = [](const Inst &i) { if (i.enc == Encoding::Sopp) return !i.branch(); - if (i.enc == Encoding::Interp || i.enc == Encoding::Export) return true; + if (i.enc == Encoding::Interp || i.enc == Encoding::Export || i.enc == Encoding::Mix) return true; if (i.enc == Encoding::Sop1) return i.name == "s_mov_b64" || i.name == "s_mov_b32"; if (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vop3 || i.enc == Encoding::Vopc) return !i.dpp_control && i.name.find("lane") == Name::npos && i.name.find("mbcnt") == Name::npos; @@ -1467,6 +1615,11 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = bool scalar_entry = true; std::set uniform_vector_values; std::set uniform_vcc_values; + // A slot index needs a finite material range for relocation. Track bounds + // by SSA value so SGPR/VGPR clobbers and control-flow joins cannot reuse + // a proof about an earlier definition of the same register. + struct IndexRange { unsigned first, last, zero_bits; }; + std::map heap_ranges; auto scalar_operand = [](unsigned s) { return s <= 105 || (s >= 128 && s <= 248) || s == 255; }; auto covered_lane = [&] { auto helper = alu.ir.invoke("i1","isHelperLane.i1",221,{},"nounwind readonly"); @@ -1476,6 +1629,28 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = GraphicsFullWave full_wave{alu, stage.wave32 ? 32u : 64u}; auto instruction = [&](const Inst &i, const State &state) { const auto pc = alu.graphics_pc = graphics.pc = i.pc; + if (waterfalls.restores.count(pc)) return; + if (auto dead=waterfalls.poisoned.find(pc);dead!=waterfalls.poisoned.end()) + for (unsigned reg:dead->second) alu.write(reg,{}); + if (waterfalls.exits.count(pc)) alu.write(128,"0"); // no remaining lanes + if (auto access=waterfalls.accesses.find(pc);access!=waterfalls.accesses.end()) { + const auto &which=access->second; + auto key=alu.read(which.key); + auto range=heap_ranges.find(key); + if (range==heap_ranges.end() || (which.key_is_bytes && (range->second.zero_bits & 31)!=31)) + refuse(pc,"waterfall requires a bounded aligned material index"); + unsigned first=range->second.first, last=range->second.last; + if (which.key_is_bytes) { + key=alu.ir.binary("lshr",key,"5"); first >>= 5; last >>= 5; + } else if (last>0x07ffffffu) { + refuse(pc,"waterfall slot range crosses a 32-bit descriptor-byte wrap"); + } + const auto &descriptor=state.at(((i.b>>16)&31)*4); + if (descriptor.definition!=which.descriptor_pc || !alu.graphics_predicate.empty()) + refuse(pc,"waterfall requires the selected descriptor and its enclosing pixel coverage"); + alu.image_io(i,state,DirectCompute::PixelHeapIndex{key,first,last,true}); + return; + } if (pixel && full_wave.emit(i,program)) return; if (wqm.packed.count(pc) && (whole_quad || exact_after_wqm || !alu.graphics_predicate.empty())) refuse(pc, "numeric EXEC region requires exact pixel entry coverage"); @@ -1585,6 +1760,11 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = auto vertex_compare_bit = [&] { return alu.ir.value("zext i1 " + alu.comparison(i) + " to i32"); }; + if (auto at=regions.inverted_compare.find(pc);at!=regions.inverted_compare.end()) { + alu.write(1024+pc,alu.ir.binary("xor",alu.read(at->second),"1")); + alu.write(i.dst,{}); alu.write(i.dst+1,{}); alu.write(128,{}); + return; + } if (regions.vertex_mask_compares.count(pc)) { alu.write(1024+pc,vertex_compare_bit()); alu.write(i.dst,{}); alu.write(i.dst+1,{}); @@ -1718,7 +1898,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = if (!straight && pc >= prologue_end && exact_after_wqm && !exact_sample_region) refuse(pc, "exact pixel mask crosses a control-flow edge"); if (move_exec && (short_mask ? i.dst <= 105 : i.dst <= 104 && !(i.dst & 1)) && - i.src[0] == 126 && pc < prologue_end) { + i.src[0] == 126 && (pc < prologue_end || waterfalls.saves.count(pc))) { saved_exec[i.dst] = whole_quad && !exact_after_wqm; // Numeric use of either half needs actual wave-mask lowering. alu.write(i.dst,{}); @@ -1799,6 +1979,15 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = refuse(pc, "DPP fetch-inactive source requires a proven whole quad"); if (!whole_quad || exact_after_wqm) refuse(pc, "pixel quad permutation without whole-quad entry"); + if (i.enc == Encoding::QuadCompare) { + if (!pixel || !alu.graphics_predicate.empty()) + refuse(pc,"DPP compare requires all four source lanes"); + const auto first = graphics.quad_source(i); + const auto pred = alu.comparison(i,first,alu.operand32(i,i.src[1])); + alu.write(106,alu.ir.value("zext i1 "+pred+" to i32")); + if (!stage.wave32) alu.write(107,{}); + return; + } const auto op = alu_rules.find(i.name); if (i.name != "v_mov_b32" && (op == alu_rules.end() || op->second.arity > 2)) refuse(pc, "unsupported DPP arithmetic"); @@ -1821,7 +2010,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = return r.name == "X2W_RAW_VERTEX" && r.semantic_index == i.literal; }); unsigned row = prior != inputs.end() ? prior->row : static_cast(inputs.size()); - const auto id = graphics.row(true, "X2W_RAW_VERTEX", i.literal, 0, i.op == 4 ? 9 : 5, + const auto id = graphics.row(true, "X2W_RAW_VERTEX", i.literal, 0, i.a ? 9 : 5, row, (1u << i.op) - 1, 0); for (unsigned c = 0; c < i.op; ++c) alu.write(i.dst + c, graphics.load(id, c)); emitter.result.vertex_fetch=true; @@ -1986,7 +2175,46 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = const unsigned count = mac || i.name == "v_fmamk_f32" || i.name == "v_fmaak_f32" ? 2 : rule->second.arity; uniform_vertex = std::all_of(i.src.begin(),i.src.begin()+count,uniform) && (!mac || uniform(i.dst)); } + // Two complementary packed FMAs under the same EXEC define + // the entire VGPR. Its incoming bits are dead when neither operation + // also reads it as an explicit operand (Victory lower.rs: mixlo/mixhi). + const bool low = i.name == "v_fma_mixlo_f16"; + if (pixel && (low || i.name == "v_fma_mixhi_f16") && alu.graphics_predicate.empty() && + !alu.graphics_registers.count(i.dst) && !graphics.partial.count(i.dst)) { + for (size_t k = program.at.at(i.pc) + 1; k < program.code.size(); ++k) { + const auto &j = program.code[k]; + if (std::find(j.src.begin(), j.src.end(), i.dst) != j.src.end()) + break; + // A scheduled FP32 FMA accesses exactly three scalar-width + // sources and one destination. It cannot change EXEC. + if (j.name == "v_fma_f32" && j.dst != i.dst) + continue; + if (j.dst == i.dst && j.name == (low ? "v_fma_mixhi_f16" : "v_fma_mixlo_f16") && + std::find(i.src.begin(), i.src.end(), i.dst) == i.src.end()) + alu.graphics_registers.emplace(i.dst, "0"); + break; + } + } + std::optional heap_range; + if (pixel && !waterfalls.accesses.empty() && alu.graphics_predicate.empty() && !i.subword && + !i.abs && !i.neg && !i.clamp && !i.scale && !i.dpp_control && + (i.name=="v_and_b32" || i.name=="v_or_b32" || i.name=="v_lshlrev_b32")) { + for (unsigned n=0;n<2;++n) { + auto scalar=source(i,i.src[n],state); + if (scalar.type!=Symbol::Type::constant) continue; + unsigned c=scalar.value; + if (i.name=="v_and_b32") heap_range=IndexRange{0,c,~c}; + else if (auto in=heap_ranges.find(alu.operand32(i,i.src[1-n]));in!=heap_ranges.end()) { + const auto r=in->second; + if (i.name=="v_or_b32" && (r.zero_bits & c)==c) + heap_range=IndexRange{r.first|c,r.last|c,r.zero_bits & ~c}; + if (i.name=="v_lshlrev_b32" && n==0 && c<32 && r.last<=(UINT_MAX>>c)) + heap_range=IndexRange{r.first< 128 || !layout.max_vertices || layout.max_vertices > 256 || + !layout.max_primitives || layout.max_primitives > 256 || layout.topology != 2 || + code.empty() || code.size() % 4) + refuse(0,"unsupported mesh group, output dimensions or topology"); + Program program; + // This subset has a single forward path after the proven exchange. + // The shared ALU's SGPR provenance lookup uses the current state. + program.graphics_wave64=!layout.wave32; + program.before.emplace_back(); + for (auto &s : program.before.front()) s.type=Symbol::Type::unbound; + Emit emitter{{},program,root}; + DirectCompute alu{emitter}; + GuestShaderStage fixed_outputs{}; + fixed_outputs.output_signature.push_back({"SV_Position",0,1,3,0,15,15}); + GraphicsStage graphics{reflected ? *reflected : fixed_outputs,alu,false}; + auto &ir = alu.ir; + ir.mesh_vertices = layout.max_vertices; + ir.mesh_primitives = layout.max_primitives; + auto thread = ir.invoke("i32","flattenedThreadIdInGroup.i32",96,{},"nounwind readnone"); + const unsigned width = layout.wave32 ? 32 : 64; + const auto wave_lane = ir.binary("and",thread,to_string(width-1)); + const auto wave_number = ir.binary("lshr",thread,layout.wave32 ? "5" : "6"); + alu.graphics_input = [&](unsigned r) -> string { + refuse(alu.graphics_pc,"unproven mesh entry register " + to_string(r)); + }; + alu.after_graphics_write = [&](unsigned r) { + if (r<106) program.before.front()[r].type=alu.graphics_registers.at(r).empty() ? + Symbol::Type::unbound : Symbol::Type::unknown; + }; + auto &state=program.before.front(); + auto inputs=layout.root_inputs; + auto heap=layout.resource_heap_sgpr; + if (reflected) { + for (const auto &input : reflected->inputs) { + if (input.type==5) { + if (heap) refuse(0,"duplicate mesh resource heap"); + heap=reflected->physical_user_sgpr(input.user_data); + } + if (input.type==1) inputs.push_back({reflected->physical_user_sgpr(input.user_data),input.root_parameter,0,true}); + if (input.type==0 || input.type==3) + inputs.push_back({reflected->physical_user_sgpr(input.user_data),input.root_parameter, + input.type==0 ? input.sgpr_count : 0}); + } + } + for (const auto &input : inputs) { + const auto at=input.sgpr, param=input.root_parameter, count=input.constant_count; + if (at<8 || at>=106 || count>106-at || param>=16) + refuse(0,"mesh root input outside user SGPR range"); + if (!reflected || root.NumParameters) { + if (param>=root.NumParameters) refuse(0,"missing mesh root parameter"); + const auto &binding=root.pParameters[param]; + if (input.root_address ? binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_SRV : + count ? (binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS || + binding.Constants.Num32BitValues!=count) : + binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + refuse(0,"mesh root parameter kind or size disagrees with entry"); + } + if (input.root_address) { + if (count || at+1>=106 || state[at].type!=Symbol::Type::unbound || state[at+1].type!=Symbol::Type::unbound) + refuse(0,"invalid mesh root address pair"); + state[at]={Symbol::Type::root_address,param,0}; + state[at+1]={Symbol::Type::root_address,param,1}; + } else if (!count) { + const Symbol table{Symbol::Type::table,param}; + if (state[at].type!=Symbol::Type::unbound && !(state[at]==table)) + refuse(0,"overlapping mesh entry table"); + state[at]=table; + } else { + for (unsigned j=0;j=106 || state[*heap].type!=Symbol::Type::unbound) refuse(0,"invalid mesh resource heap SGPR"); + state[*heap]={Symbol::Type::table,compute_resource_heap}; + } + alu.initialize_constants(); + struct RootBits { unsigned param, dword, mask, shift; }; + std::map root_values; + std::map heap_fetches; + for (const auto &block : emitter.result.constants) + for (unsigned j=0;j uniform_values; + string exec_value[2], wave_active, lane_active; + std::map> active_uniform, mask_uniform; + auto uniform=[&](const string &v) -> string { + if (v.empty()) return {}; + if (v.find_first_not_of("0123456789-")==string::npos || uniform_values.count(v)) return v; + auto it=active_uniform.find(v); return it==active_uniform.end() || it->second.first!=lane_active ? string{} : it->second.second; + }; + auto remember_scalar=[&](unsigned r) { + const auto it=alu.graphics_registers.find(r); + if (it!=alu.graphics_registers.end() && !it->second.empty()) uniform_values.insert(it->second); + }; + std::set wave_bases, low_group, low_lane, whole_lane, linear_threads; + std::set partial_writes; + bool full_exec = true, allocated = false, position = false, indices = false; + std::set parameter_exports; + std::optional allocation_word; + unsigned vertices = 0, primitives = 0; + string vertex_count, primitive_count, export_limit; + std::map upper_bound; + auto bound=[&](const Inst &op,unsigned source) { + if (auto c=constant32(op,source)) return *c; + auto it=alu.graphics_registers.find(source); + if (it!=alu.graphics_registers.end() && upper_bound.count(it->second)) return upper_bound.at(it->second); + return ~0u; + }; + string exchanged_group; + if (layout.group_stride) { + const auto group = ir.invoke("i32","groupId.i32",94,{{"i32","0"}},"nounwind readnone"); + exchanged_group = ir.binary("mul",group,to_string(layout.group_stride)); + } + unsigned scope = 0; + auto guarded = [&](const string &limit, auto body) { + auto tag = to_string(scope++); + auto pred = alu.cmp("ult",thread,limit); + ir.body << " br i1 " << pred << ", label %mesh_write" << tag << ", label %mesh_next" << tag + << "\nmesh_write" << tag << ":\n"; + body(); + ir.body << " br label %mesh_next" << tag << "\nmesh_next" << tag << ":\n"; + }; + // Scalar forward if/else only. Keep both predecessor register files so + // a value live after the join is selected from the edge that wrote it. + struct Edge { + State symbols; + decltype(alu.graphics_registers) regs; + string group; + std::set partial; + }; + struct Diamond { + unsigned start, alternate, join; + Edge entry, first; + }; + std::optional branch; + unsigned lane_else=0; + constexpr unsigned vcc_words=0x70000000, vcc_nonempty=vcc_words+2; + std::map mask_parent; + auto covered_by=[&](string current,const string &ancestor) { + if (ancestor.empty()) return true; + while (current!=ancestor) { + auto it=mask_parent.find(current); + if (it==mask_parent.end()) return false; + current=it->second; + } + return true; + }; + auto terminate_arm=[&](unsigned start,bool first) { + const string edge=(first ? "mesh_then_end" : "mesh_else_end")+to_string(start); + ir.body<<" br label %"< partial; }; + std::map saved_exec; + std::map before_narrowing; + auto saved_mask=[&](unsigned source)->const MaskState * { + if (source>104 || (source&1)) return nullptr; + const auto &lo=state[source], &hi=state[source+1]; + if (lo.type!=Symbol::Type::lane_mask || hi.type!=lo.type || lo.offset || hi.offset!=1 || lo.value!=hi.value) + return nullptr; + const auto it=saved_exec.find(lo.value); return it==saved_exec.end() ? nullptr : &it->second; + }; + auto pure_lane_arm=[&](unsigned begin,unsigned end) { + for (auto at=begin;at=256 && (inst.enc==Encoding::Vop1 || inst.enc==Encoding::Vop2 || inst.enc==Encoding::Vop3); + const bool compare=inst.enc==Encoding::Vopc && inst.dst==106 && inst.name.substr(0,6)=="v_cmp_"; + const bool literal=inst.name=="s_mov_b32" && inst.dst<106 && constant32(inst,inst.src[0]); + if ((!vector && !compare && !literal && inst.name!="s_nop") || inst.next<=at || inst.next>end) + return false; + at=inst.next; + } + return true; + }; + // Prove scalar dependencies when two mutually exclusive lane arms + // gather uniform buffer records. Scalar registers execute per wave, so + // the inverse arm may observe the first arm's writes unless it defines + // them itself before first use. + struct GatherArm { std::set writes, inputs; }; + auto gather_arm=[&](unsigned begin,unsigned end)->std::optional { + GatherArm arm; + auto use=[&](unsigned r) { if (r<=107 && !arm.writes.count(r)) arm.inputs.insert(r); }; + for (unsigned at=begin;atend || op.subword || op.dpp_control) return {}; + if (op.name=="s_add_u32" && op.dst<106) { + use(op.src[0]); use(op.src[1]); arm.writes.insert(op.dst); arm.writes.insert(128); + } else if (op.enc==Encoding::Smem && op.op==12 && op.dst+16<=106) { + for (unsigned j=0;j<4;++j) use(op.src[0]+j); + use(op.b>>25); + for (unsigned j=0;j<16;++j) arm.writes.insert(op.dst+j); + } else if (op.enc==Encoding::Vopc && op.name=="v_cmp_gt_i32" && op.dst<=106 && !(op.dst&1)) { + use(op.src[0]); use(op.src[1]); arm.writes.insert(op.dst); arm.writes.insert(op.dst+1); + } else if (op.name=="v_mov_b32" && op.dst>=256) use(op.src[0]); + else if (op.name=="v_cndmask_b32" && op.dst>=256 && op.src[2]<=106) { + use(op.src[0]); use(op.src[1]); use(op.src[2]); use(op.src[2]+1); + } else if (op.name!="s_waitcnt") return {}; + at=op.next; + } + return arm; + }; + std::set lane_scalar_clobbers; + struct Skip { unsigned start,end; Edge entry; bool per_lane; string guard; }; + std::vector skip_parents; + std::optional exec_skip; + unsigned mask_generation=0x1000000; + auto merge_edges=[&](const Edge &first, const string &l, const string &r) { + auto phi=[&](const string &a,const string &b) {return ir.value("phi i32 [ "+a+", %"+l+" ], [ "+b+", %"+r+" ]");}; + std::map> masks; + for (unsigned reg=0;reg<=104;reg+=2) { + const auto bit=[&](const Symbol &s,const auto ®s) -> string { + if ((s.type!=Symbol::Type::lane_mask && s.type!=Symbol::Type::uniform_mask) || s.offset) return {}; + auto it=regs.find(1024+s.value);return it==regs.end() ? string{} : it->second; + }; + const auto a=bit(first.symbols[reg],first.regs), b=bit(state[reg],alu.graphics_registers); + if (a.empty() || b.empty() || first.symbols[reg]==state[reg]) continue; + if (!layout.wave32 && (first.symbols[reg+1].value!=first.symbols[reg].value || + state[reg+1].value!=state[reg].value || first.symbols[reg+1].offset!=1 || state[reg+1].offset!=1 || + first.symbols[reg+1].type!=first.symbols[reg].type || state[reg+1].type!=state[reg].type)) continue; + const auto id=mask_generation++; + masks.emplace(reg,std::make_pair(Symbol{Symbol::Type::lane_mask,id,0},a==b ? a : phi(a,b))); + } + for (const auto &[reg,v] : first.regs) alu.graphics_registers.try_emplace(reg); + for (auto &[reg,v] : alu.graphics_registers) { + const auto a=first.regs.find(reg); + if (a==first.regs.end() || a->second.empty() || v.empty()) v.clear(); + else if (a->second!=v) { + const auto av=uniform(a->second), bv=uniform(v); + v=phi(a->second,v); + if (!lane_else && !av.empty() && !bv.empty()) active_uniform[v]={lane_active,av==bv ? av : phi(av,bv)}; + } + } + for (unsigned j=0;j> forward; + bool live=true; + unsigned next_edge=0; + auto arrive=[&](unsigned target) { + string label="mesh_edge"+to_string(next_edge++); + forward[target].push_back({save_edge(),label,lane_active,wave_active,full_exec}); + return label; + }; + auto restore=[&](const Edge &e) { + state=e.symbols; alu.graphics_registers=e.regs; exchanged_group=e.group; partial_writes=e.partial; + }; + unsigned pc = 0; + while (pc < code.size()) { + // All handled scalar branches are forward, so every predecessor is + // available when we reach its target. Funnel arbitrary fan-in into + // binary PHI blocks, preserving descriptor and mask provenance too. + if (!live && !forward.count(pc)) { + auto next=forward.lower_bound(pc); + if (next==forward.end()) refuse(pc,"mesh forward branch has no reachable successor"); + pc=next->first; + } + if (forward.count(pc)) { + if (live) ir.body<<" br label %"<end) { + const auto tag=to_string(exec_skip->start); + ir.body<<" br label %mesh_done"<per_lane) { + // A SALU write was made by each active wave. Inactive lanes + // skipped that invocation; deny later reads of changed scalar + // definitions. Vector values keep their actual incoming edge. + for (unsigned r=0;r<=128;++r) { + auto now=alu.graphics_registers.find(r), old=exec_skip->entry.regs.find(r); + if (now!=alu.graphics_registers.end() && (old==exec_skip->entry.regs.end() || now->second!=old->second)) { + now->second.clear(); + if (r<128) state[r].type=Symbol::Type::unbound; + } + } + } + merge_edges(exec_skip->entry,"mesh_empty"+tag,"mesh_done"+tag); + exec_skip.reset(); + if (!skip_parents.empty()) { + exec_skip=std::move(skip_parents.back());skip_parents.pop_back(); + if (pc==exec_skip->end) continue; + } + } + if (branch && pc==branch->alternate) { + if (pc==branch->join || lane_else) { + branch->first=save_edge(); + terminate_arm(branch->start,true); + } + const auto &entry=branch->entry; + state=entry.symbols; + alu.graphics_registers=entry.regs; + exchanged_group=entry.group; + partial_writes=entry.partial; + ir.body<<"\nmesh_else"<start<<":\n"; + if (lane_else) { pc=lane_else; continue; } + } + if (branch && pc==branch->join) { + const auto &first=branch->first; + terminate_arm(branch->start,false); + ir.body<<"mesh_join"<start<<":\n"; + if (lane_else) { + // A scalar literal in a nonempty wave may be written even + // for its inactive lanes. Refuse later numeric use unless a + // subsequent definition overwrites it. VCC is wave-wide too. + for (unsigned r=0;r<=128;++r) { + const auto old=branch->entry.regs.find(r); + const auto differs=[&](const auto ®s) { + auto v=regs.find(r); + return v!=regs.end() && (old==branch->entry.regs.end() || v->second!=old->second); + }; + if (differs(first.regs) || differs(alu.graphics_registers)) { + alu.graphics_registers[r].clear(); + if (r<106) state[r].type=Symbol::Type::unbound; + } + } + lane_else=0; + } + merge_edges(first,"mesh_then_end"+to_string(branch->start),"mesh_else_end"+to_string(branch->start)); + for (auto r:lane_scalar_clobbers) { + alu.write(r,{}); + if (r= 64) { + const Word save = word(code,pc+4), mask = word(code,pc+8); + constexpr Word tail[]{0x0f000000,0xbf850007,0x2c0a0a87,0x7e000280,0xd8340008,0x500, + 0xbfa3ffe3,0xbf8a0000,0xbf820004,0xbf8a0000,0x7e000280,0xd8d80008,0x05000000}; + bool exchange = (save & 0xff80ffff) == 0xbe80047e && (mask & 0xff80ffff) == 0x8700ff03; + for (unsigned k=0;k>16)&127, temp = (mask>>16)&127; + if (exchange && !branch && !exec_skip && full_exec && !layout.wave32 && layout.group_stride && !alu.graphics_registers.count(3) && + !alu.graphics_registers.count(261) && saved<=104 && !(saved&1) && temp<106 && + temp!=saved && temp!=saved+1) { + alu.write(saved,"1"); + alu.write(saved+1,"0"); + const auto merged = ir.binary("shl",wave_number,"24"); + alu.write(temp,merged); + alu.write(128,ir.value("zext i1 "+alu.cmp("ne",merged,"0")+" to i32")); + if (exchanged_group.empty()) refuse(pc,"mesh exchange lost the entry group VGPR"); + exchanged_group = ir.binary("lshr",exchanged_group,"7"); + alu.write(256,{}); + alu.write(261,{}); + full_exec=false; + pc+=64; + continue; + } + } + // A wave-zero producer sends GS_ALLOC_REQ and shares its two count + // SGPRs with the other waves through LDS. Verify the complete + // sequence, including both rendezvous, every LDS offset and every + // def-use edge before replacing it with group-shared DXIL. + if (raw==0xbf8a0000 && pc+128<=code.size() && !allocated && !branch && !exec_skip && forward.empty()) { + auto w=[&](unsigned n) { return word(code,pc+4*n); }; + const unsigned wave=w(1)&127, mask=w(3)&127, p=w(5)&255, v=w(7)&255; + const unsigned data=(w(5)>>17)&255, addr=(w(6)>>17)&255, vdata=(w(7)>>17)&255; + const unsigned temp=(w(15)>>16)&127, rp=(w(24)>>24)&255, rv=(w(26)>>24)&255; + const unsigned raddr=(w(22)>>17)&255; + const auto vector_mov=[](unsigned dst,unsigned src) { return 0x7e000200u|(dst<<17)|src; }; + bool match=w(1)==(0xbf008000u|wave) && w(2)==0xbf840010 && w(3)==(0xbefe0400u|mask) && + w(4)==0xbf880007 && w(5)==vector_mov(data,p) && w(6)==vector_mov(addr,128) && + w(7)==vector_mov(vdata,v) && data!=addr && addr!=vdata && vdata!=data && + w(8)==0xd8340000 && w(9)==((data<<8)|addr) && w(10)==0xd8340004 && w(11)==((vdata<<8)|addr) && + w(12)==0xbefe04c1 && w(13)==0xbfa3ffe3 && w(14)==0xbf8a0000 && + w(15)==(0x8f008c00u|(temp<<16)|p) && w(16)==(0x887c0000u|(v<<8)|temp) && + w(17)==0xbf900009 && w(18)==0xbf82000d && w(19)==0xbf8a0000 && w(20)==w(3) && w(21)==0xbf880009 && + w(22)==vector_mov(raddr,128) && w(23)==0xd8d80000 && w(24)==((rp<<24)|raddr) && + w(25)==0xd8d80004 && w(26)==((rv<<24)|raddr) && rp!=rv && rp!=raddr && + w(27)==0xbf8cc17f && w(28)==(0x7e000500u|(p<<17)|rp) && w(29)==0xbf8cc07f && + w(30)==(0x7e000500u|(v<<17)|rv) && w(31)==0xbefe04c1; + if (match) { + if (mask>104 || (mask&1) || p>=106 || v>=106 || p==v || temp>=106 || temp==v || + alu.read(wave)!=wave_number || alu.read(mask)!="1" || alu.read(mask+1)!="0") + refuse(pc,"unproven mesh count exchange wave or lane-zero mask"); + auto input_v=alu.read(v), input_p=alu.read(p); + if (!upper_bound.count(input_v) || !upper_bound.count(input_p) || + upper_bound.at(input_v)>(std::min)(layout.max_vertices,layout.threads) || + upper_bound.at(input_p)>(std::min)(layout.max_primitives,layout.threads)) + refuse(pc,"mesh count exchange exceeds declared range or lacks an unsigned bound"); + ir.globals<<"@meshCounts = internal addrspace(3) global [2 x i32] undef, align 4\n"; + auto ptr0=alu.shared_address("meshCounts",2,"0"),ptr1=alu.shared_address("meshCounts",2,"1"); + alu.barrier(); + guarded("1",[&] { + ir.body<<" store i32 "<>16)&127)==124))) + refuse(pc,"mesh scalar branch crosses allocation, EXEC or export"); + if (op.name=="s_endpgm") { + if (!allocated || !position || !indices) refuse(pc,"mesh ended without complete position and triangle exports"); + ir.body << " ret void\n"; + emitter.result.dxil_ir=ir.finish_compute(layout.threads,1,1,"ms"); + emitter.result.group={layout.threads,1,1}; + for (const auto &sig : ir.outputs) + emitter.result.outputs.push_back({sig.name,sig.semantic_index,sig.row,sig.first,sig.width, + sig.component,sig.used,sig.kind,sig.interpolation}); + return std::move(emitter.result); + } + if (op.name=="s_nop" || op.name=="v_nop" || op.name=="s_clause" || op.name=="s_inst_prefetch" || + op.name=="s_waitcnt" || op.name=="s_waitcnt_depctr" || op.name=="s_setprio") { + pc+=op.size; + continue; + } + // HW_REG_FLAT_SCR_LO / HI are not numeric SGPRs. Scratch accesses + // and hardware-register reads are still rejected at their own PCs. + if (raw == 0xba80f814 || raw == 0xba80f815) { + pc += op.size; + continue; + } + if (raw==0xbf900009) { + if (allocated || !allocation_word) refuse(pc,"mesh allocation requires one uniform, bounded m0 count word"); + vertices=*allocation_word & 4095; primitives=(*allocation_word>>12)&4095; + if ((*allocation_word>>24) || vertices>layout.max_vertices || primitives>layout.max_primitives || + vertices>layout.threads || primitives>layout.threads || (!vertices && primitives)) + refuse(pc,"mesh allocation exceeds declared lane-indexed output range"); + ir.invoke("void","setMeshOutputCounts",168,{{"i32",to_string(vertices)},{"i32",to_string(primitives)}},"nounwind"); + vertex_count=to_string(vertices); primitive_count=to_string(primitives); + allocated=true; pc+=4; continue; + } + if (op.form==gfx1013::Form::exp) { + const unsigned target=(raw>>4)&63, channels=raw&15; + if ((!full_exec && (export_limit.empty() || !exec_skip || exec_skip->guard!=lane_active || + export_limit!=(target==20 ? primitive_count : vertex_count))) || !allocated || (raw&0x400)) + refuse(pc,"unsupported mesh export mask or allocation"); + const auto sources=word(code,pc+4); + if ((target==12 && channels==15 && !position) || + (target>=32 && channels && parameter_exports.insert(target).second)) { + position |= target==12; + graphics.pc=pc; + guarded(vertex_count,[&] { + for (unsigned c=0;c<4;++c) { + if (!(channels & (1u<=32) { + // Identical fixed-pipeline convention to the raw PS + // interpolator: semantic index = 4 * PARAM + channel. + const unsigned id=4*(target-32)+c; + const unsigned reg=1+(layout.packed_parameters ? target-32 : id); + if (reg>=32) refuse(pc,"raw mesh PARAM exceeds signature registers"); + const auto row=static_cast(reg), bit=static_cast(1u<(target-32),0,0}); + fixed_outputs.output_signature.push_back({"TEXCOORD",id,0,3,row,bit,bit}); + } + unsigned channel=c; + const auto id=graphics.output(target,channel); + auto &sig=ir.outputs.at(id); + const unsigned col=channel-sig.first; + auto bits=alu.read(256+((sources>>(8*c))&255)); + const bool fp=sig.component==9; + ir.invoke("void",fp ? "storeVertexOutput.f32" : "storeVertexOutput.i32",171, + {{"i32",to_string(id)},{"i32","0"},{"i8",to_string(col)}, + {fp ? "float" : "i32",fp ? ir.value("bitcast i32 "+bits+" to float") : bits}, + {"i32",thread}},"nounwind"); + sig.used|=1u< triangle; + for (unsigned c=0;c<3;++c) { + triangle[c]=ir.binary("and",ir.binary("lshr",packed,to_string(10*c)),"1023"); + culled=ir.value("or i1 "+culled+", "+alu.cmp("uge",triangle[c],to_string(vertices))); + } + ir.invoke("void","emitIndices",169,{{"i32",thread},{"i32",alu.select(culled,"0",triangle[0])}, + {"i32",alu.select(culled,"0",triangle[1])},{"i32",alu.select(culled,"0",triangle[2])}},"nounwind"); + }); + } else refuse(pc,"unmapped mesh export target "+to_string(target)); + pc+=op.size; continue; + } + const auto i=decode(code,pc,true,op.form!=gfx1013::Form::mtbuf); + std::optional result_bound; + if (i.name=="s_and_b32") result_bound=(std::min)(bound(i,i.src[0]),bound(i,i.src[1])); + if (i.name=="s_bfe_u32") { + if (auto field=constant32(i,i.src[1]); field && ((*field>>16)&127)<32) + result_bound=(1u<<((*field>>16)&127))-1; + } + if (i.name=="s_add_u32") { + uint64_t sum=uint64_t(bound(i,i.src[0]))+bound(i,i.src[1]); + if (sum<=UINT32_MAX) result_bound=static_cast(sum); + } + if (i.name=="s_cselect_b32") result_bound=(std::max)(bound(i,i.src[0]),bound(i,i.src[1])); + const unsigned vec_dst=i.enc==Encoding::Mubuf ? 256+i.dst : i.dst; + std::array before_vec; + std::array before_partial{}; + if (!full_exec && !lane_active.empty() && vec_dst>=256 && vec_dst<512) { + for (unsigned j=0;j<4;++j) { + const auto old=alu.graphics_registers.find(vec_dst+j); + if (old!=alu.graphics_registers.end()) before_vec[j]=old->second; + before_partial[j]=partial_writes.count(vec_dst+j)!=0; + } + } + const bool export_cmp=i.name=="v_cmpx_gt_i32" && allocated && i.src[0]<106 && full_exec && + (alu.read(i.src[0])==vertex_count || alu.read(i.src[0])==primitive_count); + if ((i.name=="v_cmpx_gt_u32" || export_cmp) && full_exec && !branch && !exec_skip && i.enc==Encoding::Vopc && !i.wide && !i.subword && !i.dpp_control && + i.src[0]<106 && linear_threads.count(alu.operand32(i,i.src[1]))) { + // Lane-linear count comparison in a merged workgroup. Construct + // both halves from the guest wave start, independent of native + // WaveGetLaneCount. Saturation avoids shifts by 32 or unsigned + // underflow when the last group wave is empty. + const auto limit=alu.operand32(i,i.src[0]); + export_limit=export_cmp ? limit : string{}; + const auto capped=alu.select(alu.cmp("ult",limit,to_string(layout.threads)),limit,to_string(layout.threads)); + const auto base=ir.binary("sub",thread,wave_lane); + wave_active=alu.cmp("ugt",capped,base); + lane_active=alu.cmp("ult",thread,capped); + for (unsigned j=0;j<2;++j) { + if (j && layout.wave32) { exec_value[j]="0"; continue; } + const auto begin=j ? ir.binary("add",base,"32") : base; + const auto n=alu.select(alu.cmp("ugt",capped,begin),ir.binary("sub",capped,begin),"0"); + const auto bits=ir.binary("sub",ir.binary("shl","1",ir.binary("and",n,"31")),"1"); + exec_value[j]=alu.select(alu.cmp("uge",n,"32"),"4294967295",bits); + } + full_exec=false; + } else if (i.name=="v_cmpx_gt_i32" && !branch && exec_skip && !lane_active.empty() && + i.enc==Encoding::Vopc && !i.wide && !i.subword && !i.dpp_control) { + const auto a=decode(code,i.next,true,true); + if (a.name!="s_cbranch_execz" || a.target()<=a.next || a.target()>=code.size()) + refuse(pc,"mesh signed CMPX requires paired EXECZ arms"); + const auto inverse=decode(code,a.target(),true,true); + const auto b=decode(code,inverse.next,true,true); + if (inverse.name!="s_andn2_b64" || inverse.dst!=126 || inverse.src[1]!=126 || inverse.src[0]>104 || + b.name!="s_cbranch_execz" || b.target()<=b.next || b.target()>=code.size() || + !pure_lane_arm(a.next,a.target()) || !pure_lane_arm(b.next,b.target())) + refuse(pc,"mesh CMPX arms contain an unproven wave effect"); + const auto mask=saved_mask(inverse.src[0]); + if (!mask || mask->lane!=lane_active || mask->wave!=wave_active || mask->full!=full_exec) + refuse(pc,"mesh CMPX inverse lacks the saved parent EXEC"); + branch=Diamond{pc,a.target(),b.target(),save_edge(),{}}; + lane_else=b.next; + auto take=alu.comparison(i); + ir.body<<" br i1 "<i.next && i.target()exec_skip->end) refuse(pc,"overlapping mesh EXECZ exits"); + skip_parents.push_back(std::move(*exec_skip)); + } + exec_skip=Skip{pc,i.target(),save_edge(),wave_active.empty(),lane_active}; + ir.body<<" br i1 "<<(wave_active.empty() ? lane_active : wave_active)<<", label %mesh_work"<=code.size() || + (exec_skip && other>exec_skip->end)) + refuse(pc,"unsupported mesh scalar branch destination"); + for (unsigned at=i.next;atother) refuse(pc,"mesh branch target splits instruction"); + at=next; + } + const bool vcc=i.name=="s_cbranch_vccz" || i.name=="s_cbranch_vccnz"; + string value; + if (!vcc) value=alu.read(128); + else { + auto nonempty=alu.graphics_registers.find(vcc_nonempty); + if (nonempty!=alu.graphics_registers.end() && !nonempty->second.empty()) value=nonempty->second; + else { + auto lo=alu.graphics_registers.find(vcc_words), hi=alu.graphics_registers.find(vcc_words+1); + if (lo==alu.graphics_registers.end() || lo->second.empty() || + hi==alu.graphics_registers.end() || hi->second.empty()) + refuse(pc,"mesh VCC branch lacks a proven guest whole-wave mask"); + value=ir.binary("or",lo->second,hi->second); + } + } + auto take=alu.cmp(i.name=="s_cbranch_scc0" || i.name=="s_cbranch_vccz" ? "eq" : "ne",value,"0"); + const auto edge=arrive(other), fall="mesh_fall"+to_string(pc); + ir.body<<" br i1 "<=i.next && i.target()end)) { + const auto target=i.target(); + for (unsigned at=i.next;attarget) refuse(pc,"mesh branch target splits instruction"); + at=next; + } + ir.body<<" br label %"<type==Symbol::Type::byte_oob || field->type==Symbol::Type::root_stride_one_high ? + "1" : string{}); + } else if (i.enc==Encoding::Smem) { + const auto offset_reg=i.b>>25; + if ((offset_reg!=125 && offset_reg>=106) || i.src[0]>=105 || i.dst+memory_count(i)>106) + refuse(pc,"unsupported mesh scalar memory address"); + if (i.op<8 && state[i.src[0]].type!=Symbol::Type::table) + refuse(pc,"mesh scalar memory needs a verified guest root mapping: "+string(op.name)); + if (i.op<8 && offset_reg!=125 && state[i.src[0]].value!=compute_resource_heap) + refuse(pc,"indexed mesh descriptor table lacks a binding contract"); + auto next=transfer(i, state, !layout.wave32, true, false, true); + const bool global=state[i.src[0]].value==compute_resource_heap && state[i.src[0]].type==Symbol::Type::table; + if (global && layout.validate_uint_heap_reads) { + if (i.op!=2 || 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); + const auto bits=root_values.find(bytes); + if (bits==root_values.end() || bits->second.shift!=5) + refuse(pc,"mesh heap slot lacks masked root constant provenance"); + heap_fetches[pc]=bits->second; + } else alu.memory(i,state); + if (i.op<8) { + for (unsigned j=0;j>16)&31)*4; + const auto sym=state[base]; + if (sym.type!=Symbol::Type::indexed_descriptor || sym.value!=compute_resource_heap || + !heap_fetches.count(sym.definition) || 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)); + ir.features|=0x40000000; + const auto handle=ir.heap_handle(descriptor,10,261); // 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); + if (uniform_values.count(index)) uniform_values.insert(word); + } else if (op.form==gfx1013::Form::mtbuf && (full_exec || exec_skip)) { + const auto base=((i.b>>16)&31)*4; + const auto low=state[base]; + string window; + if (low.type==Symbol::Type::root_address) { + const bool zero_stride=state[base+1]==Symbol{Symbol::Type::root_address,low.value,1} && + state[base+3]==Symbol{Symbol::Type::constant,0x31016fac}; + const bool byte_stride=state[base+1]==Symbol{Symbol::Type::root_stride_one_high,low.value,1} && + state[base+3]==Symbol{Symbol::Type::constant,0x11014fac}; + if (low.offset || (!zero_stride && !byte_stride) || + !(state[base+2]==Symbol{Symbol::Type::constant,0xffffffff})) + refuse(pc,"mesh formatted root load requires an unbounded byte window"); + window=alu.root_buffer_handle(low.value,4); + } + alu.formatted_byte_load(i,state,window); + if (!full_exec) for (unsigned j=0;j<=i.op;++j) partial_writes.insert(256+i.dst+j); + } else if (i.name=="buffer_load_dword" && (full_exec || exec_skip)) { + alu.memory(i,state); + if (!full_exec) { + constexpr unsigned counts[]{1,2,4,3}; + for (unsigned j=0;j data{}; + for (unsigned j=0;j<2;++j) { + auto it=alu.graphics_registers.find(i.src[0]+j); + if (it!=alu.graphics_registers.end() && !it->second.empty()) data[j]=ir.binary("xor",it->second,"4294967295"); + } + alu.write(i.dst,data[0]); alu.write(i.dst+1,data[1]); + state[i.dst]={Symbol::Type::lane_mask,pc,0}; state[i.dst+1]={Symbol::Type::lane_mask,pc,1}; + alu.write(1024+pc,ir.binary("xor",a,"1")); alu.write(128,{}); + } else if (i.name=="s_and_b64" && i.dst==126 && i.src[1]==126 && i.src[0]<=104 && + !full_exec && exec_skip && !branch && !lane_active.empty() && + [&] { + auto a=decode(code,i.next,true,true); + if (a.name!="s_cbranch_execz" || a.target()<=a.next || a.target()+8>=code.size()) return false; + auto inv=decode(code,a.target(),true,true); + auto b=decode(code,inv.next,true,true); + if (inv.name!="s_andn2_b64" || inv.dst!=126 || inv.src[1]!=126 || + b.name!="s_cbranch_execz" || b.target()<=b.next || b.target()+4>code.size()) return false; + auto reset=decode(code,b.target(),true,true); + auto parent=saved_mask(inv.src[0]); + if (!parent || parent->lane!=lane_active || parent->wave!=wave_active || + reset.name!="s_mov_b64" || reset.dst!=126 || reset.src[0]!=inv.src[0]) return false; + auto left=gather_arm(a.next,a.target()),right=gather_arm(b.next,b.target()); + if (!left || !right) return false; + for (auto r : right->inputs) if (left->writes.count(r)) return false; + for (auto r : {inv.src[0],inv.src[0]+1}) if (left->writes.count(r) || right->writes.count(r)) return false; + branch=Diamond{pc,a.target(),b.target(),save_edge(),{}}; + lane_scalar_clobbers=left->writes; + lane_scalar_clobbers.insert(right->writes.begin(),right->writes.end()); + lane_scalar_clobbers.insert(128); + lane_else=b.next; + auto take=alu.cmp("ne",alu.graphics_lane_mask(i,state,i.src[0],"unproven mesh gather mask"),"0"); + ir.body<<" br i1 "< string { + if (src==126) return full_exec ? (j && layout.wave32 ? "0" : "4294967295") : exec_value[j]; + if (src==106) src=vcc_words; + auto v=alu.graphics_registers.find(src+j); + return v==alu.graphics_registers.end() ? string{} : v->second; + }; + const auto a=lane_bit(i.src[0]),b=lane_bit(i.src[1]); + auto combine=[&](const string &x,const string &y,bool lane) { + if (x.empty() || y.empty()) return string{}; + return ir.binary(i.name=="s_or_b64" ? "or" : "and",x,i.name=="s_andn2_b64" ? + ir.binary("xor",y,lane ? "1" : "4294967295") : y); + }; + const auto lo=combine(mask_word(i.src[0],0),mask_word(i.src[1],0),false); + const auto hi=combine(mask_word(i.src[0],1),mask_word(i.src[1],1),false); + const auto bit=combine(a,b,true); + string any; + if (!lo.empty() && !hi.empty()) any=ir.binary("or",lo,hi); + else if (((i.src[0]==126) || (i.src[1]==126 && i.name=="s_and_b64")) && (i.name=="s_andn2_b64" || i.name=="s_and_b64") && mask_uniform.count(i.src[0]==126 ? b : a) && + covered_by(lane_active,mask_uniform.at(i.src[0]==126 ? b : a).first) && + (full_exec || !wave_active.empty() || (exec_skip && exec_skip->guard==lane_active))) { + auto flag=mask_uniform.at(i.src[0]==126 ? b : a).second; + if (i.name=="s_andn2_b64") flag=ir.value("xor i1 "+flag+", true"); + if (!wave_active.empty()) flag=ir.value("and i1 "+flag+", "+wave_active); + any=ir.value("zext i1 "+flag+" to i32"); + } + if (i.dst==126) { + const auto before=lane_active; + if (i.name=="s_and_b64" && (i.src[0]==126 || i.src[1]==126)) + before_narrowing[before]=save_edge(); + full_exec=false; + lane_active=alu.cmp("ne",bit,"0"); + if (i.name!="s_or_b64" && (i.src[0]==126 || (i.name=="s_and_b64" && i.src[1]==126))) mask_parent[lane_active]=before; + wave_active=lo.empty() || hi.empty() ? string{} : alu.cmp("ne",ir.binary("or",lo,hi),"0"); + exec_value[0]=lo; exec_value[1]=hi; + } else if (i.dst==106) { + alu.write(106,bit); + alu.write(vcc_words,lo); alu.write(vcc_words+1,hi); alu.write(vcc_nonempty,any); + state[106].type=lo.empty()?Symbol::Type::unbound:Symbol::Type::unknown; + state[107].type=hi.empty()?Symbol::Type::unbound:Symbol::Type::unknown; + } else { + alu.write(i.dst,lo); alu.write(i.dst+1,hi); + state[i.dst]={Symbol::Type::lane_mask,pc,0}; + state[i.dst+1]={Symbol::Type::lane_mask,pc,1}; + alu.write(1024+pc,bit); + } + alu.write(128,any.empty() ? string{} : ir.value("zext i1 "+alu.cmp("ne",any,"0")+" to i32")); + } else if ((i.name=="s_bitset0_b32" || i.name=="s_bitset1_b32") && i.dst<106) { + auto bit=ir.binary("shl","1",ir.binary("and",alu.operand32(i,i.src[0]),"31")); + 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 (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_cmp_gt_i32" || i.name=="s_cmp_lt_i32" || i.name=="s_cmp_ge_i32" || i.name=="s_cmp_eq_u32" || i.name=="s_cmp_eq_i32" || i.name=="s_cmp_lg_u32" || i.name=="s_cmp_ge_u32" || i.name=="s_cmp_lg_i32" || i.name=="s_cmp_gt_u32" || i.name=="s_cselect_b32") { + alu.arithmetic(i,state); + } else if (raw==0xbefe04c1) { + full_exec=true; + export_limit.clear(); + for (auto r : partial_writes) alu.write(r,{}); + partial_writes.clear(); + wave_active.clear(); lane_active.clear(); + exec_value[0].clear(); exec_value[1].clear(); + } else if (i.name=="s_mov_b64" && i.dst==106 && (i.src[0]==128 || i.src[0]==193)) { + const bool set=i.src[0]==193; + auto value=set ? "4294967295" : "0"; + alu.write(106,set ? "1" : "0"); alu.write(vcc_words,value); alu.write(vcc_words+1,value); + alu.write(vcc_nonempty,value); + state[106]=state[107]={Symbol::Type::constant,set ? ~0u : 0u}; + // Thread the known-zero predecessor through a mask test before + // merging with paths that computed its optional buffer values. + if (!set && i.next+8<=code.size() && !branch && gfx1013::instruction(code,i.next).name=="s_and_b64") { + auto test=decode(code,i.next,true,true); + auto jump=decode(code,test.next,true,true); + if (test.name=="s_and_b64" && test.dst<=104 && !(test.dst&1) && + ((test.src[0]==106 && test.src[1]==126) || (test.src[0]==126 && test.src[1]==106)) && + jump.name=="s_cbranch_scc0" && jump.target()>=jump.next && jump.target()end)) { + alu.write(test.dst,"0"); alu.write(test.dst+1,"0"); alu.write(128,"0"); + state[test.dst]={Symbol::Type::uniform_mask,test.pc,0}; + state[test.dst+1]={Symbol::Type::uniform_mask,test.pc,1}; + alu.write(1024+test.pc,"0"); + ir.body<<" br label %"<second; + }; + const auto lo=physical(src), hi=physical(src+1); + string bit; + if (old[src].type==Symbol::Type::lane_mask || old[src].type==Symbol::Type::uniform_mask) + bit=alu.graphics_lane_mask(i,old,src,"unproven mesh VCC move"); + else if (!lo.empty() && !hi.empty()) { + auto half=alu.select(alu.cmp("ult",wave_lane,"32"),lo,hi); + bit=ir.binary("and",ir.binary("lshr",half,ir.binary("and",wave_lane,"31")),"1"); + } + alu.write(106,bit); alu.write(vcc_words,lo); alu.write(vcc_words+1,hi); + alu.write(vcc_nonempty,lo.empty() || hi.empty() ? string{} : ir.binary("or",lo,hi)); + state=next; + } else if (i.name=="s_mov_b64" && i.dst<=104 && !(i.dst&1) && i.src[0]==126 && + (full_exec || !lane_active.empty())) { + alu.write(i.dst,full_exec ? "4294967295" : exec_value[0]); + alu.write(i.dst+1,full_exec ? (layout.wave32 ? "0" : "4294967295") : exec_value[1]); + state[i.dst]={Symbol::Type::lane_mask,pc,0}; state[i.dst+1]={Symbol::Type::lane_mask,pc,1}; + alu.write(1024+pc,full_exec ? "1" : ir.value("zext i1 "+lane_active+" to i32")); + saved_exec[pc]={full_exec,lane_active,wave_active,exec_value[0],exec_value[1],alu.graphics_registers,partial_writes}; + } else if (i.name=="s_mov_b64" && i.dst==126 && i.src[0]<=104 && !(i.src[0]&1)) { + const auto mask=saved_mask(i.src[0]); + if (!mask) refuse(pc,"mesh EXEC restore lacks a still-valid reaching mask"); + if (mask->lane!=lane_active) { + auto at_narrow=before_narrowing.find(mask->lane); + const auto ®s=at_narrow==before_narrowing.end() ? mask->regs : at_narrow->second.regs; + const auto &valid=at_narrow==before_narrowing.end() ? mask->partial : at_narrow->second.partial; + std::set remaining; + for (auto r:partial_writes) { + auto at=regs.find(r); + if (at==regs.end() || at->second.empty() || at->second!=alu.graphics_registers.at(r)) + alu.write(r,{}); + else if (valid.count(r)) remaining.insert(r); + } + partial_writes=std::move(remaining); + } + full_exec=mask->full; lane_active=mask->lane; wave_active=mask->wave; + exec_value[0]=mask->lo; exec_value[1]=mask->hi; + } else if (i.name=="s_mov_b64" && i.dst<=104 && !(i.dst&1) && i.src[0]<=104 && !(i.src[0]&1)) { + auto next=transfer(i, state, !layout.wave32, true, false, true); + auto src=alu.graphics_registers.find(i.src[0]), high=alu.graphics_registers.find(i.src[0]+1); + auto lo=src==alu.graphics_registers.end() ? string{} : src->second; + auto hi=high==alu.graphics_registers.end() ? string{} : high->second; + alu.write(i.dst,lo); + alu.write(i.dst+1,hi); + state=next; + } else if (i.name=="s_mov_b64" && i.dst<=104 && !(i.dst&1) && i.src[0]>=128 && i.src[0]<=208) { + auto next=transfer(i, state, !layout.wave32, true, false, true); + alu.write(i.dst,to_string(next[i.dst].value)); alu.write(i.dst+1,to_string(next[i.dst+1].value)); + state=next; + } else if (i.name=="s_mov_b32" && i.dst==125 && constant32(i,i.src[0])) { + // NULL discards the scalar move; MOV does not write SCC. + } else if (i.name=="s_mov_b32" && i.dst==124) { + allocation_word=constant32(i,i.src[0]); + } 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)); + 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); + } else if (i.src[0]==253) alu.write(i.dst,alu.read(128)); + else refuse(pc,"unsupported scalar mesh entry operand"); + state[i.dst]=provenance; + } else if (i.name=="s_bfe_u32" && i.src[0]==3 && !alu.graphics_registers.count(3) && + i.src[1]==255 && i.literal==0x40018 && i.dst<106) { + alu.write(i.dst,wave_number); + alu.write(128,ir.value("zext i1 "+alu.cmp("ne",wave_number,"0")+" to i32")); + } else if (i.name=="s_bcnt1_i32_b64" && i.src[0]<=104 && !(i.src[0]&1) && i.dst<106) { + auto pop=[&](unsigned r) { + return ir.invoke("i32","unaryBits.i32",31,{{"i32",alu.read(r)}},"nounwind readnone"); + }; + const auto lo=pop(i.src[0]), hi=pop(i.src[0]+1); + const auto sum=ir.binary("add",lo,hi); + alu.write(i.dst,sum); + alu.write(128,ir.value("zext i1 "+alu.cmp("ne",sum,"0")+" to i32")); + } else if (i.name=="s_bfe_u32" || i.name=="s_min_u32") { + alu.arithmetic(i,state); + } else if (i.name=="v_readfirstlane_b32" && i.dst<106 && i.src[0]==261 && !exchanged_group.empty() && full_exec) { + alu.write(i.dst,exchanged_group); + } else if (i.name=="v_readfirstlane_b32" && i.dst<106 && (full_exec || exec_skip) && + !uniform(alu.read(i.src[0])).empty()) { + alu.write(i.dst,uniform(alu.read(i.src[0]))); + } else if (i.name=="s_pack_ll_b32_b16" || i.name=="s_pack_hh_b32_b16") { + const auto a=alu.operand32(i,i.src[0]),b=alu.operand32(i,i.src[1]); + const bool high=i.name=="s_pack_hh_b32_b16"; + alu.write(i.dst,ir.binary("or",high ? ir.binary("lshr",a,"16") : ir.binary("and",a,"65535"), + high ? ir.binary("and",b,"4294901760") : ir.binary("shl",b,"16"))); + } else if (i.enc==Encoding::Sop2 && i.dst<106 && (i.name=="s_lshr_b32" || i.name=="s_lshl_b32" || + i.name=="s_or_b32" || i.name=="s_and_b32")) { + const auto known=[&](unsigned r) { + return constant32(i,r).has_value() || + (alu.graphics_registers.count(r) && !alu.graphics_registers.at(r).empty()); + }; + if (known(i.src[0]) && known(i.src[1])) { + const auto a=alu.operand32(i,i.src[0]), b=alu.operand32(i,i.src[1]); + const bool shift=i.name=="s_lshl_b32" || i.name=="s_lshr_b32"; + const auto value=ir.binary(i.name=="s_lshl_b32" ? "shl" : i.name=="s_lshr_b32" ? "lshr" : + i.name=="s_or_b32" ? "or" : "and",a,shift ? ir.binary("and",b,"31") : b); + 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); + const auto imm=constant32(i,i.src[1]); + if (bits!=root_values.end() && imm && !bits->second.shift) { + auto out=bits->second; + if (i.name=="s_and_b32") { out.mask&=*imm; root_values.emplace(value,out); } + if (i.name=="s_lshl_b32" && *imm==5 && out.mask<=0x7ffffffu) { + out.shift=5; root_values.emplace(value,out); + } + } + const auto next=transfer(i, state, !layout.wave32, true, false, true); + alu.write(i.dst,value); + state[i.dst]=next[i.dst]; + alu.write(128,ir.value("zext i1 "+alu.cmp("ne",value,"0")+" to i32")); + } + else { + alu.write(i.dst,{}); + alu.write(128,{}); + } + } else if (full_exec && (i.name=="v_mbcnt_lo_u32_b32" || i.name=="v_mbcnt_hi_u32_b32") && i.src[0]==193) { + const auto add=i.name=="v_mbcnt_lo_u32_b32" ? alu.select(alu.cmp("ult",wave_lane,"32"),wave_lane,"32") : + alu.select(alu.cmp("ult",wave_lane,"32"),"0",ir.binary("sub",wave_lane,"32")); + const auto base=alu.operand32(i,i.src[1]); + const auto value=ir.binary("add",base,add); + if (i.name=="v_mbcnt_lo_u32_b32") { + if (base=="0") low_lane.insert(value); + if (wave_bases.count(base)) low_group.insert(value); + } else { + if (low_lane.count(base)) whole_lane.insert(value); + if (low_group.count(base)) linear_threads.insert(value); + } + alu.write(i.dst,value); + } else if (i.name=="v_perm_b32" && !i.abs && !i.neg && !i.clamp && !i.scale && !i.subword && + !i.dpp_control && (full_exec || exec_skip)) { + // RDNA V_PERM_B32: selectors 0..3 index src1, 4..7 index src0, + // 8..11 replicate the sign of each halfword; 12 zero-fills. + const auto selectors=constant32(i,i.src[2]); + if (!selectors) refuse(pc,"dynamic mesh byte permutation"); + const auto a=alu.operand32(i,i.src[0]), b=alu.operand32(i,i.src[1]); + string result="0"; + for (unsigned j=0;j<4;++j) { + const unsigned sel=(*selectors>>(j*8))&255; + string byte; + if (sel<8) byte=ir.binary("and",ir.binary("lshr",sel<4 ? b : a,to_string((sel&3)*8)),"255"); + else if (sel<12) { + const auto bit=ir.binary("and",ir.binary("lshr",sel<10 ? b : a,to_string((sel&1)*16+15)),"1"); + byte=alu.select(alu.cmp("ne",bit,"0"),"255","0"); + } else byte=sel==12 ? "0" : "255"; + result=ir.binary("or",result,ir.binary("shl",byte,to_string(j*8))); + } + alu.write(i.dst,result); + if (!full_exec) partial_writes.insert(i.dst); + } else if ((full_exec || exec_skip) && (i.name=="v_trunc_f32" || i.name=="v_floor_f32" || + i.name=="v_ceil_f32" || i.name=="v_rndne_f32" || i.name=="v_fract_f32" || + i.name=="v_cvt_u32_f32" || i.name=="v_mul_u32_u24" || i.name=="v_lshl_or_b32" || + i.name=="v_add_lshl_u32" || i.name=="v_lshrrev_b64" || i.name=="v_lshlrev_b64" || i.name=="v_mad_legacy_f32" || + i.name=="v_mul_lo_u32" || i.name=="v_mac_f32" || i.name=="v_mul_legacy_f32" || i.name=="v_sub_f32" || + i.name=="v_subrev_f32" || i.name=="v_fmac_f32" || i.name=="v_fmaak_f32" || + i.name=="v_rsq_f32" || i.name=="v_rcp_f32" || i.name=="v_sin_f32" || i.name=="v_cos_f32" || + i.name.substr(0,15)=="v_cvt_f32_ubyte" || i.name=="v_min_u32" || i.name=="v_max_f32" || + i.name=="v_mad_u32_u24" || i.name=="v_add3_u32" || i.name=="v_bfe_u32" || i.name=="v_mov_b32" || i.name=="v_add_nc_u32" || i.name=="v_lshlrev_b32" || + i.name=="v_lshrrev_b32" || i.name=="v_or_b32" || i.name=="v_and_b32" || + i.name=="v_xor_b32" || i.name=="v_lshl_add_u32" || i.name=="v_cvt_f32_u32" || i.name=="v_cvt_f32_i32" || + i.name=="v_mul_f32" || i.name=="v_add_f32" || i.name=="v_fma_f32")) { + const bool flat=i.name=="v_lshl_add_u32" && alu.operand32(i,i.src[0])==wave_number && + constant32(i,i.src[1])==(layout.wave32 ? 5u : 6u) && + whole_lane.count(alu.operand32(i,i.src[2])); + alu.arithmetic(i,state); + if (flat) linear_threads.insert(alu.read(i.dst)); + if (!full_exec) { + partial_writes.insert(i.dst); + if (i.name=="v_lshrrev_b64" || i.name=="v_lshlrev_b64") partial_writes.insert(i.dst+1); + } + } else refuse(pc,"unsupported mesh instruction or EXEC state: "+string(op.name)); + for (unsigned j=0;j<4;++j) { + if (!before_vec[j].empty() && !before_partial[j] && partial_writes.count(vec_dst+j)) { + auto &value=alu.graphics_registers.at(vec_dst+j); + auto u=uniform(value); + value=alu.select(lane_active,value,before_vec[j]); + if (!u.empty()) active_uniform[value]={lane_active,u}; + partial_writes.erase(vec_dst+j); + } + } + if (result_bound && *result_boundsecond.empty()) upper_bound[it->second]=*result_bound; + } + if (i.dst<106 && i.enc!=Encoding::Smem) remember_scalar(i.dst); + if (i.name=="v_mov_b32" && i.src[0]<106) remember_scalar(i.src[0]); + if (i.dst==261 || (i.enc==Encoding::Mubuf && i.dst==5)) exchanged_group.clear(); + pc=i.next; + } + refuse(pc,"unterminated mesh shader"); +} diff --git a/src/gfx1013_pixel_waterfall.inl b/src/gfx1013_pixel_waterfall.inl new file mode 100644 index 000000000..d61103594 --- /dev/null +++ b/src/gfx1013_pixel_waterfall.inl @@ -0,0 +1,92 @@ +// Single-block read-only descriptor waterfalls. See victory-shader/resource.rs +// (waterfall) and tools/startup/gfx2hlsl.py (waterfall_refusal). Every pass +// removes exactly the lanes it sampled. No other loop effect can be projected +// onto an individual invocation. +struct PixelWaterfalls { + struct Access { unsigned key, descriptor_pc; bool key_is_bytes; }; + std::map accesses; + std::map> poisoned; + std::set exits, saves, restores; + + void find(Program &p, bool wave32) { + auto &code=p.code; + const auto mov=wave32 ? "s_mov_b32" : "s_mov_b64"; + const auto remaining_op=wave32 ? "s_andn2_wrexec_b32" : "s_andn2_wrexec_b64"; + auto idle=[](const Inst &i) {return i.name=="s_waitcnt" || i.name=="s_nop";}; + auto pair=[&](unsigned r) {return wave32 ? r<=105 : r<=104 && !(r&1);}; + for (size_t tail=2; tail+1=retry.pc || + advance.name!=remaining_op || !pair(advance.dst) || advance.src[0]!=advance.dst || + restore.name!=mov || restore.dst!=126 || !pair(restore.src[0]) || restore.src[0]==advance.dst) continue; + const size_t head=p.at.at(retry.target()); + std::vector body; + for (size_t j=head;j98 || (load.b>>25)!=read.dst || (load.b&0xfffff) || + image.enc!=Encoding::Image || (image.op!=32 && image.op!=39 && image.op!=0) || + ((image.b>>16)&31)*4!=load.dst) continue; + const auto &table=p.before[body[body.size()-2]].at(load.src[0]); + if (table.type!=Symbol::Type::table || table.value!=compute_resource_heap) continue; + // The slot or the already shifted byte offset may be the key. + bool bytes=body.size()==4; + if (!bytes) { + const auto &shift=code[body[2]]; + if (shift.name!="s_lshl_b32" || shift.dst!=read.dst || shift.src[0]!=read.dst || + !(source(shift,shift.src[1],p.before[body[2]])==Symbol{Symbol::Type::constant,5})) continue; + } + const unsigned width=wave32 ? 1u : 2u; + auto overlaps=[](unsigned a,unsigned na,unsigned b,unsigned nb) {return astd::optional { + for (size_t at=head; at;) { + const auto &save=code[--at]; + if (save.name!=mov || save.dst!=r || save.src[0]!=126) continue; + if (!GraphicsMaskRegions::preserves_exec(p,at+1,head,r)) return {}; + for (const auto &edge:code) { + if (!edge.branch() || edge.pc==retry.pc) continue; + if (edge.target()>save.pc && edge.target()<=restore.pc && + (edge.pc=retry.pc || edge.target()>code[head].pc)) return {}; + } + return at; + } + return {}; + }; + auto parent=anchor(restore.src[0]), left=anchor(advance.dst); + if (!parent || !left) continue; + saves.insert(code[*parent].pc); + saves.insert(code[*left].pc); + restores.insert(restore.pc); + auto forget=[&](unsigned pc,unsigned r,unsigned n) { + for (unsigned j=0;j #include #include @@ -168,6 +169,37 @@ void stages(Span packed, std::vector &result, size_t &total) { } } } // namespace +unsigned GuestShaderStage::physical_user_sgpr(unsigned logical) const noexcept { + switch (stage) { + case GpuStage::ls: + case GpuStage::hs: + case GpuStage::es: + case GpuStage::gs: + case GpuStage::ms: + return logical + 8; + default: + return logical; + } +} + +std::optional native_shader_identifier(std::string_view code) { + // Two literal-bearing V_NOPs carry the sixteen DXBC HASH bytes. Each + // operand selector contributes eight bits; bit 8 is an encoding bit. + if (code.size() < 24) return {}; + ShaderIdentifier id{}; + for (unsigned half = 0; half < 2; ++half) { + const unsigned off = half * 12; + const uint32_t inst = u32(code, off), operands = u32(code, off + 4); + if (inst >> 16 != 0xd580 || (operands & 0xfffe0100u) != 0x03fe0100u) return {}; + auto* bytes = id.data() + half * 8; + bytes[0] = static_cast(inst); + bytes[1] = static_cast(inst >> 8); + bytes[2] = static_cast(operands); + bytes[3] = static_cast(operands >> 9); + std::memcpy(bytes + 4, code.data() + off + 8, 4); + } + return id; +} std::string GuestShaderStage::full_precision_code() const { auto patched = code; for (const auto &p : exports) @@ -180,6 +212,8 @@ std::vector read_guest_shader_container(std::string_view bytes std::vector result; size_t total = 0; std::vector inputs, outputs; + std::optional identifier; + std::optional mesh_threads; const auto count = u32(bytes, 28); if (count > 4096) throw std::runtime_error("invalid DXBC part count"); @@ -188,6 +222,14 @@ std::vector read_guest_shader_container(std::string_view bytes uint64_t part = u32(offsets, 4ull * i); auto data = slice(bytes, part + 8, u32(bytes, part + 4)); auto kind = slice(bytes, part, 4); + if (kind == "HASH" && data.size() == 20) { + ShaderIdentifier parsed; + std::memcpy(parsed.data(), data.data() + 4, parsed.size()); + if (identifier && *identifier != parsed) throw std::runtime_error("conflicting shader identifiers"); + identifier = parsed; + } + if (kind == "PSV0" && data.size() >= 52 && u32(data, 0) >= 48 && u32(data, 0) <= data.size() - 4) + mesh_threads = u32(data, 40); if (kind == "ISG1" || kind == "ISGN") inputs = read_signature(data, kind == "ISG1"); if (kind == "OSG1" || kind == "OSGN") @@ -209,6 +251,10 @@ std::vector read_guest_shader_container(std::string_view bytes if (stage.stage == GpuStage::vs || stage.stage == GpuStage::ps || stage.stage == GpuStage::ms) { stage.input_signature = inputs; stage.output_signature = outputs; + stage.container_identifier = identifier; + if (stage.stage == GpuStage::ms) + stage.mesh_group_stride = mesh_threads + ? std::max({*mesh_threads, stage.max_vertices, stage.max_primitives}) : stage.threads[0]; } return result; } diff --git a/src/guest_shader_container.h b/src/guest_shader_container.h index 422ac25c9..16445b03a 100644 --- a/src/guest_shader_container.h +++ b/src/guest_shader_container.h @@ -1,12 +1,15 @@ #pragma once #include #include +#include #include #include #include namespace x2w { enum class GpuStage { ls, hs, es, gs, vs, ps, ms, cs }; +using ShaderIdentifier = std::array; +std::optional native_shader_identifier(std::string_view code); struct ShaderRootInput { uint32_t type, offset_dwords, sgpr_count, base_register; uint8_t user_data, root_parameter; @@ -35,6 +38,7 @@ struct GuestShaderStage { bool fixed_vertex_abi{}; unsigned vgprs, lds_bytes; std::string code; + std::optional container_identifier; std::vector inputs; std::vector resources; std::array threads{}; @@ -46,6 +50,9 @@ struct GuestShaderStage { // The signature component (9 f32, 5 u32, 4 i32) an RTV variant request asks of each color target; 0 when none. std::array target_components{}; unsigned mesh_clip_control{}, max_vertices{}, max_primitives{}, topology{}; + unsigned mesh_group_stride{}; + // Merged hardware stages reserve the first eight SGPRs for the system entry. + unsigned physical_user_sgpr(unsigned logical) const noexcept; std::string full_precision_code() const; }; std::vector read_guest_shader_container(std::string_view container); diff --git a/src/mesh_pixel_heap.h b/src/mesh_pixel_heap.h new file mode 100644 index 000000000..dfb692483 --- /dev/null +++ b/src/mesh_pixel_heap.h @@ -0,0 +1,7 @@ +#pragma once + +namespace x2w { +// A private shader-visible heap mirrors each proven guest interval once per draw. +struct PixelHeapSpan { unsigned first, last, dimension, host_first; }; +inline constexpr unsigned first_pixel_heap_slot = 1024; // preceding slots reserved for the MS uint selector +} diff --git a/src/native_buffer_store_view.h b/src/native_buffer_store_view.h index b01d98e6a..8e2ec3c09 100644 --- a/src/native_buffer_store_view.h +++ b/src/native_buffer_store_view.h @@ -61,6 +61,12 @@ inline bool native_buffer_store_view(const ComputeViewBinding &binding, D3D12_UN stride = 4; } else if (view.Buffer.Flags) { return false; + } else if (binding.kind == ComputeViewKind::packed_d16_x_uav) { + if (stride != 2) return false; + if (view.Format == DXGI_FORMAT_R32_UINT) stride = 4; + else if (view.Format == DXGI_FORMAT_R16_FLOAT || view.Format == DXGI_FORMAT_R16_UINT) + view.Format = DXGI_FORMAT_R16_UINT; + else return false; } else if (binding.kind == ComputeViewKind::half_buffer_uav) { const auto format = native_half_buffer_format(stride); if (format == DXGI_FORMAT_UNKNOWN || view.Format != format) diff --git a/src/native_graphics_bindings.h b/src/native_graphics_bindings.h index 65d3f2989..48058797e 100644 --- a/src/native_graphics_bindings.h +++ b/src/native_graphics_bindings.h @@ -14,6 +14,8 @@ struct NativeGraphicsBindings { explicit NativeGraphicsBindings(const DirectGraphicsPair &pair) { std::vector writes; for (const auto *stage : {&pair.vertex, &pair.pixel}) { + samplers.heap |= stage->sampler_heap; + samplers.reserved_fallback |= stage->sampler_heap; for (const auto &v : stage->bindings) { auto &range = compute_uav(v.kind) ? writes : views; if (v.shader_register != range.size()) diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp index 7f3d956b9..b502e5716 100644 --- a/src/shader_compute_request.cpp +++ b/src/shader_compute_request.cpp @@ -42,6 +42,11 @@ bool lower_hex(std::string_view text) { return false; return true; } +void check_compute_extents(const Bytes &desc, size_t code, size_t data, size_t sa, size_t sb) { + if (desc.size() != 96 || read(desc, 48) != code || read(desc, 64) != data || + read(desc, 16) != sa || read(desc, 32) != sb) + throw std::runtime_error("inconsistent compute request"); +} uint64_t parse_request_stem(std::string_view stem, const char *error_message) { const std::string_view digits = stem.substr(4); uint64_t expected = 0; @@ -249,8 +254,30 @@ x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { request.rtv_formats = std::move(parsed.formats); return request; } +void read_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { + if (fs::exists(fs::path(marker).replace_extension(".psin"))) + parse_pixel_inputs(marker, expected, entry, description); + if (fs::exists(fs::path(marker).replace_extension(".ps57in"))) { + if (!entry.empty()) + throw std::runtime_error("conflicting stream and slot-57 pixel entry records"); + entry = part(marker, ".ps57in", 12); + if (entry.size() != 12 || entry.compare(0, 4, "PSI1")) + throw std::runtime_error("invalid slot-57 pixel entry record"); + description = entry; + } +} } // namespace +std::string x2w::read_pixel_input_description(const fs::path &base_marker) { + const auto stem = base_marker.stem().string(); + if (base_marker.extension() != ".a" || stem.size() != 20 || stem.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.a"); + const uint64_t expected = parse_request_stem(stem, "invalid graphics request key"); + Bytes entry, description; + read_pixel_inputs(base_marker, expected, entry, description); + return description; +} + x2w::GraphicsRequest x2w::read_graphics_request(const fs::path &marker) { if (marker.extension() == ".rtv") return read_rtv_variant(marker); auto stem = marker.stem().string(); @@ -261,8 +288,7 @@ x2w::GraphicsRequest x2w::read_graphics_request(const fs::path &marker) { part(marker, ".root", 16 << 20), {}, {}, {}, expected}; if (fs::exists(fs::path(marker).replace_extension(".ia"))) request.input_layout = part(marker, ".ia", 1 << 20); - if (fs::exists(fs::path(marker).replace_extension(".psin"))) - parse_pixel_inputs(marker, expected, request.pixel_entry, request.pixel_input_description); + read_pixel_inputs(marker, expected, request.pixel_entry, request.pixel_input_description); if (request.root.empty()) throw std::runtime_error("graphics request key mismatch or missing root"); // Match new runtime captures and keep revision-28 archives replayable. @@ -291,14 +317,21 @@ x2w::ComputeRequest x2w::read_compute_request(const fs::path &marker) { if (x2w::compute_request_key(code, data, root, desc, sa, sb) != expected && x2w::compute_request_key(code, data, root, desc, sa, sb, "x2w-startup-shader-28cs") != expected) throw std::runtime_error("compute request key mismatch"); - if (root.empty() || sa.size() != 28 || code.empty() || data.empty() || code.size() % 4) - throw std::runtime_error(sa.size() != 28 ? "compute state block A is not 28 bytes" - : "inconsistent compute request"); + ComputeRequest request{std::move(code), std::move(data), std::move(root), std::move(desc), std::move(sa), std::move(sb), expected}; + validate_compute_request_shape(request); // Bit 20 of dword 4 (bits 15:0 are Z): set for wave32, clear for wave64. Inferred from captured requests - // (docs/experiments/native-slot67-wave-size.md). - const bool wave32 = (static_cast(sa[18]) & 0x10) != 0; - return {std::move(code), std::move(data), std::move(root), std::move(desc), std::move(sa), std::move(sb), expected, - wave32}; + // (docs/experiments/native-slot67-wave-size.md). Read only after the shape check has proved 28 bytes. + request.wave32 = (static_cast(request.sa[18]) & 0x10) != 0; + return request; +} + +void x2w::validate_compute_request_shape(const ComputeRequest &r) { + check_compute_extents(r.description, r.code.size(), r.data.size(), r.sa.size(), r.sb.size()); + if (r.root.size() > (16u << 20) || r.code.size() > (1u << 20) || + r.data.size() > (1u << 20) || r.sa.size() > 4096 || r.sb.size() > 4096) + throw std::runtime_error("inconsistent compute request"); + if (r.root.empty() || r.sa.size() != 28 || r.code.empty() || r.data.empty() || r.code.size() % 4) + throw std::runtime_error(r.sa.size() != 28 ? "compute state block A is not 28 bytes" : "inconsistent compute request"); } std::string x2w::read_shader_container_bytes(const fs::path &file) { diff --git a/src/shader_compute_request.h b/src/shader_compute_request.h index 10ea8328a..b8bd53dad 100644 --- a/src/shader_compute_request.h +++ b/src/shader_compute_request.h @@ -49,8 +49,11 @@ struct GraphicsRequest { }; // marker: req_.a, or req_.rtv for an RTV variant of a base request in the same directory. GraphicsRequest read_graphics_request(const std::filesystem::path &marker); +// Canonical pixel-input sidecar (.psin or .ps57in) content for req_.a; empty when absent, throws if invalid/conflicting. +std::string read_pixel_input_description(const std::filesystem::path &base_marker); std::string read_shader_container_bytes(const std::filesystem::path &file); ComputeContainer read_compute_container(const std::filesystem::path &file); // Verify the content key over all six immutable capture parts before exposing any bytes. ComputeRequest read_compute_request(const std::filesystem::path &marker); +void validate_compute_request_shape(const ComputeRequest &request); } // namespace x2w diff --git a/tests/cmake/native_wave_virtual_derivative.cmake b/tests/cmake/native_wave_virtual_derivative.cmake new file mode 100644 index 000000000..aa3b68916 --- /dev/null +++ b/tests/cmake/native_wave_virtual_derivative.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_wave_virtual_derivative_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_wave_virtual_derivative_check.py" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_wave_virtual_derivative_controls PROPERTIES TIMEOUT 120) +endif() diff --git a/tests/native_compile_dxil_watch_check.py b/tests/native_compile_dxil_watch_check.py index 9342f23c8..a8bbbbb97 100644 --- a/tests/native_compile_dxil_watch_check.py +++ b/tests/native_compile_dxil_watch_check.py @@ -16,6 +16,7 @@ sys.path.insert(0, str(HERE.parent / "tools" / "startup")) import gfx2hlsl as G # noqa: E402 +from native_direct_container_check import patched_pixel, publish as publish_raw, vertex as container_vertex, words as raw_words # noqa: E402 from native_rtv_variant_check import FLOAT32, UINT16, UNORM8, put_variant # noqa: E402 from native_startup_request_cache_check import ( # noqa: E402 COMPUTE_GROUP, @@ -175,6 +176,33 @@ def main(argv: list[str]) -> int: assert not (d_lost / f"{lost_key:016x}.txt").exists() assert (d_lost / f"{lost_key:016x}.fail").is_file() + # A 0-byte .psdep next to a published manifest + valid .psin triggers retranslation and restores .psdep. + zero_psdep = d_lost / "zero_psdep" + zero_psdep.mkdir() + z_key = put_graphics_request(zero_psdep, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + assert run_once(cli, sdk, frontend, zero_psdep, jobs=1).returncode == 0 + z_psdep = zero_psdep / f"{z_key:016x}.psdep" + orig_dep = z_psdep.read_bytes() + assert orig_dep + z_psdep.write_bytes(b"") + r_zero = run_once(cli, sdk, frontend, zero_psdep, jobs=1) + assert r_zero.returncode == 0 and f"{z_key:016x}: compiled graphics" in r_zero.stdout, (r_zero.stdout, r_zero.stderr) + assert z_psdep.read_bytes() == orig_dep + + # A copied slot-57 sidecar can be older than the published stream manifest. + conflict_dir = work / "copied_pixel_sidecar" + conflict_dir.mkdir() + conflict_key = put_graphics_request(conflict_dir, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + assert run_once(cli, sdk, frontend, conflict_dir, jobs=1).returncode == 0 + conflict_manifest = conflict_dir / f"{conflict_key:016x}.txt" + assert conflict_manifest.is_file() + packed = conflict_dir / f"req_{conflict_key:016x}.ps57in" + packed.write_bytes(b"PSI1" + bytes(8)) + touch(packed, mtime=conflict_manifest.stat().st_mtime - 10) + conflict = run_once(cli, sdk, frontend, conflict_dir, jobs=1) + assert "conflicting stream and slot-57 pixel entry records" in conflict.stdout, conflict.stdout + assert not conflict_manifest.exists() + # Parallel --once --jobs 2 matches serial --once --jobs 1. d_serial = work / "cmp_serial" d_parallel = work / "cmp_parallel" @@ -219,6 +247,95 @@ def main(argv: list[str]) -> int: assert not (d_rtv / f"{key:016x}.txt").exists() assert (d_rtv / f"{key:016x}.fail").is_file() + # Issue #3133: sidecar content changes or contradictory .ps57in with preserved/older mtimes must invalidate. + # Contradictory .ps57in appearing with older mtime vs newer mtime must withdraw stale .txt identically. + outcomes_ps57 = [] + for label, offset in (("older", -60.0), ("newer", 10.0)): + d_cmp = work / f"ps57_contradict_{label}" + d_cmp.mkdir() + s_key = put_graphics_request(d_cmp, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + r_pub = run_once(cli, sdk, frontend, d_cmp, jobs=1) + assert r_pub.returncode == 0 and f"{s_key:016x}: compiled graphics" in r_pub.stdout, r_pub.stdout + txt_path = d_cmp / f"{s_key:016x}.txt" + fail_path = d_cmp / f"{s_key:016x}.fail" + assert txt_path.is_file() and (d_cmp / f"{s_key:016x}.psdep").is_file() + # Unchanged-input cache-hit control before adding contradictory .ps57in. + txt_ns = txt_path.stat().st_mtime_ns + r_hit = run_once(cli, sdk, frontend, d_cmp, jobs=1) + assert r_hit.returncode == 0 and f"{s_key:016x}:" not in r_hit.stdout and txt_path.stat().st_mtime_ns == txt_ns + touch( + d_cmp / f"req_{s_key:016x}.ps57in", + b"PSI1" + struct.pack(" +#include +#include +#include +#include +#include + +using namespace x2w; +namespace fs = std::filesystem; +using Clock = std::chrono::steady_clock; +static double elapsed(Clock::time_point since) { + return std::chrono::duration(Clock::now() - since).count(); +} +static void check(bool ok, const char *reason) { + if (!ok) throw std::runtime_error(reason); +} +int main(int argc, char **argv) { + try { + if (argc < 3 || argc > 4) return 2; + const fs::path input = argv[1], file = argv[2]; + std::vector markers; + for (auto &it : fs::directory_iterator(input)) + if (it.path().extension() == ".c67") markers.push_back(it.path()); + std::sort(markers.begin(), markers.end()); + auto start = Clock::now(); + auto pack = ComputeFrontendPack::load(file, 0); + const auto load_ms = elapsed(start); + std::ofstream report; + if (argc == 4) { + report.open(argv[3]); + report.exceptions(std::ios::failbit | std::ios::badbit); + report << "key\tstatus\tcold_ms\tlookup_ms\tir_sha256_or_diagnostic\tmanifest_sha256\n"; + } + size_t success = 0, refused = 0, other = 0; + double live_total = 0, warm_total = 0; + bool tested_success = false, tested_refused = false; + for (const auto &marker : markers) { + auto r = read_compute_request(marker); + NativeComputeShader warm, cold; + std::string warm_error, cold_error; + start = Clock::now(); + const auto hit = pack.lookup(r, 0, warm, warm_error); + const double warm_ms = elapsed(start); + start = Clock::now(); + ComputePackResult expected = ComputePackResult::prepared; + try { cold = translate_compute(r, 0, true); } + catch (const UnsupportedComputeShader &e) { expected = ComputePackResult::unsupported; cold_error = e.what(); } + catch (const std::runtime_error &e) { expected = ComputePackResult::miss; cold_error = e.what(); } + const double live_ms = elapsed(start); + live_total += live_ms; + warm_total += warm_ms; + check(hit == expected, "result class differs from direct frontend"); + const char *status; + std::string identity, manifest_digest; + if (hit == ComputePackResult::prepared) { + auto manifest = format_compute_runtime_manifest(cold); + check(warm.dxil_ir == cold.dxil_ir && warm.group == cold.group && + warm.instruction_count == cold.instruction_count && format_compute_runtime_manifest(warm) == manifest, + "IR, layout or manifest differs"); + status = "prepared"; + identity = shader_digest(cold.dxil_ir); + if (manifest) manifest_digest = shader_digest(*manifest); + ++success; + } else if (hit == ComputePackResult::unsupported) { + check(warm_error == cold_error, "refusal differs"); + status = "unsupported"; + identity = cold_error; + ++refused; + } else { + status = "other"; + identity = cold_error; + ++other; + } + if ((hit == ComputePackResult::prepared && !tested_success) || + (hit == ComputePackResult::unsupported && !tested_refused)) { + for (auto *part : {&r.code, &r.data, &r.root, &r.description, &r.sa, &r.sb}) { + part->push_back(0); + check(pack.lookup(r, 0, warm, warm_error) == ComputePackResult::miss, "stale input accepted"); + part->pop_back(); + } + check(pack.lookup(r, 4, warm, warm_error) == ComputePackResult::miss, "stale entry accepted"); + if (hit == ComputePackResult::prepared) tested_success = true; + else tested_refused = true; + } + if (report.is_open()) + report << marker.stem().string() << '\t' << status << '\t' << live_ms << '\t' << warm_ms << '\t' + << identity << '\t' << manifest_digest << '\n'; + } + check(tested_success && tested_refused && pack.size() == success + refused, "missing test coverage"); + std::cout << "prepared=" << success << " unsupported=" << refused << " other=" << other + << " load_ms=" << load_ms << " cold_ms=" << live_total << " lookup_ms=" << warm_total << '\n'; + return 0; + } catch (const std::exception &e) { std::cerr << e.what() << '\n'; return 1; } +} diff --git a/tests/native_compute_pack_check.py b/tests/native_compute_pack_check.py new file mode 100644 index 000000000..7925f419c --- /dev/null +++ b/tests/native_compute_pack_check.py @@ -0,0 +1,109 @@ +"""Replay source-built frontend pack and check version, input identity and integrity.""" +from pathlib import Path +import os +import subprocess +import sys +import tempfile + +from native_startup_request_cache_check import (compile_compute_root, compute_program_words, + put_compute_request, state_a, COMPUTE_GROUP, COMPUTE_RSRC2) + + +def run(cli, checker, sdk): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + inputs = base / "requests" + inputs.mkdir() + root = compile_compute_root(sdk, base) + code = compute_program_words() + state = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + put_compute_request(inputs, code, root, state) + put_compute_request(inputs, bytes.fromhex("0000f8d8 00000000 000081bf"), root, state) + build = [cli, "--prepare-compute-pack", inputs, base / "cache", "0"] + result = subprocess.run(build, capture_output=True, text=True) + assert result.returncode == 0 and "prepared=1 unsupported=1 errors=0" in result.stdout, result + pack = base / "cache" / "compute-0.pack" + subprocess.run([checker, inputs, pack], check=True) + original = pack.read_bytes() + for position in (0, 64, len(original) - 1): + damaged = bytearray(original) + damaged[position] ^= 1 + pack.write_bytes(damaged) + rejected = subprocess.run([checker, inputs, pack], capture_output=True, text=True) + assert rejected.returncode and "damaged compute pack" in rejected.stderr, rejected + pack.write_bytes(original) + # Invalid source remains retryable. Other valid records still publish. + (inputs / "req_0000000000000000.c67").write_bytes(code) + result = subprocess.run(build, capture_output=True, text=True) + assert result.returncode == 1 and "prepared=1 unsupported=1 errors=1" in result.stdout, result + assert pack.read_bytes() == original + + +def hardware(cli, consumer, sdk): + import startup_gfx2hlsl_compute_check as C + from startup_compute_dispatch_check import dispatch, lines, prepare_case + from startup_compute_dispatch_native_check import LOAD_X8, LOADS_X4 + from startup_stream_check import gfx2hlsl as G + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + cache, env = prepare_case(work, "hardware") + env.pop("X2W_NATIVE_COMPUTE_PACK", None) + env["X2W_NATIVE_SHADERS"] = str(sdk) + code_file = work / "program" + original = code_file.read_bytes() + assert original.count(LOAD_X8) == 1 + words, refused = dispatch(work, str(consumer), env, "dispatch") + assert words == [C.SENTINEL] * C.WORDS and lines(refused, "unaligned descriptor table entry"), refused.stderr + code_file.write_bytes(original.replace(LOAD_X8, LOADS_X4)) + words, result = dispatch(work, str(consumer), env, "dispatch-records32") + print(result.stdout, end="") + if lines(result, "the adapter has no 32-lane waves"): + print("SKIP: native compute requires a 32-lane wave") + sys.exit(77) + assert words == C.expected("A") and lines(result, "outputs (frontend live)"), result.stderr + build = subprocess.run([cli, "--prepare-compute-pack", cache, work / "pack", "0"], check=True, + capture_output=True, text=True) + assert "prepared=1 unsupported=1 errors=0" in build.stdout, build.stdout + env["X2W_NATIVE_COMPUTE_PACK"] = str(work / "pack" / "compute-0.pack") + words, result = dispatch(work, str(consumer), env, "dispatch-records32") + assert words == C.expected("A") and lines(result, "outputs (frontend prepared)"), result.stderr + errors = [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + assert not errors, errors[0] + layer = lines(result, "x2w-d3d12 debug layer: ") + print("Debug layer:", "enabled" if layer and "0x00000000" in layer[0] else "unavailable") + words, result = dispatch(work, str(consumer), env, "dispatch") + assert words == [C.SENTINEL] * C.WORDS and lines(result, "refused:"), result.stderr + env["X2W_D3D12_COMPUTE_OUTPUT_TRACE"] = "1" + for mode in ("raw", "structured", "typed", "wrong-slot", "copied"): + words, result = dispatch(work, str(consumer), env, f"dispatch-uav-token-{mode}") + expected = [C.SENTINEL] * C.WORDS + if mode in ("raw", "structured", "typed"): + expected[4:-4] = C.expected("A")[:-8] + assert lines(result, "offset=16 bytes=1248 result=bound"), result.stderr + elif mode == "wrong-slot": + assert lines(result, "does not identify a slot-19 UAV"), result.stderr + else: + assert lines(result, "does not uniquely alias its guest byte interval"), result.stderr + assert lines(result, "use=copy-source-attempt") and not lines(result, "use=copy-read-recorded"), result.stderr + assert lines(result, "use=map-guest-read-request") and lines(result, "x2w-compute-output-submit"), result.stderr + assert words == expected, (mode, words[:16], expected[:16], result.stderr) + errors = [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + assert not errors, errors[0] + print(f"slot-19 {mode}: all {len(words)} readback words match") + # Publish the reference artifact offline. A native refusal must still try the published shader. + subprocess.run([sys.executable, "-B", G.__file__, "--pending", cache], check=True, capture_output=True, + env=dict(os.environ, X2W_DXC=str(sdk / "dxc.exe"))) + code_file.write_bytes(original) + words, result = dispatch(work, str(consumer), env, "dispatch") + assert words == C.expected("A") and lines(result, "unaligned descriptor table entry"), result.stderr + assert lines(result, "Dispatch(3, 2, 2) translated"), result.stderr + print(f"Direct and prepared dispatch matched {C.WORDS} words. Invalid binding preserved every sentinel.") + print(f"Prepared refusal followed by published translation matched {C.WORDS} words.") + + +if __name__ == "__main__": + if sys.argv[1] == "hardware": + hardware(*(Path(a).resolve() for a in sys.argv[2:])) + else: + run(*(Path(a).resolve() for a in sys.argv[1:])) diff --git a/tests/native_direct_container_check.py b/tests/native_direct_container_check.py index 1f91dc892..22b41cf88 100644 --- a/tests/native_direct_container_check.py +++ b/tests/native_direct_container_check.py @@ -107,7 +107,7 @@ def vertex(fetch=False, constants=None, program=None, extra=(), varying=False, t return pack(body, (((b"ISG1", signature(b"POSITION")),) if fetch else ()) + extra) def patched_pixel(where=1, prefix=None, table=False, input_address=0, input_signature=(), constants=None, - export=(0xf800180f, 0), root_inputs=(), wave32=False, tail=(), attributes=()): + export=(0xf800180f, 0), root_inputs=(), wave32=False, tail=(), attributes=(), uses=()): record = 112 io = record + 84 body = bytearray(io + 0x14c + 8 * 404) @@ -133,6 +133,11 @@ def patched_pixel(where=1, prefix=None, table=False, input_address=0, input_sign struct.pack_into("> 1 + 0x7e020d01, 0x7e040d02, # convert to f32 + 0x7e060280, 0x7e0802f2, # z = 0; w = 1 + 0xf80008cf, 0x04030201, # POS0 + 0x7e0a02ff, 0x200400, # triangle indices 0,1,2 + 0xf8000941, 0x80808005, 0xbf810000, + ] + + +def checked_pixel_entry(folder, compiler, sdk): + from mesh57_pixel_entry import pixel_entry + from gfx2hlsl import fnv, mesh57_key + + # One source-built v_mov/EXP pixel program. Only a reviewed version 2 + # profile with all six exact spans may supply its entry to the offline compiler. + ms = struct.pack("<%dI" % len(triangle()), *triangle()) + ps = struct.pack("<8I", *([0x7e0002f2] * 5), 0xf800180f, 0, 0xbf810000) + root_source = folder / "checked-root.hlsl" + root_source.write_text('#define RS "RootFlags(0)"') + root_file = folder / "checked-root.bin" + subprocess.run([sdk / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", root_file, root_source], check=True) + root, state_a, state_b = root_file.read_bytes(), b"abcd", b"efgh" + key = mesh57_key(ms, ps, root) + request = folder / f"req_{key:016x}.ps57" + for ext, part in ((".m57", ms), (".ps57", ps), (".root", root)): + request.with_suffix(ext).write_bytes(part) + desc = bytearray(0x300) + for word, length in ((2, len(state_a)), (4, len(state_b)), (6, len(ps)), (14, len(ms))): + struct.pack_into("=2 + # Count active lanes in both halves of a guest wave using the + # logical workgroup index. The unsigned root parameter is the bound. + # Use source-built encodings for the group index and range test. + masks=[0x9380ff03 | (22<<16),0x40018,0x8f008616 | (28<<16), + 0xd7650000,0x000038c1,0xd7660000,0x000200c1, + 0x7da80015,0xbea8047e,0xbefe04c1,0xbe941028] + text=run('mesh-range-mask',masks+controlled) + assert 'unaryBits.i32' in text + # Two guest waves share their output counts in LDS. s34 and s35 + # are bounded by source masks on the dynamic root input. Lane 0 + # writes both LDS slots; wave 1 reads the same pair after rendezvous. + count_setup=[0x9380ff03|(22<<16),0x40018,0xbe880381,0xbe890380, + 0x87228315,0x87238115] + def movv(v,s): return 0x7e000200|(v<<17)|s + p_reg,v_reg=35,34 + allocate=[0xbf8a0000,0xbf008016,0xbf840010,0xbefe0408,0xbf880007, + movv(2,p_reg),movv(3,128),movv(4,v_reg),0xd8340000,0x0203, + 0xd8340004,0x0403,0xbefe04c1,0xbfa3ffe3,0xbf8a0000, + 0x8f088c00|p_reg,0x887c0008|(v_reg<<8),0xbf900009,0xbf82000d, + 0xbf8a0000,0xbefe0408,0xbf880009,movv(6,128),0xd8d80000, + (7<<24)|6,0xd8d80004,(6<<24)|6,0xbf8cc17f, + 0x7e000500|(p_reg<<17)|7,0xbf8cc07f,0x7e000500|(v_reg<<17)|6,0xbefe04c1] + text=run('group-counts',count_setup+allocate+program[3:]) + assert '@meshCounts' in text and 'setMeshOutputCounts(i32 168, i32 %' in text + bad_slot=allocate.copy() + bad_slot[25]=0xd8d80008 + run('wrong-count-slot',count_setup+bad_slot+program[3:],'unsupported mesh instruction') + overflow=count_setup.copy() + overflow[-1]=0x87238315 + run('too-many-primitives',overflow+allocate+program[3:],'exceeds declared range') + layout.write_text('mesh1 128 3 1 2 128 64\ntable 16 0') + run('mistyped-root',words+controlled,'root parameter kind') + layout.write_text('mesh1 128 3 1 2 128 64') + # A second allocation request/invalid maxima and unknown descriptors never emit partial bytecode. + run('second-allocation', program[:3]+[0xbf900009]+program[3:], 'requires one uniform') + run('over-limit', [program[0],0x1004]+program[2:], 'exceeds declared') + run('unknown-root', [0xf4080308,0xfa000b20]+program, 'verified guest root') + + # Lane zero of wave zero stores its group identifier, then both + # waves rendezvous before the other wave reads the word. + exchange = [0xbefe0481,0xbe88047e,0x870aff03,0x0f000000,0xbf850007,0x2c0a0a87, + 0x7e000280,0xd8340008,0x500,0xbfa3ffe3,0xbf8a0000,0xbf820004, + 0xbf8a0000,0x7e000280,0xd8d80008,0x05000000,0xbefe04c1,0x7e240505] + reads_group = program.copy() + reads_group[7] = 0x7e020c12 # v_cvt_f32_u32 v1,s18 uses the readfirstlane result + assert 'call i32 @dx.op.groupId.i32' in run('group',exchange+reads_group) + broken = exchange.copy() + broken[12] = 0xbf800000 # missing rendezvous on the reading wave + run('mismatched-barriers',broken+reads_group,'unsupported mesh instruction') + print('mesh allocation, indexed outputs, group exchange and negative controls passed') + + +if __name__ == '__main__': + main() diff --git a/tests/native_frozen_request_check.cpp b/tests/native_frozen_request_check.cpp new file mode 100644 index 000000000..7a86aa7b3 --- /dev/null +++ b/tests/native_frozen_request_check.cpp @@ -0,0 +1,54 @@ +#include "frozen_compute_requests.h" +#include +#include +#include + +namespace { +x2w::ComputeRequest fixture(uint64_t key) { + x2w::ComputeRequest r{"code", "data", "root", std::string(96, 0), std::string(28, 0), {}, key}; + const auto length = [&](size_t offset, uint64_t n) { std::memcpy(r.description.data() + offset, &n, sizeof(n)); }; + length(48, r.code.size()); + length(64, r.data.size()); + length(16, r.sa.size()); + return r; +} +void require(bool ok, const char *reason) { + if (!ok) throw std::runtime_error(reason); +} +} + +int main() { + try { + x2w::FrozenComputeRequests pool(4096, 2); + auto first = fixture(1); + pool.put(first); + first.code[0] = 'x'; + auto saved = pool.take(1); + require(saved && saved->code == "code", "snapshot changed with caller"); + x2w::validate_compute_request_shape(*saved); + require(!pool.take(1), "consumed snapshot still present"); + pool.put(first); + pool.put(fixture(2)); + pool.put(fixture(2)); + pool.put(fixture(3)); + require(!pool.take(1) && pool.take(2) && pool.take(3), "FIFO eviction or duplicate key failed"); + auto stats = pool.stats(); + require(stats.hits == 3 && stats.misses == 2 && stats.evicted == 1 && !stats.bytes && !stats.entries, + "handoff accounting mismatch"); + x2w::FrozenComputeRequests tiny(32), disabled(0); + tiny.put(first); + disabled.put(first); + require(!tiny.take(1) && !disabled.enabled() && !disabled.take(1), "byte budget exceeded"); + auto broken = *saved; + broken.description[48] ^= 1; + try { + x2w::validate_compute_request_shape(broken); + } catch (const std::runtime_error &) { + return 0; + } + throw std::runtime_error("inconsistent description accepted"); + } catch (const std::exception &e) { + std::cerr << e.what() << '\n'; + return 1; + } +} diff --git a/tests/native_graphics_interface_library_check.py b/tests/native_graphics_interface_library_check.py index 79d3142ab..206449002 100644 --- a/tests/native_graphics_interface_library_check.py +++ b/tests/native_graphics_interface_library_check.py @@ -59,6 +59,27 @@ def batch(folder, output, **kwargs): assert subprocess.run([compiler,*install],capture_output=True).returncode batch(requests,base/"retained") + # Two reflected parameter rows. The fixed PS uses P1/P2 for x + # and MOV P0 for y of row zero; hardware only allocates that row. + fixed = base / "fixed" + fixed.mkdir() + vp = [0x7e0002f2, 0xf80008cf, 0, 0xf800020f, 0, 0xf800021f, 0, end] + (fixed / "varying.cdxil").write_bytes(vertex(program=vp)) + def interpolate(attr, channel, op, dst, src): + return 0xc8000000 | dst << 18 | op << 16 | attr << 10 | channel << 8 | src + template = prefix + [interpolate(0, 0, 0, 4, 0), interpolate(0, 0, 1, 4, 1)] + attributes = [(6, row, 15, row, 0, 0, row, 2) for row in range(2)] + (fixed / "smooth.cdxil").write_bytes(patched_pixel( + len(template), template, input_address=2, attributes=attributes)) + run("--index-graphics-interfaces", fixed, cache) + for attr, count, error in ((0, 1, None), (1, 2, None), + (1, 1, "interpolation inputs disagree"), + (0, 3, "captured interpolation count")): + code = words(*template, interpolate(attr, 1, 2, 5, 2), 0xf800180f, 0x05040504, end) + folder = base / f"fixed-{attr}-{count}" + publish(folder, code, words(*vp), root, slot57_inputs=(2, count)) + batch(folder, base / f"linked-{attr}-{count}", expected=error) + # An exact VS writes a four-component image through the second # guest slot. The serialized root covers just the first slot. # The FSSM offset, descriptor width, class and SGPR establish the diff --git a/tests/native_graphics_sampler_heap_check.py b/tests/native_graphics_sampler_heap_check.py new file mode 100644 index 000000000..37f063c65 --- /dev/null +++ b/tests/native_graphics_sampler_heap_check.py @@ -0,0 +1,68 @@ +"""Read back slots in the C++ raw graphics sampler-table lowering.""" +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from native_direct_container_check import publish +from startup_sampler_heap_check import CONST_WORDS, FULLSCREEN_VS, MIXED_WORDS, PS_WORDS, VS_WORDS + + +def move(dst, src): + return struct.pack(" exact -> WQM: the exact write to unallocated v4 has no old + # helper value. Packed arithmetic observes only the eventual color. + prefix = [sop1(4, 10, 126), sop1(10, 126, 126), sop1(4, 12, 126), + sop1(4, 126, 10), vmove(4, 242), sop1(4, 126, 12)] + tail = fma(0xcc210000, 260) + high + [sop1(4, 126, 10)] + kwargs = dict(input_address=1 << 8, input_signature=(position, target)) + draw(packed_color(prefix + tail, **kwargs), expected) + quad_read = [vmove(2, 250), 0xff04b104] # DPP reads v4 from another quad lane + result = compile_guest(packed_color(prefix + quad_read + tail, **kwargs)) + assert result.returncode and "entry VGPR 4" in result.stderr, result.stderr + + # CMPX compares 4.0 < SV_Position.x. Its read-only arm updates v2 + # only on the right half of the draw; all pixels export after restore. + def cmpx(body): + code = [vmove(2, 242), sop1(4, 10, 126), 0x7c2200f6, + 0xbf880000 | len(body), *body, sop1(4, 126, 10)] + return patched_pixel(len(code), code, export=(0xf800180f, 0x02020202), **kwargs) + + draw(cmpx([vmove(2, 244)]), [(1.0 + (lane % 8 >= 4),) * 4 for lane in range(16)]) + result = compile_guest(cmpx(quad_read)) + assert result.returncode and "graphics branch on a wave mask" in result.stderr, result.stderr + + # Cross-quad EXECZ (#2907). A region term (axis, "le"|"ge", value) keeps the lanes with # SV_Position.axis <= value or >= value; the compare sets VCC for the lanes it removes. def term_compare(axis, op, value): @@ -241,6 +286,32 @@ def draw(blob, pixels): result=run(blob,pixels) assert result.returncode==0,(result.stdout,result.stderr) print(result.stdout.strip()) + # On a 2x2 quad, compare the vertical neighbor with the negated + # current value. The equal case on column two checks ordered GT. + cmp_code=[sop1(10,126,126),0x06220300,0x062222ff,0xc0600000, # v17 = x+y-3.5 + 0x7c0822fa,0xff4c4e11,0x7e0402f2,0x02000480] + def quad_compare(code): + return patched_pixel(len(code),code,input_address=0x300, + input_signature=((b"ISG1",signature(b"SV_Position",1)),)) + expected=[(float(x>=3),)*4 for y in range(2) for x in range(8)] + draw(quad_compare(cmp_code),expected) + # The high word of v54 contains floor(x). Its low word is zero. + # -1 as 32-bit raw bits is qNaN (class bit 1), while 0x7c01 is + # binary16 sNaN (bit 0). Both arms write v0, on complementary EXEC. + for half in (False,True): + selector=[0x7d1e6cf9,0x0586b40f] if half else [0x7d106cf9,0x0586b4c1] + seq=[0x7e6c0f00,0x346c6c90,0xbe8f03ff,0x7c01,0xbebc047e, + *selector,0xbeb40834,0x87fe7e34,0xbf880001,0x7e0002f2, + 0x8afe7e3c,0x7e0002f0,0xbefe043c] + flags=1 if half else 2 + reference=[(0.5 if x & flags else 1.0,)*4 for y in range(2) for x in range(8)] + draw(quad_compare(seq),reference) + for control in (0xff4ce411,0xff0c4e11): # Identity permutation or unnegated src1. + wrong=cmp_code.copy() + wrong[5]=control + failed=run(quad_compare(wrong),expected) + assert failed.returncode==1 and "pixels differ" in failed.stderr,failed.stderr + check_packed_and_exact_exec(draw, compile_guest) for lo,hi,narrow in ((0,0,False),(0,1,False),(0x80000000,0,False), (0x80000021,0x42,False),(0,1,True),(0x22,0,True)): a,b=quad_mask(lo),0 if narrow else quad_mask(hi) diff --git a/tests/native_indexed_pixel_texture_check.py b/tests/native_indexed_pixel_texture_check.py new file mode 100644 index 000000000..51504e971 --- /dev/null +++ b/tests/native_indexed_pixel_texture_check.py @@ -0,0 +1,88 @@ +"""Verify bounded eight-DWORD PS texture lookups in the linked native path.""" +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from native_direct_container_check import patched_pixel, publish, vertex, words + + +def texture_program(original, mask, opposite, base_offset=32): + # Adapt the existing MRT draw. t0 holds one runtime byte offset and the UV + # offset. t1 and t2 have different colors and different spatial patterns. + source = list(struct.unpack(f"<{len(original) // 4}I", original)) + start = source.index(0xf4100000 | (16 << 6) | 10) + assert source[start + 1] == 0xfa000020 and source[start + 3] == 0xfa000038 + + # Move the table base to s[48:49] before reading s[16:23] and s[24:31]. + source[0:2] = [0xbe800300 | (48 << 16) | 8, 0xbe800380 | (49 << 16)] + source[start - 2] = (source[start - 2] & ~63) | 24 + offset_load = source[start + 2:start + 4] + + # Explicit words of the fixture's point sampler (2 bits set at bit 54). + sampler = [0xbeac0380, 0xbead03ff, 0x00c00000, 0xbeae0380, 0xbeaf0380] + # Define untouched halves of the fixture's packed export VGPRs. + initial = [0x7e000280 | (dst << 17) for dst in (47, 80, 81)] + + def and_mask(dst, src): + return 0x87000000 | (dst << 16) | ((128 + mask) << 8) | src + + # s40 = s12 & mask; s41 = (s12 ^ toggle) & mask. Select each + # descriptor from the same base byte offset in the same bound root table. + toggle = 32 if opposite else 0 + lookups = [*offset_load, and_mask(40, 12), + 0xf40c0000 | (16 << 6) | 24, (40 << 25) | base_offset, + 0x89000000 | (41 << 16) | ((128 + toggle) << 8) | 12, + and_mask(41, 41), 0xf40c0000 | (24 << 6) | 24, (41 << 25) | base_offset] + return words(*initial, *source[:start], *lookups, *sampler, *source[start + 7:]) + + +def run(work, writer, compiler, sdk, adapter): + subprocess.run([writer, "--write-fixture", work], check=True) + vs, ps, root = [(work / name).read_bytes() for name in ("vertex.bin", "pixel.bin", "root.bin")] + cache, output = work / "cache", work / "objects" + for name, mask, offset, refusal in ( + ("distinct", 32, 32, ""), ("same", 32, 32, ""), + ("unaligned", 31, 32, "32-byte-aligned SRV offset"), + ("short-table", 32, 96, "exceeds its declared root range"), + ): + program = texture_program(ps, mask, name != "same", offset) + key = publish(work / name, program, vs, root, ps_inputs=(2, 2)) + result = subprocess.run([compiler, sdk, cache, "gfx1013-container-pair", + "--requests", work / name, output], capture_output=True, text=True) + if refusal: + assert result.returncode and refusal in result.stderr, result.stderr + print(name, refusal) + continue + assert result.returncode == 0, result.stderr + manifest = (output / f"{key}.txt").read_text().splitlines() + assert {"srv 1 tex2d table 0 32", "srv 2 tex2d table 0 64"} <= set(manifest), manifest + result = subprocess.run([writer, adapter, sdk, cache, output / f"{key}.ps.cso", output / f"{key}.vs.cso"], + text=True, capture_output=True) + print(name, result.returncode, result.stdout.strip(), result.stderr.strip()) + if result.returncode == 77: + return 77 + if name == "distinct": + assert result.returncode == 0, result.stderr + else: + assert result.returncode and "sampled MRT mismatch" in result.stderr, result.stderr + + # Type 5 denotes the global resource heap. A real table at root 0 exists, + # but a load via this unrelated ABI input must never resolve to that table. + heap = [0xbe810380, 0x8702a002, 0xf40c0200, 2 << 25, 0x7e000280, 0x7e020280, + 0xf0000108, 0x00020000] + pixel = patched_pixel(len(heap), heap, root_inputs=((5, 0, 1, 0, 0), (0, 0, 1, 0, 0x102))) + request = work / "global-heap" + key = publish(request, vertex(), pixel, root) + result = subprocess.run([compiler, sdk, cache, "gfx1013-container-pair", + "--requests", request, output], capture_output=True, text=True) + assert result.returncode and not (output / f"{key}.txt").exists(), result.stderr + assert "direct descriptor address outside bound table" in result.stderr, result.stderr + print("global-heap", result.stderr.strip()) + return 0 + + +if __name__ == "__main__": + with TemporaryDirectory() as folder: + sys.exit(run(Path(folder), *sys.argv[1:])) diff --git a/tests/native_mtbuf_check.py b/tests/native_mtbuf_check.py index a240b9c14..fe3a74029 100644 --- a/tests/native_mtbuf_check.py +++ b/tests/native_mtbuf_check.py @@ -12,6 +12,7 @@ # format, channels actually requested, immediate byte displacement (plus group.x) CASES = [(24, 2, 0), (24, 2, 4), (56, 4, 3), (60, 4, 7), (13, 1, 12), (71, 4, 12), (75, 4, 4), (2, 1, 7), (12, 1, 7), (25, 2, 3), (24, 2, 8188)] +CASES += [(fmt, 4, 1) for fmt in range(44, 56)] PACKED = struct.pack("<6I", 0x7fff8000, 0x40008001, 0x007fff81, 0xfc003c00, 0x0001bc00, 0x42987ec5) @@ -19,7 +20,7 @@ def program(unsigned): # Load a raw SRV and UAV from separate table parameters. One writer per group. words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 22, 5), sop1(3, 23, 128), 0xf4080000 | 32 << 6 | 10, 0xfa000020, 0xf4080000 | 36 << 6 | 11, 0xfa000020, - scalar(0x1e, 7, 6, 135), vmove(8, 7), sop1(3, 126, 129)] + scalar(0x1e, 7, 6, 137), vmove(8, 7), sop1(3, 126, 129)] pos = 0 for index, (fmt, channels, disp) in enumerate(CASES): if unsigned and index == 0: @@ -45,6 +46,23 @@ def expected(group): result = [] data = (PACKED * 342)[:8192] for fmt, count, disp in CASES: + if 44 <= fmt <= 55: + fields = (2, 10, 10, 10) if fmt < 50 else (10, 10, 10, 2) + number = (fmt - 44) % 6 + bits = int.from_bytes(data[disp + group:disp + group + 4], "little") + for width in fields[:count]: + value = bits & ((1 << width) - 1) + bits >>= width + if number in (1, 3, 5) and value >> (width - 1): + value -= 1 << width + if number == 0: + value = fbits(value / ((1 << width) - 1)) + elif number == 1: + value = fbits(max(-1, value / ((1 << (width - 1)) - 1))) + elif number in (2, 3): + value = fbits(value) + result.append(value & 0xffffffff) + continue width = 4 if fmt == 75 else 1 if fmt in (2, 56, 60) else 2 if disp + group + width * count > len(data): result.extend([0] * count) @@ -73,7 +91,7 @@ def main(cli, gpu, sdk): sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x8c) reference = [0x69696969] * 2064 for group in range(2): - start = 8 + 32 * group + start = 8 + 128 * group row = expected(group) reference[start:start + len(row)] = row for unsigned in (False, True): @@ -87,7 +105,7 @@ def main(cli, gpu, sdk): actual = struct.unpack("<2064I", dest.read_bytes()) differences = [i for i, (a, b) in enumerate(zip(actual, reference)) if a != b] if unsigned: - assert differences and set(differences) <= {8, 9, 40, 41}, differences + assert differences and set(differences) <= {8, 9, 136, 137}, differences else: assert not differences, [(i, hex(actual[i]), hex(reference[i])) for i in differences] insn = next(i for i, w in enumerate(words) if w >> 26 == 0x3a) diff --git a/tests/native_scalar_lds_check.py b/tests/native_scalar_lds_check.py index 01b7f7905..4f4a9280c 100644 --- a/tests/native_scalar_lds_check.py +++ b/tests/native_scalar_lds_check.py @@ -87,6 +87,29 @@ def built_root_readback(work, gpu, sdk): print("Root-built scalar x8 matched 16 words and all guards at each offset; shifting by one dword changed all 16.") + # The byte address in v8 overlaps the first destination of the x3 load. + # Select a different source window in each group and keep all guard words. + words = [sop1(3, 16, 4), scalar(0x10, 17, 5, 255), 0x10000, + sop1(3, 18, 193), sop1(3, 19, 255), 0x11014fac, + sop1(3, 20, 6), sop1(3, 21, 128), 0xf4080000 | 40 << 6 | 10, 0xfa000020, + scalar(0x1e, 12, 7, 132), vmove(8, 12), vmove(11, 12), + # The replay fixture creates the smallest raw SRV requested by the + # program. A scalar load at byte 24 provisions the seven-word view. + 0xf4200000 | (25 << 6) | 8, 0xfa000018, + 0xe03c1000, 0x80040808, sop1(3, 126, 129)] + for j in range(3): + words.extend([0xe0701000 | 4*j, 0x800a000b | (8+j) << 8]) + marker = write_request(work, words + [0xbf810000], root.read_bytes(), sa) + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + expected = [0x69696969] * 2064 + for group in range(2): + for j in range(3): + expected[8 + group * 4 + j] = 0x51aa0000 + group * 4 + j + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i,a,b) for i,(a,b) in enumerate(zip(actual,expected)) if a!=b][:10] + print("Root descriptor with byte stride one: x3 load matches both source windows and all guards.") + + def vector_carry_readback(work, gpu, sdk): def vop2(op, dst, a, b): return op << 25 | dst << 17 | b << 9 | a diff --git a/tests/native_store_replay.cpp b/tests/native_store_replay.cpp index 43b7af3df..e6eb4f184 100644 --- a/tests/native_store_replay.cpp +++ b/tests/native_store_replay.cpp @@ -187,7 +187,8 @@ int wmain(int argc, wchar_t **argv) { transition(cmd.list.Get(),w.resource.Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_UNORDERED_ACCESS); D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; v.ViewDimension=D3D12_UAV_DIMENSION_BUFFER;v.Buffer.FirstElement=guard;v.Buffer.NumElements=elements; - v.Format=raw?DXGI_FORMAT_R32_TYPELESS:typed_format(stride,b.kind==ComputeViewKind::half_buffer_uav,false); + v.Format=raw?DXGI_FORMAT_R32_TYPELESS:typed_format(stride,b.kind==ComputeViewKind::half_buffer_uav || + b.kind==ComputeViewKind::packed_d16_x_uav,false); if(raw)v.Buffer.Flags=D3D12_BUFFER_UAV_FLAG_RAW; if (indexed) { if (stride > 4) { @@ -203,7 +204,8 @@ int wmain(int argc, wchar_t **argv) { if(!native_buffer_store_view(b,v,w.bytes,&shape) || native_buffer_store_view(b,truncated,w.bytes-guard*stride-1,&shape)) return 2; if (indexed) atomic.push_back(shape); - if(reference&&!raw)v.Format=typed_format(stride,b.kind==ComputeViewKind::half_buffer_uav,true); + if(reference&&!raw)v.Format=typed_format(stride,b.kind==ComputeViewKind::half_buffer_uav || + b.kind==ComputeViewKind::packed_d16_x_uav,true); device->CreateUnorderedAccessView(w.resource.Get(),nullptr,&v,cpu); w.readback=make_buffer(device.Get(),w.bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); } else { diff --git a/tests/native_wave_virtual_derivative_check.py b/tests/native_wave_virtual_derivative_check.py new file mode 100644 index 000000000..17dfacfa3 --- /dev/null +++ b/tests/native_wave_virtual_derivative_check.py @@ -0,0 +1,93 @@ +"""Packed slot-67 control for implicit derivatives in a virtual wave64 group. + +The virtual-wave scheduler needs the packed state, more than one guest wave64, +and a conditional branch plus a synchronizing instruction. The container +fixture does not enter that path. This source-built request keeps the explicit +LOD and ordinary implicit cases compiling, and requires the combination to be +refused at the image opcode instead of producing a shader with no scheduler +readback. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request + + +WIDTH = 8 +SAMPLER = (0x12, 0xFFF000, 0x04500000, 0) + + +def bits(value): + return struct.unpack(" +#include #include #include #include @@ -110,7 +112,9 @@ static std::optional compile_one(x2w::ShaderDxilCompiler& compiler, const std::wstring direct_prefix=L"gfx1013-direct-cs@"; const bool container=profile==L"gfx1013-container-cs"; const bool graphics=profile==L"gfx1013-container-vs" || profile==L"gfx1013-container-ps"; - const bool direct=container || graphics || profile==L"gfx1013-direct-constant-ps" || profile.compare(0,direct_prefix.size(),direct_prefix)==0; + const bool mesh_pixel=profile==L"gfx1013-raw-mesh-ps"; + const bool mesh=profile==L"gfx1013-container-ms-uint-heap" || profile==L"gfx1013-container-ms" || profile==L"gfx1013-raw-ms"; + const bool direct=container || graphics || mesh || mesh_pixel || profile==L"gfx1013-direct-constant-ps" || profile.compare(0,direct_prefix.size(),direct_prefix)==0; const std::wstring compute_prefix=direct?direct_prefix:L"gfx1013-compute-wave32@"; if(container || profile.compare(0,compute_prefix.size(),compute_prefix)==0){ auto offset=container?L"0":profile.substr(compute_prefix.size()); @@ -168,7 +172,88 @@ static std::optional compile_one(x2w::ShaderDxilCompiler& compiler, source.assign(std::istreambuf_iterator(input),{}); if (input.bad()) throw std::runtime_error("source read failed"); } - if(graphics){ + if(mesh){ + auto mesh_ir=[&](x2w::NativeComputeShader shader) { + for (const auto &read : shader.mesh_heap_reads) + report<<"requires_heap_r32_uint root="<>version>>layout.threads>>layout.max_vertices>>layout.max_primitives>>layout.topology>> + layout.group_stride>>wave) || version!="mesh1" || (wave!=32 && wave!=64)) + throw std::runtime_error("raw mesh requires explicit mesh1 threads vertices primitives topology group_stride wave"); + layout.wave32=wave==32; + while (meta>>extra) { + if (extra=="packed_parameters") { + layout.packed_parameters=true; + continue; + } + if (extra=="validate_uint_heap_reads") { + layout.validate_uint_heap_reads=true; + continue; + } + if (extra=="resource_heap") { + unsigned sgpr; + if (layout.resource_heap_sgpr || !(meta>>sgpr)) throw std::runtime_error("invalid mesh resource heap"); + layout.resource_heap_sgpr=sgpr; + continue; + } + x2w::MeshRootInput input{}; + input.root_address=extra=="root_address"; + if ((extra!="table" && extra!="constants" && !input.root_address) || !(meta>>input.sgpr>>input.root_parameter) || + (extra=="constants" && (!(meta>>input.constant_count) || !input.constant_count))) + throw std::runtime_error("invalid mesh entry root mapping"); + layout.root_inputs.push_back(input); + } + if (layout.root_inputs.empty()) source=mesh_ir(x2w::translate_mesh_program(source,layout)); + else { + auto bytes=x2w::read_shader_container_bytes(fs::path(input_path).replace_extension(L".root")); + Microsoft::WRL::ComPtr signature; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *desc=nullptr; + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(bytes.data(),bytes.size(),IID_PPV_ARGS(&signature))) || + FAILED(signature->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1,&desc))) + throw std::runtime_error("invalid raw mesh root signature"); + source=mesh_ir(x2w::translate_mesh_program(source,layout,desc->Desc_1_1)); + } + } + profile=L"ms_6_6"; + } else if (mesh_pixel) { + std::ifstream meta(fs::path(input_path).replace_extension(L".pslayout")); + std::string tag, extra; + unsigned enable, address, wave; + if (!(meta >> tag)) + throw std::runtime_error("raw mesh PS needs a reviewed entry layout"); + if (tag == "meshps1") { + if (!(meta >> enable >> address >> wave)) + throw std::runtime_error("raw mesh PS needs meshps1 enable address wave (decimal)"); + } else if (tag == "meshps2") { + // As in Victory's native PS reflection, this record names the + // inputs delivered by ADDR when a separate ENA mask is unavailable. + if (!(meta >> address >> wave)) + throw std::runtime_error("raw mesh PS needs meshps2 input-address wave (decimal)"); + enable = address; + } else { + throw std::runtime_error("unknown raw mesh PS entry layout version"); + } + const bool guest_root = bool(meta >> extra); + if (guest_root && (extra!="guest_root" || (meta >> extra))) + throw std::runtime_error("unexpected raw mesh PS layout field"); + Microsoft::WRL::ComPtr signature; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *desc=nullptr; + if (guest_root) { + auto bytes=x2w::read_shader_container_bytes(fs::path(input_path).replace_extension(L".root")); + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(bytes.data(),bytes.size(),IID_PPV_ARGS(&signature))) || + FAILED(signature->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1,&desc))) + throw std::runtime_error("invalid raw mesh PS root signature"); + } + source=x2w::translate_mesh_pixel_program(source,enable,address,wave,desc ? &desc->Desc_1_1 : nullptr).dxil_ir; + profile=L"ps_6_6"; + } else if(graphics){ bool pixel=profile==L"gfx1013-container-ps"; if(linked)source=linked->dxil_ir; else source=x2w::translate_graphics_container(source,pixel).dxil_ir; @@ -629,6 +714,18 @@ struct WatchRequest { bool compute = false; }; +static bool read_small_file(const fs::path& path, size_t max_bytes, std::string& out) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + if (!file) + return false; + const auto size = file.tellg(); + if (size < 0 || static_cast(size) > max_bytes) + return false; + out.assign(static_cast(size), '\0'); + file.seekg(0); + return !size || static_cast(file.read(out.data(), size)); +} + static bool is_watch_request_pending(const fs::path& request_dir, const WatchRequest& req, bool skip_failed) { std::error_code ec; const auto marker_mtime = fs::last_write_time(req.marker, ec); @@ -640,20 +737,38 @@ static bool is_watch_request_pending(const fs::path& request_dir, const WatchReq const fs::path psdep_path = fs::path(stem) += L".psdep"; std::optional psin_mtime; + bool dependency_changed = false; bool lost = false; + bool sidecar_changed = false; if (!req.compute) { if (const auto psin_path = graphics_psin_path(req.marker)) { - if (fs::is_regular_file(*psin_path, ec)) { - const auto t = fs::last_write_time(*psin_path, ec); + const auto packed_path = fs::path(*psin_path).replace_extension(L".ps57in"); + const bool stream = fs::is_regular_file(*psin_path, ec); + const bool packed = fs::is_regular_file(packed_path, ec); + if (stream || packed) { + const auto time = fs::last_write_time(stream ? *psin_path : packed_path, ec); if (!ec) - psin_mtime = t; + psin_mtime = time; + } + const bool has_psdep = fs::is_regular_file(psdep_path, ec); + std::string published_dep; + if (has_psdep && (!read_small_file(psdep_path, 256, published_dep) || published_dep.empty())) { + sidecar_changed = true; + } else { + try { + const std::string current_dep = + x2w::read_pixel_input_description(fs::path(*psin_path).replace_extension(L".a")); + sidecar_changed = current_dep != published_dep; + } catch (const std::exception&) { + sidecar_changed = true; + } } - lost = !psin_mtime.has_value() && fs::is_regular_file(psdep_path, ec); } + lost = !psin_mtime.has_value() && fs::is_regular_file(psdep_path, ec); } const bool has_manifest = fs::is_regular_file(manifest_path, ec); - if (has_manifest && !lost) { + if (has_manifest && !sidecar_changed && !lost && !dependency_changed) { if (req.compute) { // A native manifest from another revision, or an unmarked one without the Python translator's // .cs.hlsl, is stale. Other outputs, and a manifest that cannot be read, go on to the usual @@ -680,7 +795,7 @@ static bool is_watch_request_pending(const fs::path& request_dir, const WatchReq } } - const bool recheck = lost && has_manifest; + const bool recheck = sidecar_changed && has_manifest; if (skip_failed && !recheck && fs::is_regular_file(fail_path, ec)) { const auto fail_mtime = fs::last_write_time(fail_path, ec); const auto latest_input = @@ -1281,6 +1396,22 @@ int wmain(int argc, wchar_t** argv) { return run_watch(argc, argv); if (argc >= 2 && std::wstring_view(argv[1]) == L"--refusals") return run_refusals(argc, argv); + if (argc == 5 && std::wstring_view(argv[1]) == L"--prepare-compute-pack") { + try { + std::wstring number(argv[4]); + if (number.empty() || number.size() > 7 || number.find_first_not_of(L"0123456789") != number.npos) + throw std::runtime_error("invalid compute entry byte offset"); + auto start = Clock::now(); + auto counts = x2w::build_compute_frontend_pack(argv[2], argv[3], static_cast(std::stoul(number))); + for (const auto &error : counts.errors) std::cerr << "unprepared " << error << "\n"; + std::cout << "prepared=" << counts.prepared << " unsupported=" << counts.unsupported + << " errors=" << counts.errors.size() << " elapsed_ms=" << std::chrono::duration(Clock::now()-start).count() << "\n"; + return counts.errors.empty() ? 0 : 1; + } catch (const std::exception &error) { + std::cerr << "pack not published: " << error.what() << "\n"; + return 1; + } + } if (argc == 4 && std::wstring_view(argv[1]) == L"--index-graphics-interfaces") { try { const auto stages = x2w::index_graphics_interfaces(argv[2],argv[3]); @@ -1301,7 +1432,9 @@ int wmain(int argc, wchar_t** argv) { "gfx1013-vertex-id-vs or gfx1013-buffered-vs for a raw vertex program. gfx1013-sampled-pair takes one VS and one PS (in order).\n" "gfx1013-buffered-pair takes a buffered vertex program and a pixel HLSL source.\n" "gfx1013-group-clear@BYTE_OFFSET and gfx1013-compute-wave32@BYTE_OFFSET take a req_.c67.\n" - "Direct DXIL profiles: gfx1013-direct-cs@BYTE_OFFSET, gfx1013-container-cs, gfx1013-container-vs, gfx1013-container-ps.\n" + "Direct DXIL profiles: gfx1013-direct-cs@BYTE_OFFSET, gfx1013-container-cs, gfx1013-container-vs, gfx1013-container-ps, gfx1013-container-ms.\n" + "gfx1013-raw-ms reads guest mesh bytes and an explicit .mslayout sidecar.\n" + "gfx1013-raw-mesh-ps uses a reviewed .pslayout sidecar (meshps1 or meshps2).\n" "gfx1013-container-cs reads an optional req_.views next to the .cdx (GPU-selected heap slot view types).\n" "gfx1013-container-pair accepts two containers and emits VS then PS using the runtime register allocation.\n" "For capture directories use PROFILE --requests DIRECTORY OUTPUT_DIRECTORY. " @@ -1310,7 +1443,8 @@ int wmain(int argc, wchar_t** argv) { "Use --refusals REQUEST_DIRECTORY [--jobs N] [--json] for a read-only refusal summary.\n" "Use --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY [--jobs N] [--interval MS] [--once] to translate pending requests.\n" "Use --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N] to copy requests under the current cache revision keys.\n" - "Use --index-graphics-interfaces REVIEWED_DIRECTORY CACHE_DIRECTORY to index native graphics interfaces.\n"; + "Use --index-graphics-interfaces REVIEWED_DIRECTORY CACHE_DIRECTORY to index native graphics interfaces.\n" + "Use --prepare-compute-pack REQUEST_DIRECTORY CACHE_DIRECTORY ENTRY_BYTE_OFFSET for captured compute.\n"; return 2; } try { @@ -1374,6 +1508,13 @@ int wmain(int argc, wchar_t** argv) { jobs = (std::min)(parse_jobs_count(argv[4]), count); auto start=Clock::now(); std::set occupied(inputs.begin(),inputs.end()); + if(profile==L"gfx1013-raw-ms" || profile==L"gfx1013-raw-mesh-ps") { + for (const auto& input : inputs) { + const auto layout = profile==L"gfx1013-raw-ms" ? L".mslayout" : L".pslayout"; + occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(layout))); + occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(L".root"))); + } + } if(compute_request) { for(const auto& input : inputs) { for(auto suffix : {L".root",L".data",L".sa",L".sb",L".desc",L".views"}) @@ -1382,7 +1523,7 @@ int wmain(int argc, wchar_t** argv) { } if(graphics_batch) { for(const auto& input : inputs) { - for(auto suffix : {L".b",L".root",L".ia",L".psin"}) + for(auto suffix : {L".b",L".root",L".ia",L".psin",L".ps57in"}) occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(suffix))); } } @@ -1441,19 +1582,26 @@ int wmain(int argc, wchar_t** argv) { if (!manifest && !input.rtv_request.empty()) throw std::runtime_error("RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described"); std::vector gs_dxil; - if (rectangles) { - auto ir=x2w::native_rectangle_geometry(pair.vertex.outputs,pair.pixel.inputs); - gs_dxil = compile_to_dxil(compiler, ir, L"gs_6_6", argv[2], true, report); + if (rectangles || (manifest && !pair.input_layout.empty())) { + std::string ir; + try { ir = x2w::native_rectangle_geometry(pair.vertex.outputs, pair.pixel.inputs); } + catch (const x2w::UnsupportedComputeShader&) { if (rectangles) throw; } + if (!ir.empty()) { + gs_dxil = compile_to_dxil(compiler, ir, L"gs_6_6", argv[2], true, report); + if (manifest) *manifest += "fixedrectgs\n"; + } } auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", argv[2], true, report); auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", argv[2], true, report); - if (rectangles) + if (!gs_dxil.empty()) publish_atomic(fs::path(stems[i]) += L".gs.cso", gs_dxil.data(), gs_dxil.size()); publish_atomic(outputs[i], vs_dxil.data(), vs_dxil.size()); publish_atomic(fs::path(stems[i]) += L".ps.cso", ps_dxil.data(), ps_dxil.size()); if (manifest) { if (!input.pixel_input_description.empty()) publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size()); + else + fs::remove(psdep_path, ignored); publish_atomic(manifest_path, manifest->data(), manifest->size()); } fs::remove(fs::path(stems[i]) += L".fail", ignored); diff --git a/tools/startup/mesh57_pixel_entry.py b/tools/startup/mesh57_pixel_entry.py new file mode 100644 index 000000000..89d356d64 --- /dev/null +++ b/tools/startup/mesh57_pixel_entry.py @@ -0,0 +1,75 @@ +"""Read a reviewed pixel entry only when a slot 57 creation archive and all six profile spans match.""" +import argparse +from pathlib import Path +import struct +import sys + +from gfx2hlsl import fnv, mesh57_key + + +def pixel_entry(request, archive, profile): + ms, ps, root = (request.with_suffix(ext).read_bytes() for ext in (".m57", ".ps57", ".root")) + key = mesh57_key(ms, ps, root) + if request.name != f"req_{key:016x}.ps57": + raise ValueError("raw MS, PS or creation root disagrees with request key") + data = archive.read_bytes() + if len(data) < 20: + raise ValueError("truncated fixed creation archive") + recorded, desc_size, a_size, b_size = struct.unpack_from(" 0x1000 or len(data) != 20 + desc_size + a_size + b_size: + raise ValueError("creation archive key or lengths disagree") + desc = data[20:20 + desc_size] + a = data[20 + desc_size:20 + desc_size + a_size] + b = data[20 + desc_size + a_size:] + fields = struct.unpack_from("<15Q", desc) + if (any(fields[i] for i in (0,1,3,5,9,10,13)) or + (fields[2], fields[4], fields[6], fields[14]) != (len(a), len(b), len(ps), len(ms))): + raise ValueError("normalized mesh descriptor disagrees with request and state lengths") + variant = key + for part in (desc, a, b): + variant = fnv(part, fnv(struct.pack(" 0xffff or enable & ~address or wave not in (32, 64): + raise ValueError("invalid reviewed pixel entry") + parts = (desc, a, b, root, ms, ps) + if struct.unpack_from("<6I", data, 8) != tuple(map(len, parts)): + raise ValueError("profile span lengths disagree") + offset = header_size + 12 + version = data[6] - ord("0") + if version >= 3: + offset += 12 # MS constant mapping + if version >= 4: + if offset + 4 > len(data): + raise ValueError("truncated view count") + count, = struct.unpack_from("= 5: + offset += 4 # MS resource heap SGPR + for part in parts: + if data[offset:offset + len(part)] != part: + raise ValueError("profile creation or shader bytes differ") + offset += len(part) + if offset != len(data): + raise ValueError("trailing profile data") + return f"meshps1 {enable} {address} {wave}" + (" guest_root" if version == 6 else "") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("request", type=Path, help="req_.ps57 with adjacent .m57 and .root") + parser.add_argument("archive", type=Path, help="req_.s57 from the same creation") + parser.add_argument("reviewed_profile", type=Path, help=".mesh57-state carrying reviewed pixel entry metadata") + args = parser.parse_args() + try: + print(pixel_entry(args.request, args.archive, args.reviewed_profile)) + except (OSError, ValueError) as error: + sys.exit(str(error))