stats: time and allocations per compilation stage

A caller that wants them points stats.current at a Stats for the thread;
zones in compile (options, preprocess, parse, sema, lower, ir_opt, DXIL,
SPIR-V) and in DXIL emission (lowering, finish, promote, sccp, unroll,
bitcode, container) add their time and the caller's allocation counts,
and counters record DXIL instructions lowered and kept. Without a Stats a
zone costs one thread-local load.
This commit is contained in:
peterino2 2026-11-03 01:03:23 -08:00
parent 72f1760844
commit e6a089eb34
7 changed files with 139 additions and 0 deletions

View File

@ -11,6 +11,7 @@ const container = zdxc.dxil.container;
const front = zdxc.front; const front = zdxc.front;
const options = zdxc.options; const options = zdxc.options;
const FileSystem = front.source.FileSystem; const FileSystem = front.source.FileSystem;
const stats = zdxc.stats;
pub const Request = struct { pub const Request = struct {
/// dxc command-line options, without the program name: "-T", "ps_6_0", /// dxc command-line options, without the program name: "-T", "ps_6_0",
@ -371,7 +372,9 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op
} }
fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
const za = stats.begin(.args);
const opts = try parseArgs(ctx, arena, ctx.req.args) orelse return; const opts = try parseArgs(ctx, arena, ctx.req.args) orelse return;
za.end();
ctx.result.object_name = opts.output; ctx.result.object_name = opts.output;
ctx.result.root_signature_name = opts.rootsig_output; ctx.result.root_signature_name = opts.rootsig_output;
ctx.result.preprocessed_name = opts.pp_output; ctx.result.preprocessed_name = opts.pp_output;
@ -445,13 +448,18 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
}); });
var out: Io.Writer.Allocating = .init(arena); var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null; var module: ?zdxc.ir.ir.Module = null;
const zp = stats.begin(.preprocess);
const opened = try pp.enterMainFile(input); const opened = try pp.enterMainFile(input);
if (opened) { if (opened) {
if (opts.preprocess) { if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer); try front.pp_print.print(&pp, &out.writer);
zp.end();
} else { } else {
var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp); var parser = try front.parser.Parser.fromPreprocessor(arena, &diags, &pp);
zp.end();
const zparse = stats.begin(.parse);
const tu = try parser.parseTranslationUnit(); const tu = try parser.parseTranslationUnit();
zparse.end();
if (opts.dump_ast) try front.ast_dump.dumpUnit(ctx.stdout, tu); if (opts.dump_ast) try front.ast_dump.dumpUnit(ctx.stdout, tu);
if (!opts.parse) { if (!opts.parse) {
const is_lib = if (profile) |p| p.kind == .library else true; const is_lib = if (profile) |p| p.kind == .library else true;
@ -467,8 +475,10 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
}); });
// About one resolution per expression: reserve rather // About one resolution per expression: reserve rather
// than grow, which leaves every old buffer in the arena. // than grow, which leaves every old buffer in the arena.
const zs = stats.begin(.sema);
try sema.resolutions.ensureTotalCapacity(arena, parser.toks.len); try sema.resolutions.ensureTotalCapacity(arena, parser.toks.len);
try sema.checkUnit(tu); try sema.checkUnit(tu);
zs.end();
if (!opts.sema and !diags.hasErrors() and profile != null) { if (!opts.sema and !diags.hasErrors() and profile != null) {
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) { const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {
.vertex => .vertex, .vertex => .vertex,
@ -481,10 +491,12 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
.amplification => .amplification, .amplification => .amplification,
else => .library, else => .library,
}; };
const zl = stats.begin(.lower);
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) { module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {
error.Unsupported => null, error.Unsupported => null,
else => |x| return x, else => |x| return x,
}; };
zl.end();
if (module) |*mm| { if (module) |*mm| {
mm.native_16bit = opts.enable_16bit; mm.native_16bit = opts.enable_16bit;
mm.row_major = opts.row_major; mm.row_major = opts.row_major;
@ -510,7 +522,11 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
if (opts.parse or opts.sema) return; if (opts.parse or opts.sema) return;
if (profile == null) return ctx.fail("missing -T <profile>", .{}); if (profile == null) return ctx.fail("missing -T <profile>", .{});
if (module) |*m| { if (module) |*m| {
const zo = stats.begin(.ir_opt);
try zdxc.ir.opt.run(arena, m); try zdxc.ir.opt.run(arena, m);
zo.end();
const zv = stats.begin(.spirv);
defer if (opts.spirv) zv.end();
if (opts.spirv) { if (opts.spirv) {
zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => { error.Unsupported => {
@ -546,6 +562,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) { if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed; m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
}; };
const zd = stats.begin(.dxil);
const dxil_out = zdxc.dxil.emit.emitWithReflection(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) { const dxil_out = zdxc.dxil.emit.emitWithReflection(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) {
error.Unsupported => { error.Unsupported => {
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
@ -553,6 +570,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
}, },
else => |x| return x, else => |x| return x,
}; };
zd.end();
try ctx.needOutput(opts); try ctx.needOutput(opts);
ctx.result.object = dxil_out.object; ctx.result.object = dxil_out.object;
ctx.result.reflection = dxil_out.reflection; ctx.result.reflection = dxil_out.reflection;

View File

@ -25,6 +25,7 @@ const reflect = @import("reflect.zig");
const rootsig = @import("rootsig.zig"); const rootsig = @import("rootsig.zig");
const promote = @import("promote.zig"); const promote = @import("promote.zig");
const unroll = @import("unroll.zig"); const unroll = @import("unroll.zig");
const stats = @import("../stats.zig");
const sccp = @import("sccp.zig"); const sccp = @import("sccp.zig");
const opt = @import("../ir/opt.zig"); const opt = @import("../ir/opt.zig");
@ -511,8 +512,10 @@ const Emitter = struct {
try e.buildSignatures(entry); try e.buildSignatures(entry);
if (entry.stage == .amplification) e.findDispatchPayload(); if (entry.stage == .amplification) e.findDispatchPayload();
e.cur = try e.newBlock(); e.cur = try e.newBlock();
const zl = stats.begin(.dxil_lower);
try e.createHandles(); try e.createHandles();
_ = try e.inlineCall(entry.wrapper, &.{}); _ = try e.inlineCall(entry.wrapper, &.{});
zl.end();
try e.finish(e.main_fn); try e.finish(e.main_fn);
if (entry.patch_wrapper) |pw| { if (entry.patch_wrapper) |pw| {
// The patch constant function is a function of its own. // The patch constant function is a function of its own.
@ -536,6 +539,7 @@ const Emitter = struct {
if (e.optimize) e.inputUsage(); if (e.optimize) e.inputUsage();
if (e.optimize and e.profile.minor >= 6) try e.dropDeadResources(); if (e.optimize and e.profile.minor >= 6) try e.dropDeadResources();
for (e.dm.functions.items) |f| stats.add(.dxil_final, f.insts.items.len);
const bitcode = try e.writeModule(entry); const bitcode = try e.writeModule(entry);
defer gpa.free(bitcode); defer gpa.free(bitcode);
return e.assemble(gpa, entry, bitcode); return e.assemble(gpa, entry, bitcode);
@ -1352,6 +1356,7 @@ const Emitter = struct {
/// Assigns final instruction indices: prologue first, then blocks in /// Assigns final instruction indices: prologue first, then blocks in
/// creation order. /// creation order.
fn finish(e: *Emitter, func: u32) Error!void { fn finish(e: *Emitter, func: u32) Error!void {
const zf = stats.begin(.dxil_finish);
if (e.lib_removable.count() > 0) try e.pruneProlog(); if (e.lib_removable.count() > 0) try e.pruneProlog();
const map = try e.arena.alloc(u32, e.next_id); const map = try e.arena.alloc(u32, e.next_id);
var n: u32 = 0; var n: u32 = 0;
@ -1375,6 +1380,7 @@ const Emitter = struct {
return out; return out;
} }
}; };
stats.add(.dxil_lowered, n);
try f.insts.ensureUnusedCapacity(e.dm.allocator(), n); try f.insts.ensureUnusedCapacity(e.dm.allocator(), n);
const all = [_][]const PInst{e.prologue.items}; const all = [_][]const PInst{e.prologue.items};
for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap)); for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
@ -1384,6 +1390,7 @@ const Emitter = struct {
while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*); while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*);
e.dyn_ranges.clearRetainingCapacity(); e.dyn_ranges.clearRetainingCapacity();
e.array_pool.clearRetainingCapacity(); e.array_pool.clearRetainingCapacity();
zf.end();
if (e.optimize) { if (e.optimize) {
try promote.run(e.arena, &e.dm, func, &ranges); try promote.run(e.arena, &e.dm, func, &ranges);
// Values only ever one constant (through loops too), and the // Values only ever one constant (through loops too), and the
@ -6578,6 +6585,8 @@ const Emitter = struct {
} }
fn writeModule(e: *Emitter, entry: ir.Entry) Error![]u8 { fn writeModule(e: *Emitter, entry: ir.Entry) Error![]u8 {
const zone = stats.begin(.bitcode);
defer zone.end();
const dm = &e.dm; const dm = &e.dm;
const mdI32 = struct { const mdI32 = struct {
fn f(m: *module.Module, v: i64) !module.MdId { fn f(m: *module.Module, v: i64) !module.MdId {
@ -6648,6 +6657,8 @@ const Emitter = struct {
} }
fn assemble(e: *Emitter, gpa: Allocator, entry: ir.Entry, bitcode: []const u8) Error![]u8 { fn assemble(e: *Emitter, gpa: Allocator, entry: ir.Entry, bitcode: []const u8) Error![]u8 {
const zone = stats.begin(.container);
defer zone.end();
const dxil_part = try shader.programPart(gpa, e.profile, bitcode); const dxil_part = try shader.programPart(gpa, e.profile, bitcode);
defer gpa.free(dxil_part); defer gpa.free(dxil_part);
var binds: std.ArrayList(shader.ResourceBind) = .empty; var binds: std.ArrayList(shader.ResourceBind) = .empty;

View File

@ -15,6 +15,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const module = @import("module.zig"); const module = @import("module.zig");
const stats = @import("../stats.zig");
const Value = module.Value; const Value = module.Value;
const Inst = module.Inst; const Inst = module.Inst;
@ -123,6 +124,9 @@ fn isScalar(m: *const module.Module, ty: TypeId) bool {
/// `dyn` maps the dynamically indexed getelementptrs into locals to the /// `dyn` maps the dynamically indexed getelementptrs into locals to the
/// components [lo, hi) they can reach; one missing from it can reach all. /// components [lo, hi) they can reach; one missing from it can reach all.
pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashMapUnmanaged(u32, [2]u32)) Allocator.Error!void { pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashMapUnmanaged(u32, [2]u32)) Allocator.Error!void {
const zone = stats.begin(.promote);
stats.add(.promote_runs, 1);
defer zone.end();
const f = &m.functions.items[func]; const f = &m.functions.items[func];
const insts = f.insts.items; const insts = f.insts.items;
const n: u32 = @intCast(insts.len); const n: u32 = @intCast(insts.len);

View File

@ -12,6 +12,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const module = @import("module.zig"); const module = @import("module.zig");
const stats = @import("../stats.zig");
const unroll = @import("unroll.zig"); const unroll = @import("unroll.zig");
const Value = module.Value; const Value = module.Value;
@ -101,6 +102,8 @@ fn successors(term: Inst) Succs {
/// Runs the propagation on `func`; true if it changed anything. /// Runs the propagation on `func`; true if it changed anything.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.sccp);
defer zone.end();
const f = &m.functions.items[func]; const f = &m.functions.items[func];
const insts = f.insts.items; const insts = f.insts.items;
const n: u32 = @intCast(insts.len); const n: u32 = @intCast(insts.len);

View File

@ -15,6 +15,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const module = @import("module.zig"); const module = @import("module.zig");
const stats = @import("../stats.zig");
const promote = @import("promote.zig"); const promote = @import("promote.zig");
const Value = module.Value; const Value = module.Value;
@ -33,6 +34,8 @@ const max_growth = 65536;
/// Unrolls the qualifying loops of `func`, innermost first; true if any. /// Unrolls the qualifying loops of `func`, innermost first; true if any.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool { pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const zone = stats.begin(.unroll);
defer zone.end();
var budget: usize = max_growth; var budget: usize = max_growth;
var tried: std.AutoHashMapUnmanaged(u32, void) = .empty; var tried: std.AutoHashMapUnmanaged(u32, void) = .empty;
var any = false; var any = false;

View File

@ -3,6 +3,7 @@
pub const diag = @import("diag.zig"); pub const diag = @import("diag.zig");
pub const options = @import("options.zig"); pub const options = @import("options.zig");
pub const compile = @import("compile.zig"); pub const compile = @import("compile.zig");
pub const stats = @import("stats.zig");
pub const Diagnostics = diag.Diagnostics; pub const Diagnostics = diag.Diagnostics;
pub const front = struct { pub const front = struct {

99
src/stats.zig Normal file
View File

@ -0,0 +1,99 @@
//! Time and allocations per compilation stage, for benchmarks. A caller
//! that wants them points `current` at a `Stats` for the thread's
//! compilation; zones anywhere in the compiler then add to it. With no
//! `Stats` (the default) a zone costs one thread-local load.
const std = @import("std");
pub const Stage = enum {
/// Command-line options and setup.
args,
/// Preprocessing and lexing, up to a token array.
preprocess,
parse,
sema,
lower,
ir_opt,
/// DXIL emission, in all (the zones below are inside it).
dxil,
/// Lowering the entry's IR to DXIL instructions (inlining every call).
dxil_lower,
/// Renumbering a function's instructions into its body.
dxil_finish,
promote,
sccp,
unroll,
bitcode,
container,
spirv,
/// Diagnostics rendering and the rest of `compile`.
other,
};
pub const count = @typeInfo(Stage).@"enum".field_names.len;
/// Sizes of the work, to explain the times.
pub const Counter = enum {
/// DXIL instructions lowering produced (before any optimization).
dxil_lowered,
/// DXIL instructions left in the emitted functions.
dxil_final,
/// Times promotion ran.
promote_runs,
};
pub const counter_count = @typeInfo(Counter).@"enum".field_names.len;
/// What the caller's allocator counters read at a point (the caller's
/// `sample` fills it in).
pub const Sample = struct { calls: u64 = 0, bytes: u64 = 0 };
pub const Stats = struct {
io: std.Io,
ns: [count]u64 = @splat(0),
/// Allocation calls and bytes requested in each stage.
calls: [count]u64 = @splat(0),
bytes: [count]u64 = @splat(0),
/// Times each zone was entered.
entries: [count]u32 = @splat(0),
counters: [counter_count]u64 = @splat(0),
sample: ?*const fn (ctx: ?*anyopaque) Sample = null,
sample_ctx: ?*anyopaque = null,
fn read(s: *const Stats) Sample {
return if (s.sample) |f| f(s.sample_ctx) else .{};
}
};
pub threadlocal var current: ?*Stats = null;
pub const Zone = struct {
stage: Stage,
t0: i96 = 0,
s0: Sample = .{},
on: bool = false,
/// Ends the zone, adding its time and allocations to its stage
/// (inclusive of zones nested in it).
pub fn end(z: Zone) void {
if (!z.on) return;
const s = current orelse return;
const t1 = std.Io.Clock.awake.now(s.io).toNanoseconds();
const s1 = s.read();
const k = @backingInt(z.stage);
s.ns[k] += @intCast(t1 - z.t0);
s.calls[k] += s1.calls - z.s0.calls;
s.bytes[k] += s1.bytes - z.s0.bytes;
s.entries[k] += 1;
}
};
/// Adds `n` to a counter.
pub fn add(c: Counter, n: u64) void {
if (current) |s| s.counters[@backingInt(c)] += n;
}
pub fn begin(stage: Stage) Zone {
const s = current orelse return .{ .stage = stage };
return .{ .stage = stage, .t0 = std.Io.Clock.awake.now(s.io).toNanoseconds(), .s0 = s.read(), .on = true };
}