Files
mandy/runtime/test/vk_pipeline_check.cpp
DadaCap 4295601b81 Merge pull request #2088 from c0pperlane/vk-pipeline-large-admission
vk_pipeline_check: a large module that must wait frees its worker (VK-PIPELINE-CHECK-LARGE-ADMISSION)
2026-11-28 09:06:04 +01:00

2051 lines
108 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) and checks module and pipeline creation for compatible
// entries 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 and 26..28; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants
// sized from push_constant_bytes, default 144 or 128 with pc_tail):
// - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for
// descriptor-free shaders with the standard push-constant range
// - 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)
// VK_EXT_mesh_shader (with meshShaderQueries), VK_KHR_maintenance8 and VK_EXT_transform_feedback are always enabled
// when supported so the saved pipeline cache matches the runtime's device key; other optional device extensions are
// enabled only when needed by the selected shaders. 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 up to N worker threads (default: half the hardware threads)
// --large-module-bytes N modules larger than N bytes are "large" (default: 4194304; 0 disables the gate)
// --large-parallel N how many large modules may be in the driver at once: 0 (default) = as many as fit 3/4 of
// the memory available at start, at large_module_gate.h's estimate per module, up to --jobs, with the
// small ones compiling alongside; 1 = each large module alone, the other threads waiting (the
// behaviour before; also what 0 falls back to when the available memory can't be read)
// --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.
// --nv-diagnostics create the device with VK_NV_device_diagnostics_config and the flags the runtime's
// LEONIDA_DEVICE_FAULT=1 / LEONIDA_AFTERMATH=1 use (shader debug info, resource tracking, automatic
// checkpoints), to measure what that does to compile times and to cache hits
// --isolate check in child processes, --isolate-batch modules at a time (default 256), so a module
// that kills the driver 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 (with --large-parallel 1 it is alone then, so F
// names exactly it; otherwise F names every module in flight and make_game.py retries each alone)
// and by the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage
// reads it. With --isolate, the active child writes the snapshot.
// --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] simulates a process crash
// 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 "../src/pipeline_cache_file.h"
#include "pipeline_cache_snapshot.h"
#include "large_module_gate.h"
#include "pipeline_summary.h"
#include "../src/spirv_words.h"
#include "../src/subgroup_size.h"
#include "../src/vulkan_bindless.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <charconv>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cerrno>
#include <csignal>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <shared_mutex>
#include <string>
#include <type_traits>
#include <string_view>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
#ifndef _WIN32
#include <sys/wait.h>
#include <unistd.h>
#include <cerrno>
#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;
uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144)
uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0
bool no_set0_bindings = false;
bool wave64 = false;
std::array<uint32_t, 3> local_size{1, 1, 1};
std::string wave64_exchange;
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;
}
void parse_local_size(std::array<uint32_t, 3>& out) {
if (!consume('[')) { skip_value(); return; }
for (size_t dim = 0; !error && i < s.size(); ++dim) {
if (consume(']')) return;
const char* start = s.data() + i;
skip_value();
if (dim < out.size()) {
char* end = nullptr;
const double size = std::strtod(start, &end);
out[dim] = end == s.data() + i && size >= 0 && size <= UINT32_MAX ? uint32_t(size) : 0;
}
if (consume(']')) return;
if (!consume(',')) { fail("expected ',' or ']' in local size"); return; }
}
if (!error) fail("unterminated local size");
}
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;
}
uint32_t parse_strict_u32(const char* what) {
ws();
uint32_t v = 0;
const auto [end, ec] = std::from_chars(s.data() + i, s.data() + s.size(), v);
if (ec != std::errc{}) { fail(what); return 0u; }
i = static_cast<size_t>(end - s.data());
if (i < s.size() && (s[i] == '.' || s[i] == 'e' || s[i] == 'E')) { fail(what); return 0u; }
return v;
}
uint32_t parse_pc_tail_bytes() {
ws();
if (s.compare(i, 4, "null") == 0) { i += 4; return 0u; }
if (!consume('{')) { fail("expected object for pc_tail"); return 0u; }
uint32_t bytes = 0;
while (!error && i < s.size()) {
if (consume('}')) return bytes;
const size_t before = i;
std::string k = parse_string();
if (error) return bytes;
if (!consume(':')) { fail("expected ':' in pc_tail"); return bytes; }
if (k == "bytes") bytes = parse_strict_u32("expected unsigned 32-bit pc_tail.bytes");
else skip_value();
if (error) return bytes;
if (consume('}')) return bytes;
if (!consume(',') || i == before) { fail("expected ',' or '}' in pc_tail"); return bytes; }
}
if (!error) fail("unterminated pc_tail object");
return bytes;
}
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") m.lds_bytes = parse_strict_u32("expected unsigned 32-bit lds_bytes");
else if (k == "push_constant_bytes")
m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes");
else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes();
else if (k == "bindings") {
const size_t start = i;
m.no_set0_bindings = consume('[') && consume(']');
if (!m.no_set0_bindings) {
i = start;
skip_value();
}
}
else if (k == "wave64") {
ws();
if (s.compare(i, 4, "true") == 0 || s.compare(i, 5, "false") == 0) m.wave64 = parse_bool();
else skip_value();
}
else if (k == "wave64_exchange") {
ws();
if (i < s.size() && s[i] == '"') m.wave64_exchange = parse_string();
else skip_value();
}
else if (k == "local_size") parse_local_size(m.local_size);
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; }
constexpr std::string_view utf8_bom = "\xef\xbb\xbf";
JsonParser p{s, s.starts_with(utf8_bom) ? utf8_bom.size() : 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});
// Push-constant range size a shader needs: its index push_constant_bytes when recorded (128 with --pc-tail-ubo,
// 144 by default, 152 with --mesh-compute), or 128 when pc_tail is present, else 144. Rounded up to 4 bytes
// (Vulkan requires VkPushConstantRange::size to be a positive multiple of 4).
constexpr uint32_t required_push_bytes(uint32_t push_constant_bytes, uint32_t pc_tail_bytes) {
const uint32_t raw = push_constant_bytes ? push_constant_bytes : (pc_tail_bytes ? 128u : 144u);
return raw > (std::numeric_limits<uint32_t>::max() - 3u) ? raw : ((raw + 3u) & ~3u);
}
constexpr uint32_t runtime_compute_push_bytes = 144; // sizeof(leonida::ShaderUserData)
bool uses_runtime_compute_layout(const ShaderMeta& meta) {
return meta.stage == "cs" && meta.no_set0_bindings && !meta.pc_tail_bytes &&
required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes) == runtime_compute_push_bytes;
}
static_assert(required_push_bytes(0, 0) == 144);
static_assert(required_push_bytes(0, 16) == 128);
static_assert(required_push_bytes(128, 0) == 128);
static_assert(required_push_bytes(128, 16) == 128);
static_assert(required_push_bytes(144, 0) == 144);
static_assert(required_push_bytes(152, 0) == 152);
// --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);
}
}
#endif
// --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
uint32_t status = 0; // exit status when it exited (a full DWORD on Windows)
std::string runner_error;
std::string out; // its stdout
};
std::string child_exit_status(uint32_t status) {
#ifdef _WIN32
if (status >= 0x80000000u) {
char hex[11];
std::snprintf(hex, sizeof hex, "0x%08x", static_cast<unsigned>(status));
return hex;
}
#endif
return std::to_string(status);
}
std::filesystem::path self_executable(const char* argv0) {
#ifdef _WIN32
(void)argv0;
std::wstring path(32768, L'\0');
const DWORD len = GetModuleFileNameW(nullptr, path.data(), static_cast<DWORD>(path.size()));
if (!len || len == path.size()) return {};
path.resize(len);
return path;
#else
std::error_code ec;
auto self = std::filesystem::read_symlink("/proc/self/exe", ec);
return ec ? std::filesystem::path(argv0) : self;
#endif
}
#ifdef _WIN32
// Quote one argument for the Windows CRT, including backslashes before quotes and at the end.
std::wstring quote_child_arg(std::wstring_view arg) {
std::wstring quoted = L"\"";
size_t slashes = 0;
for (wchar_t c : arg) {
if (c == L'\\') {
++slashes;
} else {
if (c == L'\"') quoted.append(slashes + 1, L'\\');
slashes = 0;
}
quoted += c;
}
return quoted.append(slashes, L'\\') + L"\"";
}
void collect_child(const std::filesystem::path& exe, std::vector<std::string>& args, ChildRun& r) {
const auto failed = [&](const char* api) {
const DWORD error = GetLastError();
r.runner_error = std::string(api) + " failed (Win32 error " + std::to_string(error) + ")";
};
std::wstring command = quote_child_arg(exe.native());
for (const auto& arg : args) {
// The checker uses narrow CRT argv. Round-trip the arguments through its active ANSI code page.
const int len = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, arg.c_str(), -1, nullptr, 0);
if (!len) return failed("MultiByteToWideChar");
std::wstring wide(len, L'\0');
if (!MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, arg.c_str(), -1, wide.data(), len))
return failed("MultiByteToWideChar");
wide.pop_back();
command += L' ';
command += quote_child_arg(wide);
}
using Handle = std::unique_ptr<void, decltype(&CloseHandle)>;
SECURITY_ATTRIBUTES inherited{sizeof(inherited), nullptr, TRUE};
HANDLE read_handle = nullptr, write_handle = nullptr;
if (!CreatePipe(&read_handle, &write_handle, &inherited, 0)) return failed("CreatePipe");
Handle read_end(read_handle, CloseHandle), write_end(write_handle, CloseHandle);
if (!SetHandleInformation(read_end.get(), HANDLE_FLAG_INHERIT, 0)) return failed("SetHandleInformation");
// Only stdout is captured. Keep stderr live for driver diagnostics and give the child no interactive input.
const HANDLE nul_handle = CreateFileW(L"NUL", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
&inherited, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (nul_handle == INVALID_HANDLE_VALUE) return failed("CreateFileW(NUL)");
Handle nul(nul_handle, CloseHandle), stderr_copy(nullptr, CloseHandle);
const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
if (stderr_handle && stderr_handle != INVALID_HANDLE_VALUE) {
HANDLE duplicate = nullptr;
const HANDLE current = GetCurrentProcess();
if (!DuplicateHandle(current, stderr_handle, current, &duplicate, 0, TRUE, DUPLICATE_SAME_ACCESS))
return failed("DuplicateHandle(stderr)");
stderr_copy.reset(duplicate);
}
STARTUPINFOEXW startup{};
startup.StartupInfo.cb = sizeof(startup);
startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput = nul.get();
startup.StartupInfo.hStdOutput = write_end.get();
startup.StartupInfo.hStdError = stderr_copy ? stderr_copy.get() : nul.get();
// Inherit only the standard handles, even when the caller gave the parent other inheritable handles.
HANDLE child_handles[] = {nul.get(), write_end.get(), stderr_copy.get()};
SIZE_T attr_bytes = 0;
InitializeProcThreadAttributeList(nullptr, 1, 0, &attr_bytes);
if (!attr_bytes) return failed("InitializeProcThreadAttributeList");
std::vector<unsigned char> attrs(attr_bytes);
startup.lpAttributeList = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(attrs.data());
if (!InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0, &attr_bytes))
return failed("InitializeProcThreadAttributeList");
std::fflush(nullptr);
const bool configured = UpdateProcThreadAttribute(startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
child_handles, (stderr_copy ? 3 : 2) * sizeof(HANDLE),
nullptr, nullptr);
PROCESS_INFORMATION process{};
const bool started = configured && CreateProcessW(exe.c_str(), command.data(), nullptr, nullptr, TRUE,
EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr,
&startup.StartupInfo, &process);
const DWORD start_error = started ? 0 : GetLastError();
DeleteProcThreadAttributeList(startup.lpAttributeList);
if (!started) {
SetLastError(start_error);
return failed(configured ? "CreateProcessW" : "UpdateProcThreadAttribute");
}
CloseHandle(process.hThread);
Handle child(process.hProcess, CloseHandle);
write_end.reset(); // EOF must depend on the child closing its write handle.
char buffer[4096];
DWORD bytes = 0;
while (ReadFile(read_end.get(), buffer, sizeof buffer, &bytes, nullptr)) {
if (bytes) r.out.append(buffer, bytes);
}
if (GetLastError() != ERROR_BROKEN_PIPE) failed("ReadFile(child stdout)");
read_end.reset();
if (WaitForSingleObject(child.get(), INFINITE) != WAIT_OBJECT_0) return failed("WaitForSingleObject");
DWORD status = 0;
if (!GetExitCodeProcess(child.get(), &status)) return failed("GetExitCodeProcess");
r.status = status;
}
#else
void collect_child(const std::filesystem::path& exe, std::vector<std::string>& args, ChildRun& r) {
args.insert(args.begin(), exe.native());
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; }
std::fflush(nullptr);
const pid_t pid = fork();
if (pid < 0) { close(fds[0]); close(fds[1]); r.status = 127; return; }
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;
}
#endif
std::string_view next_child_line(std::string_view& output) {
const size_t end = output.find('\n');
auto line = output.substr(0, end);
output.remove_prefix(end == std::string_view::npos ? output.size() : end + 1);
if (line.ends_with('\r')) line.remove_suffix(1);
return line;
}
ChildRun run_child(const std::filesystem::path& 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 = {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)});
collect_child(exe, args, r);
std::string_view output = r.out;
while (!output.empty()) {
const auto line = next_child_line(output);
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; }
}
return r;
}
} // 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] [--large-parallel 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;
bool cache_given = false; // an empty cache_path alone can't tell "not given" from an empty argument
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;
unsigned large_parallel = 0; // 0 = by the memory budget
double slow = 30.0;
std::string stage_filter = "all";
bool cache_feedback = false, isolate = false, iso_child = false, nv_diagnostics = 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;
if constexpr (std::is_floating_point_v<std::decay_t<decltype(dest)>>) {
// Apple's libc++ has no floating-point from_chars overload. Parse the whole token with strtod,
// as shader_library.h does for JSON numbers; --slow also checks isfinite and >= 0 below.
const std::string token(text);
char* end = nullptr;
errno = 0;
const double parsed = std::strtod(token.c_str(), &end);
if (errno == ERANGE || end != token.c_str() + token.size()) return false;
dest = static_cast<std::decay_t<decltype(dest)>>(parsed);
return true;
} else {
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 == "--large-parallel") valid = number(large_parallel);
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 == "--nv-diagnostics") nv_diagnostics = 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_given) {
cache_path = a;
cache_given = true;
} else {
std::fprintf(stderr, "unexpected argument '%s' (a cache path was already given: '%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 (iso_child) SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#endif
const std::string index_path = dir + "/index.json";
const auto same_file = [](const std::string& a, const std::string& b) {
std::error_code error;
return std::filesystem::equivalent(a, b, error);
};
// These inputs already exist on a valid invocation. Compare file identity so aliases are also protected.
for (const auto& [option, output] : {std::pair{"cache path", &cache_path},
std::pair{"--stats", &stats_path},
std::pair{"--inflight-file", &inflight_path}}) {
if (output->empty()) continue;
const char* input = nullptr;
if (same_file(*output, index_path)) input = "index.json";
else if (!skip_path.empty() && same_file(*output, skip_path)) input = "--skip-file";
if (input) {
std::fprintf(stderr, "error: %s must not overwrite %s\n", option, input);
return 2;
}
}
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(index_path, 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);
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.
const auto exe = self_executable(argv[0]);
if (exe.empty()) {
std::fprintf(stderr, "error: could not find the executable for --isolate\n");
return 1;
}
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),
"--large-parallel", std::to_string(large_parallel)};
if (cache_feedback) pass.push_back("--cache-feedback");
if (!inflight_path.empty()) pass.insert(pass.end(), {"--inflight-file", inflight_path});
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) {
std::string_view output = r.out;
while (!output.empty()) {
const std::string line(next_child_line(output));
// 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.runner_error.empty()) {
std::fprintf(stderr, "error: could not run an isolation child: %s\n", r.runner_error.c_str());
setup_failed = true;
return 0;
}
if (r.done) { commit(r); return 0; }
const std::string status = child_exit_status(r.status);
#ifndef _WIN32
const std::string signal = r.sig ? signal_label(r.sig) : "";
#else
const std::string signal;
#endif
if (!r.ready) { // died or exited before the work loop: not a module's fault
std::fputs(r.out.c_str(), stdout);
if (!signal.empty()) std::fprintf(stderr, "error: a child process died during setup (%s)\n", signal.c_str());
else std::fprintf(stderr, "error: a child process failed during setup (exit status %s)\n", status.c_str());
setup_failed = true;
return 0;
}
const std::string why = signal.empty() ? "driver exited with status " + status : "driver crashed: " + signal;
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;) {
const size_t batch = std::min(isolate_batch, hi - s);
bisect(bisect, s, batch);
s += batch;
}
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()) {
std::error_code ec;
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;
}
// Scan selected shaders to request the optional shader extensions they use. VK_EXT_mesh_shader and
// VK_KHR_maintenance8 are always enabled when supported (even for compute-only runs), because
// create_vulkan_device_standalone enables both unconditionally and NVIDIA includes them in its cache key.
bool want_bary = false, want_lock = false, want_fma = false, want_clock = false;
for (auto& [_, meta] : work) {
for (const auto& feat : meta->features) {
if (feat == "fragmentShaderBarycentric") want_bary = true;
else if (feat == "fragmentShaderPixelInterlock") want_lock = true;
else if (feat == "shaderFmaFloat32" || feat == "shaderFmaFloat64") want_fma = true; // OpFmaKHR (--fma khr)
else if (feat == "shaderSubgroupClock" || feat == "shaderDeviceClock") want_clock = true;
}
}
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};
VkPhysicalDeviceVulkan11Properties indexing_limits{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES};
// Vulkan12Properties already includes the float controls (do not chain both promoted structs).
VkPhysicalDeviceVulkan12Properties indexed{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES};
VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
indexing_limits.pNext = &indexed;
sgProps.pNext = &indexing_limits;
props2.pNext = &sgProps;
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 the core and optional device features used by the checker.
VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
VkPhysicalDeviceTransformFeedbackFeaturesEXT tf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_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};
VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
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(&f11, reinterpret_cast<VkBaseOutStructure*>(&f11), nullptr, true); // shaderDrawParameters (VS v0/v3)
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, true);
// The runtime's device enables VK_EXT_transform_feedback (transformFeedback, and geometryStreams when the device
// offers it) whenever the extension is present (D3D-302), and a driver makes it part of a pipeline's cache key, so
// the checker enables it too (docs/pipeline_check.md, "The cache and the runtime's device").
link(&tf, reinterpret_cast<VkBaseOutStructure*>(&tf), VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME, true);
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, true);
#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
VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR};
const bool ext_clock = link(&clock, reinterpret_cast<VkBaseOutStructure*>(&clock), VK_KHR_SHADER_CLOCK_EXTENSION_NAME, want_clock);
VkPhysicalDeviceDiagnosticsConfigFeaturesNV diag_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV};
const bool ext_diag = link(&diag_features, reinterpret_cast<VkBaseOutStructure*>(&diag_features),
VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME, nv_diagnostics);
if (nv_diagnostics && !ext_diag) {
std::fprintf(stderr, "--nv-diagnostics: the device has no %s\n", VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME);
return 1;
}
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
// The runtime's device (create_vulkan_device_standalone) never enables the first two, and a driver makes them part
// of a pipeline's cache key: with either of them on here, the cache this tool saves does not hit in gta6rt
// (pipeline_cache_seed_test; docs/pipeline_check.md, "The cache and the runtime's device"). The runtime enables
// robustImageAccess where supported (for 1D and 3D storage views), so its queried value is kept.
f2.features.robustBufferAccess = VK_FALSE;
f12.scalarBlockLayout = VK_FALSE;
VkPhysicalDeviceMeshShaderPropertiesEXT mesh_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT};
if (ext_mesh && mesh.meshShader) {
VkPhysicalDeviceProperties2 mesh_device_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
mesh_device_props.pNext = &mesh_props;
vkGetPhysicalDeviceProperties2(pd, &mesh_device_props);
}
if (ext_mesh) {
// Keep meshShaderQueries as supported: create_vulkan_device_standalone enables it when present (#577),
// and NVIDIA hashes it into the pipeline cache key even for compute pipelines.
if (!f2.features.pipelineStatisticsQuery) mesh.meshShaderQueries = VK_FALSE;
mesh.multiviewMeshShader = mesh.primitiveFragmentShadingRateMeshShader = 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();
VkDeviceDiagnosticsConfigCreateInfoNV diag_config{VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV};
if (ext_diag) {
diag_config.flags = VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV |
VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV |
VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV;
diag_config.pNext = dci.pNext;
dci.pNext = &diag_config;
std::printf("device: VK_NV_device_diagnostics_config on (shader debug info, resource tracking, checkpoints)\n");
}
VkDevice dev;
if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; }
leonida::SubgroupSizeCaps runtime_subgroups;
leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, pd, f13.subgroupSizeControl,
f13.computeFullSubgroups, runtime_subgroups);
auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool {
return f13.subgroupSizeControl &&
sg >= sgProps.minSubgroupSize &&
sg <= sgProps.maxSubgroupSize &&
(sgProps.requiredSubgroupSizeStages & bit);
};
auto runtime_compute_subgroup = [&](const ShaderMeta& meta) {
leonida::ShaderEntry entry;
entry.stage = meta.stage;
entry.subgroup_size = meta.subgroup_size;
entry.wave64 = meta.wave64;
entry.wave64_exchange = meta.wave64_exchange;
entry.local_size = meta.local_size;
return leonida::decide_subgroup_size(entry, runtime_subgroups);
};
{
std::map<uint32_t, std::set<std::string>> unforced_by_sg;
for (const auto& [_, meta] : work) {
if (uses_runtime_compute_layout(*meta)) {
const auto request = runtime_compute_subgroup(*meta);
if (request.outcome == leonida::SubgroupOutcome::unavailable)
unforced_by_sg[request.wanted].insert(meta->stage);
continue;
}
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(vkGetDescriptorSetLayoutSupport);
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;
// These capability requirements apply as soon as the module is passed to Vulkan.
auto check_missing_module_feature = [&](const ShaderMeta& meta) -> std::string {
for (const auto& feat : meta.features) {
if (feat == "shaderSampledImageArrayDynamicIndexing" && !f2.features.shaderSampledImageArrayDynamicIndexing)
return "no " + feat;
if (feat == "shaderStorageImageArrayDynamicIndexing" && !f2.features.shaderStorageImageArrayDynamicIndexing)
return "no " + feat;
// A device without the OpFmaKHR width can reject the module itself, so skip before vkCreateShaderModule.
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 == "shaderFmaFloat64") {
#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME
if (!(ext_fma && fma.shaderFmaFloat64)) return "no VK_KHR_shader_fma (shaderFmaFloat64)";
#else
return "no VK_KHR_shader_fma (shaderFmaFloat64)";
#endif
}
}
return {};
};
// Keep the remaining pipeline compatibility checks after module creation.
auto check_missing_feature = [&](const ShaderMeta& meta) -> std::string {
const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes);
if (need_pc > props.limits.maxPushConstantsSize) {
return "needs " + std::to_string(need_pc) + " push-constant bytes, device has " +
std::to_string(props.limits.maxPushConstantsSize) +
(need_pc > 128 ? " (translate with --pc-tail-ubo)" : "");
}
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, and 64 with Float64;
// DenormPreserve 16) need a device property, not a feature.
for (const auto& fc : meta.float_controls) {
if (fc == "shaderSignedZeroInfNanPreserveFloat32") {
if (!indexed.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc;
} else if (fc == "shaderSignedZeroInfNanPreserveFloat64") {
if (!indexed.shaderSignedZeroInfNanPreserveFloat64) return "no " + fc;
} else if (fc == "shaderDenormPreserveFloat16") {
if (!indexed.shaderDenormPreserveFloat16) return "no " + fc;
} else {
return "unknown float control " + fc;
}
}
// Per-format read/write support for formatless storage is checked when the runtime binds the actual view.
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 == "shaderSubgroupClock" && !(ext_clock && clock.shaderSubgroupClock)) return "no shaderSubgroupClock";
if (feat == "shaderDeviceClock" && !(ext_clock && clock.shaderDeviceClock)) return "no shaderDeviceClock";
if (feat == "shaderFloat64" && !f2.features.shaderFloat64) return "no shaderFloat64";
if (feat == "shaderInt64" && !f2.features.shaderInt64) return "no shaderInt64";
if (feat == "shaderDrawParameters" && !f11.shaderDrawParameters) return "no shaderDrawParameters";
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 (props.apiVersion < VK_API_VERSION_1_3) {
if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat)
return "no shaderStorageImageWriteWithoutFormat";
if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat)
return "no shaderStorageImageReadWithoutFormat";
}
}
return {};
};
// Use the runtime's set-0 layout and sizing rules. The translator does not declare the runtime-only MS SRVs.
leonida::BindlessFeatures bindless{};
std::function<bool(const leonida::BindlessFeatures&)> layout_supported;
if (vkGetDescriptorSetLayoutSupport)
layout_supported = [&](const leonida::BindlessFeatures& candidate) {
const leonida::bindless::SetLayout layout(candidate);
VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT};
vkGetDescriptorSetLayoutSupport(dev, &layout.info, &support);
return support.supported == VK_TRUE;
};
if (!leonida::bindless::size_bindings(bindless, props2.properties.limits, indexing_limits, indexed, layout_supported) &&
f12.descriptorBindingSampledImageUpdateAfterBind && f12.descriptorBindingStorageImageUpdateAfterBind &&
f12.descriptorBindingStorageBufferUpdateAfterBind) {
bindless.update_after_bind = true;
leonida::bindless::size_bindings(bindless, props2.properties.limits, indexing_limits, indexed, layout_supported);
}
const leonida::bindless::SetLayout layout(bindless);
VkDescriptorSetLayout dsl;
if (VkResult r = vkCreateDescriptorSetLayout(dev, &layout.info, nullptr, &dsl)) {
std::fprintf(stderr, "layout %d\n", r);
return 1;
}
// Set 1 of --pc-tail-ubo shaders (docs/design.md): dynamic uniform block at binding 0 holding heap/code base.
const VkDescriptorSetLayoutBinding tail_binding{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1,
VK_SHADER_STAGE_ALL, nullptr};
VkDescriptorSetLayoutCreateInfo tail_dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
tail_dli.bindingCount = 1; tail_dli.pBindings = &tail_binding;
VkDescriptorSetLayout dsl_tail = VK_NULL_HANDLE;
if (VkResult r = vkCreateDescriptorSetLayout(dev, &tail_dli, nullptr, &dsl_tail)) {
std::fprintf(stderr, "tail layout %d\n", r); return 1;
}
// One VkPipelineLayout per (push_constant_bytes, has_pc_tail) needed by the selected shaders that fits
// maxPushConstantsSize; never declares a range above the device limit (VUID-VkPushConstantRange-size-00298).
std::map<std::pair<uint32_t, bool>, VkPipelineLayout> layouts;
for (const auto& [_, meta] : work) {
const uint32_t need_pc = required_push_bytes(meta->push_constant_bytes, meta->pc_tail_bytes);
if (need_pc > props.limits.maxPushConstantsSize) continue;
const std::pair<uint32_t, bool> key{need_pc, meta->pc_tail_bytes != 0};
if (layouts.count(key)) continue;
VkPushConstantRange pcr{VK_SHADER_STAGE_ALL, 0, need_pc};
VkDescriptorSetLayout sets[2] = {dsl, dsl_tail};
VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
pli.setLayoutCount = key.second ? 2u : 1u;
pli.pSetLayouts = sets;
pli.pushConstantRangeCount = 1;
pli.pPushConstantRanges = &pcr;
VkPipelineLayout pl = VK_NULL_HANDLE;
if (VkResult r = vkCreatePipelineLayout(dev, &pli, nullptr, &pl)) {
std::fprintf(stderr, "pipeline layout (%u bytes%s) %d\n", need_pc, key.second ? ", set 1" : "", r);
return 1;
}
layouts.emplace(key, pl);
}
auto layout_for = [&](const ShaderMeta& meta) -> VkPipelineLayout {
const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes);
return layouts.at({need_pc, meta.pc_tail_bytes != 0});
};
VkPipelineLayout runtime_compute_layout = VK_NULL_HANDLE;
if (runtime_compute_push_bytes <= props.limits.maxPushConstantsSize &&
std::any_of(work.begin(), work.end(), [](const Item& item) {
return uses_runtime_compute_layout(*item.second);
})) {
const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, runtime_compute_push_bytes};
VkPipelineLayoutCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
info.pushConstantRangeCount = 1;
info.pPushConstantRanges = &push;
if (VkResult r = vkCreatePipelineLayout(dev, &info, nullptr, &runtime_compute_layout)) {
std::fprintf(stderr, "runtime compute pipeline layout %d\n", r);
return 1;
}
}
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;
}
};
const auto worker_count = static_cast<unsigned>(std::min<size_t>(jobs, work.size()));
std::fprintf(stderr, "checking %zu shaders [%zu, %zu) (stage=%s) on %u threads\n",
work.size(), lo, hi, stage_filter.c_str(), worker_count);
std::mutex mu; // guards counters, stdout, stub cache and in-flight table
std::shared_mutex compile_gate; // --large-parallel 1: large modules exclude other shader and pipeline work
size_t isolated_modules = 0;
// Otherwise large modules share a memory budget and the small ones are never held back (large_module_gate.h).
const uint64_t available_memory = leonida::available_memory_bytes();
const bool large_exclusive = large_parallel == 1 || (large_parallel == 0 && available_memory == 0);
leonida::LargeModuleGate large_gate(
large_parallel == 0 ? available_memory / 4 * 3 : UINT64_MAX,
large_parallel == 0 ? jobs : std::min<unsigned>(large_parallel, jobs));
leonida::LargeModuleQueue work_queue(large_gate, work.size()); // a large module that must wait frees its thread
if (large_module_bytes) {
if (large_exclusive)
std::fprintf(stderr, "large modules (over %zu bytes): one at a time, the other threads waiting\n",
large_module_bytes);
else if (large_parallel == 0)
std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once within %.1f GB "
"(3/4 of the %.1f GB available)\n", large_module_bytes, large_gate.max_inflight(),
large_gate.budget() / 1e9, available_memory / 1e9);
else
std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once\n", large_module_bytes,
large_gate.max_inflight());
}
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> 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;
// Publish a complete snapshot at the moments named in the header. This keeps the last full report if the
// process dies while staging the next one. Called with mu held.
auto write_inflight = [&] {
if (inflight_path.empty()) return;
std::string snapshot;
for (const auto& [tid, job] : inflight) {
snapshot += job.name;
snapshot += '\t';
snapshot += job.phase;
snapshot += '\n';
}
if (const auto error = write_pipeline_cache_file(inflight_path, snapshot.data(), snapshot.size()))
std::fprintf(stderr, "in-flight snapshot save to %s failed: %s\n",
inflight_path.c_str(), error.message().c_str());
};
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::ios::ate);
const auto code = leonida::read_spirv_words(f, f.tellg());
VkShaderModule mod = VK_NULL_HANDLE;
if (!code.empty()) {
VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
smi.codeSize = code.size() * sizeof(code.front());
smi.pCode = 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 (alone with --large-parallel 1)
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);
#ifdef _WIN32
if (sim_crash.sig == SIGFPE) TerminateProcess(GetCurrentProcess(), EXCEPTION_FLT_DIVIDE_BY_ZERO);
if (sim_crash.sig == SIGSEGV) TerminateProcess(GetCurrentProcess(), EXCEPTION_ACCESS_VIOLATION);
#endif
std::raise(sim_crash.sig);
}
};
auto worker = [&] {
while (auto claim = work_queue.take()) { // its ticket is left after the module and its pipeline are gone
const size_t k = claim->index;
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;
}
uint32_t shared_memory_limit = 0;
if (stage == "cs") shared_memory_limit = props.limits.maxComputeSharedMemorySize;
else if (stage == "ms") shared_memory_limit = mesh_props.maxMeshSharedMemorySize;
if (shared_memory_limit && meta.lds_bytes > shared_memory_limit) {
const char* limit_name = stage == "cs" ? "maxComputeSharedMemorySize" : "maxMeshSharedMemorySize";
std::lock_guard<std::mutex> g(mu);
modules_bad[stage]++;
std::printf("MODULE FAIL %s (workgroup memory %u bytes exceeds %s %u)\n",
name.c_str(), meta.lds_bytes, limit_name, shared_memory_limit);
++done;
continue;
}
if (const std::string miss = check_missing_module_feature(meta); !miss.empty()) {
// No module was attempted, so only the pipeline skip is counted.
record_skip(name, stage, miss);
++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 (large_exclusive) {
if (isolated) exclusive.lock();
else if (large_module_bytes) parallel.lock();
} else if (isolated && !work_queue.admit(*claim, leonida::large_module_estimate(file_size))) {
continue; // not within the budget yet: put back, and this thread takes the next module
}
{ // 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(); // a large module: name it now (alone with --large-parallel 1)
}
const auto code = leonida::read_spirv_words(f, file_size);
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() * sizeof(code.front());
smi.pCode = 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{};
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";
bool sg_forced = false;
if (uses_runtime_compute_layout(meta)) {
const auto request = runtime_compute_subgroup(meta);
leonida::apply_subgroup_request(request, reqSg, cpi.stage);
sg_forced = request.size != 0;
cpi.layout = runtime_compute_layout;
} else {
reqSg.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO;
reqSg.requiredSubgroupSize = meta.subgroup_size;
sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT);
if (sg_forced) cpi.stage.pNext = &reqSg;
cpi.layout = layout_for(meta);
}
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(); // a large module: name it now (alone with --large-parallel 1)
}
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 = layout_for(meta);
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(); // a large module: name it now (alone with --large-parallel 1)
}
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 (unsigned t = 0; t < worker_count; 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);
const std::set<std::string> all_stages =
leonida::summary_stages(modules_ok, modules_bad, stats, big_skipped);
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 %s: %zu (over %zu bytes)\n",
large_exclusive ? "exclusively" : "within the memory budget", isolated_modules,
large_module_bytes);
std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count);
const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed
if (stats_out) {
const bool write_failed = std::ferror(stats_out) != 0;
const bool close_failed = std::fclose(stats_out) != 0;
if (write_failed || close_failed) {
std::fprintf(stderr, "cannot write pipeline statistics to %s\n", stats_path.c_str());
check_failed = true;
}
}
return (check_failed || !cache_saved) ? 1 : 0;
}