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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ if(WIN32)
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_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
native_graphics_bindings.h native_compute_output.h shader_dxil_compiler.h
shader_compute_request.cpp shader_compute_request.h shader_translation_error.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}")
Expand Down
3 changes: 2 additions & 1 deletion CMakePresets.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
"xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check",
"xmem_page_runs_device_check", "linear_buffer_backing_check", "existing_heap_shared_buffer_check", "startup_request_publisher_check", "mesh86_typed_vsharp_check", "mesh86_typed_vsharp_wide_format_mut", "mesh86_typed_vsharp_any_map_mut", "mesh86_typed_vsharp_any_swizzle_mut", "mesh86_typed_vsharp_any_tid_mut",
"bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock",
"native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check"
"native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check",
"native_direct_cache_check"
]
},
{ "name": "release", "configurePreset": "release" },
Expand Down
332 changes: 223 additions & 109 deletions src/direct_compute_cache.cpp

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions src/direct_compute_cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@

// The result includes the emitted DXIL module and its exact desktop/guest binding layout.
namespace x2w {
namespace native_frontend_cache {
std::string encode(const NativeComputeShader &program);
NativeComputeShader decode(std::string_view bytes);
}

enum class ComputePackResult { miss, prepared, unsupported };
struct ComputePackCounts {
size_t prepared{}, unsupported{}, internal{};
Expand Down
12 changes: 12 additions & 0 deletions src/gfx1013_compute_native.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@
#include <stdexcept>
#include <string_view>

const x2w::TranslationOptions &x2w::translation_options() {
static const TranslationOptions options = [] {
#if defined(_MSC_VER)
// C4996: keep the existing read-only CRT environment lookup without allocating a copy.
#pragma warning(suppress: 4996)
#endif
const char *value = std::getenv("X2W_MESH57_PARTIAL_ZERO");
return TranslationOptions{value && value[0] == '1'};
}();
return options;
}

namespace {
using namespace x2w;
using std::string;
Expand Down
6 changes: 6 additions & 0 deletions src/gfx1013_compute_native.h
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ struct ComputeStrideSource {
bool writable;
};

struct TranslationOptions {
bool mesh_partial_zero = false;
};
// First-use process snapshot shared by the frontend cache and lowering.
const TranslationOptions &translation_options();
struct NativeComputeShader {
std::vector<PixelHeapSpan> pixel_heap_spans;
std::vector<MeshHeapRead> mesh_heap_reads;
Expand All @@ -179,6 +184,7 @@ struct NativeComputeShader {
bool vertex_fetch = false;
std::array<unsigned, 8> pixel_writes{};
};
bool operator==(const NativeComputeShader &left, const NativeComputeShader &right);
// The view class a GPU-selected descriptor heap slot is read as. none: the slot and its view type are not known, so a
// heap read is refused. raw_buffer: the capture says the selected slot is a raw buffer SRV. other: the capture names a
// view type that is not translated (refused when the shader reads the heap).
Expand Down
14 changes: 3 additions & 11 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
// Lower the shared decoded CFG to DXIL operations. A scalar register holds one
// 32-bit word per wave. Ordinary vector writes retain their old value on inactive lanes.
inline bool mesh_partial_zero()
{
#if defined(_MSC_VER)
// C4996: keep the existing read-only CRT environment lookup without allocating a copy.
#pragma warning(suppress: 4996)
#endif
const char* value=std::getenv("X2W_MESH57_PARTIAL_ZERO");
return value && value[0]=='1';
}
struct DirectCompute {
// The nine inline float constants as binary16, which an f16 operand reads instead of the f32 pattern.
static constexpr Word inline_half_words[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000,
Expand Down Expand Up @@ -71,6 +62,7 @@ struct DirectCompute {
refuse(i.pc, "lane read/write needs full waves");
}
Emit &analysis;
const TranslationOptions options{};
const GuestShaderStage *graphics_interface = nullptr;
DxilModule ir;
std::set<unsigned> allocated;
Expand Down Expand Up @@ -185,7 +177,7 @@ struct DirectCompute {
string read(unsigned r) {
if (compute_state && compute_state->has_spill(r))
refuse(compute_pc, "symbolic VGPR lane read of " + reg(r));
if (graphics_input && !graphics_half_writes && mesh_partial_zero()) {
if (graphics_input && !graphics_half_writes && options.mesh_partial_zero) {
const auto found = graphics_registers.find(r);
if (found == graphics_registers.end() || found->second.empty()) {
const auto partial = partial_values.find(r);
Expand All @@ -195,7 +187,7 @@ struct DirectCompute {
return read_storage(r);
}
string read_export(unsigned r) {
if (graphics_half_writes || !mesh_partial_zero()) return read_storage(r);
if (graphics_half_writes || !options.mesh_partial_zero) return read_storage(r);
const auto found = graphics_registers.find(r);
if (found != graphics_registers.end() && !found->second.empty()) return found->second;
const auto partial = partial_values.find(r);
Expand Down
2 changes: 1 addition & 1 deletion src/gfx1013_direct_graphics.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1824,7 +1824,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv =
emitter.srv = first_srv;
emitter.uav = first_uav;
emitter.first_sampler = first_sampler;
DirectCompute alu{emitter};
DirectCompute alu{emitter, translation_options()};
const bool pixel = stage.stage == GpuStage::ps;
alu.graphics_interface = &stage;
alu.pixel_stage = pixel;
Expand Down
4 changes: 2 additions & 2 deletions src/gfx1013_direct_mesh.inl
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout
program.before.emplace_back();
for (auto &s : program.before.front()) s.type=Symbol::Type::unbound;
Emit emitter{{},program,root};
DirectCompute alu{emitter};
DirectCompute alu{emitter, translation_options()};
// A container stage reflects its table records; an IDXEN raw load takes its record stride from them.
alu.graphics_interface=reflected;
// The mesh tracks which half of a VGPR a 16-bit write defined: a mixed
Expand Down Expand Up @@ -853,7 +853,7 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout
if (uniform_join && group_uniform_value(a) && group_uniform_value(b)) group_uniform.insert(v);
return v;
};
const bool partial_zero=!layout.texture_heap_slot_map && mesh_partial_zero();
const bool partial_zero=!layout.texture_heap_slot_map && alu.options.mesh_partial_zero;
if (!branch || !branch->masks) remember_partial();
std::map<unsigned,std::pair<Symbol,string>> masks;
for (unsigned reg=0;reg<=104;reg+=2) {
Expand Down
14 changes: 14 additions & 0 deletions tests/cmake/native_direct_cache.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
if(TARGET x2w_shader_compiler)
add_executable(native_direct_cache_check tests/native_direct_cache_check.cpp)
target_link_libraries(native_direct_cache_check PRIVATE x2w_shader_compiler)
set_property(TARGET native_direct_cache_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
add_test(NAME native_direct_cache_controls COMMAND native_direct_cache_check)
endif()

if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll"
AND EXISTS "${INTAKE_PYTHON}")
add_test(NAME native_direct_cache_key_controls
COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_direct_container_check.py"
--cache-options "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
set_tests_properties(native_direct_cache_key_controls PROPERTIES TIMEOUT 60)
endif()
8 changes: 3 additions & 5 deletions tests/native_compute_pack_check.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ static int same(const fs::path &input, const fs::path &a_file, const fs::path &b
NativeComputeShader pa, pb;
std::string da, db;
const auto ra = a.lookup(r, 0, pa, da), rb = b.lookup(r, 0, pb, db);
check(ra == rb && da == db && pa.dxil_ir == pb.dxil_ir && pa.group == pb.group &&
pa.instruction_count == pb.instruction_count &&
check(ra == rb && da == db && pa == pb &&
format_compute_runtime_manifest(pa) == format_compute_runtime_manifest(pb), "lookup results differ");
found += ra != ComputePackResult::miss;
}
Expand All @@ -69,7 +68,7 @@ static int old_layout(const fs::path &file, const fs::path &out) {
std::ifstream in(file, std::ios::binary);
std::string bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
check(bytes.size() > 128 + 72 && bytes.compare(128, 4, std::string("\1\0\0\0", 4)) == 0, "not a single-part pack");
std::string version = X2W_NATIVE_SHADER_REVISION "/slot67/cs_6_6/prepared-1";
std::string version = X2W_NATIVE_SHADER_REVISION "/frontend-3/slot67/cs_6_6/prepared-1";
version.append(4, '\0');
const auto payload = bytes.substr(132, 4) + bytes.substr(128 + 72);
std::ofstream o(out, std::ios::binary);
Expand Down Expand Up @@ -119,8 +118,7 @@ int main(int argc, char **argv) {
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,
check(warm == cold && format_compute_runtime_manifest(warm) == manifest,
"IR, layout or manifest differs");
status = "prepared";
identity = shader_digest(cold.dxil_ir);
Expand Down
65 changes: 65 additions & 0 deletions tests/native_direct_cache_check.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#include "direct_compute_cache.h"
#include <iostream>

using namespace x2w;
using native_frontend_cache::decode;
using native_frontend_cache::encode;

static void check(bool ok, const char *reason) {
if (!ok) throw std::runtime_error(reason);
}

static bool refuses(std::string_view bytes) {
try { decode(bytes); }
catch (const std::runtime_error &) { return true; }
return false;
}

int main() {
try {
NativeComputeShader shader{};
shader.pixel_heap_spans = {{4, 17, 5, 1024}, {60, 63, 1, 1038}};
shader.mesh_heap_reads = {{2, 3, 1023, 4, 6}};
shader.mesh_texture_heap_slot_map = true;
shader.pixel_texture_heap_slot_map = true;
shader.pixel_quad_coverage_branch = true;
shader.pixel_descriptor_word_tables = {2, 5};
shader.pixel_descriptor_records = {{2, 32}, {5, 160}};
shader.mesh_heap_tokens = MeshHeapTokens{5, 6, 7, 8};
shader.inputs = {{"TEXCOORD", 3, 6, 1, 2, 9, 3, 1, 2},
{"SV_Barycentrics", 1, ~0u, 0, 3, 9, 7, 28, 4}};
shader.outputs = {{"SV_Target", 2, ~0u, 1, 3, 5, 7, 16, 1}};
shader.constants = {{4, 28, 8}};
shader.stride_sources = {{3, false}, {9, true}};
shader.hlsl = "fixture HLSL\n";
shader.dxil_ir = "fixture DXIL IR\n";
shader.bindings = {{ComputeViewKind::cube_sample_srv, 3, 80, 5, 32, 4, 2, 3,
ComputeViewBinding::ScalarTable::srv, true}};
shader.samplers = {{{17, 29, 61, 85}, true, true}};
shader.sampler_heap = true;
shader.instruction_count = 73;
shader.group = {32, 7, 2};
shader.vertex_fetch = true;
shader.pixel_writes = {15, 2, 13, 4, 11, 6, 9, 8};

const auto payload = encode(shader);
check(decode(payload) == shader, "populated frontend shader changed on round trip");
check(refuses(std::string_view(payload).substr(0, payload.size() - 1)), "accepted truncated payload");
check(refuses(payload + 'x'), "accepted trailing payload data");

auto different = shader;
different.mesh_heap_tokens.reset();
check(!(different == shader), "comparison ignored absent mesh heap tokens");
check(decode(encode(different)) == different, "absent mesh heap tokens changed on round trip");
different = shader;
different.pixel_descriptor_records.back().second += 32;
check(!(different == shader), "comparison ignored a pixel descriptor record");
different = shader;
different.hlsl.clear();
check(!(different == shader), "comparison ignored HLSL");
check(decode(encode(different)) == different, "empty HLSL changed on round trip");
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
return 1;
}
}
27 changes: 27 additions & 0 deletions tests/native_direct_container_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,34 @@ def check_scc_writer_mutant():
print("scc writer mutant: each new case is live once its overwrite entry is removed")


def check_cache_options(exe, sdk):
with tempfile.TemporaryDirectory() as tmp:
folder = pathlib.Path(tmp)
cache = folder / "cache"
vs, ps = folder / "vertex", folder / "pixel"
vs.write_bytes(vertex())
ps.write_bytes(patched_pixel())
vs_out, ps_out = folder / "vertex.cso", folder / "pixel.cso"
cmd = [exe, sdk, cache, "gfx1013-container-pair", vs, vs_out, ps, ps_out]
expected_dxil = None
for value, hit in (("0", 0), ("1", 0), ("1", 1), ("0", 1)):
env = dict(os.environ, X2W_MESH57_PARTIAL_ZERO=value)
result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env)
assert f"graphics_pair frontend_cache_hit={hit}" in result.stdout, result.stdout
dxil = (vs_out.read_bytes(), ps_out.read_bytes())
if expected_dxil is None:
expected_dxil = dxil
assert dxil == expected_dxil, f"DXIL changed with option {value}, hit={hit}"
entries = list(cache.glob("*.pairir"))
assert len(entries) == 2, entries
# The fixture has no partial register writes. Both keys must store the same frontend payload.
assert entries[0].read_bytes()[128:] == entries[1].read_bytes()[128:]


def main():
if len(sys.argv) == 4 and sys.argv[1] == "--cache-options":
check_cache_options(*sys.argv[2:])
return
check_scc_writer_mutant()
if len(sys.argv) == 4 and sys.argv[1] in ("--sampler-pso", "--graphics-sampler-pso"):
sdk, probe = sys.argv[2:]
Expand Down
Loading