Files
mandy/runtime/test/vk_pipeline_check.cpp
2026-11-22 11:43:06 -05:00

1540 lines
80 KiB
C++

// Driver-level check of the translated corpus: vk_pipeline_check <spirv dir> [pipeline_cache.bin]
// Reads <spirv dir>/index.json (written by tools/rdna2spirv.py), creates a VkShaderModule for every entry and a real
// pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash
// table 2; storage images 4, 7 and 8..19; push constants 144 bytes):
// - cs: compute pipeline via vkCreateComputePipelines
// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass)
// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py)
// Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders
// whose required features or partner stubs are unavailable are reported as skipped rather than failed.
// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every
// 10 minutes and at the end
// --jobs N compile on N threads (default: half the hardware threads)
// --large-module-bytes N compile modules larger than N bytes alone (default: 4194304; 0 disables isolation)
// --start I --count N check only index entries [I, I+N) (sorted by name)
// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running
// --max-bytes N skip modules whose .spv is larger than N bytes (0 = no limit; names every skip)
// --stage S which stages to check: all (default), cs, or graphics (aliases: --compute-only, --graphics-only)
// --stats FILE write the driver's statistics for each translated shader (VK_KHR_pipeline_executable_properties:
// instructions, registers, spills, scratch, waves...) as CSV rows name,stage,statistic,value. Only
// the executable that runs the translated shader is written, not the partner stub's. Use without
// cache.bin: a pipeline loaded from the cache may come without statistics.
// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and
// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a
// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count.
// --isolate (POSIX only) check in child processes, --isolate-batch modules at a time (default 256), so a module
// that kills the driver (SIGFPE, SIGSEGV, ...) is recorded as failed ("MODULE CRASH") and the pass
// goes on. A crashed batch is bisected to the module. Children run one after the other and share
// cache.bin. Not compatible with --stats.
// --inflight-file F keep the modules that are in the driver in F, one "name<TAB>phase" line each (phase: module
// while vkCreateShaderModule runs, pipeline while its pipeline is created), so whoever ran the check
// can tell which module was there when the process died. F is rewritten when a module over
// --large-module-bytes enters or leaves the driver (it is alone then, so F names exactly it) and by
// the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage reads it.
// --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted
// as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F
// after a crash, so the next run checks everything else instead of dying on the same module.
// test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL] raises SIGNAL (default SIGFPE)
// just before the pipeline of a matching module is created. For testing --isolate and the
// pipelines stage's retry.
#include "vulkan_loader.h"
#include "vk_device_pick.h"
#include "pipeline_cache_file.h"
#include "pipeline_cache_snapshot.h"
#include <algorithm>
#include <atomic>
#include <cctype>
#include <charconv>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <csignal>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iterator>
#include <limits>
#include <map>
#include <mutex>
#include <set>
#include <shared_mutex>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
#ifndef _WIN32
#include <sys/wait.h>
#include <unistd.h>
#include <cerrno>
#include <filesystem>
#endif
static PFN_vkGetInstanceProcAddr gipa;
struct VertexInputMeta {
uint32_t location = 0;
std::string type = "float";
};
struct ShaderMeta {
std::string stage;
uint32_t subgroup_size = 0;
uint32_t lds_bytes = 0;
bool writes_depth = false;
bool needs_maintenance8 = false;
std::vector<std::string> features;
std::vector<std::string> float_controls; // VkPhysicalDeviceFloatControlsProperties members that must be true
std::vector<uint32_t> inputs;
std::vector<uint32_t> outputs;
std::vector<uint32_t> params;
std::vector<uint32_t> gs_inputs;
std::vector<uint32_t> gs_outputs;
std::vector<uint32_t> gs_input_locations;
std::vector<uint32_t> gs_output_locations;
bool has_gs_input_locations = false;
bool has_gs_output_locations = false;
std::vector<VertexInputMeta> vertex_inputs;
};
// Minimal recursive-descent JSON reader for index.json (handles strings, numbers, bools, arrays, objects).
namespace {
struct JsonParser {
const std::string& s;
size_t i = 0;
bool error = false;
std::string error_msg;
void fail(const char* ctx) {
if (!error) {
error = true;
error_msg = std::string(ctx) + " at byte " + std::to_string(i);
}
}
void ws() {
while (i < s.size() && std::isspace(static_cast<unsigned char>(s[i]))) i++;
}
bool consume(char c) {
ws();
if (i < s.size() && s[i] == c) { i++; return true; }
return false;
}
std::string parse_string() {
ws();
if (i >= s.size() || s[i] != '"') { fail("expected string"); return {}; }
i++;
std::string out;
while (i < s.size() && s[i] != '"') {
if (s[i] == '\\' && i + 1 < s.size()) {
i++;
out.push_back(s[i++]);
} else {
out.push_back(s[i++]);
}
}
if (i >= s.size() || s[i] != '"') { fail("unterminated string"); return out; }
i++;
return out;
}
uint32_t parse_u32() {
ws();
const size_t start = i;
bool neg = false;
if (i < s.size() && s[i] == '-') { neg = true; i++; }
uint32_t v = 0;
const size_t digits_start = i;
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {
v = v * 10 + uint32_t(s[i] - '0');
i++;
}
if (i == digits_start) { i = start; fail("expected unsigned integer"); return 0u; }
while (i < s.size() && (s[i] == '.' || s[i] == 'e' || s[i] == 'E' || s[i] == '+' || s[i] == '-' ||
(s[i] >= '0' && s[i] <= '9'))) i++;
return neg ? 0u : v;
}
bool parse_bool() {
ws();
if (s.compare(i, 4, "true") == 0) { i += 4; return true; }
if (s.compare(i, 5, "false") == 0) { i += 5; return false; }
fail("expected boolean");
return false;
}
void skip_value() {
ws();
if (i >= s.size()) { fail("unexpected end of JSON"); return; }
char c = s[i];
if (c == '"') { parse_string(); return; }
if (c == '{') {
i++;
while (!error && i < s.size()) {
if (consume('}')) return;
const size_t before = i;
parse_string();
if (error) return;
if (!consume(':')) { fail("expected ':' in object"); return; }
skip_value();
if (error) return;
if (consume('}')) return;
if (!consume(',') || i == before) { fail("expected ',' or '}' in object"); return; }
}
if (!error) fail("unterminated object");
return;
}
if (c == '[') {
i++;
while (!error && i < s.size()) {
if (consume(']')) return;
const size_t before = i;
skip_value();
if (error) return;
if (consume(']')) return;
if (!consume(',') || i == before) { fail("expected ',' or ']' in array"); return; }
}
if (!error) fail("unterminated array");
return;
}
const size_t before = i;
while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']' &&
!std::isspace(static_cast<unsigned char>(s[i]))) i++;
if (i == before) fail("unexpected token in value");
}
std::vector<uint32_t> parse_u32_array() {
std::vector<uint32_t> out;
if (!consume('[')) { skip_value(); return out; }
while (!error && i < s.size()) {
if (consume(']')) return out;
const size_t before = i;
out.push_back(parse_u32());
if (error) return out;
if (consume(']')) return out;
if (!consume(',') || i == before) { fail("expected ',' or ']' in u32 array"); return out; }
}
if (!error) fail("unterminated u32 array");
return out;
}
std::vector<std::string> parse_str_array() {
std::vector<std::string> out;
if (!consume('[')) { skip_value(); return out; }
while (!error && i < s.size()) {
if (consume(']')) return out;
const size_t before = i;
out.push_back(parse_string());
if (error) return out;
if (consume(']')) return out;
if (!consume(',') || i == before) { fail("expected ',' or ']' in string array"); return out; }
}
if (!error) fail("unterminated string array");
return out;
}
std::vector<VertexInputMeta> parse_vertex_inputs() {
std::vector<VertexInputMeta> out;
if (!consume('[')) { skip_value(); return out; }
while (!error && i < s.size()) {
if (consume(']')) return out;
const size_t before = i;
VertexInputMeta vi;
if (consume('{')) {
while (!error && i < s.size()) {
if (consume('}')) break;
const size_t obj_before = i;
std::string k = parse_string();
if (error) return out;
if (!consume(':')) { fail("expected ':' in vertex_inputs entry"); return out; }
if (k == "location") vi.location = parse_u32();
else if (k == "type") vi.type = parse_string();
else skip_value();
if (error) return out;
if (consume('}')) break;
if (!consume(',') || i == obj_before) { fail("expected ',' or '}' in vertex_inputs entry"); return out; }
}
if (error) return out;
out.push_back(std::move(vi));
} else {
skip_value();
if (error) return out;
}
if (consume(']')) return out;
if (!consume(',') || i == before) { fail("expected ',' or ']' in vertex_inputs"); return out; }
}
if (!error) fail("unterminated vertex_inputs array");
return out;
}
ShaderMeta parse_meta() {
ShaderMeta m;
if (!consume('{')) { skip_value(); return m; }
while (!error && i < s.size()) {
if (consume('}')) return m;
const size_t before = i;
std::string k = parse_string();
if (error) return m;
if (!consume(':')) { fail("expected ':' in shader metadata"); return m; }
if (k == "stage") m.stage = parse_string();
else if (k == "subgroup_size") {
// null: translated with --wave64-emulate, exact on any subgroup size, so request none (0)
ws();
if (s.compare(i, 4, "null") == 0) { i += 4; m.subgroup_size = 0; }
else m.subgroup_size = parse_u32();
}
else if (k == "lds_bytes") {
ws();
const auto [end, ec] = std::from_chars(s.data() + i, s.data() + s.size(), m.lds_bytes);
if (ec != std::errc{}) fail("expected unsigned 32-bit lds_bytes");
else i = static_cast<size_t>(end - s.data());
}
else if (k == "writes_depth") m.writes_depth = parse_bool();
else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool();
else if (k == "features") m.features = parse_str_array();
else if (k == "float_controls") m.float_controls = parse_str_array();
else if (k == "inputs") m.inputs = parse_u32_array();
else if (k == "outputs") m.outputs = parse_u32_array();
else if (k == "params") m.params = parse_u32_array();
else if (k == "gs_inputs") m.gs_inputs = parse_u32_array();
else if (k == "gs_outputs") m.gs_outputs = parse_u32_array();
else if (k == "gs_input_locations") { m.gs_input_locations = parse_u32_array(); m.has_gs_input_locations = true; }
else if (k == "gs_output_locations") { m.gs_output_locations = parse_u32_array(); m.has_gs_output_locations = true; }
else if (k == "vertex_inputs") m.vertex_inputs = parse_vertex_inputs();
else skip_value();
if (error) return m;
if (consume('}')) return m;
if (!consume(',') || i == before) { fail("expected ',' or '}' in shader metadata"); return m; }
}
if (!error) fail("unterminated shader metadata object");
return m;
}
};
std::map<std::string, ShaderMeta> read_index(const std::string& path, std::string& err, bool& unreadable) {
std::ifstream f(path, std::ios::binary);
std::map<std::string, ShaderMeta> out;
unreadable = false;
if (!f) { err = "cannot open the file"; unreadable = true; return out; } // a missing index must not read as an empty corpus
// Read with read() so that a failure shows in the stream state (istreambuf_iterator bypasses it).
f.seekg(0, std::ios::end);
const std::streamoff size = f.tellg();
f.seekg(0, std::ios::beg);
if (!f || size < 0) { err = "cannot determine the file size"; unreadable = true; return out; }
std::string s(static_cast<size_t>(size), '\0');
if (size > 0 && (!f.read(s.data(), size) || f.gcount() != size)) { err = "read error"; unreadable = true; return out; }
JsonParser p{s, 0};
p.ws();
if (p.i >= s.size()) { err = "the file is empty (an intentionally empty index is {})"; return out; }
if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; }
// After the closing '}' only whitespace may remain ({}garbage is malformed).
auto closed = [&] {
p.ws();
if (p.i != s.size()) { err = "unexpected data after the top-level object at byte " + std::to_string(p.i); return std::map<std::string, ShaderMeta>{}; }
return std::move(out);
};
while (!p.error && p.i < s.size()) {
if (p.consume('}')) return closed();
const size_t before = p.i;
std::string name = p.parse_string();
if (p.error) break;
if (!p.consume(':')) { p.fail("expected ':' after shader name"); break; }
out[name] = p.parse_meta();
if (p.error) break;
if (p.consume('}')) return closed();
if (!p.consume(',') || p.i == before) { p.fail("expected ',' or '}' in index.json"); break; }
}
if (p.error) { err = p.error_msg; return {}; }
err = "unterminated top-level object at byte " + std::to_string(p.i);
return {};
}
std::string stub_filename(const char* kind, const std::vector<uint32_t>& raw_locs) {
std::vector<uint32_t> locs = raw_locs;
std::sort(locs.begin(), locs.end());
locs.erase(std::unique(locs.begin(), locs.end()), locs.end());
std::string out = std::string(kind) + "_";
if (locs.empty()) {
out += "empty";
} else {
for (size_t i = 0; i < locs.size(); i++) {
if (i) out += "_";
out += std::to_string(locs[i]);
}
}
out += ".spv";
return out;
}
bool is_graphics_stage(const std::string& st) {
return st == "ps" || st == "vs" || st == "ms" || st == "gs";
}
std::string upper_stage(const std::string& st) {
std::string u = st;
for (char& c : u) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
return u;
}
VkShaderStageFlagBits stage_bit(const std::string& st) {
if (st == "cs") return VK_SHADER_STAGE_COMPUTE_BIT;
if (st == "ps") return VK_SHADER_STAGE_FRAGMENT_BIT;
if (st == "vs") return VK_SHADER_STAGE_VERTEX_BIT;
if (st == "ms") return VK_SHADER_STAGE_MESH_BIT_EXT;
if (st == "gs") return VK_SHADER_STAGE_GEOMETRY_BIT;
return VkShaderStageFlagBits(0);
}
struct StageStats {
uint32_t pipes_ok = 0;
uint32_t pipes_bad = 0;
uint32_t pipes_skipped = 0;
uint32_t crash_skipped = 0; // --skip-file: counted in pipes_bad, not compiled
uint32_t w32_ok = 0;
uint32_t w32_bad = 0;
uint32_t w32_unforced = 0;
uint32_t w64_ok = 0;
uint32_t w64_bad = 0;
uint32_t w64_unforced = 0;
uint32_t feedback[3] = {}; // --cache-feedback, successful pipelines only, indexed by feedback_outcome
double seconds = 0.0;
double max_sec = 0.0;
std::string max_name;
std::map<std::string, uint32_t> skip_reasons;
};
constexpr std::pair<size_t, size_t> shader_slice(size_t size, size_t start, size_t count) {
const size_t lo = std::min(start, size);
const size_t remaining = size - lo;
const size_t hi = count ? lo + std::min(count, remaining) : size;
return {lo, hi};
}
static_assert(shader_slice(7, 2, 3) == std::pair<size_t, size_t>{2, 5});
static_assert(shader_slice(7, 2, 0) == std::pair<size_t, size_t>{2, 7});
static_assert(shader_slice(7, 8, 3) == std::pair<size_t, size_t>{7, 7});
static_assert(shader_slice(7, 2, std::numeric_limits<size_t>::max()) == std::pair<size_t, size_t>{2, 7});
// --cache-feedback class of a successful pipeline: 0 hit, 1 no hit reported, 2 unavailable. A hit counts only with
// VALID; the duration and base-pipeline bits are not classified.
constexpr int feedback_outcome(VkPipelineCreationFeedbackFlags f) {
if (!(f & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT)) return 2;
return (f & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) ? 0 : 1;
}
static_assert(feedback_outcome(0) == 2);
static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 2);
static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) == 1);
static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT |
VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 0);
// Test hook (see the header): VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL].
struct SimulatedCrash {
bool enabled = false;
std::string pattern;
int sig = SIGFPE;
};
int signal_from_name(std::string n) {
for (char& c : n) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
if (n.rfind("SIG", 0) == 0) n = n.substr(3);
if (n == "FPE") return SIGFPE;
if (n == "SEGV") return SIGSEGV;
if (n == "ABRT") return SIGABRT;
if (n == "ILL") return SIGILL;
if (n == "TERM") return SIGTERM;
#ifndef _WIN32
if (n == "BUS") return SIGBUS;
if (n == "KILL") return SIGKILL;
#endif
return 0;
}
SimulatedCrash read_simulated_crash() {
SimulatedCrash c;
const char* env = std::getenv("VK_PIPELINE_CHECK_SIMULATE_CRASH");
if (!env || !*env) return c;
std::string v = env;
const size_t colon = v.rfind(':');
if (colon != std::string::npos) {
if (const int sig = signal_from_name(v.substr(colon + 1))) {
c.sig = sig;
v.resize(colon);
}
}
c.enabled = true;
c.pattern = v;
return c;
}
#ifndef _WIN32
std::string signal_label(int sig) {
switch (sig) {
case SIGFPE: return "SIGFPE";
case SIGSEGV: return "SIGSEGV";
case SIGABRT: return "SIGABRT";
case SIGILL: return "SIGILL";
case SIGBUS: return "SIGBUS";
case SIGKILL: return "SIGKILL";
case SIGTERM: return "SIGTERM";
default: return "signal " + std::to_string(sig);
}
}
// --isolate: one child run of this executable over [start, start + count) of the stage-filtered list.
struct ChildRun {
bool ready = false; // reached the work loop (ISO-READY): Vulkan and the cache were set up
bool done = false; // finished the pass and saved the cache (ISO-DONE)
bool cache_ok = true;
int sig = 0; // killed by this signal
int status = 0; // exit status when it exited
std::string out; // its stdout
};
ChildRun run_child(const std::string& exe, const std::string& dir, const std::vector<std::string>& pass,
const std::string& cache_path, size_t start, size_t count) {
ChildRun r;
std::vector<std::string> args = {exe, dir};
if (!cache_path.empty()) args.push_back(cache_path);
for (const auto& a : pass) args.push_back(a);
args.insert(args.end(), {"--isolate-child", "--start", std::to_string(start), "--count", std::to_string(count)});
std::vector<char*> argv;
for (auto& a : args) argv.push_back(a.data());
argv.push_back(nullptr);
int fds[2];
if (pipe(fds) != 0) { r.status = 127; return r; }
std::fflush(nullptr);
const pid_t pid = fork();
if (pid < 0) { close(fds[0]); close(fds[1]); r.status = 127; return r; }
if (pid == 0) {
dup2(fds[1], 1);
close(fds[0]); close(fds[1]);
execv(exe.c_str(), argv.data());
_exit(127);
}
close(fds[1]);
char buf[4096];
for (;;) {
const ssize_t n = read(fds[0], buf, sizeof buf);
if (n > 0) r.out.append(buf, size_t(n));
else if (n < 0 && errno == EINTR) continue;
else break;
}
close(fds[0]);
int st = 0;
while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {}
if (WIFSIGNALED(st)) r.sig = WTERMSIG(st);
else r.status = WIFEXITED(st) ? WEXITSTATUS(st) : 1;
size_t pos = 0;
while (pos < r.out.size()) {
size_t e = r.out.find('\n', pos);
if (e == std::string::npos) e = r.out.size();
const std::string_view line(r.out.data() + pos, e - pos);
if (line == "ISO-READY") r.ready = true;
else if (line.rfind("ISO-DONE", 0) == 0) { r.done = true; r.cache_ok = line.find("cache_ok=0") == std::string_view::npos; }
pos = e + 1;
}
return r;
}
#endif
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::fprintf(stderr,
"usage: vk_pipeline_check <spirv dir> [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] "
"[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] "
"[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] "
"[--skip-file F]\n");
return 2;
}
std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen
std::string dir = argv[1], cache_path, stats_path, inflight_path, skip_path;
uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2);
size_t start = 0, count = 0, max_bytes = 0;
size_t large_module_bytes = 4 * 1024 * 1024;
double slow = 30.0;
std::string stage_filter = "all";
bool cache_feedback = false, isolate = false, iso_child = false;
size_t isolate_batch = 256;
for (int i = 2; i < argc; i++) {
std::string a = argv[i];
auto value = [&]() -> std::string_view {
if (i + 1 == argc || std::string_view(argv[i + 1]).starts_with("--")) return {};
return argv[++i];
};
auto number = [&](auto& dest) {
const auto text = value();
if (text.empty()) return false;
const auto end = text.data() + text.size();
const auto [ptr, ec] = std::from_chars(text.data(), end, dest);
return ec == std::errc{} && ptr == end;
};
bool valid = true;
if (a == "--jobs") {
valid = number(jobs);
jobs = std::max(1u, jobs);
} else if (a == "--start") valid = number(start);
else if (a == "--count") valid = number(count);
else if (a == "--slow") valid = number(slow) && std::isfinite(slow) && slow >= 0.0;
else if (a == "--stage") valid = !(stage_filter = value()).empty();
else if (a == "--compute-only") stage_filter = "cs";
else if (a == "--graphics-only") stage_filter = "graphics";
else if (a == "--max-bytes") valid = number(max_bytes);
else if (a == "--large-module-bytes") valid = number(large_module_bytes);
else if (a == "--stats") valid = !(stats_path = value()).empty();
else if (a == "--inflight-file") valid = !(inflight_path = value()).empty();
else if (a == "--skip-file") valid = !(skip_path = value()).empty();
else if (a == "--cache-feedback") cache_feedback = true;
else if (a == "--isolate") isolate = true;
else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs
else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch
valid = number(isolate_batch);
isolate_batch = std::max<size_t>(1, isolate_batch);
}
else if (a.starts_with("--")) { // not a cache path: an option this build doesn't know
std::fprintf(stderr, "unknown option %s\n", a.c_str());
return 2;
} else if (cache_path.empty()) cache_path = a;
else {
std::fprintf(stderr, "unexpected argument %s (the cache path is already %s)\n", a.c_str(),
cache_path.c_str());
return 2;
}
if (!valid) {
std::fprintf(stderr, "%s requires a valid value\n", a.c_str());
return 2;
}
}
if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") {
std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str());
return 2;
}
if (isolate && !stats_path.empty()) {
std::fprintf(stderr, "--isolate cannot be combined with --stats\n");
return 2;
}
#ifdef _WIN32
if (isolate) {
std::fprintf(stderr, "--isolate is not supported on Windows (it needs fork/waitpid); run without it\n");
return 2;
}
#endif
std::set<std::string> skip_names; // --skip-file: modules that killed the driver in an earlier run
if (!skip_path.empty()) {
std::ifstream sf(skip_path);
if (!sf) {
std::fprintf(stderr, "error: cannot read --skip-file %s\n", skip_path.c_str());
return 2;
}
for (std::string line; std::getline(sf, line);) {
while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) line.pop_back();
if (!line.empty()) skip_names.insert(line);
}
}
std::string index_err;
bool index_unreadable = false;
auto index = read_index(dir + "/index.json", index_err, index_unreadable);
if (!index_err.empty()) {
std::fprintf(stderr, index_unreadable ? "error: cannot read %s/index.json: %s\n" : "error: malformed JSON in %s/index.json: %s\n",
dir.c_str(), index_err.c_str());
return 2;
}
std::fprintf(stderr, "%zu shaders in index\n", index.size());
// Build work list: index order (sorted by name), optionally filtered by stage, then [start, start + count).
using Item = std::pair<const std::string*, const ShaderMeta*>;
std::vector<Item> all;
for (auto& [name, meta] : index) {
if (stage_filter == "cs" && meta.stage != "cs") continue;
if (stage_filter == "graphics" && !is_graphics_stage(meta.stage)) continue;
all.push_back({&name, &meta});
}
const auto [lo, hi] = shader_slice(all.size(), start, count);
const std::vector<Item> work(all.begin() + lo, all.begin() + hi);
#ifndef _WIN32
if (isolate) {
// Parent: no Vulkan here. Run the check in child processes, one at a time, in batches of --isolate-batch
// modules. A child that dies mid-batch has its output discarded and the batch is bisected until the one
// module that kills the driver is found; the clean sub-runs partition the rest, so nothing is counted twice.
std::string exe = argv[0];
std::error_code ec;
if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string();
std::vector<std::string> pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter,
"--max-bytes", std::to_string(max_bytes),
"--large-module-bytes", std::to_string(large_module_bytes)};
if (cache_feedback) pass.push_back("--cache-feedback");
if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path});
struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; };
std::map<std::string, Agg> agg;
std::vector<std::string> crashes;
bool cache_ok = true, setup_failed = false;
size_t unreproduced = 0;
const auto t_iso = std::chrono::steady_clock::now();
std::fprintf(stderr, "isolating %zu shaders [%zu, %zu) (stage=%s) in child processes, %zu per batch\n",
work.size(), lo, hi, stage_filter.c_str(), isolate_batch);
auto commit = [&](const ChildRun& r) {
size_t pos = 0;
while (pos < r.out.size()) {
size_t e = r.out.find('\n', pos);
if (e == std::string::npos) e = r.out.size();
const std::string line = r.out.substr(pos, e - pos);
pos = e + 1;
// The parent prints one cache line at the end instead of one per child.
if (line == "ISO-READY" || line.rfind("ISO-DONE", 0) == 0 || line.rfind("pipeline cache: ", 0) == 0) continue;
if (line.rfind("ISO-RESULT ", 0) == 0) {
char st[16];
unsigned v[9] = {};
if (std::sscanf(line.c_str(), "ISO-RESULT %15s %u %u %u %u %u %u %u %u %u", st, v, v + 1, v + 2, v + 3,
v + 4, v + 5, v + 6, v + 7, v + 8) == 10) {
Agg& a = agg[st];
a.mod_ok += v[0]; a.mod_bad += v[1]; a.pipe_ok += v[2]; a.pipe_bad += v[3]; a.pipe_skip += v[4];
a.big += v[5]; a.fb[0] += v[6]; a.fb[1] += v[7]; a.fb[2] += v[8];
}
continue;
}
std::printf("%s\n", line.c_str());
}
std::fflush(stdout);
if (!r.cache_ok) cache_ok = false;
};
// Returns the number of failures recorded for [s, s + n): crashed modules, or 1 for a crash that vanished.
auto bisect = [&](auto&& self, size_t s, size_t n) -> size_t {
if (setup_failed) return 0;
const ChildRun r = run_child(exe, dir, pass, cache_path, s, n);
if (r.done) { commit(r); return 0; }
if (!r.ready) { // died or exited before the work loop: not a module's fault
std::fputs(r.out.c_str(), stdout);
if (r.sig) std::fprintf(stderr, "error: a child process died during setup (%s)\n", signal_label(r.sig).c_str());
else std::fprintf(stderr, "error: a child process failed during setup (exit status %d)\n", r.status);
setup_failed = true;
return 0;
}
const std::string why = r.sig ? "driver crashed: " + signal_label(r.sig)
: "driver exited with status " + std::to_string(r.status);
if (n == 1) {
const std::string& name = *all[s].first;
const std::string& st = all[s].second->stage;
std::printf("MODULE CRASH %s (%s, %s)\n", name.c_str(), st.c_str(), why.c_str());
std::fflush(stdout);
crashes.push_back(name + " (" + st + ", " + why + ")");
agg[st].pipe_bad++;
agg[st].crashed++;
return 1;
}
std::fprintf(stderr, "child over [%zu, %zu) died (%s); bisecting\n", s, s + n, why.c_str());
const size_t half = n / 2;
size_t found = self(self, s, half);
found += self(self, s + half, n - half);
if (found == 0 && !setup_failed) {
std::printf("MODULE CRASH [%zu, %zu) not reproduced when split (%s); counted as failed\n", s, s + n, why.c_str());
++unreproduced;
return 1;
}
return found;
};
for (size_t s = lo; s < hi && !setup_failed; s += isolate_batch) bisect(bisect, s, std::min(isolate_batch, hi - s));
if (setup_failed) return 1;
bool failed = !crashes.empty() || unreproduced || !cache_ok;
for (const auto& [st, a] : agg) {
std::printf("%s: %u modules ok, %u failed\n", st.c_str(), a.mod_ok, a.mod_bad);
std::printf("%s pipelines: %u ok, %u failed, %u skipped\n", st.c_str(), a.pipe_ok, a.pipe_bad, a.pipe_skip);
if (a.crashed) std::printf(" %s crashed the driver: %u (counted as failed)\n", st.c_str(), a.crashed);
if (cache_feedback)
std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n", st.c_str(), a.fb[0], a.fb[1], a.fb[2]);
if (a.mod_bad || a.pipe_bad) failed = true;
}
uint32_t big_total = 0;
for (const auto& [st, a] : agg) big_total += a.big;
if (big_total) std::printf("big modules skipped: %u (limit %zu bytes)\n", big_total, max_bytes);
if (!crashes.empty()) {
std::printf("modules that crashed the driver: %zu\n", crashes.size());
for (const auto& c : crashes) std::printf(" %s\n", c.c_str());
}
if (unreproduced) std::printf("crashes not reproduced after splitting: %zu\n", unreproduced);
if (!cache_path.empty()) {
const auto sz = std::filesystem::file_size(cache_path, ec);
if (!ec) std::printf("pipeline cache: %ju bytes -> %s\n", static_cast<uintmax_t>(sz), cache_path.c_str());
}
std::printf("wall time: %.1fs (isolated)\n",
std::chrono::duration<double>(std::chrono::steady_clock::now() - t_iso).count());
return failed ? 1 : 0;
}
#endif
// Scan selected shaders to request only the optional extensions they actually use.
bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false;
for (auto& [_, meta] : work) {
if (meta->stage == "ms") want_mesh = true;
if (meta->needs_maintenance8) want_m8 = true;
for (const auto& feat : meta->features) {
if (feat == "meshShader") want_mesh = true;
else if (feat == "fragmentShaderBarycentric") want_bary = true;
else if (feat == "fragmentShaderPixelInterlock") want_lock = true;
else if (feat == "shaderFmaFloat32") want_fma = true; // OpFmaKHR (rdna2spirv.py --fma khr)
}
}
gipa = load_vulkan();
if (!gipa) return 1;
#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name))
VkInstance inst = VK_NULL_HANDLE;
LOADI(vkCreateInstance);
VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO};
app.apiVersion = VK_API_VERSION_1_3;
VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
ici.pApplicationInfo = &app;
if (vkCreateInstance(&ici, nullptr, &inst)) return 1;
LOADI(vkEnumeratePhysicalDevices); LOADI(vkGetPhysicalDeviceProperties); LOADI(vkCreateDevice);
LOADI(vkGetPhysicalDeviceProperties2);
LOADI(vkGetDeviceProcAddr); LOADI(vkEnumerateDeviceExtensionProperties); LOADI(vkGetPhysicalDeviceFeatures2);
uint32_t n = 0;
vkEnumeratePhysicalDevices(inst, &n, nullptr);
if (n == 0) { std::fprintf(stderr, "no Vulkan physical devices found\n"); return 1; }
std::vector<VkPhysicalDevice> pds(n);
vkEnumeratePhysicalDevices(inst, &n, pds.data());
std::vector<VkPhysicalDeviceProperties> candidates(pds.size());
for (std::size_t i = 0; i < pds.size(); ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]);
const std::size_t chosen = leonida::vk_test::pick_device(candidates);
VkPhysicalDevice pd = chosen < pds.size() ? pds[chosen] : VK_NULL_HANDLE;
if (!pd) {
leonida::vk_test::report_no_device();
return 1;
}
VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props);
VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES};
VkPhysicalDeviceFloatControlsProperties fcProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES};
VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
props2.pNext = &sgProps;
sgProps.pNext = &fcProps;
vkGetPhysicalDeviceProperties2(pd, &props2);
std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize);
uint32_t en = 0;
vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, nullptr);
std::vector<VkExtensionProperties> exts(en);
vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, exts.data());
auto has = [&](const char* e) { for (auto& x : exts) if (!std::strcmp(x.extensionName, e)) return true; return false; };
std::vector<const char*> enable;
// Query what the GPU supports for core 1.2/1.3 and any optional extensions requested by `work`.
VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR};
VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT};
#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
VkPhysicalDeviceMaintenance8FeaturesKHR m8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR};
#endif
VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR exe{
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR};
VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
void* chain = nullptr;
auto link = [&](void* s, VkBaseOutStructure* b, const char* ext, bool needed) -> bool {
if (!needed) return false;
if (ext && !has(ext)) return false;
if (ext) enable.push_back(ext);
b->pNext = static_cast<VkBaseOutStructure*>(chain); chain = s;
return true;
};
link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true);
link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true);
const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, want_mesh);
const bool ext_bary = link(&bary, reinterpret_cast<VkBaseOutStructure*>(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary);
const bool ext_lock = link(&lock, reinterpret_cast<VkBaseOutStructure*>(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock);
#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
const bool ext_m8 = link(&m8, reinterpret_cast<VkBaseOutStructure*>(&m8), VK_KHR_MAINTENANCE_8_EXTENSION_NAME, want_m8);
#else
(void)want_m8;
#endif
#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
VkPhysicalDeviceShaderFmaFeaturesKHR fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR};
const bool ext_fma = link(&fma, reinterpret_cast<VkBaseOutStructure*>(&fma), VK_KHR_SHADER_FMA_EXTENSION_NAME, want_fma);
#else
const bool ext_fma = false;
(void)want_fma;
#endif
const bool ext_exe = link(&exe, reinterpret_cast<VkBaseOutStructure*>(&exe),
VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty());
if (!stats_path.empty() && !ext_exe) {
std::fprintf(stderr, "--stats: the device has no %s\n", VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME);
return 1;
}
// --cache-feedback: core in Vulkan 1.3 (no feature bit). A pre-1.3 device needs VK_EXT_pipeline_creation_feedback;
// without it nothing is chained and every successful pipeline counts as unavailable.
const bool fb_ext = cache_feedback && props.apiVersion < VK_API_VERSION_1_3 &&
has(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME);
if (fb_ext) enable.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME);
const bool feedback = cache_feedback && (props.apiVersion >= VK_API_VERSION_1_3 || fb_ext);
if (cache_feedback && !feedback)
std::fprintf(stderr, "note: --cache-feedback: no Vulkan 1.3 or %s; every pipeline is counted unavailable\n",
VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME);
VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
f2.pNext = chain;
vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported
if (ext_mesh) {
mesh.multiviewMeshShader = mesh.primitiveFragmentShadingRateMeshShader = mesh.meshShaderQueries = VK_FALSE;
mesh.taskShader = VK_FALSE;
}
float prio = 1;
VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
qci.queueFamilyIndex = 0; qci.queueCount = 1; qci.pQueuePriorities = &prio;
VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2;
dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data();
VkDevice dev;
if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; }
auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool {
return f13.subgroupSizeControl &&
sg >= sgProps.minSubgroupSize &&
sg <= sgProps.maxSubgroupSize &&
(sgProps.requiredSubgroupSizeStages & bit);
};
{
std::map<uint32_t, std::set<std::string>> unforced_by_sg;
for (const auto& [_, meta] : work) {
const VkShaderStageFlagBits bit = stage_bit(meta->stage);
if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) {
unforced_by_sg[meta->subgroup_size].insert(meta->stage);
}
}
for (const auto& [sg, stages] : unforced_by_sg) {
std::string list;
for (const auto& st : stages) {
if (!list.empty()) list += "/";
list += st;
}
std::fprintf(stderr,
"note: %u-wide subgroups not supported for %s; those pipelines are compiled without a required subgroup size\n",
sg, list.c_str());
}
}
#define LOADD(name) auto name = reinterpret_cast<PFN_##name>(vkGetDeviceProcAddr(dev, #name))
LOADD(vkCreateShaderModule); LOADD(vkDestroyShaderModule); LOADD(vkCreateDescriptorSetLayout);
LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateGraphicsPipelines);
LOADD(vkDestroyPipeline); LOADD(vkCreatePipelineCache); LOADD(vkGetPipelineCacheData);
LOADD(vkGetPipelineExecutablePropertiesKHR); LOADD(vkGetPipelineExecutableStatisticsKHR);
const VkPipelineCreateFlags capture = stats_path.empty() ? 0 : VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR;
// Map enabled device features for per-shader compatibility checks.
auto check_missing_feature = [&](const ShaderMeta& meta) -> std::string {
if (is_graphics_stage(meta.stage) && !f13.dynamicRendering) return "no dynamicRendering";
if (meta.stage == "ms" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader";
if (meta.stage == "gs" && !f2.features.geometryShader) return "no geometryShader";
if (meta.needs_maintenance8) {
#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
if (!(ext_m8 && m8.maintenance8)) return "no VK_KHR_maintenance8";
#else
return "no VK_KHR_maintenance8";
#endif
}
// Execution modes the translator declares (SignedZeroInfNanPreserve 32) need a device property, not a feature.
for (const auto& fc : meta.float_controls) {
if (fc == "shaderSignedZeroInfNanPreserveFloat32") {
if (!fcProps.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc;
} else {
return "unknown float control " + fc;
}
}
for (const auto& feat : meta.features) {
if (feat == "meshShader" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader";
if (feat == "geometryShader" && !f2.features.geometryShader) return "no geometryShader";
if (feat == "fragmentShaderBarycentric" && !(ext_bary && bary.fragmentShaderBarycentric)) return "no fragmentShaderBarycentric";
if (feat == "fragmentShaderPixelInterlock" && !(ext_lock && lock.fragmentShaderPixelInterlock)) return "no fragmentShaderPixelInterlock";
if (feat == "shaderFmaFloat32") {
#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
if (!(ext_fma && fma.shaderFmaFloat32)) return "no VK_KHR_shader_fma (shaderFmaFloat32)";
#else
return "no VK_KHR_shader_fma (shaderFmaFloat32)";
#endif
}
if (feat == "shaderFloat64" && !f2.features.shaderFloat64) return "no shaderFloat64";
if (feat == "shaderInt64" && !f2.features.shaderInt64) return "no shaderInt64";
if (feat == "bufferDeviceAddress" && !f12.bufferDeviceAddress) return "no bufferDeviceAddress";
if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray";
if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended";
if (feat == "shaderResourceMinLod" && !f2.features.shaderResourceMinLod) return "no shaderResourceMinLod";
if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat)
return "no shaderStorageImageWriteWithoutFormat";
if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat)
return "no shaderStorageImageReadWithoutFormat";
}
return {};
};
// Resource contract (docs/design.md): set 0, runtime-sized arrays as large bindless arrays.
std::vector<VkDescriptorSetLayoutBinding> b;
auto add = [&](uint32_t bind, VkDescriptorType t, uint32_t cnt) {
b.push_back({bind, t, cnt, VK_SHADER_STAGE_ALL, nullptr});
};
add(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096); add(1, VK_DESCRIPTOR_TYPE_SAMPLER, 1024);
add(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1); add(3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024);
add(4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024); add(5, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256);
add(6, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); add(7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256);
for (uint32_t i = 8; i <= 19; i++) add(i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256);
VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
dli.bindingCount = uint32_t(b.size()); dli.pBindings = b.data();
VkDescriptorSetLayout dsl;
if (VkResult r = vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)) { std::fprintf(stderr, "layout %d\n", r); return 1; }
VkPushConstantRange pcr{VK_SHADER_STAGE_ALL, 0, 144};
VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
VkPipelineLayout pl; vkCreatePipelineLayout(dev, &pli, nullptr, &pl);
VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
std::vector<char> seed;
if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly
std::ifstream cf(cache_path, std::ios::binary);
seed.assign(std::istreambuf_iterator<char>(cf), {});
if (!seed.empty()) std::fprintf(stderr, "seeded the pipeline cache with %zu bytes from %s\n", seed.size(), cache_path.c_str());
}
pci.initialDataSize = seed.size(); pci.pInitialData = seed.empty() ? nullptr : seed.data();
VkPipelineCache cache = VK_NULL_HANDLE;
if (vkCreatePipelineCache(dev, &pci, nullptr, &cache)) { // data from another driver: start empty
pci.initialDataSize = 0; pci.pInitialData = nullptr;
if (VkResult r = vkCreatePipelineCache(dev, &pci, nullptr, &cache)) {
std::fprintf(stderr, "vkCreatePipelineCache failed: %d\n", r);
return 1;
}
}
std::vector<char>().swap(seed); // the driver has copied the seed; it can be several GiB
auto save_cache = [&](bool final_save) {
if (cache_path.empty()) return true;
try {
const auto data = pipeline_cache_snapshot([&](size_t* size, void* dest) {
return vkGetPipelineCacheData(dev, cache, size, dest);
});
if (auto error = write_pipeline_cache_file(cache_path, data.data(), data.size()))
throw std::system_error(error);
if (final_save) std::printf("pipeline cache: %zu bytes -> %s\n", data.size(), cache_path.c_str());
return true;
} catch (const std::exception& e) {
std::fprintf(stderr, "%s pipeline cache save to %s failed: %s\n",
final_save ? "final" : "periodic", cache_path.c_str(), e.what());
return false;
}
};
std::fprintf(stderr, "checking %zu shaders [%zu, %zu) (stage=%s) on %u threads\n",
work.size(), lo, hi, stage_filter.c_str(), jobs);
std::mutex mu; // guards counters, stdout, stub cache and in-flight table
std::shared_mutex compile_gate; // large modules exclude other shader and pipeline work
size_t isolated_modules = 0;
std::map<std::string, uint32_t> modules_ok, modules_bad, big_skipped;
std::map<std::string, StageStats> stats;
std::map<std::string, VkShaderModule> stub_cache;
std::atomic<size_t> next{0}, done{0};
std::atomic<uint32_t> total_pipes_done{0};
// What each worker is doing in the driver: creating the shader module, then creating its pipeline.
struct InFlight {
std::string name;
std::chrono::steady_clock::time_point since;
const char* phase; // "module" or "pipeline"
};
std::map<std::thread::id, InFlight> inflight;
// --inflight-file: rewrite the file from `inflight`, one "name<TAB>phase" line per module. Called with mu held, at
// the moments named in the header.
auto write_inflight = [&] {
if (inflight_path.empty()) return;
if (std::FILE* f = std::fopen(inflight_path.c_str(), "w")) {
for (const auto& [tid, job] : inflight) std::fprintf(f, "%s\t%s\n", job.name.c_str(), job.phase);
std::fclose(f);
}
};
const auto t_start = std::chrono::steady_clock::now();
auto elapsed = [&] { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count(); };
auto load_stub = [&](const std::string& fname) -> VkShaderModule {
{
std::lock_guard<std::mutex> g(mu);
auto it = stub_cache.find(fname);
if (it != stub_cache.end()) return it->second;
}
std::ifstream f(dir + "/stubs/" + fname, std::ios::binary);
std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
VkShaderModule mod = VK_NULL_HANDLE;
if (!code.empty()) {
VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
smi.codeSize = code.size();
smi.pCode = reinterpret_cast<const uint32_t*>(code.data());
if (vkCreateShaderModule(dev, &smi, nullptr, &mod) != VK_SUCCESS) mod = VK_NULL_HANDLE;
}
std::lock_guard<std::mutex> g(mu);
auto [it, inserted] = stub_cache.emplace(fname, mod);
if (!inserted && mod) vkDestroyShaderModule(dev, mod, nullptr);
return it->second;
};
auto record_skip = [&](const std::string& name, const std::string& stage, const std::string& reason) {
std::lock_guard<std::mutex> g(mu);
auto& st = stats[stage];
st.pipes_skipped++;
st.skip_reasons[reason]++;
std::printf("SKIPPED %s (%s)\n", name.c_str(), reason.c_str());
};
std::FILE* stats_out = stats_path.empty() ? nullptr : std::fopen(stats_path.c_str(), "w");
if (!stats_path.empty() && !stats_out) { std::fprintf(stderr, "cannot write %s\n", stats_path.c_str()); return 1; }
if (stats_out) std::fprintf(stats_out, "name,stage,statistic,value\n");
// --stats: one CSV row per statistic of the executable that runs the translated shader (stage bit `bit`).
auto write_stats = [&](const std::string& name, const std::string& stage, VkShaderStageFlagBits bit, VkPipeline p) {
if (!stats_out) return;
VkPipelineInfoKHR pi{VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR};
pi.pipeline = p;
uint32_t n = 0;
vkGetPipelineExecutablePropertiesKHR(dev, &pi, &n, nullptr);
std::vector<VkPipelineExecutablePropertiesKHR> exes(n, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_PROPERTIES_KHR});
vkGetPipelineExecutablePropertiesKHR(dev, &pi, &n, exes.data());
for (uint32_t e = 0; e < n; e++) {
if (!(exes[e].stages & bit)) continue;
VkPipelineExecutableInfoKHR ei{VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_INFO_KHR};
ei.pipeline = p; ei.executableIndex = e;
uint32_t m = 0;
vkGetPipelineExecutableStatisticsKHR(dev, &ei, &m, nullptr);
std::vector<VkPipelineExecutableStatisticKHR> st(m, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_STATISTIC_KHR});
vkGetPipelineExecutableStatisticsKHR(dev, &ei, &m, st.data());
std::lock_guard<std::mutex> g(mu);
for (auto& x : st) {
std::fprintf(stats_out, "%s,%s,%s,", name.c_str(), stage.c_str(), x.name);
switch (x.format) {
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR: std::fprintf(stats_out, "%u\n", x.value.b32); break;
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR: std::fprintf(stats_out, "%lld\n", (long long)x.value.i64); break;
case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR: std::fprintf(stats_out, "%llu\n", (unsigned long long)x.value.u64); break;
default: std::fprintf(stats_out, "%g\n", x.value.f64); break;
}
}
}
};
auto record_pipe = [&](const std::string& name, const std::string& stage, uint32_t sg, bool sg_forced,
VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) {
std::lock_guard<std::mutex> g(mu);
inflight.erase(std::this_thread::get_id());
if (inflight.empty()) write_inflight(); // a large module just finished (it compiles alone)
auto& st = stats[stage];
st.seconds += sec;
if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; }
if (sec > slow) std::printf("SLOW %s %s (w%u, %.1fs)\n", upper_stage(stage).c_str(), name.c_str(), sg, sec);
if (sg > 0 && !sg_forced) {
if (sg == 64) st.w64_unforced++; else st.w32_unforced++;
}
if (r) {
st.pipes_bad++;
if (sg == 64) st.w64_bad++; else st.w32_bad++;
std::printf("PIPELINE FAIL %s (%s w%u, %d)\n", name.c_str(), stage.c_str(), sg, r);
} else {
st.pipes_ok++;
if (cache_feedback) st.feedback[feedback_outcome(fb_flags)]++;
if (sg == 64) st.w64_ok++; else st.w32_ok++;
}
uint32_t n_done = ++total_pipes_done;
if (n_done % 250 == 0) std::fprintf(stderr, " pipelines %u (%.0fs elapsed)\n", n_done, elapsed());
};
const SimulatedCrash sim_crash = read_simulated_crash();
auto maybe_simulate_crash = [&](const std::string& name) { // test hook, see the header
if (sim_crash.enabled && name.find(sim_crash.pattern) != std::string::npos) {
std::fprintf(stderr, "simulating signal %d before the pipeline of %s\n", sim_crash.sig, name.c_str());
std::fflush(nullptr);
std::raise(sim_crash.sig);
}
};
auto worker = [&] {
for (size_t k; (k = next++) < work.size();) {
const std::string& name = *work[k].first;
const ShaderMeta& meta = *work[k].second;
const std::string& stage = meta.stage;
if (skip_names.count(name)) { // --skip-file: it killed the driver in an earlier run
{
std::lock_guard<std::mutex> g(mu);
auto& st = stats[stage];
st.pipes_bad++;
st.crash_skipped++;
std::printf("MODULE CRASH %s (%s, killed the driver in an earlier run; not retried)\n",
name.c_str(), stage.c_str());
}
++done;
continue;
}
std::ifstream f(dir + "/" + name + ".spv", std::ios::binary | std::ios::ate);
const std::streamoff file_size = f.tellg();
if (max_bytes && std::cmp_greater(file_size, max_bytes)) { // multi-MB ray-tracing shaders (#108)
{
std::lock_guard<std::mutex> g(mu);
big_skipped[stage]++;
std::printf("BIG SKIP %s (%lld bytes, limit %zu)\n",
name.c_str(), static_cast<long long>(file_size), max_bytes);
}
++done;
continue;
}
if (stage == "cs" && meta.lds_bytes > props.limits.maxComputeSharedMemorySize) {
std::lock_guard<std::mutex> g(mu);
modules_bad[stage]++;
std::printf("MODULE FAIL %s (workgroup memory %u bytes exceeds maxComputeSharedMemorySize %u)\n",
name.c_str(), meta.lds_bytes, props.limits.maxComputeSharedMemorySize);
++done;
continue;
}
// Enter before reading the module: creation can also enter the driver. Hold until its pipeline and
// module have been destroyed, including on failure. The watchdog and cache writer don't take this lock.
const bool isolated = large_module_bytes && std::cmp_greater(file_size, large_module_bytes);
std::unique_lock exclusive(compile_gate, std::defer_lock);
std::shared_lock parallel(compile_gate, std::defer_lock);
if (isolated) exclusive.lock();
else if (large_module_bytes) parallel.lock();
{ // in flight from here: vkCreateShaderModule can also take long or die in the driver
std::lock_guard<std::mutex> g(mu);
inflight[std::this_thread::get_id()] = {name, std::chrono::steady_clock::now(), "module"};
if (isolated) write_inflight(); // alone in flight: the file names exactly this module
}
f.seekg(0);
std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
VkShaderModule sm = VK_NULL_HANDLE;
bool mod_ok = false;
if (!code.empty()) {
VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data());
mod_ok = vkCreateShaderModule(dev, &smi, nullptr, &sm) == VK_SUCCESS;
}
{
std::lock_guard<std::mutex> g(mu);
if (isolated) ++isolated_modules;
if (mod_ok) modules_ok[stage]++;
else { modules_bad[stage]++; std::printf("MODULE FAIL %s\n", name.c_str()); }
}
if (mod_ok && stage == "cs") {
const std::string miss = check_missing_feature(meta);
if (!miss.empty()) {
record_skip(name, stage, miss);
} else {
VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
reqSg.requiredSubgroupSize = meta.subgroup_size;
VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main";
const bool sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT);
if (sg_forced) cpi.stage.pNext = &reqSg;
cpi.layout = pl;
cpi.flags = capture;
// Only whole-pipeline feedback is reported.
VkPipelineCreationFeedback fb{};
VkPipelineCreationFeedbackCreateInfo fci{
VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, nullptr, &fb, 0, nullptr};
if (feedback) cpi.pNext = &fci;
const auto t0 = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> g(mu);
inflight[std::this_thread::get_id()] = {name, t0, "pipeline"};
if (isolated) write_inflight(); // alone in flight: the file names exactly this module
}
VkPipeline p = VK_NULL_HANDLE;
maybe_simulate_crash(name);
VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p);
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p);
if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr);
record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec, fb.flags);
}
} else if (mod_ok && is_graphics_stage(stage)) {
const std::string miss = check_missing_feature(meta);
if (!miss.empty()) {
record_skip(name, stage, miss);
} else {
std::vector<VkPipelineShaderStageCreateInfo> stages;
VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
reqSg.requiredSubgroupSize = meta.subgroup_size;
bool sg_forced = false;
auto make_stage = [&](VkShaderStageFlagBits bit, VkShaderModule mod, bool real) {
VkPipelineShaderStageCreateInfo si{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
si.stage = bit; si.module = mod; si.pName = "main";
if (real && can_require_sg(meta.subgroup_size, bit)) {
si.pNext = &reqSg;
sg_forced = true;
}
return si;
};
std::string skip_reason;
std::vector<VkFormat> color_formats;
VkFormat depth_format = VK_FORMAT_UNDEFINED;
bool use_vertex_input = true;
if (stage == "ps") {
std::string vs_fn = stub_filename("vs", meta.inputs);
VkShaderModule vs_mod = load_stub(vs_fn);
if (!vs_mod) {
skip_reason = "missing stub " + vs_fn;
} else {
uint32_t n_color = 0;
for (uint32_t loc : meta.outputs) n_color = std::max(n_color, loc + 1);
if (n_color > props.limits.maxColorAttachments) {
skip_reason = "exceeds maxColorAttachments";
} else {
color_formats.assign(n_color, VK_FORMAT_R32G32B32A32_SFLOAT);
if (meta.writes_depth) depth_format = VK_FORMAT_D32_SFLOAT;
stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_mod, false));
stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, sm, true));
}
}
} else if (stage == "vs") {
std::string ps_fn = stub_filename("ps", meta.outputs);
VkShaderModule ps_mod = load_stub(ps_fn);
if (!ps_mod) {
skip_reason = "missing stub " + ps_fn;
} else {
color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT);
stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, sm, true));
stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false));
}
} else if (stage == "ms") {
use_vertex_input = false;
std::string ps_fn = stub_filename("ps", meta.params);
VkShaderModule ps_mod = load_stub(ps_fn);
if (!ps_mod) {
skip_reason = "missing stub " + ps_fn;
} else {
color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT);
stages.push_back(make_stage(VK_SHADER_STAGE_MESH_BIT_EXT, sm, true));
stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false));
}
} else if (stage == "gs") {
const auto& gs_in = meta.has_gs_input_locations ? meta.gs_input_locations : meta.gs_inputs;
const auto& gs_out = meta.has_gs_output_locations ? meta.gs_output_locations : meta.gs_outputs;
std::string vs_fn = stub_filename("vs", gs_in);
std::string ps_fn = stub_filename("ps", gs_out);
VkShaderModule vs_mod = load_stub(vs_fn);
VkShaderModule ps_mod = load_stub(ps_fn);
if (!vs_mod) skip_reason = "missing stub " + vs_fn;
else if (!ps_mod) skip_reason = "missing stub " + ps_fn;
else {
color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT);
stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_mod, false));
stages.push_back(make_stage(VK_SHADER_STAGE_GEOMETRY_BIT, sm, true));
stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false));
}
}
if (!skip_reason.empty()) {
record_skip(name, stage, skip_reason);
} else {
VkVertexInputBindingDescription vbind{0, 16, VK_VERTEX_INPUT_RATE_VERTEX};
std::vector<VkVertexInputAttributeDescription> vattrs;
if (stage == "vs") {
for (const auto& vi : meta.vertex_inputs) {
VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT;
if (vi.type == "uint") fmt = VK_FORMAT_R32G32B32A32_UINT;
else if (vi.type == "sint") fmt = VK_FORMAT_R32G32B32A32_SINT;
vattrs.push_back({vi.location, 0, fmt, 0});
}
}
VkPipelineVertexInputStateCreateInfo vi_state{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
if (!vattrs.empty()) {
vi_state.vertexBindingDescriptionCount = 1;
vi_state.pVertexBindingDescriptions = &vbind;
vi_state.vertexAttributeDescriptionCount = uint32_t(vattrs.size());
vi_state.pVertexAttributeDescriptions = vattrs.data();
}
VkPipelineInputAssemblyStateCreateInfo ia_state{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};
ia_state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkPipelineViewportStateCreateInfo vp_state{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
vp_state.viewportCount = 1;
vp_state.scissorCount = 1;
VkDynamicState dyn_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dyn_state{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dyn_state.dynamicStateCount = 2;
dyn_state.pDynamicStates = dyn_states;
VkPipelineRasterizationStateCreateInfo rast{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO};
rast.polygonMode = VK_POLYGON_MODE_FILL;
rast.cullMode = VK_CULL_MODE_NONE;
rast.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rast.lineWidth = 1.0f;
VkPipelineMultisampleStateCreateInfo msaa{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};
msaa.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineDepthStencilStateCreateInfo ds{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
if (depth_format != VK_FORMAT_UNDEFINED) {
ds.depthTestEnable = VK_TRUE;
ds.depthWriteEnable = VK_TRUE;
ds.depthCompareOp = VK_COMPARE_OP_LESS;
}
std::vector<VkPipelineColorBlendAttachmentState> blend_atts(color_formats.size());
for (auto& ba : blend_atts) ba.colorWriteMask = 0xF;
VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
blend.attachmentCount = uint32_t(blend_atts.size());
blend.pAttachments = blend_atts.empty() ? nullptr : blend_atts.data();
VkPipelineRenderingCreateInfo rend{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO};
rend.colorAttachmentCount = uint32_t(color_formats.size());
rend.pColorAttachmentFormats = color_formats.empty() ? nullptr : color_formats.data();
rend.depthAttachmentFormat = depth_format;
VkGraphicsPipelineCreateInfo gpci{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
gpci.pNext = &rend;
gpci.stageCount = uint32_t(stages.size());
gpci.pStages = stages.data();
gpci.pVertexInputState = use_vertex_input ? &vi_state : nullptr;
gpci.pInputAssemblyState = use_vertex_input ? &ia_state : nullptr;
gpci.pViewportState = &vp_state;
gpci.pRasterizationState = &rast;
gpci.pMultisampleState = &msaa;
gpci.pDepthStencilState = &ds;
gpci.pColorBlendState = &blend;
gpci.pDynamicState = &dyn_state;
gpci.layout = pl;
gpci.renderPass = VK_NULL_HANDLE;
gpci.flags = capture;
// Zeroed per call and read after it returns; per-stage entries are required but not reported.
VkPipelineCreationFeedback fb{};
VkPipelineCreationFeedbackCreateInfo fci{
VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, &rend, &fb, 0, nullptr};
if (feedback) gpci.pNext = &fci; // keeps rend chained behind it
const auto t0 = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> g(mu);
inflight[std::this_thread::get_id()] = {name, t0, "pipeline"};
if (isolated) write_inflight(); // alone in flight: the file names exactly this module
}
VkPipeline p = VK_NULL_HANDLE;
maybe_simulate_crash(name);
VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p);
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p);
if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr);
record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec, fb.flags);
}
}
} else if (mod_ok) {
record_skip(name, stage, "unsupported stage " + stage);
}
if (sm) vkDestroyShaderModule(dev, sm, nullptr);
{ // out of the driver on every path (a pipeline, a skip, a failed module)
std::lock_guard<std::mutex> g(mu);
if (inflight.erase(std::this_thread::get_id()) && inflight.empty()) write_inflight();
}
if (++done % 1000 == 0) {
std::lock_guard<std::mutex> g(mu);
std::fprintf(stderr, " %zu/%zu (%.0fs)\n", size_t(done), work.size(), elapsed());
}
}
};
if (iso_child) std::printf("ISO-READY\n");
std::fflush(stdout);
std::vector<std::thread> pool;
for (uint32_t t = 0; t < jobs; t++) pool.emplace_back(worker);
// Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes.
std::condition_variable watch_cv;
bool all_done = false;
std::thread watch([&] {
auto last_save = std::chrono::steady_clock::now();
std::unique_lock<std::mutex> g(mu);
while (!all_done) {
if (watch_cv.wait_for(g, std::chrono::seconds(5), [&] { return all_done; })) break;
const auto now = std::chrono::steady_clock::now();
write_inflight(); // --inflight-file: the modules compiling right now
for (auto& [tid, job] : inflight) {
const double s = std::chrono::duration<double>(now - job.since).count();
if (s > 60 && int(s) % 60 < 5)
std::fprintf(stderr, " still %s %s after %.0fs\n",
job.phase[0] == 'm' ? "creating the shader module of" : "compiling",
job.name.c_str(), s);
}
if (now - last_save > std::chrono::minutes(10)) {
g.unlock();
save_cache(false);
g.lock();
last_save = now;
}
}
});
for (auto& t : pool) t.join();
{
std::lock_guard<std::mutex> g(mu);
all_done = true;
inflight.clear();
write_inflight(); // the pass finished: nothing was compiling when the process ended
}
watch_cv.notify_one();
watch.join();
for (auto& [_, mod] : stub_cache) if (mod) vkDestroyShaderModule(dev, mod, nullptr);
std::set<std::string> all_stages;
for (auto& [st, _] : modules_ok) all_stages.insert(st);
for (auto& [st, _] : modules_bad) all_stages.insert(st);
for (auto& [st, _] : stats) all_stages.insert(st);
if (iso_child) { // --isolate child: machine-readable counts; the parent prints the summary
for (const auto& st : all_stages) {
const StageStats* s = stats.count(st) ? &stats[st] : nullptr;
uint32_t big = big_skipped.count(st) ? big_skipped[st] : 0;
std::printf("ISO-RESULT %s %u %u %u %u %u %u %u %u %u\n", st.c_str(), modules_ok[st], modules_bad[st],
s ? s->pipes_ok : 0u, s ? s->pipes_bad : 0u, s ? s->pipes_skipped : 0u, big,
s ? s->feedback[0] : 0u, s ? s->feedback[1] : 0u, s ? s->feedback[2] : 0u);
}
const bool saved = save_cache(true);
std::printf("ISO-DONE cache_ok=%d\n", saved ? 1 : 0);
std::fflush(stdout);
return saved ? 0 : 1;
}
bool check_failed = false;
for (const auto& st : all_stages) {
std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]);
if (modules_bad[st]) check_failed = true;
const auto it = stats.find(st);
if (it != stats.end()) {
const auto& s = it->second;
if (s.pipes_bad) check_failed = true;
const uint32_t compiled = s.pipes_ok + s.pipes_bad;
std::printf("%s pipelines: %u ok, %u failed, %u skipped\n",
st.c_str(), s.pipes_ok, s.pipes_bad, s.pipes_skipped);
if (cache_feedback)
std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n",
st.c_str(), s.feedback[0], s.feedback[1], s.feedback[2]);
if (s.crash_skipped)
std::printf(" %s not retried after killing the driver (--skip-file): %u (counted as failed)\n",
st.c_str(), s.crash_skipped);
if (!s.skip_reasons.empty()) {
for (const auto& [reason, cnt] : s.skip_reasons)
std::printf(" %s skipped (%s): %u\n", st.c_str(), reason.c_str(), cnt);
}
if (compiled > 0) {
auto fmt_unforced = [](uint32_t cnt) -> std::string {
return cnt ? (" (" + std::to_string(cnt) + " without required subgroup size)") : "";
};
std::printf(" %s wave32: %u ok, %u failed%s; wave64: %u ok, %u failed%s\n",
st.c_str(),
s.w32_ok, s.w32_bad, fmt_unforced(s.w32_unforced).c_str(),
s.w64_ok, s.w64_bad, fmt_unforced(s.w64_unforced).c_str());
std::printf(" %s compile time: %.2fs total, %.3fs mean, slowest %s (%.2fs)\n",
st.c_str(), s.seconds, s.seconds / compiled, s.max_name.c_str(), s.max_sec);
}
}
}
uint32_t big_total = 0;
for (auto& [st, c] : big_skipped) big_total += c;
if (big_total) {
std::printf("big modules skipped: %u (limit %zu bytes)", big_total, max_bytes);
for (auto& [st, c] : big_skipped) std::printf(" %s=%u", st.c_str(), c);
std::printf("; checked %zu of %zu\n", work.size() - big_total, work.size());
}
if (isolated_modules)
std::printf("large modules checked exclusively: %zu (over %zu bytes)\n", isolated_modules,
large_module_bytes);
std::printf("wall time: %.1fs on %u threads\n", elapsed(), jobs);
const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed
if (stats_out) std::fclose(stats_out);
return (check_failed || !cache_saved) ? 1 : 0;
}