zdxc: --job=<job.json> batch mode

Compile every shader a JSON job file lists in one process, on all cores.
Each job is a dxc command line; shared args come first. Outputs are
byte-identical to separate runs and each job's diagnostics print together
in job order. 1481 corpus shaders: 0.064 s, against 1.09 s for one zdxc
per shader on 10 cores and 1.68 s for dxc.

Also: an unreadable input exits 1 as in dxc (was 5), and stdout/stderr
write in streaming mode so `2>> log` appends instead of overwriting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peter Li 2026-11-01 09:46:47 -08:00
parent c51e594db8
commit 44b8e0bd26
7 changed files with 324 additions and 7 deletions

View File

@ -83,6 +83,11 @@ pub fn build(b: *std.Build) void {
spirv_checks.setCwd(b.path("."));
spirv_checks.has_side_effects = true;
oracle_step.dependOn(&spirv_checks.step);
const job_checks = b.addSystemCommand(&.{ "sh", "test/job/check.sh" });
job_checks.addArtifactArg(exe);
job_checks.setCwd(b.path("."));
job_checks.has_side_effects = true;
oracle_step.dependOn(&job_checks.step);
const oracle_parse_step = b.step("oracle-parse", "Parse every dxc-valid corpus file with zdxc");
const oracle_parse = b.addSystemCommand(&.{ "sh", "test/oracle/parse.sh" });

64
docs/batch.md Normal file
View File

@ -0,0 +1,64 @@
# Batch mode: `--job=<job.json>`
`zdxc --job=build/shaders.json` compiles every shader a job file lists in
one process, on all cores. Starting a process costs more than compiling most
shaders (about 2 ms against a few hundred microseconds), so a build with many
shaders is much faster this way than with one compiler run per shader.
On the 1,481 corpus shaders zdxc compiles (10-core M-series Mac, release
build):
| How | Wall time |
| ------------------------------------------- | --------: |
| `zdxc --job`, all cores | 0.064 s |
| `zdxc --job`, `"threads": 1` | 0.24 s |
| one `zdxc` per shader, 10 in parallel | 1.09 s |
| one `dxc` per shader, 10 in parallel | 1.68 s |
## The job file
```json
{
"threads": 8,
"args": ["-HV", "2021", "-I", "shaders/include"],
"jobs": [
{ "args": ["-T", "cs_6_0", "shaders/blur.hlsl", "-Fo", "out/blur.dxo"] },
{ "args": ["-T", "ps_6_0", "-E", "PS", "shaders/mesh.hlsl", "-Fo", "out/mesh_ps.dxo"] },
{ "args": ["-T", "vs_6_0", "-E", "VS", "-spirv", "shaders/mesh.hlsl", "-Fo", "out/mesh_vs.spv"] }
]
}
```
- `jobs` (required): each job's `args` is a dxc command line without the
program name — any option zdxc accepts on its own command line.
- `args` (optional): options shared by every job.
- `threads` (optional): how many shaders compile at once. Defaults to the
number of CPUs.
A job's full command line is the file's `args`, then any options given next
to `--job` on the real command line, then the job's own `args`. So
`zdxc --job=shaders.json -O3 -Qstrip_debug` adds `-O3 -Qstrip_debug` to every
job, and a job can override a shared option where a later option wins on the
command line. Unknown fields are errors, reported with their line and column.
Paths in the file are relative to the current directory, as on the command
line, not to the job file. `--job` cannot appear inside a job file.
## Output and exit code
Every job writes its own `-Fo` / `-Fh` / ... outputs. What a job prints —
diagnostics, and text output such as `-P` without a file — comes out
exactly as one zdxc run of that command line would print it, kept together
and in job order, whatever order the jobs finish in. The outputs are
byte-identical to separate runs (`test/job/check.sh` checks this).
When jobs fail, the other jobs still run, and a last line says how many
failed:
```
zdxc: 2 of 112 jobs failed
```
The exit code is 0 when every job succeeds; otherwise 1 if any job failed
on its command line or on I/O (a missing input, an unwritable output), else
5 (compile errors) — the codes one zdxc run uses.

156
src/job.zig Normal file
View File

@ -0,0 +1,156 @@
//! `--job=<job.json>`: compile every shader a job file lists in one
//! process, on several threads. Starting a process costs more than
//! compiling most shaders, so a build with many shaders is much faster
//! this way than with one zdxc run per shader.
//!
//! The job file:
//!
//! {
//! "threads": 8,
//! "args": ["-HV", "2021"],
//! "jobs": [
//! { "args": ["-T", "cs_6_0", "a.hlsl", "-Fo", "a.dxo"] },
//! { "args": ["-T", "ps_6_0", "-E", "PS", "b.hlsl", "-Fo", "b.dxo"] }
//! ]
//! }
//!
//! Each job is a dxc command line. The top-level `args`, then any other
//! options given next to `--job`, come before every job's own. `threads`
//! defaults to the number of CPUs. Paths are relative to the current
//! directory, as on the command line. Each job's output and diagnostics
//! are printed in job order; the exit code is 0 when every job succeeds,
//! else 1 if any job failed on its command line or I/O, else 5.
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
/// Compiles one job: `args` is a full command line (argv[0] first). It
/// writes to `stdout` / `stderr` and returns the exit code.
pub const CompileFn = *const fn (io: Io, arena: Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8;
const JobFile = struct {
threads: ?u32 = null,
args: []const []const u8 = &.{},
jobs: []const struct { args: []const []const u8 },
};
/// The index of `--job=<file>` in `argv`, if any.
pub fn find(argv: []const [:0]const u8) ?usize {
for (argv[1..], 1..) |a, i| if (std.mem.startsWith(u8, a, "--job=")) return i;
return null;
}
/// Runs the job file `argv[at]` names; the other arguments apply to every
/// job. Returns the process exit code.
pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, compile: CompileFn, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
const path = argv[at]["--job=".len..];
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 30)) catch |e| {
try stderr.print("zdxc: error: cannot read job file '{s}': {s}\n", .{ path, @errorName(e) });
return 1;
};
var scanner = std.json.Scanner.initCompleteInput(arena, text);
var diag: std.json.Diagnostics = .{};
scanner.enableDiagnostics(&diag);
const file = std.json.parseFromTokenSourceLeaky(JobFile, arena, &scanner, .{}) catch |e| {
try stderr.print("zdxc: error: {s}:{d}:{d}: invalid job file: {s}\n", .{ path, diag.getLine(), diag.getColumn(), @errorName(e) });
return 1;
};
// argv[0], the file's common args, the command line's, then the job's.
var common: std.ArrayList([:0]const u8) = .empty;
try common.append(arena, argv[0]);
for (file.args) |a| try common.append(arena, try arena.dupeSentinel(u8, a, 0));
for (argv[1..], 1..) |a, i| if (i != at) try common.append(arena, a);
const jobs = try arena.alloc([]const [:0]const u8, file.jobs.len);
for (jobs, file.jobs) |*j, fj| {
const full = try arena.alloc([:0]const u8, common.items.len + fj.args.len);
@memcpy(full[0..common.items.len], common.items);
for (full[common.items.len..], fj.args) |*d, a| d.* = try arena.dupeSentinel(u8, a, 0);
j.* = full;
}
var b: Batch = .{ .io = io, .jobs = jobs, .results = try arena.alloc(Result, jobs.len), .compile = compile, .stdout = stdout, .stderr = stderr };
@memset(b.results, .{});
const cpus: u32 = @intCast(std.Thread.getCpuCount() catch 1);
const nthreads = @max(1, @min(file.threads orelse cpus, jobs.len));
// The calling thread is one of the workers.
const threads = try arena.alloc(std.Thread, nthreads - 1);
var spawned: usize = 0;
for (threads) |*t| {
t.* = std.Thread.spawn(.{}, Batch.work, .{&b}) catch break;
spawned += 1;
}
b.work();
for (threads[0..spawned]) |t| t.join();
var failed: usize = 0;
var code: u8 = 0;
for (b.results) |r| if (r.code != 0) {
failed += 1;
if (code != 1) code = r.code;
};
if (failed > 0) try stderr.print("zdxc: {d} of {d} jobs failed\n", .{ failed, jobs.len });
return code;
}
const Result = struct {
done: bool = false,
code: u8 = 0,
out: []u8 = &.{},
err: []u8 = &.{},
};
const Batch = struct {
io: Io,
jobs: []const []const [:0]const u8,
results: []Result,
compile: CompileFn,
stdout: *Io.Writer,
stderr: *Io.Writer,
next: std.atomic.Value(usize) = .init(0),
/// Guards `results` and the writers; jobs are printed in order.
mutex: Io.Mutex = .init,
printed: usize = 0,
fn work(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
while (true) {
const i = b.next.fetchAdd(1, .monotonic);
if (i >= b.jobs.len) return;
_ = arena.reset(.retain_capacity);
const a = arena.allocator();
var out: Io.Writer.Allocating = .init(a);
var err: Io.Writer.Allocating = .init(a);
const code = b.compile(b.io, a, b.jobs[i], &out.writer, &err.writer);
// The arena is reused for the next job: keep the output.
b.finish(i, .{
.done = true,
.code = code,
.out = gpa.dupe(u8, out.written()) catch &.{},
.err = gpa.dupe(u8, err.written()) catch &.{},
});
}
}
/// Records job `i` and prints every finished job not yet printed, in
/// order.
fn finish(b: *Batch, i: usize, r: Result) void {
b.mutex.lockUncancelable(b.io);
defer b.mutex.unlock(b.io);
b.results[i] = r;
while (b.printed < b.results.len and b.results[b.printed].done) : (b.printed += 1) {
const p = &b.results[b.printed];
b.stdout.writeAll(p.out) catch {};
b.stderr.writeAll(p.err) catch {};
std.heap.smp_allocator.free(p.out);
std.heap.smp_allocator.free(p.err);
p.out = &.{};
p.err = &.{};
}
b.stdout.flush() catch {};
b.stderr.flush() catch {};
}
};

View File

@ -6,6 +6,7 @@ const container = zdxc.dxil.container;
const front = zdxc.front;
const options = zdxc.options;
const job = @import("job.zig");
const Options = struct {
profile: ?[]const u8 = null,
@ -45,6 +46,8 @@ const Options = struct {
opt_level: enum { od, o0, o1, o2, o3 } = .o3,
/// Accepted options with no effect yet, reported once each.
ignored: std.ArrayList([]const u8) = .empty,
/// `--job=<file>` (handled before run; here only inside a job file).
job: ?[]const u8 = null,
};
const Cli = struct {
@ -62,15 +65,22 @@ pub fn main(init: std.process.Init) !u8 {
const arena = init.arena.allocator();
const io = init.io;
var stderr_buf: [1024]u8 = undefined;
var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buf);
// Streaming, not positional: `2>> log` must append.
var stderr_writer: Io.File.Writer = .initStreaming(.stderr(), io, &stderr_buf);
var stdout_buf: [4096]u8 = undefined;
var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buf);
var stdout_writer: Io.File.Writer = .initStreaming(.stdout(), io, &stdout_buf);
const cli: Cli = .{ .io = io, .stderr = &stderr_writer.interface };
defer stderr_writer.interface.flush() catch {};
const args = try init.minimal.args.toSlice(arena);
if (job.find(args)) |at| {
const code = try job.run(io, arena, args, at, compileJob, &stdout_writer.interface, &stderr_writer.interface);
try stdout_writer.interface.flush();
return code;
}
// Exit codes follow dxc: 1 for command-line and I/O errors, 5 when the
// compilation reports errors.
run(cli, arena, try init.minimal.args.toSlice(arena), &stdout_writer.interface) catch |err| switch (err) {
run(cli, arena, args, &stdout_writer.interface) catch |err| switch (err) {
error.Fatal => return 1,
error.CompileFailed => return 5,
else => return err,
@ -79,6 +89,20 @@ pub fn main(init: std.process.Init) !u8 {
return 0;
}
/// One job of a `--job` file: `run`, with its exit code.
fn compileJob(io: Io, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
const cli: Cli = .{ .io = io, .stderr = stderr };
run(cli, arena, args, stdout) catch |err| switch (err) {
error.Fatal => return 1,
error.CompileFailed => return 5,
else => {
stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {};
return 1;
},
};
return 0;
}
/// Parse a dxc-style command line. Returns null when the command is
/// complete (`-help`, `--version`).
fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer) !?Options {
@ -105,6 +129,7 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
},
.zdxc_sema => opts.sema = true,
.zdxc_ir => opts.dump_ir = true,
.job => opts.job = a.value(),
.fcolor_diagnostics => opts.color = true,
.fno_color_diagnostics => opts.color = false,
},
@ -244,6 +269,7 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *Io.Writer) !void {
const opts = try parseArgs(cli, arena, args, stdout) orelse return;
if (opts.job != null) return cli.fail("--job cannot be used inside a job file", .{});
if (opts.check_hash) {
const path = opts.input orelse return cli.fail("no input file", .{});
@ -313,7 +339,8 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
});
var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
if (try pp.enterMainFile(input)) {
const opened = try pp.enterMainFile(input);
if (opened) {
if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
} else {
@ -364,6 +391,8 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
const color = opts.color orelse (Io.File.stderr().supportsAnsiEscapeCodes(cli.io) catch false);
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = color });
try cli.stderr.flush();
// An unreadable input is an I/O error, as in dxc.
if (!opened) return error.Fatal;
if (diags.hasErrors()) return error.CompileFailed;
if (opts.preprocess) {
if (opts.pp_output) |path| {

View File

@ -29,11 +29,12 @@ pub const Extra = enum {
zdxc_ast,
zdxc_sema,
zdxc_ir,
job,
fcolor_diagnostics,
fno_color_diagnostics,
};
const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const u8 }{
const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const u8, kind: Kind = .flag, meta: []const u8 = "" }{
.{ .id = .zdxc_empty, .spelling = "zdxc-empty", .help = "Emit an empty shader for -T instead of compiling the input (development)" },
.{ .id = .zdxc_check_hash, .spelling = "zdxc-check-hash", .help = "Verify the container hash of the input (development)" },
.{ .id = .zdxc_lex, .spelling = "zdxc-lex", .help = "Print the input's tokens, one per line (development)" },
@ -41,6 +42,7 @@ const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const
.{ .id = .zdxc_ast, .spelling = "zdxc-ast", .help = "Preprocess, parse and dump the syntax tree (development)" },
.{ .id = .zdxc_sema, .spelling = "zdxc-sema", .help = "Run the front end through semantic analysis only (development)" },
.{ .id = .zdxc_ir, .spelling = "zdxc-ir", .help = "Print the lowered IR instead of compiling (development)" },
.{ .id = .job, .spelling = "-job=", .kind = .joined, .meta = "<job.json>", .help = "Compile every shader a JSON job file lists, in one process, on all cores (see docs/batch.md)" },
.{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" },
.{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" },
};
@ -133,7 +135,7 @@ fn parseOne(arena: Allocator, argv: []const []const u8, index: *usize, failure:
}
for (extra_options) |o| {
if (prefixFits(str, "-", o.spelling) and n < cands.len) {
cands[n] = .{ .which = .{ .extra = o.id }, .kind = .flag, .count = 0, .prefix_len = 1, .spelling_len = o.spelling.len };
cands[n] = .{ .which = .{ .extra = o.id }, .kind = o.kind, .count = 0, .prefix_len = 1, .spelling_len = o.spelling.len };
n += 1;
}
}
@ -287,7 +289,7 @@ pub fn printHelp(w: *std.Io.Writer, show_hidden: bool) !void {
}
}
try w.writeAll("\nzdxc options:\n");
for (extra_options) |o| try printOption(w, o.spelling, .flag, "", o.help, false);
for (extra_options) |o| try printOption(w, o.spelling, o.kind, o.meta, o.help, false);
}
fn printOption(w: *std.Io.Writer, spelling: []const u8, kind: Kind, meta: []const u8, help: []const u8, ignored: bool) !void {

59
test/job/check.sh Normal file
View File

@ -0,0 +1,59 @@
#!/bin/sh
# --job=<job.json> checks: a job file listing the DXIL and SPIR-V check
# tests (plus two jobs that fail) must give byte-identical outputs and the
# same diagnostics, in job order, as one zdxc run per job, with the exit
# code of the failures (1 if any failed on its command line, else 5).
#
# Usage: test/job/check.sh <path-to-zdxc>
set -u
ZDXC=$1
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
mkdir "$TMP/job" "$TMP/one"
n=0
# The job file and, one per line, the same command lines for separate runs;
# @ stands for the output directory.
{
printf '{ "args": ["-no-warnings"], "jobs": [\n'
for f in test/dxil/*.hlsl test/spirv/*.hlsl; do
profile=$(sed -n 's|^// PROFILE: *||p' "$f")
flags=$(sed -n 's|^// FLAGS: *||p' "$f")
case "$f" in test/spirv/*)
env=$(sed -n 's|^// ENV: *||p' "$f")
flags="$flags -spirv -fspv-target-env=${env:-vulkan1.0}" ;;
esac
args=""
for a in -T "$profile" $flags "$f" -Fo "@/$n.out"; do args="$args\"$a\", "; done
printf ' { "args": [%s] },\n' "${args%, }"
n=$((n + 1))
done
# A compile error (5) and a missing input (1).
printf ' { "args": ["-T", "cs_6_0", "test/job/error.hlsl", "-Fo", "@/err.out"] },\n'
printf ' { "args": ["-T", "cs_6_0", "test/job/missing.hlsl", "-Fo", "@/missing.out"] }\n'
printf '] }\n'
} > "$TMP/job.in"
sed "s|@|$TMP/job|g" "$TMP/job.in" > "$TMP/job.json"
# Each job's args back to a command line.
sed -n 's|^ { "args": \[\(.*\)\] },*$|\1|p' "$TMP/job.in" | sed 's|", "| |g; s|"||g' > "$TMP/lines"
n=$(($(wc -l < "$TMP/lines") - 2))
"$ZDXC" --job="$TMP/job.json" > "$TMP/job.stdout" 2> "$TMP/job.stderr"
code=$?
: > "$TMP/one.stderr"
while read -r line; do
# shellcheck disable=SC2086
"$ZDXC" -no-warnings $(printf '%s' "$line" | sed "s|@|$TMP/one|g") 2>> "$TMP/one.stderr" > /dev/null
done < "$TMP/lines"
fail=0
for f in "$TMP"/one/*; do
cmp -s "$f" "$TMP/job/$(basename "$f")" || { echo "FAIL: $(basename "$f") differs from a run of its own"; fail=1; }
done
[ "$(ls "$TMP/one" | wc -l)" -eq "$(ls "$TMP/job" | wc -l)" ] || { echo "FAIL: different sets of outputs"; fail=1; }
grep -v 'jobs failed$' "$TMP/job.stderr" | sed "s|$TMP/job|@|g" > "$TMP/a"
sed "s|$TMP/one|@|g" "$TMP/one.stderr" > "$TMP/b"
cmp -s "$TMP/a" "$TMP/b" || { echo "FAIL: diagnostics differ or are out of order"; diff "$TMP/a" "$TMP/b" | head; fail=1; }
grep -q '^zdxc: 2 of [0-9]* jobs failed$' "$TMP/job.stderr" || { echo "FAIL: no failure summary"; fail=1; }
[ "$code" -eq 1 ] || { echo "FAIL: exit code $code, expected 1"; fail=1; }
echo "job checks: $n compiled + 2 failing jobs, $([ $fail = 0 ] && echo passed || echo FAILED)"
[ $fail = 0 ]

2
test/job/error.hlsl Normal file
View File

@ -0,0 +1,2 @@
// A compile error, for test/job/check.sh.
[numthreads(1, 1, 1)] void main() { undeclared = 1; }