From 2526fa65f74014738a5922173667781742f8f350 Mon Sep 17 00:00:00 2001 From: peterino2 Date: Mon, 2 Nov 2026 07:28:12 -0800 Subject: [PATCH] --job: keep file I/O off the compile threads Windows (here, with Defender's on-access scanning) serializes opening files: creating the corpus's 8,772 outputs takes about 1.8 s whatever the thread count. The compile threads blocked on it, so --job barely gained past 8 threads. - A reading thread reads each job's input ahead of the compiles (at most 256 jobs ahead), and a writing thread writes the outputs, in job order, after them. An output that cannot be written is reported after every job's output and fails its job. - Files the jobs read through the compiler (headers) are cached for the whole run, with misses remembered, so each is opened once instead of once per job and include directory searched. On the Glide corpus: compiles only, 13.6 -> 12.1 s on 1 thread and 2.75 -> 2.6 s on 24; preprocess and compile, 36.2 -> 17.1 s on 1 thread and 7.3 -> 5.9 s on 24, which is about the time it takes to create its 17,544 output files. Outputs and diagnostics are identical to 0622292 on all 17,544 calls. --- src/job.zig | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++- src/main.zig | 35 +++++--- 2 files changed, 244 insertions(+), 15 deletions(-) diff --git a/src/job.zig b/src/job.zig index 91c9723..dc2bf4e 100644 --- a/src/job.zig +++ b/src/job.zig @@ -20,14 +20,44 @@ //! 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. +//! +//! Two more threads read the jobs' input files ahead of the compiles and +//! write their outputs after them, so the compile threads do not wait on +//! opening files (which Windows, with its on-access scanner, serializes). +//! An output that cannot be written is reported after every job's output, +//! and fails its job. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; +const FileSystem = @import("zdxc").front.source.FileSystem; /// 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; +pub const CompileFn = *const fn (io: Io, arena: Allocator, args: []const [:0]const u8, ctx: Context, stdout: *Io.Writer, stderr: *Io.Writer) u8; + +/// What a run gives a compile besides its command line. +pub const Context = struct { + /// The input file's text, already read. + source: ?[]const u8 = null, + /// Reads the other files (null: from disk). + fs: ?FileSystem = null, + /// Where to add the files to write (allocated in the compile's arena), + /// instead of writing them. + outputs: ?*Outputs = null, +}; + +/// A file a job writes. +pub const Output = struct { path: []const u8, bytes: []const u8 }; +pub const Outputs = std.ArrayList(Output); + +/// The input file a job's command line names, if any. +pub const InputFn = *const fn (arena: Allocator, args: []const [:0]const u8) ?[]const u8; + +/// How many jobs the reading thread may get ahead of the compiles. +const read_ahead = 256; +/// The compiles wake the reading thread every this many jobs. +const wake_every = 32; const JobFile = struct { threads: ?u32 = null, @@ -43,7 +73,7 @@ pub fn find(argv: []const [:0]const u8) ?usize { /// 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 { +pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, compile: CompileFn, input: InputFn, 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) }); @@ -70,8 +100,23 @@ pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, comp j.* = full; } - var b: Batch = .{ .io = io, .jobs = jobs, .results = try arena.alloc(Result, jobs.len), .compile = compile, .stdout = stdout, .stderr = stderr }; + var b: Batch = .{ + .io = io, + .jobs = jobs, + .results = try arena.alloc(Result, jobs.len), + .sources = try arena.alloc(Source, jobs.len), + .files = .{ .io = io }, + .compile = compile, + .input = input, + .stdout = stdout, + .stderr = stderr, + }; @memset(b.results, .{}); + @memset(b.sources, .{}); + const reader: ?std.Thread = std.Thread.spawn(.{}, Batch.read, .{&b}) catch null; + b.reading = reader != null; + const writer: ?std.Thread = std.Thread.spawn(.{}, Batch.write, .{&b}) catch null; + b.writing = writer != null; 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. @@ -83,6 +128,9 @@ pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, comp } b.work(); for (threads[0..spawned]) |t| t.join(); + if (reader) |t| t.join(); + if (writer) |t| t.join(); + try stderr.writeAll(b.write_errors.items); var failed: usize = 0; var code: u8 = 0; @@ -99,20 +147,160 @@ const Result = struct { code: u8 = 0, out: []u8 = &.{}, err: []u8 = &.{}, + /// Files for the writing thread; owned by smp_allocator. + writes: []Output = &.{}, +}; + +/// Files the jobs read (headers, mostly), shared by the whole run: each is +/// opened once, rather than once per job and include directory searched. +/// Files that do not exist are remembered too. The text lives until the +/// process exits. +const FileCache = struct { + io: Io, + mutex: Io.Mutex = .init, + files: std.StringHashMapUnmanaged(?[]const u8) = .empty, + + fn fileSystem(c: *FileCache) FileSystem { + return .{ .ctx = c, .readFn = read }; + } + + fn read(ctx: *anyopaque, _: Allocator, path: []const u8) ?[]const u8 { + const c: *FileCache = @ptrCast(@alignCast(ctx)); + const gpa = std.heap.smp_allocator; + { + c.mutex.lockUncancelable(c.io); + defer c.mutex.unlock(c.io); + if (c.files.get(path)) |cached| return cached; + } + // Read outside the lock: other jobs keep using the cache meanwhile. + const text: ?[]const u8 = Io.Dir.cwd().readFileAlloc(c.io, path, gpa, .limited(256 << 20)) catch null; + c.mutex.lockUncancelable(c.io); + defer c.mutex.unlock(c.io); + const key = gpa.dupe(u8, path) catch return text; + const gop = c.files.getOrPut(gpa, key) catch { + gpa.free(key); + return text; + }; + if (gop.found_existing) { + gpa.free(key); + if (text) |t| gpa.free(t); + return gop.value_ptr.*; + } + gop.value_ptr.* = text; + return text; + } +}; + +/// A job's input file, as read by the reading thread. +const Source = struct { + state: std.atomic.Value(State) = .init(.pending), + /// Valid once `state` is `.read`; owned by smp_allocator. + text: []u8 = &.{}, + + const State = enum(u32) { + pending, + read, + /// No input named, or it could not be read: the compile reads (and + /// reports) it itself. + none, + }; }; const Batch = struct { io: Io, jobs: []const []const [:0]const u8, results: []Result, + sources: []Source, + files: FileCache, compile: CompileFn, + input: InputFn, stdout: *Io.Writer, stderr: *Io.Writer, + /// Whether the reading thread is running (else every source is read by + /// its compile). + reading: bool = false, + /// Whether the writing thread is running (else every compile writes its + /// own outputs). + writing: bool = false, + /// Messages for the outputs the writing thread could not write. + write_errors: std.ArrayList(u8) = .empty, + /// `printed`, for the writing thread to wait on: it writes a job's + /// outputs once the job is printed. + printed_count: std.atomic.Value(u32) = .init(0), next: std.atomic.Value(usize) = .init(0), + /// Jobs taken by the compiles, for the reading thread to wait on. + started: std.atomic.Value(u32) = .init(0), /// Guards `results` and the writers; jobs are printed in order. mutex: Io.Mutex = .init, printed: usize = 0, + /// Reads every job's input file in job order, at most `read_ahead` + /// jobs ahead of the compiles. + fn read(b: *Batch) void { + const gpa = std.heap.smp_allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + for (b.jobs, b.sources, 0..) |args, *s, i| { + while (true) { + const started = b.started.load(.acquire); + if (i < @as(usize, started) + read_ahead) break; + b.io.futexWaitUncancelable(u32, &b.started.raw, started); + } + _ = arena.reset(.retain_capacity); + const text: ?[]u8 = if (b.input(arena.allocator(), args)) |path| + Io.Dir.cwd().readFileAlloc(b.io, path, gpa, .limited(256 << 20)) catch null + else + null; + if (text) |t| s.text = t; + s.state.store(if (text != null) .read else .none, .release); + b.io.futexWake(Source.State, &s.state.raw, std.math.maxInt(u32)); + } + } + + /// Writes every job's outputs, in job order, as the jobs are printed. + fn write(b: *Batch) void { + const gpa = std.heap.smp_allocator; + for (b.results, 0..) |*r, i| { + while (true) { + const printed = b.printed_count.load(.acquire); + if (i < printed) break; + b.io.futexWaitUncancelable(u32, &b.printed_count.raw, printed); + } + for (r.writes) |o| { + Io.Dir.cwd().writeFile(b.io, .{ .sub_path = o.path, .data = o.bytes }) catch |e| { + b.write_errors.print(gpa, "zdxc: error: cannot write '{s}': {s}\n", .{ o.path, @errorName(e) }) catch {}; + r.code = 1; + }; + gpa.free(o.path); + gpa.free(o.bytes); + } + gpa.free(r.writes); + r.writes = &.{}; + } + } + + /// The outputs of a job, copied out of its arena (null if out of + /// memory: then the job fails). + fn keep(outputs: []const Output) ?[]Output { + const gpa = std.heap.smp_allocator; + const kept = gpa.alloc(Output, outputs.len) catch return null; + for (kept, outputs, 0..) |*k, o, n| { + const path = gpa.dupe(u8, o.path) catch null; + const bytes = if (path != null) gpa.dupe(u8, o.bytes) catch null else null; + if (bytes == null) { + if (path) |p| gpa.free(p); + for (kept[0..n]) |d| { + gpa.free(d.path); + gpa.free(d.bytes); + } + gpa.free(kept); + return null; + } + k.* = .{ .path = path.?, .bytes = bytes.? }; + } + return kept; + } + fn work(b: *Batch) void { const gpa = std.heap.smp_allocator; var arena: std.heap.ArenaAllocator = .init(gpa); @@ -120,17 +308,43 @@ const Batch = struct { while (true) { const i = b.next.fetchAdd(1, .monotonic); if (i >= b.jobs.len) return; + if (b.started.fetchAdd(1, .release) % wake_every == wake_every - 1) b.io.futexWake(u32, &b.started.raw, 1); _ = 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); + const s = &b.sources[i]; + var source: ?[]const u8 = null; + if (b.reading) { + while (true) switch (s.state.load(.acquire)) { + .pending => b.io.futexWaitUncancelable(Source.State, &s.state.raw, .pending), + .read => { + source = s.text; + break; + }, + .none => break, + }; + } + var outputs: Outputs = .empty; + var code = b.compile(b.io, a, b.jobs[i], .{ + .source = source, + .fs = b.files.fileSystem(), + .outputs = if (b.writing) &outputs else null, + }, &out.writer, &err.writer); + gpa.free(s.text); + s.text = &.{}; // The arena is reused for the next job: keep the output. + const writes: []Output = keep(outputs.items) orelse writes: { + err.writer.writeAll("zdxc: error: OutOfMemory\n") catch {}; + code = 1; + break :writes &.{}; + }; b.finish(i, .{ .done = true, .code = code, .out = gpa.dupe(u8, out.written()) catch &.{}, .err = gpa.dupe(u8, err.written()) catch &.{}, + .writes = writes, }); } } @@ -152,5 +366,7 @@ const Batch = struct { } b.stdout.flush() catch {}; b.stderr.flush() catch {}; + b.printed_count.store(@intCast(b.printed), .release); + b.io.futexWake(u32, &b.printed_count.raw, 1); } }; diff --git a/src/main.zig b/src/main.zig index 6cf52ee..d7b71c8 100644 --- a/src/main.zig +++ b/src/main.zig @@ -18,9 +18,9 @@ pub fn main(init: std.process.Init) !u8 { const args = try init.minimal.args.toSlice(arena); const code = if (job.find(args)) |at| - try job.run(io, arena, args, at, runCommandLine, &stdout_writer.interface, &stderr_writer.interface) + try job.run(io, arena, args, at, runCommandLine, inputFile, &stdout_writer.interface, &stderr_writer.interface) else - runCommandLine(io, arena, args, &stdout_writer.interface, &stderr_writer.interface); + runCommandLine(io, arena, args, .{}, &stdout_writer.interface, &stderr_writer.interface); try stdout_writer.interface.flush(); return code; } @@ -28,19 +28,30 @@ pub fn main(init: std.process.Init) !u8 { /// Runs one command line (argv[0] first) and returns its exit code, which /// follows dxc: 1 for command-line and I/O errors, 5 when the compilation /// reports errors. -fn runCommandLine(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 { - return runOrFail(io, arena, argv, stdout, stderr) catch |err| { +fn runCommandLine(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, ctx: job.Context, stdout: *Io.Writer, stderr: *Io.Writer) u8 { + return runOrFail(io, arena, argv, ctx, stdout, stderr) catch |err| { stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {}; stderr.flush() catch {}; return 1; }; } -fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) !u8 { +/// The input file a command line (argv[0] first) compiles, if it names one. +fn inputFile(arena: std.mem.Allocator, argv: []const [:0]const u8) ?[]const u8 { + const args = arena.alloc([]const u8, argv.len -| 1) catch return null; + for (args, argv[1..]) |*a, v| a.* = v; + var failure: zdxc.options.Failure = .{}; + const parsed = zdxc.options.parse(arena, args, &failure) catch return null; + return if (parsed.inputs.len > 0) parsed.inputs[parsed.inputs.len - 1] else null; +} + +fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, ctx: job.Context, stdout: *Io.Writer, stderr: *Io.Writer) !u8 { const args = try arena.alloc([]const u8, argv.len -| 1); for (args, argv[1..]) |*a, v| a.* = v; const r = try zdxc.compile.compile(arena, .{ .args = args, + .source = ctx.source, + .fs = ctx.fs, .io = io, .color = Io.File.stderr().supportsAnsiEscapeCodes(io) catch false, .require_output = true, @@ -48,17 +59,19 @@ fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdou try stdout.writeAll(r.text); try stderr.writeAll(r.diagnostics); try stderr.flush(); - if (r.status != .ok) return @intFromEnum(r.status); - if (r.object) |bytes| try write(io, stderr, r.object_name.?, bytes) orelse return 1; - if (r.root_signature) |bytes| try write(io, stderr, r.root_signature_name.?, bytes) orelse return 1; + if (r.status != .ok) return @backingInt(r.status); + if (r.object) |bytes| try write(io, arena, ctx.outputs, stderr, r.object_name.?, bytes) orelse return 1; + if (r.root_signature) |bytes| try write(io, arena, ctx.outputs, stderr, r.root_signature_name.?, bytes) orelse return 1; if (r.preprocessed) |text| { - if (r.preprocessed_name) |path| try write(io, stderr, path, text) orelse return 1 else try stdout.writeAll(text); + if (r.preprocessed_name) |path| try write(io, arena, ctx.outputs, stderr, path, text) orelse return 1 else try stdout.writeAll(text); } return 0; } -/// Writes an output file; null (after an error message) if it cannot. -fn write(io: Io, stderr: *Io.Writer, path: []const u8, bytes: []const u8) !?void { +/// Writes an output file (or adds it to `outputs`); null (after an error +/// message) if it cannot. +fn write(io: Io, arena: std.mem.Allocator, outputs: ?*job.Outputs, stderr: *Io.Writer, path: []const u8, bytes: []const u8) !?void { + if (outputs) |o| return try o.append(arena, .{ .path = path, .bytes = bytes }); Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = bytes }) catch |err| { try stderr.print("zdxc: error: cannot write '{s}': {s}\n", .{ path, @errorName(err) }); try stderr.flush();