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
6 changes: 4 additions & 2 deletions src/startup_stubs/d3d12_compute_dispatch.inl
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ bool translate_compute_natively(ComputeTranslation& tr)
wchar_t sdk[MAX_PATH], path[MAX_PATH];
const DWORD length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH);
if (!length || length >= MAX_PATH) return false;
NativeShaderTimer native_work(native_compute_totals);
if (!cache_path(path, L"req_", tr.key, L".c67")) return false;
auto refuse_native = [&](const char* reason) {
tr.uds.clear();
Expand All @@ -483,6 +484,7 @@ bool translate_compute_natively(ComputeTranslation& tr)
tr.samplers = {}; // a published manifest read next numbers its sampler lines from 0
tr.root.Reset();
tr.pipeline.Reset();
count_native_compute_refusal(reason);
static LONG logged;
if (first_calls(logged, 16))
log("x2w-draw compute pipeline %016llx not translated natively: %s", tr.key, reason);
Expand Down Expand Up @@ -583,8 +585,8 @@ bool translate_compute_natively(ComputeTranslation& tr)
// Never released: a static destructor would release DXC after its module may have detached.
static x2w::ShaderDxilCompiler* const compiler =
new x2w::ShaderDxilCompiler(x2w::ShaderDxilCompiler::runtime_worker(sdk));
const auto shader = compiler->compile(program.dxil_ir, L"cs_6_6", std::filesystem::path(path).parent_path() / L"native",
x2w::ShaderSourceFormat::dxil_ir);
const auto shader = compile_native_shader(native_compute_totals, *compiler, program.dxil_ir, L"cs_6_6",
std::filesystem::path(path).parent_path() / L"native");
if (const char* failure = create_compute_pipeline(tr, shader.dxil.data(), shader.dxil.size()))
throw std::runtime_error(failure);
log("x2w-draw compute pipeline %016llx translated natively: %zu entry values, %zu inputs, %zu outputs (frontend %s)", tr.key,
Expand Down
6 changes: 4 additions & 2 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,9 @@ static bool try_native_graphics(Translation& tr, bool variant = false)
{
wchar_t sdk[MAX_PATH], path[MAX_PATH];
const auto length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH);
if (!length || length >= MAX_PATH || !cache_path(path, L"req_", tr.key, variant ? L".rtv" : L".a")) return false;
if (!length || length >= MAX_PATH) return false;
NativeShaderTimer native_work(native_graphics_totals);
if (!cache_path(path, L"req_", tr.key, variant ? L".rtv" : L".a")) return false;
try {
const auto request = x2w::read_graphics_request(path);
const auto cache = std::filesystem::path(path).parent_path();
Expand All @@ -635,7 +637,7 @@ static bool try_native_graphics(Translation& tr, bool variant = false)
if (!manifest) throw std::runtime_error("unsupported graphics binding layout");
auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk);
auto stage = [&](const std::string& ir, const wchar_t* profile, bool& hit) {
const auto output = compiler.compile(ir, profile, cache, x2w::ShaderSourceFormat::dxil_ir);
const auto output = compile_native_shader(native_graphics_totals, compiler, ir, profile, cache);
hit = output.cache_hit;
x2w_startup::ComPtr<ID3DBlob> blob;
if (FAILED(D3DCreateBlob(output.dxil.size(), &blob))) throw std::bad_alloc();
Expand Down
105 changes: 105 additions & 0 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@

#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <cstdarg>
#include <cstdio>
Expand Down Expand Up @@ -422,6 +423,105 @@ void log(const char* format, ...)
x2w_trap::append_log(line, static_cast<DWORD>(n), false);
}

#ifdef X2W_NATIVE_SHADERS
struct NativeShaderTotals {
std::atomic<u64> compiles{0}, compile_ticks{0}, max_ticks{0}, locked_ticks{0};
};
NativeShaderTotals native_compute_totals, native_graphics_totals;

// Both native translation paths already hold draw_lock. The presenter samples the counters atomically.
struct NativeShaderTimer {
NativeShaderTotals& totals;
bool compile;
LARGE_INTEGER start{};

explicit NativeShaderTimer(NativeShaderTotals& totals, bool compile = false)
: totals(totals), compile(compile) { QueryPerformanceCounter(&start); }

~NativeShaderTimer()
{
LARGE_INTEGER end{};
QueryPerformanceCounter(&end);
const auto ticks = static_cast<u64>(end.QuadPart - start.QuadPart);
if (compile) {
totals.compile_ticks.fetch_add(ticks, std::memory_order_relaxed);
if (ticks > totals.max_ticks.load(std::memory_order_relaxed))
totals.max_ticks.store(ticks, std::memory_order_relaxed);
totals.compiles.fetch_add(1, std::memory_order_release);
} else {
totals.locked_ticks.fetch_add(ticks, std::memory_order_relaxed);
}
}
};

// Count calls to the compiler, including cache lookups and failures. Graphics calls it once per stage.
x2w::CompiledShader compile_native_shader(NativeShaderTotals& totals, x2w::ShaderDxilCompiler& compiler,
const std::string& ir, const wchar_t* profile, const std::filesystem::path& cache)
{
NativeShaderTimer timer(totals, true);
return compiler.compile(ir, profile, cache, x2w::ShaderSourceFormat::dxil_ir);
}

struct NativeComputeRefusal {
char reason[72]{};
std::atomic<u64> count{0};
};
NativeComputeRefusal native_compute_refusals[12]; // All entries and counts fit in one log line.
std::atomic<u64> native_compute_refusal_overflow{0};

void count_native_compute_refusal(std::string_view reason)
{
// The instruction PC is context for the detail log. Group the same compiler reason across PCs.
const auto separator = reason.find(": ");
if (reason.rfind("native compute +0x", 0) == 0 && separator != std::string_view::npos)
reason.remove_prefix(separator + 2);
for (auto& entry : native_compute_refusals) {
if (reason.size() >= sizeof(entry.reason)) break;
if (!entry.count.load(std::memory_order_relaxed)) {
std::memcpy(entry.reason, reason.data(), reason.size());
entry.count.store(1, std::memory_order_release); // Publish the immutable reason to the presenter.
return;
}
if (reason == entry.reason) {
entry.count.fetch_add(1, std::memory_order_relaxed);
return;
}
}
native_compute_refusal_overflow.fetch_add(1, std::memory_order_relaxed);
}

void log_native_shader_totals()
{
LARGE_INTEGER frequency{};
QueryPerformanceFrequency(&frequency);
const double ms = 1000.0 / frequency.QuadPart;
char line[1534] = "x2w-render native shader totals:";
std::size_t used = std::strlen(line);
const auto append = [&](const char* name, const NativeShaderTotals& totals) {
const auto count = totals.compiles.load(std::memory_order_acquire);
used += std::snprintf(line + used, sizeof(line) - used,
" %s compiles=%llu total_ms=%.3f max_ms=%.3f draw_lock_ms=%.3f;", name, count,
totals.compile_ticks.load(std::memory_order_relaxed) * ms,
totals.max_ticks.load(std::memory_order_relaxed) * ms,
totals.locked_ticks.load(std::memory_order_relaxed) * ms);
};
append("compute", native_compute_totals);
append("graphics", native_graphics_totals);
used += std::snprintf(line + used, sizeof(line) - used, " compute refusal_overflow=%llu",
native_compute_refusal_overflow.load(std::memory_order_relaxed));
for (const auto& entry : native_compute_refusals) {
const auto count = entry.count.load(std::memory_order_acquire);
if (!count) break;
char label[sizeof(entry.reason)];
std::memcpy(label, entry.reason, sizeof(label));
for (char* c = label; *c; ++c)
if (static_cast<unsigned char>(*c) < ' ' || *c == '"') *c = '?';
used += std::snprintf(line + used, sizeof(line) - used, " \"%s\"=%llu", label, count);
}
log("%s", line);
}
#endif

void guid_text(const GUID* g, char* out, std::size_t size)
{
if (!g || !x2w_local::readable(g, sizeof(GUID))) {
Expand Down Expand Up @@ -8065,6 +8165,11 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa
}
log("%s", line);
}
#ifdef X2W_NATIVE_SHADERS
if ((frame % 300 == 0 || now - last_report >= 5000) && render_mode() &&
GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0))
log_native_shader_totals();
#endif
if (now - last_report >= 5000) {
last_report = now;
log("x2w-d3d12 views noted %lld (distinct %lld), descriptors copied %lld, heaps %llu, placed buffers %lld "
Expand Down
8 changes: 8 additions & 0 deletions tests/cmake/startup_compute_dispatch_native.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,13 @@ if(TARGET x2w_shader_compiler AND TARGET startup_stream_consumer AND EXISTS "${I
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_native_check.py"
"$<TARGET_FILE:startup_stream_consumer>" "${DXC_BIN_DIR}" ${adapter})
set_tests_properties(startup_compute_dispatch_native_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
add_test(NAME startup_native_shader_totals_compile_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_native_check.py"
"$<TARGET_FILE:startup_stream_consumer>" "${DXC_BIN_DIR}" ${adapter} compile)
set_tests_properties(startup_native_shader_totals_compile_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
add_test(NAME startup_native_shader_totals_refusals_warp COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_native_check.py"
"$<TARGET_FILE:startup_stream_consumer>" "${DXC_BIN_DIR}" warp refusals)
set_tests_properties(startup_native_shader_totals_refusals_warp PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endif()
48 changes: 48 additions & 0 deletions tests/startup_compute_dispatch_native_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"""
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
Expand Down Expand Up @@ -341,6 +342,51 @@ def texture_outputs(directory, consumer, dxc_dir, adapter, capability_refusal):
assert not published, published


def native_totals(consumer, dxc_dir, adapter, case):
with tempfile.TemporaryDirectory() as temporary:
directory = Path(temporary)
_, env = prepare_case(directory, adapter)
env.update(X2W_NATIVE_SHADERS=dxc_dir, X2W_NATIVE_SHADERS_ONLY='1')
env.pop('X2W_NATIVE_COMPUTE_PACK', None)
mode = 'dispatch-native-totals-refusals' if case == 'refusals' else 'dispatch-native-totals'
if case == 'compile':
path = directory / 'program'
program = path.read_bytes()
assert program.count(LOAD_X8) == 1
path.write_bytes(program.replace(LOAD_X8, LOADS_X4))

got, result = dispatch(directory, consumer, env, mode, probe=True)
reports = lines(result, 'x2w-render native shader totals:')
assert reports, result.stderr[-3000:]
report = reports[-1]
match = re.fullmatch(
r'x2w-render native shader totals: compute compiles=(\d+) total_ms=([\d.]+) '
r'max_ms=([\d.]+) draw_lock_ms=([\d.]+); '
r'graphics compiles=0 total_ms=0\.000 max_ms=0\.000 draw_lock_ms=0\.000; '
r'compute refusal_overflow=0(.*)', report)
assert match, report
count, total, maximum, locked, reasons = match.groups()
assert 0 <= float(maximum) <= float(total) <= float(locked) and float(locked) > 0, report

untouched = [C.SENTINEL] * C.WORDS
if case == 'refusals':
assert got == untouched and count == '0' and float(total) == 0, report
assert len(lines(result, 'not translated natively: ')) == 16, result.stderr[-3000:]
assert reasons == (' "unaligned descriptor table entry"=11'
' "compute state block A is not 28 bytes"=10'), report
else:
for diagnostic in CAPABILITY_REFUSALS:
if lines(result, diagnostic):
assert got == untouched and count == '0', report
print(f'SKIP on {adapter}: {diagnostic}')
return 77
assert got == C.expected('A'), 'native Dispatch output differed from the CPU reference'
assert lines(result, 'translated natively: '), result.stderr[-3000:]
assert count == '1' and 0 < float(total) == float(maximum) and not reasons, report
print(report)
return 0


def main(consumer, dxc_dir, adapter):
scalar_window_case(consumer, dxc_dir, adapter)
with tempfile.TemporaryDirectory() as temporary:
Expand Down Expand Up @@ -426,6 +472,8 @@ def main(consumer, dxc_dir, adapter):


if __name__ == '__main__':
if len(sys.argv) == 5 and sys.argv[3] in ('warp', 'hardware') and sys.argv[4] in ('refusals', 'compile'):
sys.exit(native_totals(*sys.argv[1:]))
if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'):
sys.exit(__doc__)
main(*sys.argv[1:])
28 changes: 25 additions & 3 deletions tests/startup_stream_consumer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ static void* desktop_pipeline(void* device)
static void* slot67_pipeline;
static void* slot67_root;
static void* slot67_other_root; // a second root signature object, for the root-change controls
static std::array<void*, 21> native_refusal_pipelines;

// The stand-in gives a committed resource title memory only through the title's exported __XMemAllocationHooks__
// (title_resource_memory). This one hands out memory only while committed_title_memory is set, so every other mode
Expand Down Expand Up @@ -265,6 +266,8 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin
constexpr UINT long_records = 2u << 20, long_frames = 48;
const bool shared_uav = mode == "dispatch-read-write-uav";
const bool typed_output_offset = mode == "dispatch-records32-output-offset";
const bool native_totals = mode == "dispatch-native-totals";
const bool native_refusals = mode == "dispatch-native-totals-refusals";
// dispatch-records32-input-at-<bytes>: dispatch-records32 with the input descriptor that many bytes into its buffer.
const std::string input_at = "dispatch-records32-input-at-";
const UINT input_offset = mode.rfind(input_at, 0) == 0 ? static_cast<UINT>(std::stoul(mode.substr(input_at.size()))) : 0;
Expand Down Expand Up @@ -427,9 +430,9 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin
std::memcpy(reinterpret_cast<void*>(cpu + 32), descriptors[1], sizeof(descriptors[1]));
}
// X2W_TEST_RECORDS32=1 moves the output descriptor to byte 32 for programs whose descriptor loads are
// split into aligned dwordx4 loads (the D16 sample tests); every other mode keeps byte 16.
// split into aligned dwordx4 loads (the D16 sample tests).
const char* records32 = std::getenv("X2W_TEST_RECORDS32");
if (mode == "dispatch-records32" || typed_output_offset || input_offset || shared_uav ||
if (mode == "dispatch-records32" || native_totals || typed_output_offset || input_offset || shared_uav ||
mode == "dispatch-srv-token-typed" || mode == "dispatch-records32-input-null" ||
mode.rfind("dispatch-cube", 0) == 0 ||
(records32 && std::strcmp(records32, "1") == 0)) { // output at byte 32, none at byte 16
Expand Down Expand Up @@ -900,7 +903,12 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin
}
if (mode == "dispatch-table-offset") invoke(list, 32, 1, word(&heap)); // same heap keeps the offset table
if (pixel) record.capture_before_consumer(adapter, device, list);
if (indirect) record.execute(list, mode == "dispatch-indirect-multi" ? 2 : 1,
if (native_refusals) {
for (auto* pipeline : native_refusal_pipelines) {
invoke(list, 25, word(pipeline));
invoke(list, 14, 3, 2, 2);
}
} else if (indirect) record.execute(list, mode == "dispatch-indirect-multi" ? 2 : 1,
mode == "dispatch-indirect-counted", mode == "dispatch-indirect-outside");
else if (heap_waterfall) invoke(list, 14, 1, 1, 1);
else if (mode == "dispatch-reference-2" || mode == "dispatch-reference-5")
Expand Down Expand Up @@ -956,6 +964,8 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin
if (buffers[0][i] != input[i]) return 79;
}
}
if (native_totals || native_refusals)
for (int frame = 0; frame < 300; ++frame) invoke(queue, 32, 0, 0, 0);
x2w_d3d12_compute_census();
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH);
Expand Down Expand Up @@ -1284,6 +1294,18 @@ static bool create_slot67(void* device, const char* code_path, const char* data_
slot67_root = root;
return created;
};
if (m == "dispatch-native-totals-refusals") {
if (state.size() != 28) return false;
for (std::size_t i = 0; i < native_refusal_pipelines.size(); ++i) {
// Vary the plain descriptor word so each Dispatch tries native translation for a fresh key.
words[11] = i;
words[2] = state.size() - (i % 2 ? 4 : 0);
std::memcpy(desc, words, sizeof(words));
if (!create(desc)) return false;
native_refusal_pipelines[i] = slot67_pipeline;
}
return true;
}
if (m == "order") {
if (!create(desc)) return false;
UINT64 refused[12];
Expand Down
Loading