From 2ed08b08e1e8e32fc9479fddb3b56f5231b1cc60 Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Mon, 2 Nov 2026 06:55:33 +0000 Subject: [PATCH 1/8] SPIR-V: loop controls from [unroll] and [loop] Loops the IR keeps (its unrolling gave up, or [loop] asked it not to) lost their attribute: every OpLoopMerge had loop control None. The driver now gets Unroll for [unroll] and DontUnroll for [loop], as from dxc. On the Hyperion engine's Glide shaders this is what made its half resolution Glimmer irradiance pass about 5% slower than with dxc: an [unroll] loop over a run-time count that RADV unrolls for dxc's output stayed a loop for zdxc's (2381 instructions against dxc's 5765; now 5856). --- src/spirv/emit.zig | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index a695b55..f2829cb 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -2189,7 +2189,14 @@ const Emitter = struct { switch (blk.merge) { .none => {}, .selection => |mb| try e.b.emit(.functions, .selection_merge, &.{ labels[mb.index()], 0 }), - .loop => |l| try e.b.emit(.functions, .loop_merge, &.{ labels[l.merge.index()], labels[l.@"continue".index()], 0 }), + // [unroll] / [loop] the IR could not act on are the + // driver's to honor (LoopControl Unroll / DontUnroll), as + // in dxc. + .loop => |l| try e.b.emit(.functions, .loop_merge, &.{ labels[l.merge.index()], labels[l.@"continue".index()], switch (l.unroll) { + .auto => 0, + .unroll => 1, + .dont => 2, + } }), } switch (blk.term) { .none, .@"unreachable" => try e.b.emit(.functions, .@"unreachable", &.{}), From afc4587596ac61a420d12ffe779639db10da742d Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Mon, 2 Nov 2026 07:09:50 +0000 Subject: [PATCH 2/8] SPIR-V: inline calls in the IR dxc's SPIR-V gets its calls inlined by legalization; zdxc emitted every function and left inlining to the driver, with 10361 calls across the Hyperion engine's Glide shaders. ir/inline.zig now inlines bottom-up before emission: - The calling block is split at the call: it branches to a copy of the callee, and the rest of the block (terminator and merge included) moves to a continuation block. Parameters become the arguments. - A callee with one return outside every construct branches from it to the continuation. Returns inside selections or switches become breaks out of a loop that runs once around the callee, the return value going through a local. - Callees that return from inside a loop, [noinline] ones, ones with RayQuery or by-reference resource parameters, and ones returning a resource from several places stay functions (resource arguments then still get specializations). - Functions nothing reaches any more are marked dead and not emitted. Only modules with vertex, pixel and compute entry points and no rasterizer-ordered views for now (the emitter treats the others' functions specially). -Od and the new -zdxc-no-opt skip it; -zdxc-ir prints the IR after the SPIR-V passes. On Glide: 37 calls left; the SPIR-V grows (517k to 838k instructions, callee bodies copied, one-trip loops) until promotion to SSA values removes the locals; compile time 597 to 765 ms. The driver's own statistics barely move, except one compute shader passing float4[28] arrays by value, whose copies now take more scratch. --- src/compile.zig | 18 ++- src/ir/inline.zig | 382 +++++++++++++++++++++++++++++++++++++++++++++ src/ir/ir.zig | 2 + src/options.zig | 2 + src/root.zig | 1 + src/spirv/emit.zig | 3 +- 6 files changed, 403 insertions(+), 5 deletions(-) create mode 100644 src/ir/inline.zig diff --git a/src/compile.zig b/src/compile.zig index 4ffad96..2298e21 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -187,6 +187,8 @@ const Options = struct { dump_ast: bool = false, sema: bool = false, dump_ir: bool = false, + /// -zdxc-no-opt: no SPIR-V IR optimizations. + no_opt: bool = false, /// -O0..-O3 / -Od (default -O3, as in dxc). opt_level: enum { od, o0, o1, o2, o3 } = .o3, /// Accepted options with no effect yet, reported once each. @@ -219,6 +221,7 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op }, .zdxc_sema => opts.sema = true, .zdxc_ir => opts.dump_ir = true, + .zdxc_no_opt => opts.no_opt = true, .job => opts.job = a.value(), .fcolor_diagnostics => opts.color = true, .fno_color_diagnostics => opts.color = false, @@ -493,10 +496,6 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { if (profile == null) return ctx.fail("missing -T ", .{}); if (module) |*m| { try zdxc.ir.opt.run(arena, m); - if (opts.dump_ir) { - try zdxc.ir.ir.dump(m, ctx.stdout); - return; - } if (opts.spirv) { zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { error.Unsupported => { @@ -505,6 +504,17 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { }, else => |x| return x, }; + // Legalization and cleanup dxc's SPIR-V gets from its + // optimizer (skipped for -Od). + if (!opts.no_opt and opts.opt_level != .od) { + try zdxc.ir.inline_calls.run(m); + } + } + if (opts.dump_ir) { + try zdxc.ir.ir.dump(m, ctx.stdout); + return; + } + if (opts.spirv) { const bytes = zdxc.spirv.emit.emit(arena, m, &diags, zdxc.spirv.emit.TargetEnv.parse(opts.target_env) orelse return ctx.fail("unknown SPIR-V target environment '{s}'", .{opts.target_env})) catch |err| switch (err) { error.Unsupported => { try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); diff --git a/src/ir/inline.zig b/src/ir/inline.zig new file mode 100644 index 0000000..caa14da --- /dev/null +++ b/src/ir/inline.zig @@ -0,0 +1,382 @@ +//! Inlining for SPIR-V: calls are replaced by copies of their callees, as +//! dxc's legalization does, so drivers get one function per entry point +//! (and later passes see across call boundaries). +//! +//! Callees are inlined bottom-up. The calling block is split at the call: +//! it branches to the copy of the callee's entry, and the rest of the block +//! (with its terminator and merge) moves to a continuation block. A callee +//! with one return outside every construct branches from it to the +//! continuation. Returns inside selections first become breaks out of a +//! loop that runs once (the callee wrapped in it), with the return value in +//! a local; the loop's merge block is where the callee returns, once. +//! Returns inside loops would need a break per loop level: those callees +//! stay functions. +//! +//! Functions no root reaches any more are marked dead (and not emitted). + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ir = @import("ir.zig"); +const types = @import("../sema/types.zig"); +const opt = @import("opt.zig"); + +const Ref = ir.Ref; +const BlockId = ir.BlockId; +const TypeTable = types.TypeTable; + +pub const Error = Allocator.Error; + +/// Whether the module is one the pass handles: graphics and compute entry +/// points only (the emitter treats hull, mesh, geometry and ray tracing +/// functions specially), and no rasterizer-ordered views (the pixel +/// shader's call of its entry function is the interlocked region). +fn eligible(m: *const ir.Module) bool { + if (m.entries.items.len == 0) return false; + for (m.entries.items) |e| switch (e.stage) { + .vertex, .pixel, .compute => {}, + else => return false, + }; + for (m.globals.items) |g| { + var t = g.ty; + while (m.types.get(t) == .array) t = m.types.get(t).array.elem; + if (m.types.get(t) == .resource and std.mem.startsWith(u8, m.types.get(t).resource.name, "RasterizerOrdered")) return false; + } + return true; +} + +pub fn run(m: *ir.Module) Error!void { + if (!eligible(m)) return; + const a = m.arena; + const n = m.functions.items.len; + // Callees first: post-order over the call graph from every function. + const state = try a.alloc(u8, n); // 0 new, 1 in progress, 2 done + @memset(state, 0); + var order: std.ArrayList(u32) = .empty; + for (0..n) |fi| try postOrder(a, m, @intCast(fi), state, &order); + const shapes = try a.alloc(?Shape, n); + @memset(shapes, null); + for (order.items) |fi| { + try inlineCalls(m, m.functions.items[fi], shapes); + shapes[fi] = try shapeOf(a, m, m.functions.items[fi]); + } + try markDead(m); +} + +fn postOrder(a: Allocator, m: *const ir.Module, fi: u32, state: []u8, out: *std.ArrayList(u32)) Error!void { + if (state[fi] != 0) return; + state[fi] = 1; + const f = m.functions.items[fi]; + for (f.insts.items) |inst| if (inst.op == .call) try postOrder(a, m, inst.op.call.func, state, out); + state[fi] = 2; + try out.append(a, fi); +} + +/// How a function returns, for inlining it. +const Shape = union(enum) { + /// Not inlinable. + keep, + /// One return, outside every construct: that block. + single: u32, + /// Returns inside selections (or several): wrap in a one-trip loop. + wrap, +}; + +fn shapeOf(a: Allocator, m: *const ir.Module, f: *const ir.Function) Error!Shape { + if (f.no_inline) return .keep; + for (f.params) |p| { + if (isRayQuery(m.types, p.ty)) return .keep; + if (p.by_ref and isResource(m.types, p.ty)) return .keep; + } + const nb = f.blocks.items.len; + // The innermost construct (header block) around each block, from a + // structured walk: a header's merge is at the header's level, its other + // successors are inside; exits to an enclosing merge or continue are + // not followed (their header places those blocks). + const root = std.math.maxInt(u32); + const ctx = try a.alloc(u32, nb); + const seen = try a.alloc(bool, nb); + const parent = try a.alloc(u32, nb); + @memset(seen, false); + @memset(parent, root); + var stack: std.ArrayList(struct { b: u32, c: u32 }) = .empty; + try stack.append(a, .{ .b = 0, .c = root }); + while (stack.pop()) |it| { + if (seen[it.b]) continue; + seen[it.b] = true; + ctx[it.b] = it.c; + const blk = f.blocks.items[it.b]; + var inner = it.c; + switch (blk.merge) { + .none => {}, + .selection => |mb| { + try stack.append(a, .{ .b = mb.index(), .c = it.c }); + parent[it.b] = it.c; + inner = it.b; + }, + .loop => |l| { + try stack.append(a, .{ .b = l.merge.index(), .c = it.c }); + try stack.append(a, .{ .b = l.@"continue".index(), .c = it.b }); + parent[it.b] = it.c; + inner = it.b; + }, + } + for (try successors(a, blk.term)) |s| { + if (s == .none) continue; + if (isExit(f, inner, parent, s.index())) continue; + try stack.append(a, .{ .b = s.index(), .c = inner }); + } + } + var rets: u32 = 0; + var ret_block: u32 = 0; + var nested = false; + for (f.blocks.items, 0..) |blk, bi| { + if (!seen[bi] or blk.term != .ret) continue; + rets += 1; + ret_block = @intCast(bi); + // Inside a loop: not inlinable. + var c = ctx[bi]; + while (c != root) : (c = parent[c]) { + if (f.blocks.items[c].merge == .loop) return .keep; + } + if (ctx[bi] != root) nested = true; + } + if (rets == 0) return .keep; // (never returns: leave it alone) + if (rets == 1 and !nested) return .{ .single = ret_block }; + // A resource returned through a local would be a resource local + // assigned in several places. + if (isResource(m.types, f.ret)) return .keep; + return .wrap; +} + +/// Whether `s`, a successor of a block whose innermost construct is headed +/// by `inner`, is that construct's (or an enclosing one's) merge or +/// continue target. +fn isExit(f: *const ir.Function, inner: u32, parent: []const u32, s: u32) bool { + var c = inner; + while (c != std.math.maxInt(u32)) : (c = parent[c]) { + switch (f.blocks.items[c].merge) { + .none => {}, + .selection => |mb| if (mb.index() == s) return true, + .loop => |l| if (l.merge.index() == s or l.@"continue".index() == s) return true, + } + } + return false; +} + +fn successors(a: Allocator, term: ir.Terminator) Error![]const BlockId { + return switch (term) { + .br => |b| try a.dupe(BlockId, &.{b}), + .cond_br => |c| try a.dupe(BlockId, &.{ c.then, c.@"else" }), + .@"switch" => |sw| blk: { + const out = try a.alloc(BlockId, sw.cases.len + 1); + out[0] = sw.default; + for (sw.cases, out[1..]) |c, *o| o.* = c.block; + break :blk out; + }, + else => &.{}, + }; +} + +fn isRayQuery(t: *TypeTable, ty: types.TypeId) bool { + return switch (t.get(ty)) { + .resource => |r| r.kind == .other and std.mem.eql(u8, r.name, "RayQuery"), + else => false, + }; +} + +fn isResource(t: *TypeTable, ty: types.TypeId) bool { + return switch (t.get(ty)) { + .resource => !isRayQuery(t, ty), + .sampler => true, + .array => |x| isResource(t, x.elem), + else => false, + }; +} + +fn newBlock(a: Allocator, f: *ir.Function, blk: ir.Block) Error!u32 { + try f.blocks.append(a, blk); + return @intCast(f.blocks.items.len - 1); +} + +fn newInst(a: Allocator, f: *ir.Function, inst: ir.Inst) Error!Ref { + try f.insts.append(a, inst); + return @fromBackingInt(@intCast(f.insts.items.len - 1)); +} + +/// Inlines every call in `f` whose callee has an inlinable shape. +fn inlineCalls(m: *ir.Module, f: *ir.Function, shapes: []const ?Shape) Error!void { + const a = m.arena; + // Call results, replaced by the callees' return values at the end. + var results: std.AutoHashMapUnmanaged(u32, Ref) = .empty; + var bi: usize = 0; + while (bi < f.blocks.items.len) : (bi += 1) { + var pos: usize = 0; + while (pos < f.blocks.items[bi].insts.items.len) : (pos += 1) { + const r = f.blocks.items[bi].insts.items[pos]; + const call = switch (f.inst(r).op) { + .call => |c| c, + else => continue, + }; + const shape = shapes[call.func] orelse continue; + if (shape == .keep) continue; + // A loop header keeps its instructions (its back edges target it). + if (f.blocks.items[bi].merge == .loop) continue; + const callee = m.functions.items[call.func]; + const value = try inlineOne(a, f, @intCast(bi), pos, call.args, callee, shape); + try results.put(a, r.index(), value); + // The rest of the block moved to the continuation block, which + // is later in the block list. + break; + } + } + if (results.count() == 0) return; + const Map = struct { + res: *const std.AutoHashMapUnmanaged(u32, Ref), + pub fn map(c: @This(), x: Ref) Ref { + var y = x; + while (y != .none) { + y = c.res.get(y.index()) orelse return y; + } + return y; + } + }; + const mp = Map{ .res = &results }; + for (f.blocks.items) |*blk| { + for (blk.insts.items) |r| f.insts.items[r.index()].op = try opt.mapOp(a, f.inst(r).op, mp); + blk.term = mapTerm(blk.term, mp); + } +} + +fn mapTerm(term: ir.Terminator, mp: anytype) ir.Terminator { + return switch (term) { + .ret => |v| .{ .ret = mp.map(v) }, + .cond_br => |c| .{ .cond_br = .{ .cond = mp.map(c.cond), .then = c.then, .@"else" = c.@"else" } }, + .@"switch" => |s| .{ .@"switch" = .{ .value = mp.map(s.value), .default = s.default, .cases = s.cases } }, + else => term, + }; +} + +/// Inlines `callee(args)`, the instruction at `pos` of block `bi` of `f`. +/// Returns the value the call produced (`.none` for void). +fn inlineOne(a: Allocator, f: *ir.Function, bi: u32, pos: usize, args: []const Ref, callee: *const ir.Function, shape: Shape) Error!Ref { + // Continuation: the instructions after the call, the terminator and + // the merge. + const cont = try newBlock(a, f, .{}); + { + const blk = &f.blocks.items[bi]; + try f.blocks.items[cont].insts.appendSlice(a, blk.insts.items[pos + 1 ..]); + f.blocks.items[cont].term = blk.term; + f.blocks.items[cont].merge = blk.merge; + blk.insts.shrinkRetainingCapacity(pos); + blk.merge = .none; + } + + // Copies of the callee's blocks and instructions (parameters become + // the arguments). + const bmap = try a.alloc(u32, callee.blocks.items.len); + for (bmap) |*b| b.* = try newBlock(a, f, .{}); + const imap = try a.alloc(Ref, callee.insts.items.len); + for (callee.insts.items, imap) |inst, *x| { + x.* = switch (inst.op) { + .param => |p| args[p], + else => try newInst(a, f, inst), + }; + } + const Map = struct { + imap: []const Ref, + pub fn map(c: @This(), x: Ref) Ref { + return if (x == .none) x else c.imap[x.index()]; + } + }; + const mp = Map{ .imap = imap }; + for (callee.insts.items, 0..) |inst, k| { + if (inst.op == .param) continue; + f.insts.items[imap[k].index()].op = try opt.mapOp(a, inst.op, mp); + } + const B = struct { + fn map(bm: []const u32, b: BlockId) BlockId { + return if (b == .none) b else @fromBackingInt(@intCast(bm[b.index()])); + } + }; + + // Wrapping: header -> (callee entry) ... -> exit; an unreachable + // continue block; the return value in a local. + var exit: u32 = cont; + var ret_var: Ref = .none; + var result: Ref = .none; + var entry_target: u32 = bmap[0]; + if (shape == .wrap) { + exit = try newBlock(a, f, .{}); + const header = try newBlock(a, f, .{}); + const latch = try newBlock(a, f, .{ .term = .{ .br = @fromBackingInt(@intCast(header)) } }); + f.blocks.items[header].merge = .{ .loop = .{ .merge = @fromBackingInt(@intCast(exit)), .@"continue" = @fromBackingInt(@intCast(latch)), .unroll = .auto } }; + f.blocks.items[header].term = .{ .br = @fromBackingInt(@intCast(bmap[0])) }; + entry_target = header; + if (callee.ret != TypeTable.void_type) { + ret_var = try newInst(a, f, .{ .op = .local_var, .ty = callee.ret, .ptr = .function }); + result = try newInst(a, f, .{ .op = .{ .load = ret_var }, .ty = callee.ret }); + try f.blocks.items[exit].insts.append(a, result); + } + f.blocks.items[exit].term = .{ .br = @fromBackingInt(@intCast(cont)) }; + } + + for (callee.blocks.items, 0..) |src, k| { + var insts: std.ArrayList(Ref) = .empty; + for (src.insts.items) |r| { + if (callee.inst(r).op == .param) continue; + try insts.append(a, imap[r.index()]); + } + var term: ir.Terminator = switch (src.term) { + .ret => |v| blk: { + if (shape == .wrap) { + if (ret_var != .none and v != .none) { + const st = try newInst(a, f, .{ .op = .{ .store = .{ .ptr = ret_var, .value = mp.map(v) } }, .ty = TypeTable.void_type }); + try insts.append(a, st); + } + break :blk .{ .br = @fromBackingInt(@intCast(exit)) }; + } + if (v != .none) result = mp.map(v); + break :blk .{ .br = @fromBackingInt(@intCast(cont)) }; + }, + .br => |b| .{ .br = B.map(bmap, b) }, + .cond_br => |c| .{ .cond_br = .{ .cond = mp.map(c.cond), .then = B.map(bmap, c.then), .@"else" = B.map(bmap, c.@"else") } }, + .@"switch" => |sw| blk: { + const cases = try a.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len); + for (sw.cases, cases) |c, *o| o.* = .{ .value = c.value, .block = B.map(bmap, c.block) }; + break :blk .{ .@"switch" = .{ .value = mp.map(sw.value), .default = B.map(bmap, sw.default), .cases = cases } }; + }, + else => src.term, + }; + _ = &term; + const merge: ir.Merge = switch (src.merge) { + .none => .none, + .selection => |mb| .{ .selection = B.map(bmap, mb) }, + .loop => |l| .{ .loop = .{ .merge = B.map(bmap, l.merge), .@"continue" = B.map(bmap, l.@"continue"), .unroll = l.unroll } }, + }; + f.blocks.items[bmap[k]] = .{ .insts = insts, .term = term, .merge = merge }; + } + f.blocks.items[bi].term = .{ .br = @fromBackingInt(@intCast(entry_target)) }; + return result; +} + +/// Marks functions no root (entry wrappers and patch wrappers, exports) +/// reaches through calls as dead. +fn markDead(m: *ir.Module) Error!void { + const a = m.arena; + const n = m.functions.items.len; + const live = try a.alloc(bool, n); + @memset(live, false); + var stack: std.ArrayList(u32) = .empty; + for (m.entries.items) |e| { + try stack.append(a, e.wrapper); + if (e.patch_wrapper) |p| try stack.append(a, p); + } + try stack.appendSlice(a, m.exports.items); + while (stack.pop()) |fi| { + if (live[fi]) continue; + live[fi] = true; + const f = m.functions.items[fi]; + for (f.blocks.items) |blk| for (blk.insts.items) |r| if (f.inst(r).op == .call) try stack.append(a, f.inst(r).op.call.func); + } + for (m.functions.items, live) |f, l| f.dead = !l; +} diff --git a/src/ir/ir.zig b/src/ir/ir.zig index ac27764..7ca434f 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -208,6 +208,8 @@ pub const Function = struct { /// `[noinline]` (plain functions, not methods or template instances): /// libraries keep it a function of its own. no_inline: bool = false, + /// Nothing calls it any more (inlined everywhere): not emitted. + dead: bool = false, insts: std.ArrayList(Inst) = .empty, blocks: std.ArrayList(Block) = .empty, diff --git a/src/options.zig b/src/options.zig index e91fdde..a8abd9c 100644 --- a/src/options.zig +++ b/src/options.zig @@ -29,6 +29,7 @@ pub const Extra = enum { zdxc_ast, zdxc_sema, zdxc_ir, + zdxc_no_opt, job, fcolor_diagnostics, fno_color_diagnostics, @@ -42,6 +43,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 = .zdxc_no_opt, .spelling = "zdxc-no-opt", .help = "Skip the SPIR-V IR optimizations: inlining, promotion to SSA values (development)" }, .{ .id = .job, .spelling = "-job=", .kind = .joined, .meta = "", .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" }, diff --git a/src/root.zig b/src/root.zig index efd87d2..a708ff6 100644 --- a/src/root.zig +++ b/src/root.zig @@ -35,6 +35,7 @@ pub const ir = struct { pub const texture = @import("ir/texture.zig"); pub const opt = @import("ir/opt.zig"); pub const split_resources = @import("ir/split_resources.zig"); + pub const inline_calls = @import("ir/inline.zig"); }; pub const sema = struct { diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index f2829cb..2d09458 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -945,6 +945,7 @@ const Emitter = struct { } for (m.functions.items, e.func_ids) |f, id| { + if (f.dead) continue; e.setEntry(f.entry); if (!e.hasResourceParams(f)) try e.emitFunction(f, id, &.{}); } @@ -984,7 +985,7 @@ const Emitter = struct { try e.entryPoint(entry); } for (m.functions.items, e.func_ids) |f, id| { - if (!e.hasResourceParams(f)) try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{}); + if (!f.dead and !e.hasResourceParams(f)) try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{}); } } From d39ee30a4c5e7a33c4f005a906ac06ab85840bbe Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Mon, 2 Nov 2026 07:54:10 +0000 Subject: [PATCH 3/8] SPIR-V: promote locals to SSA values; inline top-down ir/ssa.zig, after inlining: 1. A local struct or array accessed only whole and with constant indices is split into one local per leaf member / element (scalar replacement, up to 64 leaves): whole reads construct the value, whole writes store each part. Promoting whole aggregates instead made each member write a copy of the aggregate; on the Glide shader that has many of them RADV then spilled ten times as many scalar registers. 2. Locals loaded and stored only whole (no resources) become SSA values: semi-pruned phi placement over dominance frontiers, renaming over the dominator tree, trivial phis folded, dead phis (cycles included) dropped. Reads before any write are the new IR `undef` (OpUndef). Phis take one value per predecessor the emitter writes, unreachable merge and continue targets included. Constants that were behind locals fold afterwards. The SPIR-V emitter emits OpPhi, patching operands emitted after the phi. The inliner now works top-down from the entry points (each call gets a copy of the callee's own body, whose calls are inlined as the scan reaches them), copies only instructions in the callee's blocks (and locals on first use), and remaps only instructions naming a call result; scans use a non-allocating operand visitor (opt.eachOperand). On Glide: loads 115040 -> 20322, stores 63644 -> 5832 (dxc: 11423, 2498), SPIR-V 12.0 -> 13.2 MB (callee bodies copied); compile time 587 -> 771 ms on 327 shaders (dxc: 8.6 s). Two more corpus files compile (texel offsets that are constants once promoted). --- src/compile.zig | 1 + src/dxil/emit.zig | 1 + src/ir/inline.zig | 110 +++--- src/ir/ir.zig | 4 + src/ir/opt.zig | 64 +++- src/ir/ssa.zig | 811 +++++++++++++++++++++++++++++++++++++++++++++ src/root.zig | 1 + src/spirv/emit.zig | 40 ++- 8 files changed, 992 insertions(+), 40 deletions(-) create mode 100644 src/ir/ssa.zig diff --git a/src/compile.zig b/src/compile.zig index 2298e21..077a92a 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -508,6 +508,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { // optimizer (skipped for -Od). if (!opts.no_opt and opts.opt_level != .od) { try zdxc.ir.inline_calls.run(m); + try zdxc.ir.ssa.run(m); } } if (opts.dump_ir) { diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 6f24795..90e9663 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -1965,6 +1965,7 @@ const Emitter = struct { }, .output_vertex => |x| return e.outputControlPoint(x.element, i.ty, x.vertex), .phi => return e.unsupported("phi", .{}), + .undef => return e.unsupported("undef", .{}), } } diff --git a/src/ir/inline.zig b/src/ir/inline.zig index caa14da..abb381d 100644 --- a/src/ir/inline.zig +++ b/src/ir/inline.zig @@ -2,7 +2,8 @@ //! dxc's legalization does, so drivers get one function per entry point //! (and later passes see across call boundaries). //! -//! Callees are inlined bottom-up. The calling block is split at the call: +//! Calls are inlined top-down from the entry points. The calling block is +//! split at the call: //! it branches to the copy of the callee's entry, and the rest of the block //! (with its terminator and merge) moves to a continuation block. A callee //! with one return outside every construct branches from it to the @@ -30,7 +31,7 @@ pub const Error = Allocator.Error; /// points only (the emitter treats hull, mesh, geometry and ray tracing /// functions specially), and no rasterizer-ordered views (the pixel /// shader's call of its entry function is the interlocked region). -fn eligible(m: *const ir.Module) bool { +pub fn eligible(m: *const ir.Module) bool { if (m.entries.items.len == 0) return false; for (m.entries.items) |e| switch (e.stage) { .vertex, .pixel, .compute => {}, @@ -48,29 +49,30 @@ pub fn run(m: *ir.Module) Error!void { if (!eligible(m)) return; const a = m.arena; const n = m.functions.items.len; - // Callees first: post-order over the call graph from every function. - const state = try a.alloc(u8, n); // 0 new, 1 in progress, 2 done - @memset(state, 0); - var order: std.ArrayList(u32) = .empty; - for (0..n) |fi| try postOrder(a, m, @intCast(fi), state, &order); + // Shapes from the original bodies (inlining a function's callees does + // not change how it returns). const shapes = try a.alloc(?Shape, n); - @memset(shapes, null); - for (order.items) |fi| { - try inlineCalls(m, m.functions.items[fi], shapes); - shapes[fi] = try shapeOf(a, m, m.functions.items[fi]); + for (m.functions.items, shapes) |f, *sh| sh.* = try shapeOf(a, m, f); + // Top-down from the roots: each call is replaced by a copy of the + // callee's own body, whose calls are inlined in turn as the scan + // reaches the copied blocks; a function only gets expanded where it + // ends up. Callees that stay functions are expanded as roots. + const done = try a.alloc(bool, n); + @memset(done, false); + var work: std.ArrayList(u32) = .empty; + for (m.entries.items) |e| { + try work.append(a, e.wrapper); + if (e.patch_wrapper) |pw| try work.append(a, pw); + } + try work.appendSlice(a, m.exports.items); + while (work.pop()) |fi| { + if (done[fi]) continue; + done[fi] = true; + try inlineCalls(m, m.functions.items[fi], shapes, &work); } try markDead(m); } -fn postOrder(a: Allocator, m: *const ir.Module, fi: u32, state: []u8, out: *std.ArrayList(u32)) Error!void { - if (state[fi] != 0) return; - state[fi] = 1; - const f = m.functions.items[fi]; - for (f.insts.items) |inst| if (inst.op == .call) try postOrder(a, m, inst.op.call.func, state, out); - state[fi] = 2; - try out.append(a, fi); -} - /// How a function returns, for inlining it. const Shape = union(enum) { /// Not inlinable. @@ -203,8 +205,9 @@ fn newInst(a: Allocator, f: *ir.Function, inst: ir.Inst) Error!Ref { return @fromBackingInt(@intCast(f.insts.items.len - 1)); } -/// Inlines every call in `f` whose callee has an inlinable shape. -fn inlineCalls(m: *ir.Module, f: *ir.Function, shapes: []const ?Shape) Error!void { +/// Inlines every call in `f` whose callee has an inlinable shape (calls +/// in the copies included); callees of calls that stay go to `work`. +fn inlineCalls(m: *ir.Module, f: *ir.Function, shapes: []const ?Shape, work: *std.ArrayList(u32)) Error!void { const a = m.arena; // Call results, replaced by the callees' return values at the end. var results: std.AutoHashMapUnmanaged(u32, Ref) = .empty; @@ -217,10 +220,12 @@ fn inlineCalls(m: *ir.Module, f: *ir.Function, shapes: []const ?Shape) Error!voi .call => |c| c, else => continue, }; - const shape = shapes[call.func] orelse continue; - if (shape == .keep) continue; + const shape = shapes[call.func] orelse .keep; // A loop header keeps its instructions (its back edges target it). - if (f.blocks.items[bi].merge == .loop) continue; + if (shape == .keep or f.blocks.items[bi].merge == .loop) { + try work.append(a, call.func); + continue; + } const callee = m.functions.items[call.func]; const value = try inlineOne(a, f, @intCast(bi), pos, call.args, callee, shape); try results.put(a, r.index(), value); @@ -241,8 +246,19 @@ fn inlineCalls(m: *ir.Module, f: *ir.Function, shapes: []const ?Shape) Error!voi } }; const mp = Map{ .res = &results }; + const Hit = struct { + res: *const std.AutoHashMapUnmanaged(u32, Ref), + hit: *bool, + pub fn use(c: @This(), x: Ref) void { + if (x != .none and c.res.contains(x.index())) c.hit.* = true; + } + }; for (f.blocks.items) |*blk| { - for (blk.insts.items) |r| f.insts.items[r.index()].op = try opt.mapOp(a, f.inst(r).op, mp); + for (blk.insts.items) |r| { + var hit = false; + opt.eachOperand(f.inst(r).op, Hit{ .res = &results, .hit = &hit }); + if (hit) f.insts.items[r.index()].op = try opt.mapOp(a, f.inst(r).op, mp); + } blk.term = mapTerm(blk.term, mp); } } @@ -272,27 +288,45 @@ fn inlineOne(a: Allocator, f: *ir.Function, bi: u32, pos: usize, args: []const R } // Copies of the callee's blocks and instructions (parameters become - // the arguments). + // the arguments). Only instructions in its blocks are copied up front; + // others it refers to (locals live in no block) are copied on first + // use: the callee's array also holds what earlier inlining left behind. const bmap = try a.alloc(u32, callee.blocks.items.len); for (bmap) |*b| b.* = try newBlock(a, f, .{}); const imap = try a.alloc(Ref, callee.insts.items.len); - for (callee.insts.items, imap) |inst, *x| { - x.* = switch (inst.op) { + @memset(imap, .none); + for (callee.blocks.items) |blk| for (blk.insts.items) |r| { + const inst = callee.inst(r); + imap[r.index()] = switch (inst.op) { .param => |p| args[p], else => try newInst(a, f, inst), }; - } + }; const Map = struct { - imap: []const Ref, - pub fn map(c: @This(), x: Ref) Ref { - return if (x == .none) x else c.imap[x.index()]; + imap: []Ref, + f: *ir.Function, + callee: *const ir.Function, + args: []const Ref, + al: Allocator, + pub fn map(c: *const @This(), x: Ref) Ref { + if (x == .none) return x; + if (c.imap[x.index()] != .none) return c.imap[x.index()]; + const inst = c.callee.inst(x); + const y = switch (inst.op) { + .param => |p| c.args[p], + else => newInst(c.al, c.f, inst) catch return x, + }; + c.imap[x.index()] = y; + if (inst.op != .param) c.f.insts.items[y.index()].op = opt.mapOp(c.al, inst.op, c) catch inst.op; + return y; } }; - const mp = Map{ .imap = imap }; - for (callee.insts.items, 0..) |inst, k| { + const mp = &Map{ .imap = imap, .f = f, .callee = callee, .args = args, .al = a }; + for (callee.blocks.items) |blk| for (blk.insts.items) |r| { + const inst = callee.inst(r); if (inst.op == .param) continue; - f.insts.items[imap[k].index()].op = try opt.mapOp(a, inst.op, mp); - } + f.insts.items[imap[r.index()].index()].op = try opt.mapOp(a, inst.op, mp); + }; const B = struct { fn map(bm: []const u32, b: BlockId) BlockId { return if (b == .none) b else @fromBackingInt(@intCast(bm[b.index()])); @@ -324,7 +358,7 @@ fn inlineOne(a: Allocator, f: *ir.Function, bi: u32, pos: usize, args: []const R var insts: std.ArrayList(Ref) = .empty; for (src.insts.items) |r| { if (callee.inst(r).op == .param) continue; - try insts.append(a, imap[r.index()]); + try insts.append(a, mp.map(r)); } var term: ir.Terminator = switch (src.term) { .ret => |v| blk: { diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 7ca434f..c5a50b5 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -141,6 +141,9 @@ pub const Op = union(enum) { emit: u32, cut: u32, phi: []const struct { value: Ref, block: BlockId }, + /// An undefined value of the result type (a read before any write, + /// after promotion to SSA values). + undef, }; pub const Inst = struct { @@ -705,6 +708,7 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo }, .input => |i| try w.print("input {d}", .{i}), .output => |o| try w.print("output {d}, %{d}", .{ o.element, o.value.index() }), + .undef => try w.writeAll("undef"), .phi => |ins| { try w.writeAll("phi"); for (ins, 0..) |in, i| try w.print("{s} [%{d}, b{d}]", .{ if (i > 0) "," else "", in.value.index(), in.block.index() }); diff --git a/src/ir/opt.zig b/src/ir/opt.zig index 79f3349..4d71ad8 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const /// `op` with every operand passed through `ctx.map`. pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { return switch (op) { - .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant => op, + .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => op, .load => |p| .{ .load = ctx.map(p) }, .store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } }, .access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } }, @@ -223,6 +223,68 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { }; } +/// Calls `ctx.use(r)` for every operand of `op` (none skipped), without +/// allocating. +pub fn eachOperand(op: Op, ctx: anytype) void { + switch (op) { + .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => {}, + .load => |p| ctx.use(p), + .store => |x| { + ctx.use(x.ptr); + ctx.use(x.value); + }, + .access => |x| { + ctx.use(x.base); + for (x.indices) |r| ctx.use(r); + }, + .binary => |x| { + ctx.use(x.lhs); + ctx.use(x.rhs); + }, + .unary => |x| ctx.use(x.operand), + .cmp => |x| { + ctx.use(x.lhs); + ctx.use(x.rhs); + }, + .convert, .bitcast, .splat => |x| ctx.use(x), + .extract => |x| ctx.use(x.agg), + .insert => |x| { + ctx.use(x.agg); + ctx.use(x.value); + }, + .construct => |xs| for (xs) |r| ctx.use(r), + .shuffle => |x| ctx.use(x.vec), + .select => |x| { + ctx.use(x.cond); + ctx.use(x.t); + ctx.use(x.f); + }, + .call => |x| for (x.args) |r| ctx.use(r), + .intrinsic => |x| for (x.args) |r| ctx.use(r), + .res_load => |x| { + ctx.use(x.res); + ctx.use(x.index); + }, + .res_store => |x| { + ctx.use(x.res); + ctx.use(x.index); + ctx.use(x.value); + }, + .method => |x| { + ctx.use(x.res); + for (x.args) |r| ctx.use(r); + }, + .output => |x| ctx.use(x.value), + .heap_resource => |h| ctx.use(h.index), + .spirv_inst => |x| for (x.operands) |o| switch (o) { + .value => |v| ctx.use(v), + .literal, .type => {}, + }, + .patch_output => |x| ctx.use(x.value), + .phi => |ps| for (ps) |pp| ctx.use(pp.value), + } +} + /// Calls `ctx.use(r)` for every operand of `op` and of terminator `term`. fn forOperands(a: Allocator, op: Op, ctx: anytype) Allocator.Error!void { const Collect = struct { diff --git a/src/ir/ssa.zig b/src/ir/ssa.zig new file mode 100644 index 0000000..b891d3b --- /dev/null +++ b/src/ir/ssa.zig @@ -0,0 +1,811 @@ +//! Promotion of locals to SSA values for SPIR-V (dxc's SPIR-V gets it from +//! its optimizer's ssa-rewrite and local-access-chain-convert): drivers get +//! values instead of Function variables, and inlined code its parameters +//! and temporaries as values. +//! +//! 1. A local struct or array accessed only with constant indices (and +//! whole) is split into one local per leaf member / element (scalar +//! replacement): whole reads construct the value, whole writes store +//! each part. Promoting whole aggregates instead would turn each member +//! write into a copy of the aggregate, which drivers do not undo. +//! 2. Locals then only loaded and stored whole (not resources) are +//! promoted: phis where values of a variable live across blocks meet +//! (semi-pruned SSA over dominance frontiers), loads replaced by the +//! value reaching them, stores and the locals removed. A read before any +//! write is `undef`. +//! +//! Phis get one incoming value per predecessor the emitter writes out, +//! unreachable merge and continue targets included (`undef` from those). + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ir = @import("ir.zig"); +const types = @import("../sema/types.zig"); +const opt = @import("opt.zig"); + +const Ref = ir.Ref; +const BlockId = ir.BlockId; +const TypeId = types.TypeId; +const TypeTable = types.TypeTable; + +pub const Error = Allocator.Error; + +pub fn run(m: *ir.Module) Error!void { + // (The same modules as inlining, for now.) + if (!@import("inline.zig").eligible(m)) return; + for (m.functions.items) |f| { + if (f.dead) continue; + try splitLocals(m, f); + try promote(m, f); + // Values that were behind locals may fold now. + try opt.fold(m.arena, m.types, f); + } +} + +// ---------------------------------------------------------------------- +// Uses + +fn addInst(a: Allocator, f: *ir.Function, inst: ir.Inst) Error!Ref { + try f.insts.append(a, inst); + return @fromBackingInt(@intCast(f.insts.items.len - 1)); +} + +/// Calls `ctx.use(r)` for every operand of `op` (not `.none`). +fn forOperands(a: Allocator, op: ir.Op, ctx: anytype) Error!void { + _ = a; + const Skip = struct { + inner: @TypeOf(ctx), + pub fn use(c: @This(), r: Ref) void { + if (r != .none) c.inner.use(r); + } + }; + opt.eachOperand(op, Skip{ .inner = ctx }); +} + +fn termOperand(term: ir.Terminator) Ref { + return switch (term) { + .ret => |r| r, + .cond_br => |c| c.cond, + .@"switch" => |s| s.value, + else => .none, + }; +} + +fn successors(a: Allocator, term: ir.Terminator) Error![]const BlockId { + return switch (term) { + .br => |b| try a.dupe(BlockId, &.{b}), + .cond_br => |c| if (c.then == c.@"else") try a.dupe(BlockId, &.{c.then}) else try a.dupe(BlockId, &.{ c.then, c.@"else" }), + .@"switch" => |sw| blk: { + var out: std.ArrayList(BlockId) = .empty; + try out.append(a, sw.default); + for (sw.cases) |c| { + if (std.mem.indexOfScalar(BlockId, out.items, c.block) == null) try out.append(a, c.block); + } + break :blk out.items; + }, + else => &.{}, + }; +} + +/// A local's type is promotable: no resources, ray queries or other opaque +/// values anywhere in it. +fn plainType(t: *TypeTable, ty: TypeId) bool { + return switch (t.get(ty)) { + .scalar, .vector, .matrix, .@"enum" => true, + .array => |x| x.len > 0 and plainType(t, x.elem), + .@"struct" => |st| { + for (st.fields.items) |fld| if (!plainType(t, fld.type)) return false; + for (st.bases.items) |_| return false; + return true; + }, + else => false, + }; +} + +// ---------------------------------------------------------------------- +// 1. Scalar replacement + +/// Where each instruction is: block and position (for instructions in a +/// block). +const Place = struct { block: u32, pos: u32 }; + +fn constIndex(f: *const ir.Function, r: Ref) ?u32 { + const i = f.inst(r); + if (i.op != .constant or i.op.constant != .int) return null; + const v = i.op.constant.int; + if (v < 0 or v > std.math.maxInt(u32)) return null; + return @intCast(v); +} + +/// The type one constant index into `ty` selects (structs and arrays). +fn stepType(t: *TypeTable, ty: TypeId, k: u32) ?TypeId { + return switch (t.get(ty)) { + .@"struct" => |st| if (k < st.fields.items.len) st.fields.items[k].type else null, + .array => |x| if (k < x.len) x.elem else null, + else => null, + }; +} + +fn splitLocals(m: *ir.Module, f: *ir.Function) Error!void { + const a = m.arena; + const t = m.types; + const n = f.insts.items.len; + // Uses of every instruction (in blocks), and whether each is in one. + const in_block = try a.alloc(bool, n); + @memset(in_block, false); + for (f.blocks.items) |blk| for (blk.insts.items) |r| { + in_block[r.index()] = true; + }; + // root[x]: the local an access chain `x` is rooted at (none if not one + // of a convertible chain); path from the root. + const root = try a.alloc(Ref, n); + @memset(root, .none); + const paths = try a.alloc([]const u32, n); + // Candidate locals: struct / array locals of plain types. + const cand = try a.alloc(bool, n); + @memset(cand, false); + var any = false; + for (f.insts.items, 0..) |inst, i| { + // (Locals are function-wide: some live in no block.) + if (inst.op != .local_var or inst.ptr != .function) continue; + const k = t.get(inst.ty); + if ((k == .@"struct" or k == .array) and plainType(t, inst.ty)) { + cand[i] = true; + root[i] = @fromBackingInt(@intCast(i)); + paths[i] = &.{}; + any = true; + } + } + if (!any) return; + // Chains in instruction order: an access's base precedes it in f.insts + // when lowering made it; iterate to a fixed point to be safe. + var changed = true; + while (changed) { + changed = false; + for (f.insts.items, 0..) |inst, i| { + if (!in_block[i] or root[i] != .none) continue; + const acc = switch (inst.op) { + .access => |x| x, + else => continue, + }; + const rb = root[acc.base.index()]; + if (rb == .none or !cand[rb.index()]) continue; + var ty = f.inst(acc.base).ty; + var path: std.ArrayList(u32) = .empty; + try path.appendSlice(a, paths[acc.base.index()]); + const ok = for (acc.indices) |x| { + const k = constIndex(f, x) orelse break false; + ty = stepType(t, ty, k) orelse break false; + try path.append(a, k); + } else true; + if (!ok) { + cand[rb.index()] = false; + continue; + } + root[i] = rb; + paths[i] = path.items; + changed = true; + } + } + // Every use of a chain (or of the local) must be a load, a store to it + // or a further chain; anything else disqualifies the local. + const Check = struct { + f: *const ir.Function, + root: []const Ref, + cand: []bool, + user: Ref, + pub fn use(c: @This(), x: Ref) void { + const rt = c.root[x.index()]; + if (rt == .none) return; + const u = c.f.inst(c.user).op; + const fine = switch (u) { + .load => true, + .store => |s| s.ptr == x and s.value != x, + .access => |acc| acc.base == x and c.root[c.user.index()] == rt, + else => false, + }; + if (!fine) c.cand[rt.index()] = false; + } + }; + for (f.blocks.items) |blk| { + for (blk.insts.items) |r| try forOperands(a, f.inst(r).op, Check{ .f = f, .root = root, .cand = cand, .user = r }); + const tr = termOperand(blk.term); + if (tr != .none and root[tr.index()] != .none) cand[root[tr.index()].index()] = false; + } + // Split each remaining candidate into one local per leaf (scalar, + // vector or matrix member / element), in depth-first order; aggregates + // with too many leaves stay whole. + const leaf_base = try a.alloc(u32, n); // first leaf local of a candidate + var leaves: std.ArrayList(Ref) = .empty; + for (0..n) |i| { + if (!cand[i]) continue; + const count = leafCount(t, f.inst(@fromBackingInt(@intCast(i))).ty); + if (count > max_leaves) { + cand[i] = false; + continue; + } + leaf_base[i] = @intCast(leaves.items.len); + try addLeaves(a, f, t, f.inst(@fromBackingInt(@intCast(i))).ty, &leaves); + } + defer for (0..n) |i| if (cand[i]) { + // Split: the aggregate local is gone (the emitter declares every + // local_var). + f.insts.items[i] = .{ .op = .undef, .ty = f.insts.items[i].ty }; + }; + // Rewrite loads and stores through the candidates and their chains. + for (f.blocks.items) |*blk| { + var out: std.ArrayList(Ref) = .empty; + for (blk.insts.items) |r| { + const inst = f.inst(r); + switch (inst.op) { + .access => if (root[r.index()] != .none and cand[root[r.index()].index()]) continue, + .local_var => if (cand[r.index()]) continue, + .load => |p| { + const rt = root[p.index()]; + if (rt != .none and cand[rt.index()]) { + const at = leafAt(t, f.inst(rt).ty, paths[p.index()]); + const base = leaves.items[leaf_base[rt.index()] + at.offset ..]; + const v = try gather(a, f, t, at.ty, base, &out); + // The load becomes the gathered value. + f.insts.items[r.index()].op = f.inst(v).op; + if (out.items.len > 0 and out.items[out.items.len - 1] == v) out.items[out.items.len - 1] = r else try out.append(a, r); + continue; + } + }, + .store => |st| { + const rt = root[st.ptr.index()]; + if (rt != .none and cand[rt.index()]) { + const at = leafAt(t, f.inst(rt).ty, paths[st.ptr.index()]); + const base = leaves.items[leaf_base[rt.index()] + at.offset ..]; + try scatter(a, f, t, at.ty, base, st.value, &out); + continue; + } + }, + else => {}, + } + try out.append(a, r); + } + blk.insts = out; + } +} + +/// Aggregates split into at most this many locals. +const max_leaves = 64; + +fn isAggregate(t: *TypeTable, ty: TypeId) bool { + return switch (t.get(ty)) { + .@"struct", .array => true, + else => false, + }; +} + +fn leafCount(t: *TypeTable, ty: TypeId) u32 { + return switch (t.get(ty)) { + .@"struct" => |st| blk: { + var c: u32 = 0; + for (st.fields.items) |fld| c +|= leafCount(t, fld.type); + break :blk c; + }, + .array => |x| x.len *| leafCount(t, x.elem), + else => 1, + }; +} + +fn addLeaves(a: Allocator, f: *ir.Function, t: *TypeTable, ty: TypeId, out: *std.ArrayList(Ref)) Error!void { + switch (t.get(ty)) { + .@"struct" => |st| for (st.fields.items) |fld| try addLeaves(a, f, t, fld.type, out), + .array => |x| for (0..x.len) |_| try addLeaves(a, f, t, x.elem, out), + else => try out.append(a, try addInst(a, f, .{ .op = .local_var, .ty = ty, .ptr = .function })), + } +} + +/// The member a path selects: its type and first leaf (depth-first). +fn leafAt(t: *TypeTable, ty0: TypeId, path: []const u32) struct { ty: TypeId, offset: u32 } { + var ty = ty0; + var off: u32 = 0; + for (path) |k| switch (t.get(ty)) { + .@"struct" => |st| { + for (st.fields.items[0..k]) |fld| off += leafCount(t, fld.type); + ty = st.fields.items[k].type; + }, + .array => |x| { + off += k * leafCount(t, x.elem); + ty = x.elem; + }, + else => unreachable, + }; + return .{ .ty = ty, .offset = off }; +} + +/// The value of type `ty` held in the leaf locals from `leaves[0]`: a load +/// of a leaf, or a construct of its members' values. +fn gather(a: Allocator, f: *ir.Function, t: *TypeTable, ty: TypeId, leaves: []const Ref, out: *std.ArrayList(Ref)) Error!Ref { + if (!isAggregate(t, ty)) { + const v = try addInst(a, f, .{ .op = .{ .load = leaves[0] }, .ty = ty }); + try out.append(a, v); + return v; + } + var parts: std.ArrayList(Ref) = .empty; + var off: u32 = 0; + switch (t.get(ty)) { + .@"struct" => |st| for (st.fields.items) |fld| { + try parts.append(a, try gather(a, f, t, fld.type, leaves[off..], out)); + off += leafCount(t, fld.type); + }, + .array => |x| for (0..x.len) |_| { + try parts.append(a, try gather(a, f, t, x.elem, leaves[off..], out)); + off += leafCount(t, x.elem); + }, + else => unreachable, + } + const v = try addInst(a, f, .{ .op = .{ .construct = parts.items }, .ty = ty }); + try out.append(a, v); + return v; +} + +/// Stores value `v` of type `ty` into the leaf locals from `leaves[0]`. +fn scatter(a: Allocator, f: *ir.Function, t: *TypeTable, ty: TypeId, leaves: []const Ref, v: Ref, out: *std.ArrayList(Ref)) Error!void { + if (!isAggregate(t, ty)) { + try out.append(a, try addInst(a, f, .{ .op = .{ .store = .{ .ptr = leaves[0], .value = v } }, .ty = TypeTable.void_type })); + return; + } + var off: u32 = 0; + switch (t.get(ty)) { + .@"struct" => |st| for (st.fields.items, 0..) |fld, k| { + const x = try addInst(a, f, .{ .op = .{ .extract = .{ .agg = v, .index = @intCast(k) } }, .ty = fld.type }); + try out.append(a, x); + try scatter(a, f, t, fld.type, leaves[off..], x, out); + off += leafCount(t, fld.type); + }, + .array => |arr| for (0..arr.len) |k| { + const x = try addInst(a, f, .{ .op = .{ .extract = .{ .agg = v, .index = @intCast(k) } }, .ty = arr.elem }); + try out.append(a, x); + try scatter(a, f, t, arr.elem, leaves[off..], x, out); + off += leafCount(t, arr.elem); + }, + else => unreachable, + } +} + +// ---------------------------------------------------------------------- +// 2. Promotion + +fn promote(m: *ir.Module, f: *ir.Function) Error!void { + const a = m.arena; + const t = m.types; + const nb = f.blocks.items.len; + const ni = f.insts.items.len; + + // Promotable locals: plain types, every use a whole load or a store to + // them. + const var_of = try a.alloc(u32, ni); // inst -> var index (maxInt: none) + const none = std.math.maxInt(u32); + @memset(var_of, none); + var vars: std.ArrayList(Ref) = .empty; + const in_block = try a.alloc(bool, ni); + @memset(in_block, false); + for (f.blocks.items) |blk| for (blk.insts.items) |r| { + in_block[r.index()] = true; + }; + for (f.insts.items, 0..) |inst, i| { + if (inst.op != .local_var or inst.ptr != .function or !plainType(t, inst.ty)) continue; + var_of[i] = @intCast(vars.items.len); + try vars.append(a, @fromBackingInt(@intCast(i))); + } + if (vars.items.len == 0) return; + const ok = try a.alloc(bool, vars.items.len); + @memset(ok, true); + const Check = struct { + f: *const ir.Function, + var_of: []const u32, + ok: []bool, + user: Ref, + pub fn use(c: @This(), x: Ref) void { + const v = c.var_of[x.index()]; + if (v == std.math.maxInt(u32)) return; + const fine = switch (c.f.inst(c.user).op) { + .load => true, + .store => |s| s.ptr == x and s.value != x, + else => false, + }; + if (!fine) c.ok[v] = false; + } + }; + for (f.blocks.items) |blk| { + for (blk.insts.items) |r| try forOperands(a, f.inst(r).op, Check{ .f = f, .var_of = var_of, .ok = ok, .user = r }); + const tr = termOperand(blk.term); + if (tr != .none and var_of[tr.index()] != none) ok[var_of[tr.index()]] = false; + } + // Renumber the promoted ones. + var pvars: std.ArrayList(Ref) = .empty; + for (vars.items, 0..) |v, k| { + if (ok[k]) { + var_of[v.index()] = @intCast(pvars.items.len); + try pvars.append(a, v); + } else var_of[v.index()] = none; + } + const nv = pvars.items.len; + if (nv == 0) return; + // CFG: reachable blocks (from the entry) and emitted ones (reachable, + // plus unreachable merge / continue targets and what they reach, as + // the emitter's block order). + const succs = try a.alloc([]const BlockId, nb); + for (f.blocks.items, succs) |blk, *s| s.* = try successors(a, blk.term); + const reach = try a.alloc(bool, nb); + @memset(reach, false); + var rpo: std.ArrayList(u32) = .empty; + { + // Iterative DFS post-order. + var post: std.ArrayList(u32) = .empty; + var stack: std.ArrayList(struct { b: u32, next: u32 }) = .empty; + reach[0] = true; + try stack.append(a, .{ .b = 0, .next = 0 }); + while (stack.items.len > 0) { + const top = &stack.items[stack.items.len - 1]; + const ss = succs[top.b]; + if (top.next < ss.len) { + const s = ss[top.next].index(); + top.next += 1; + if (!reach[s]) { + reach[s] = true; + try stack.append(a, .{ .b = s, .next = 0 }); + } + } else { + try post.append(a, top.b); + _ = stack.pop(); + } + } + var i = post.items.len; + while (i > 0) { + i -= 1; + try rpo.append(a, post.items[i]); + } + } + const emitted = try a.alloc(bool, nb); + @memcpy(emitted, reach); + { + var changed = true; + while (changed) { + changed = false; + for (f.blocks.items, 0..) |blk, bi| { + if (!emitted[bi]) continue; + const targets: [2]BlockId = switch (blk.merge) { + .none => .{ .none, .none }, + .selection => |mb| .{ mb, .none }, + .loop => |l| .{ l.merge, l.@"continue" }, + }; + for (targets) |tb| if (tb != .none and !emitted[tb.index()]) { + emitted[tb.index()] = true; + changed = true; + }; + for (succs[bi]) |s| if (!emitted[s.index()]) { + emitted[s.index()] = true; + changed = true; + }; + } + } + } + // Predecessors (emitted ones). + var preds = try a.alloc(std.ArrayList(u32), nb); + for (preds) |*p| p.* = .empty; + for (0..nb) |bi| { + if (!emitted[bi]) continue; + for (succs[bi]) |s| try preds[s.index()].append(a, @intCast(bi)); + } + // Dominators over reachable blocks (Cooper, Harvey, Kennedy). + const rpo_num = try a.alloc(u32, nb); + @memset(rpo_num, none); + for (rpo.items, 0..) |b, k| rpo_num[b] = @intCast(k); + const idom = try a.alloc(u32, nb); + @memset(idom, none); + idom[0] = 0; + { + var changed = true; + while (changed) { + changed = false; + for (rpo.items[1..]) |b| { + var new: u32 = none; + for (preds[b].items) |p| { + if (!reach[p] or idom[p] == none) continue; + if (new == none) { + new = p; + continue; + } + // intersect + var x = p; + var y = new; + while (x != y) { + while (rpo_num[x] > rpo_num[y]) x = idom[x]; + while (rpo_num[y] > rpo_num[x]) y = idom[y]; + } + new = x; + } + if (new != none and idom[b] != new) { + idom[b] = new; + changed = true; + } + } + } + } + // Dominance frontiers. + var df = try a.alloc(std.ArrayList(u32), nb); + for (df) |*d| d.* = .empty; + for (rpo.items) |b| { + var rp: u32 = 0; + for (preds[b].items) |p| if (reach[p]) { + rp += 1; + }; + if (rp < 2) continue; + for (preds[b].items) |p| { + if (!reach[p]) continue; + var runner = p; + while (runner != idom[b]) { + if (std.mem.indexOfScalar(u32, df[runner].items, b) == null) try df[runner].append(a, b); + runner = idom[runner]; + } + } + } + // Semi-pruned: variables read in some block before being written there + // (live into it) get phis; the others are block-local. + const global = try a.alloc(bool, nv); + @memset(global, false); + var def_blocks = try a.alloc(std.ArrayList(u32), nv); + for (def_blocks) |*d| d.* = .empty; + { + const written = try a.alloc(u32, nv); // block that last wrote it (+1) + @memset(written, 0); + for (rpo.items) |b| { + for (f.blocks.items[b].insts.items) |r| switch (f.inst(r).op) { + .load => |p| { + const v = var_of[p.index()]; + if (v != none and written[v] != b + 1) global[v] = true; + }, + .store => |s| { + const v = var_of[s.ptr.index()]; + if (v != none) { + if (written[v] != b + 1) try def_blocks[v].append(a, b); + written[v] = b + 1; + } + }, + else => {}, + }; + } + } + // Phi placement: phi_of[b] lists (var, phi ref). + var phis = try a.alloc(std.ArrayList(struct { v: u32, r: Ref }), nb); + for (phis) |*p| p.* = .empty; + { + const has_phi = try a.alloc(u32, nb); // var + 1 that last placed one + const in_work = try a.alloc(u32, nb); + @memset(has_phi, 0); + @memset(in_work, 0); + var work: std.ArrayList(u32) = .empty; + for (0..nv) |v| { + if (!global[v]) continue; + const tag: u32 = @intCast(v + 1); + work.clearRetainingCapacity(); + for (def_blocks[v].items) |b| { + in_work[b] = tag; + try work.append(a, b); + } + while (work.pop()) |b| { + for (df[b].items) |d| { + if (has_phi[d] == tag) continue; + has_phi[d] = tag; + const ty = f.inst(pvars.items[v]).ty; + const r = try addInst(a, f, .{ .op = .{ .phi = &.{} }, .ty = ty }); + try phis[d].append(a, .{ .v = @intCast(v), .r = r }); + if (in_work[d] != tag) { + in_work[d] = tag; + try work.append(a, d); + } + } + } + } + } + // Undefined values, one per variable (made on first use). + const undefs = try a.alloc(Ref, nv); + @memset(undefs, .none); + const Undef = struct { + fn get(al: Allocator, fx: *ir.Function, us: []Ref, pv: []const Ref, v: u32) Error!Ref { + if (us[v] == .none) us[v] = try addInst(al, fx, .{ .op = .undef, .ty = fx.inst(pv[v]).ty }); + return us[v]; + } + }; + + // Renaming over the dominator tree. + var children = try a.alloc(std.ArrayList(u32), nb); + for (children) |*c| c.* = .empty; + for (rpo.items[1..]) |b| if (idom[b] != none) try children[idom[b]].append(a, b); + // Incoming values: per phi, (value, block) as preds are processed. + var incoming = try a.alloc(std.ArrayList(@typeInfo(@FieldType(ir.Op, "phi")).pointer.child), f.insts.items.len); + for (incoming) |*x| x.* = .empty; + // Replacements (promoted loads, trivial phis), by instruction; the + // values made later (undefs) have none. + const Repl = struct { + to: []Ref, + fn put(r: *@This(), k: u32, v: Ref) void { + r.to[k] = v; + } + fn get(r: *const @This(), k: u32) ?Ref { + if (k >= r.to.len or r.to[k] == .none) return null; + return r.to[k]; + } + fn contains(r: *const @This(), k: u32) bool { + return r.get(k) != null; + } + }; + var repl = Repl{ .to = try a.alloc(Ref, f.insts.items.len) }; + @memset(repl.to, .none); + const cur = try a.alloc(Ref, nv); + for (cur, 0..) |*c, v| c.* = try Undef.get(a, f, undefs, pvars.items, @intCast(v)); + var log: std.ArrayList(struct { v: u32, old: Ref }) = .empty; + var stack: std.ArrayList(struct { b: u32, mark: usize, enter: bool }) = .empty; + try stack.append(a, .{ .b = 0, .mark = 0, .enter = true }); + while (stack.pop()) |fr| { + if (!fr.enter) { + while (log.items.len > fr.mark) { + const e = log.pop().?; + cur[e.v] = e.old; + } + continue; + } + const b = fr.b; + try stack.append(a, .{ .b = b, .mark = log.items.len, .enter = false }); + for (phis[b].items) |p| { + try log.append(a, .{ .v = p.v, .old = cur[p.v] }); + cur[p.v] = p.r; + } + for (f.blocks.items[b].insts.items) |r| switch (f.inst(r).op) { + .load => |p| { + const v = var_of[p.index()]; + if (v != none) repl.put(r.index(), cur[v]); + }, + .store => |s| { + const v = var_of[s.ptr.index()]; + if (v != none) { + try log.append(a, .{ .v = v, .old = cur[v] }); + cur[v] = s.value; + } + }, + else => {}, + }; + for (succs[b]) |s| for (phis[s.index()].items) |p| { + try incoming[p.r.index()].append(a, .{ .value = cur[p.v], .block = @fromBackingInt(@intCast(b)) }); + }; + for (children[b].items) |c| try stack.append(a, .{ .b = c, .mark = 0, .enter = true }); + } + // Unreachable emitted blocks: loads read undef; their edges into phis + // carry undef. + for (0..nb) |bi| { + if (reach[bi]) continue; + for (f.blocks.items[bi].insts.items) |r| switch (f.inst(r).op) { + .load => |p| { + const v = var_of[p.index()]; + if (v != none) repl.put(r.index(), try Undef.get(a, f, undefs, pvars.items, v)); + }, + else => {}, + }; + if (!emitted[bi]) continue; + for (succs[bi]) |s| for (phis[s.index()].items) |p| { + try incoming[p.r.index()].append(a, .{ .value = try Undef.get(a, f, undefs, pvars.items, p.v), .block = @fromBackingInt(@intCast(bi)) }); + }; + } + // Resolve: replacements may name other replaced loads; trivial phis + // (one distinct incoming value besides themselves) become that value. + const Resolve = struct { + repl: *const Repl, + pub fn map(c: @This(), x: Ref) Ref { + var y = x; + var n: u32 = 0; + while (y != .none and n < 1 << 20) : (n += 1) { + y = c.repl.get(y.index()) orelse return y; + } + return y; + } + }; + const rs = Resolve{ .repl = &repl }; + const Hit = struct { + repl: *const Repl, + hit: *bool, + pub fn use(c: @This(), x: Ref) void { + if (c.repl.contains(x.index())) c.hit.* = true; + } + }; + // Phi incoming lists in place; then fold trivial phis to a fixed point. + var all_phis: std.ArrayList(Ref) = .empty; + for (phis) |ps| for (ps.items) |p| { + f.insts.items[p.r.index()].op = .{ .phi = incoming[p.r.index()].items }; + try all_phis.append(a, p.r); + }; + var changed = true; + while (changed) { + changed = false; + for (all_phis.items) |p| { + if (repl.contains(p.index())) continue; + var same: Ref = .none; + var trivial = true; + for (f.inst(p).op.phi) |in| { + const v = rs.map(in.value); + if (v == p or v == same) continue; + if (same != .none) { + trivial = false; + break; + } + same = v; + } + if (trivial and same != .none) { + repl.put(p.index(), same); + changed = true; + } + } + } + // Rewrite every block: drop promoted loads / stores / locals, place the + // remaining phis first, map operands. + for (f.blocks.items, 0..) |*blk, bi| { + var out: std.ArrayList(Ref) = .empty; + for (phis[bi].items) |p| if (!repl.contains(p.r.index())) try out.append(a, p.r); + for (blk.insts.items) |r| { + const op = f.inst(r).op; + switch (op) { + .local_var => if (var_of[r.index()] != none) continue, + .load => |p| if (var_of[p.index()] != none) continue, + .store => |s| if (var_of[s.ptr.index()] != none) continue, + else => {}, + } + try out.append(a, r); + } + for (out.items) |r| { + var hit = false; + try forOperands(a, f.inst(r).op, Hit{ .repl = &repl, .hit = &hit }); + if (hit) f.insts.items[r.index()].op = try opt.mapOp(a, f.inst(r).op, rs); + } + blk.insts = out; + blk.term = switch (blk.term) { + .ret => |v| .{ .ret = rs.map(v) }, + .cond_br => |c| .{ .cond_br = .{ .cond = rs.map(c.cond), .then = c.then, .@"else" = c.@"else" } }, + .@"switch" => |s| .{ .@"switch" = .{ .value = rs.map(s.value), .default = s.default, .cases = s.cases } }, + else => blk.term, + }; + } + // The promoted locals are gone (the emitter declares every local_var). + for (pvars.items) |v| f.insts.items[v.index()] = .{ .op = .undef, .ty = f.inst(v).ty }; + try removeDeadPhis(a, f); +} + +/// Drops phis nothing but dead phis uses: phis are live when a non-phi +/// instruction or a terminator uses them, or a live phi does (dead cycles +/// through loop headers go too). +fn removeDeadPhis(a: Allocator, f: *ir.Function) Error!void { + const n = f.insts.items.len; + const live = try a.alloc(bool, n); + @memset(live, false); + var work: std.ArrayList(Ref) = .empty; + const Mark = struct { + f: *const ir.Function, + live: []bool, + work: *std.ArrayList(Ref), + al: Allocator, + pub fn use(c: @This(), x: Ref) void { + if (c.live[x.index()] or c.f.inst(x).op != .phi) return; + c.live[x.index()] = true; + c.work.append(c.al, x) catch {}; + } + }; + const mk = Mark{ .f = f, .live = live, .work = &work, .al = a }; + for (f.blocks.items) |blk| { + for (blk.insts.items) |r| if (f.inst(r).op != .phi) try forOperands(a, f.inst(r).op, mk); + const tr = termOperand(blk.term); + if (tr != .none) mk.use(tr); + } + while (work.pop()) |r| for (f.inst(r).op.phi) |in| mk.use(in.value); + for (f.blocks.items) |*blk| { + var k: usize = 0; + while (k < blk.insts.items.len) { + const r = blk.insts.items[k]; + if (f.inst(r).op == .phi and !live[r.index()]) { + _ = blk.insts.orderedRemove(k); + } else k += 1; + } + } +} diff --git a/src/root.zig b/src/root.zig index a708ff6..a1bcadd 100644 --- a/src/root.zig +++ b/src/root.zig @@ -36,6 +36,7 @@ pub const ir = struct { pub const opt = @import("ir/opt.zig"); pub const split_resources = @import("ir/split_resources.zig"); pub const inline_calls = @import("ir/inline.zig"); + pub const ssa = @import("ir/ssa.zig"); }; pub const sema = struct { diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index 2d09458..8d4ab35 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -226,6 +226,13 @@ const Emitter = struct { /// through them). nonuniform_ids: std.AutoHashMapUnmanaged(Id, void) = .empty, variants: std.ArrayList(struct { fi: u32, bindings: []const Id, id: Id }) = .empty, + /// The current function's block labels, and phi operands (word + /// positions in the functions section) naming values emitted after the + /// phi, patched when the function is done. + labels: []const Id = &.{}, + phi_patches: std.ArrayList(struct { pos: usize, ref: Ref }) = .empty, + /// OpUndef by type. + undef_ids: std.AutoHashMapUnmanaged(TypeId, Id) = .empty, /// The bindings of the function being emitted (a specialization). cur_bindings: []const Id = &.{}, /// Per instruction (current function): resource locals assigned @@ -2131,10 +2138,13 @@ const Emitter = struct { const order = try blockOrder(e.arena, f); const labels = try e.arena.alloc(Id, f.blocks.items.len); for (labels) |*l| l.* = e.b.newId(); + e.labels = labels; + e.phi_patches = .empty; // Constants and parameters first (they may be used in any block). for (f.insts.items, 0..) |inst, i| switch (inst.op) { .constant => |c| e.vals[i] = try e.constant(inst.ty, c), + .undef => e.vals[i] = try e.undefOf(inst.ty), .param => |p| { e.vals[i] = param_ids[p]; if (e.mesh_params.get(.{ f, p })) |kind| try e.mesh_places.put(e.arena, @intCast(i), .{ .kind = kind, .ty = inst.ty }); @@ -2231,9 +2241,22 @@ const Emitter = struct { .discard => try e.b.emit(.functions, .kill, &.{}), } } + const words = e.b.sections.getPtr(.functions).items; + for (e.phi_patches.items) |p| { + words[p.pos] = e.val(p.ref); + if (words[p.pos] == 0) return e.unsupported("internal: a phi names a value that is never emitted", .{}); + } try e.b.emit(.functions, .function_end, &.{}); } + fn undefOf(e: *Emitter, ty: TypeId) Error!Id { + if (e.undef_ids.get(ty)) |id| return id; + const id = e.b.newId(); + try e.b.emit(.types_globals, .undef, &.{ try e.typeId(ty), id }); + try e.undef_ids.put(e.arena, ty, id); + return id; + } + /// For the hull shader's entry wrapper: the patch constant wrapper it /// calls before returning. fn hullEpilogue(e: *Emitter, fn_id: Id) ?Id { @@ -2918,7 +2941,22 @@ const Emitter = struct { try e.b.emit(.functions, .store, &.{ ptr, v }); } else try e.b.emit(.functions, .store, &.{ iface.var_id, v }); }, - .phi => return e.unsupported("phi", .{}), + .undef => {}, + .phi => |ins| { + // Values from back edges are emitted later: patched at the + // end of the function. + const id = e.b.newId(); + var ops: std.ArrayList(u32) = .empty; + try ops.appendSlice(e.arena, &.{ try e.typeId(i.ty), id }); + const base = e.b.sections.getPtr(.functions).items.len + 1; + for (ins) |in| { + const v = e.val(in.value); + if (v == 0) try e.phi_patches.append(e.arena, .{ .pos = base + ops.items.len, .ref = in.value }); + try ops.appendSlice(e.arena, &.{ v, e.labels[in.block.index()] }); + } + try e.b.emit(.functions, .phi, ops.items); + e.vals[ri] = id; + }, } } From 97517cc5b1086a35d983f48ba2944eabfd5164da Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Mon, 2 Nov 2026 08:00:54 +0000 Subject: [PATCH 4/8] SPIR-V: selection controls from [branch] and [flatten] [branch] and [flatten] on if and switch were dropped: every OpSelectionMerge had selection control None, leaving the driver to flatten or keep the branch by its own heuristics. They now become DontFlatten and Flatten, as in dxc (the Hyperion engine's shaders use them 21 times). The IR keeps them on the header block; unrolling and inlining carry them over. --- src/ir/inline.zig | 4 +++- src/ir/ir.zig | 4 ++++ src/ir/lower.zig | 15 +++++++++++++-- src/ir/opt.zig | 2 +- src/spirv/emit.zig | 8 +++++++- 5 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/ir/inline.zig b/src/ir/inline.zig index abb381d..6d69561 100644 --- a/src/ir/inline.zig +++ b/src/ir/inline.zig @@ -283,8 +283,10 @@ fn inlineOne(a: Allocator, f: *ir.Function, bi: u32, pos: usize, args: []const R try f.blocks.items[cont].insts.appendSlice(a, blk.insts.items[pos + 1 ..]); f.blocks.items[cont].term = blk.term; f.blocks.items[cont].merge = blk.merge; + f.blocks.items[cont].selection_control = blk.selection_control; blk.insts.shrinkRetainingCapacity(pos); blk.merge = .none; + blk.selection_control = .none; } // Copies of the callee's blocks and instructions (parameters become @@ -387,7 +389,7 @@ fn inlineOne(a: Allocator, f: *ir.Function, bi: u32, pos: usize, args: []const R .selection => |mb| .{ .selection = B.map(bmap, mb) }, .loop => |l| .{ .loop = .{ .merge = B.map(bmap, l.merge), .@"continue" = B.map(bmap, l.@"continue"), .unroll = l.unroll } }, }; - f.blocks.items[bmap[k]] = .{ .insts = insts, .term = term, .merge = merge }; + f.blocks.items[bmap[k]] = .{ .insts = insts, .term = term, .merge = merge, .selection_control = src.selection_control }; } f.blocks.items[bi].term = .{ .br = @fromBackingInt(@intCast(entry_target)) }; return result; diff --git a/src/ir/ir.zig b/src/ir/ir.zig index c5a50b5..019fc35 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -180,8 +180,12 @@ pub const Block = struct { insts: std.ArrayList(Ref) = .empty, term: Terminator = .none, merge: Merge = .none, + /// `[flatten]` / `[branch]` on the selection this block heads. + selection_control: SelectionControl = .none, }; +pub const SelectionControl = enum { none, flatten, dont_flatten }; + pub const Param = struct { name: []const u8, ty: TypeId, diff --git a/src/ir/lower.zig b/src/ir/lower.zig index bf02060..3711239 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -565,6 +565,7 @@ const Lowerer = struct { const merge = try l.b.newBlock(); const else_b = if (x.@"else" != null) try l.b.newBlock() else merge; l.b.f.block(l.b.cur).merge = .{ .selection = merge }; + l.b.f.block(l.b.cur).selection_control = selectionControl(st.attrs); l.b.terminate(.{ .cond_br = .{ .cond = cond, .then = then_b, .@"else" = else_b } }); l.b.setBlock(then_b); try l.stmt(x.then); @@ -597,7 +598,7 @@ const Lowerer = struct { l.b.terminate(.{ .br = target.cont }); }, .discard => l.b.terminate(.discard), - .@"switch" => |x| try l.switchStmt(x), + .@"switch" => |x| try l.switchStmt(x, st.attrs), .case, .default => { l.unsupported(st.loc, "case labels outside a switch body", .{}); return error.Unsupported; @@ -607,7 +608,16 @@ const Lowerer = struct { /// `switch`: the header branches to one block per label (labels in a /// row get their own, falling through); `break` goes to the merge. - fn switchStmt(l: *Lowerer, x: @FieldType(ast.Stmt.Kind, "switch")) Error!void { + /// `[flatten]` / `[branch]` on an `if` or `switch`. + fn selectionControl(attrs: []const ast.Attribute) ir.SelectionControl { + for (attrs) |a| { + if (std.ascii.eqlIgnoreCase(a.name, "flatten")) return .flatten; + if (std.ascii.eqlIgnoreCase(a.name, "branch")) return .dont_flatten; + } + return .none; + } + + fn switchStmt(l: *Lowerer, x: @FieldType(ast.Stmt.Kind, "switch"), attrs: []const ast.Attribute) Error!void { if (x.cond_decl) |d| try l.localDecl(d); const t = l.types(); var cond_ty = x.cond.ty; @@ -648,6 +658,7 @@ const Lowerer = struct { if (sg.value) |v| try cases.append(l.arena, .{ .value = v, .block = sg.block }) else default = sg.block; } l.b.f.block(header).merge = .{ .selection = merge }; + l.b.f.block(header).selection_control = selectionControl(attrs); l.b.terminate(.{ .@"switch" = .{ .value = cond, .default = default, .cases = cases.items } }); const cont: BlockId = if (l.loops.items.len > 0) l.loops.getLast().cont else .none; try l.loops.append(l.arena, .{ .brk = merge, .cont = cont }); diff --git a/src/ir/opt.zig b/src/ir/opt.zig index 4d71ad8..def9e96 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -734,7 +734,7 @@ fn unrollOne(a: Allocator, t: *TypeTable, f: *ir.Function, h: u32, set: []const .selection => |b| .{ .selection = mapBlock(&bmap, b) }, .loop => |l| .{ .loop = .{ .merge = mapBlock(&bmap, l.merge), .@"continue" = mapBlock(&bmap, l.@"continue"), .unroll = l.unroll } }, }; - f.blocks.items[nb] = .{ .insts = insts, .term = term, .merge = mg }; + f.blocks.items[nb] = .{ .insts = insts, .term = term, .merge = mg, .selection_control = src.selection_control }; } entries[iter] = bmap.get(body).?; conts[iter] = bmap.get(cont).?; diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index 8d4ab35..68532eb 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -2199,7 +2199,13 @@ const Emitter = struct { for (blk.insts.items) |r| try e.emitInst(r); switch (blk.merge) { .none => {}, - .selection => |mb| try e.b.emit(.functions, .selection_merge, &.{ labels[mb.index()], 0 }), + // [flatten] / [branch]: SelectionControl Flatten / + // DontFlatten, as in dxc. + .selection => |mb| try e.b.emit(.functions, .selection_merge, &.{ labels[mb.index()], switch (blk.selection_control) { + .none => 0, + .flatten => 1, + .dont_flatten => 2, + } }), // [unroll] / [loop] the IR could not act on are the // driver's to honor (LoopControl Unroll / DontUnroll), as // in dxc. From ab7b1672704d180c1c9e84dcdedf78c1f33cae46 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sun, 1 Nov 2026 21:24:31 -0800 Subject: [PATCH 5/8] DXIL: keep the library prologue's use marks per thread markUses kept the array it marks in a static, which concurrent library compiles under --job shared: one could mark into another's array, or index past its own. Make it thread-local. --- src/dxil/emit.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 90e9663..86f3a9f 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -1237,7 +1237,7 @@ const Emitter = struct { fn markUses(a: Allocator, inst: module.Inst, used: []bool) void { const M = struct { - var u: []bool = &.{}; + threadlocal var u: []bool = &.{}; fn v(_: []const u32, x: Value) Value { if (x == .inst) u[x.inst] = true; return x; From cd951ea29b68be0efbe1007cd884f535d5d29687 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sun, 1 Nov 2026 21:24:32 -0800 Subject: [PATCH 6/8] DXIL: dynamic constant buffer vector indices, library resource arrays, selected resource locals - A constant buffer vector indexed at run time loads the whole vector and selects the component. - Resource arrays in libraries: globals of class arrays, mangled as pointers to their element (as dxc); each access loads its element for createHandleForLib. NonUniform indices put !dx.nonuniform on the getelementptr, so the bitcode writer now writes metadata kinds and instruction attachments. - Array types in mangled names count their dimensions as dxc does. - A resource local assigned different elements of one resource array keeps the element's index and makes the handle where it is read. --- src/dxil/emit.zig | 168 +++++++++++++++++++++++++++++++++++++++---- src/dxil/libinfo.zig | 5 ++ src/dxil/mangle.zig | 8 ++- src/dxil/module.zig | 30 ++++++++ 4 files changed, 196 insertions(+), 15 deletions(-) diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 86f3a9f..f33b9e3 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -59,6 +59,9 @@ const Lowered = union(enum) { /// A local holding a resource (index into Emitter.res_locals): an /// alias of the one resource stored into it. res_local: u32, + /// A local assigned different elements of one resource array (index + /// into Emitter.res_index_locals): it holds the element's index. + res_index_local: u32, /// A RayQuery local (index into Emitter.rq_locals) and a query handle. rq_local: u32, ray_query: Value, @@ -68,8 +71,9 @@ const Lowered = union(enum) { /// far. res_array: struct { res: u32, index: ?Value = null, ty: TypeId }, /// A place in a constant buffer: byte offset plus a dynamic register - /// offset. - cbuf: struct { res: u32, offset: u32 = 0, dyn_regs: ?Value = null, row_major: bool = false }, + /// offset; with `dyn_comp`, the component of the `vec` vector at + /// `offset` that index picks at run time. + cbuf: struct { res: u32, offset: u32 = 0, dyn_regs: ?Value = null, row_major: bool = false, dyn_comp: ?Value = null, vec: TypeId = 0 }, /// A place in a mesh shader output array: the vertex / primitive index /// and a flattened component offset within it. mesh: struct { kind: ir.MeshOutput, index: ?Value = null, offset: u32 = 0, ty: TypeId }, @@ -201,6 +205,9 @@ const Emitter = struct { /// RayQuery locals: the query handle (allocated in the prologue on /// first use, or a copy of another query) and the query type. rq_locals: std.ArrayList(struct { h: ?Value, ty: TypeId }) = .empty, + /// Resource locals holding an element index of resource array `res`: + /// the index's storage, and whether any index stored is NonUniform. + res_index_locals: std.ArrayList(struct { ptr: Ptr, res: u32, nonuniform: bool = false }) = .empty, /// The ResRet of the last texture operation (for status arguments). last_resret: Value = undefined, /// Status values, forwarded through locals within a block: the @@ -510,8 +517,8 @@ const Emitter = struct { // A global per resource, named as dxc mangles it. for (e.resources.items) |*r| { if (r.view) continue; - if (r.count != 1) return e.unsupported("resource arrays in libraries are not supported yet", .{}); const g = m.globals.items[r.global]; + // (Arrays: of the class, all dimensions flattened.) const ty = try e.classType(r.*); const name = if (g.space == .resource) try mangle.global(e.arena, e.t, g.name, g.ty) else g.name; const v = try e.dm.addGlobal(name, ty, 0); @@ -574,6 +581,7 @@ const Emitter = struct { e.nonuniform = .empty; e.res_locals = .empty; e.rq_locals = .empty; + e.res_index_locals = .empty; e.forwarded = .empty; e.status_vals = .empty; e.payload_global = null; @@ -766,6 +774,7 @@ const Emitter = struct { e.nonuniform = .empty; e.res_locals = .empty; e.rq_locals = .empty; + e.res_index_locals = .empty; e.forwarded = .empty; e.status_vals = .empty; e.lib_args = &.{}; @@ -828,6 +837,8 @@ const Emitter = struct { const i32t = try e.dm.intType(32); for (e.resources.items) |*res| { const lg = res.lib_global orelse continue; + // (Arrays: a handle per element access, in arrayElement.) + if (res.count != 1) continue; const gty = e.dm.globals.items[lg].ty; const loaded = try e.addPrologue(gty, .{ .load = .{ .ptr = .{ .global = lg }, .@"align" = 4 } }); try e.lib_removable.put(e.arena, loaded.inst, {}); @@ -1612,6 +1623,10 @@ const Emitter = struct { try e.rq_locals.append(e.arena, .{ .h = null, .ty = i.ty }); return .{ .rq_local = @intCast(e.rq_locals.items.len - 1) }; } + if (isResourceType(e.t, i.ty) and e.t.get(i.ty) != .array) if (e.indexedLocal(f, r)) |ri| { + try e.res_index_locals.append(e.arena, .{ .ptr = try e.alloca(try e.t.scalar(.uint)), .res = ri }); + return .{ .res_index_local = @intCast(e.res_index_locals.items.len - 1) }; + }; // (An array of resources is one alias too: of an array.) if (isResourceType(e.t, i.ty) or e.isResourceArray(i.ty)) { try e.res_locals.append(e.arena, null); @@ -1641,6 +1656,12 @@ const Emitter = struct { }, .rq_local => |k| return .{ .ray_query = try e.rqHandle(k) }, .res_local => |k| return e.res_locals.items[k] orelse return e.unsupported("a resource local read before it is assigned", .{}), + .res_index_local => |k| { + const il = e.res_index_locals.items[k]; + const idx = (try e.loadPtr(il.ptr, try e.t.scalar(.uint))).scalars[0]; + if (il.nonuniform) try e.nonuniform.put(e.arena, idx, {}); + return e.elementHandle(il.res, idx, il.nonuniform); + }, .res_array => |ra| return .{ .res_array = ra }, .texel => |tx| { const res = e.resources.items[tx.res]; @@ -1648,7 +1669,11 @@ const Emitter = struct { if (res.kind == 10) return .{ .scalars = try e.typedBufferLoad(res, tx.coords[0], i.ty) }; return .{ .scalars = try e.textureLoad(res, mip, tx.coords, null, i.ty) }; }, - .cbuf => |c| return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty), + .cbuf => |c| { + const dc = c.dyn_comp orelse return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty); + const whole = (try e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, c.vec)).scalars; + return .{ .scalars = try e.arena.dupe(Value, &.{try e.pickComponent(whole, dc, i.ty)}) }; + }, .buf => |b| { const mat = b.mat orelse return .{ .scalars = try e.structuredLoad(e.resources.items[b.res], b.index, b.offset, b.dyn, b.row_major, i.ty) }; const m = e.t.get(mat.ty).matrix; @@ -1687,6 +1712,15 @@ const Emitter = struct { e.rq_locals.items[frame.vals[s.ptr.index()].rq_local].h = v.ray_query; return .none; } + if (frame.vals[s.ptr.index()] == .res_index_local) { + const il = &e.res_index_locals.items[frame.vals[s.ptr.index()].res_index_local]; + const acc = resourceElement(f, s.value).?; + const g = f.inst(acc.base).op.global; + const elem = try e.arrayIndex(frame, .{ .res = il.res, .ty = e.m.globals.items[g].ty }, acc.indices); + if (elem.nonuniform) il.nonuniform = true; + try e.storePtr(il.ptr, &.{elem.ra.index orelse try e.i32Const(0)}, try e.t.scalar(.uint)); + return .none; + } if (frame.vals[s.ptr.index()] == .res_local) { const slot = &e.res_locals.items[frame.vals[s.ptr.index()].res_local]; const h = frame.vals[s.value.index()]; @@ -3116,9 +3150,13 @@ const Emitter = struct { cur = arr.elem; }, .vector => |v| { - if (xi.op != .constant) return e.unsupported("dynamic indexing of constant buffer vectors", .{}); - c.offset += @as(u32, @intCast(xi.op.constant.int)) * storageScalar(v.elem).size(); cur = try e.t.scalar(v.elem); + if (xi.op != .constant) { + c.dyn_comp = (try e.scalars(frame, x))[0]; + c.vec = try e.t.vector(v.elem, v.len); + continue; + } + c.offset += @as(u32, @intCast(xi.op.constant.int)) * storageScalar(v.elem).size(); }, .matrix => |mt| { if (xi.op != .constant) return e.unsupported("dynamic indexing of constant buffer matrices", .{}); @@ -3193,6 +3231,18 @@ const Emitter = struct { return .{ .scalars = out }; } + /// Component `idx` (a dynamic index) of `vals`: a chain of selects. + fn pickComponent(e: *Emitter, vals: []const Value, idx: Value, ty: TypeId) Error!Value { + const i1t = try e.dm.intType(1); + const dty = try e.scalarTy(e.compOf(ty)); + var acc = vals[0]; + for (vals[1..], 1..) |v, k| { + const is_k = try e.add(i1t, .{ .cmp = .{ .pred = 32, .lhs = idx, .rhs = try e.i32Const(@intCast(k)) } }); + acc = try e.select(is_k, v, acc, dty); + } + return acc; + } + /// The scalar type of flattened component `k` of `ty`. fn componentType(e: *Emitter, ty: TypeId, k: u32) Error!TypeId { switch (e.t.get(ty)) { @@ -3218,6 +3268,59 @@ const Emitter = struct { /// `array[i]...` on a resource array: a sub-array, or the element's /// handle (created here, at register lower bound + flattened index). fn arrayElement(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "res_array"), indices: []const Ref) Error!Lowered { + const elem = try e.arrayIndex(frame, start, indices); + if (e.t.get(elem.ra.ty) == .array) return .{ .res_array = elem.ra }; + return e.elementHandle(elem.ra.res, elem.ra.index orelse try e.i32Const(0), elem.nonuniform); + } + + /// The resource array global behind `v`, an element of it (possibly + /// loaded), and the indices; null for anything else. + fn resourceElement(f: *const ir.Function, v: Ref) ?@FieldType(ir.Op, "access") { + var x = v; + while (f.inst(x).op == .load) x = f.inst(x).op.load; + if (f.inst(x).op != .access) return null; + const acc = f.inst(x).op.access; + var base = acc.base; + while (f.inst(base).op == .load) base = f.inst(base).op.load; + if (f.inst(base).op != .global) return null; + return .{ .base = base, .indices = acc.indices }; + } + + /// For a resource local of `f`, the resource array whose elements are + /// all that is stored into it, when they are different ones (as in a + /// switch picking a texture): such a local holds the element's index. + fn indexedLocal(e: *Emitter, f: *const ir.Function, local: Ref) ?u32 { + var first: ?@FieldType(ir.Op, "access") = null; + var first_value: Ref = .none; + var distinct = false; + for (f.insts.items) |st| { + if (st.op != .store or st.op.store.ptr != local) continue; + const acc = resourceElement(f, st.op.store.value) orelse return null; + if (first) |fa| { + if (st.op.store.value != first_value) distinct = true; + if (f.inst(fa.base).op.global != f.inst(acc.base).op.global or fa.indices.len != acc.indices.len) return null; + } else { + first = acc; + first_value = st.op.store.value; + } + } + const fa = first orelse return null; + if (!distinct) return null; + const g = f.inst(fa.base).op.global; + const ri = e.resource_of_global.get(g) orelse return null; + if (e.resources.items[ri].count == 1) return null; + // Indexed down to single resources. + var ty = e.m.globals.items[g].ty; + for (fa.indices) |_| { + if (e.t.get(ty) != .array) return null; + ty = e.t.get(ty).array.elem; + } + if (e.t.get(ty) == .array) return null; + return ri; + } + + /// The flattened index of an element of a resource array. + fn arrayIndex(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "res_array"), indices: []const Ref) Error!struct { ra: @FieldType(Lowered, "res_array"), nonuniform: bool } { var ra = start; const i32t = try e.dm.intType(32); var nonuniform = false; @@ -3236,10 +3339,21 @@ const Emitter = struct { ra.ty = arr.elem; } _ = i32t; - if (e.t.get(ra.ty) == .array) return .{ .res_array = ra }; - const res = e.resources.items[ra.res]; + return .{ .ra = ra, .nonuniform = nonuniform }; + } + + /// A handle for element `index` (flattened) of resource array `ri`. + fn elementHandle(e: *Emitter, ri: u32, index: Value, nonuniform: bool) Error!Lowered { + const res = e.resources.items[ri]; + if (res.lib_global) |lg| { + var view = res; + view.view = true; + view.handle = try e.libArrayHandle(res, lg, index, nonuniform); + try e.resources.append(e.arena, view); + return .{ .handle = @intCast(e.resources.items.len - 1) }; + } const lb = e.binding(res).index; - const idx = try e.intArith(.add, ra.index orelse try e.i32Const(0), try e.i32Const(lb)); + const idx = try e.intArith(.add, index, try e.i32Const(lb)); var view = res; view.view = true; view.handle = try e.makeHandle(res, idx, nonuniform, false); @@ -3247,6 +3361,27 @@ const Emitter = struct { return .{ .handle = @intCast(e.resources.items.len - 1) }; } + /// A library's handle for element `index` of a resource array: of the + /// element loaded from the array's global. + fn libArrayHandle(e: *Emitter, res: Resource, lg: u32, index: Value, nonuniform: bool) Error!Value { + const i32t = try e.dm.intType(32); + const arr_ty = e.dm.globals.items[lg].ty; + const class_ty = e.dm.types.items[arr_ty].array.elem; + const ptr = try e.add(try e.dm.ptrType(class_ty), .{ .gep = .{ .elem = arr_ty, .ptr = .{ .global = lg }, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), index }) } }); + if (nonuniform) { + const blk = e.blocks.items[e.cur].items; + blk[blk.len - 1].inst.md = .{ .kind = try e.dm.mdKind("dx.nonuniform"), .node = try e.dm.mdNode(&.{try e.dm.mdI32(1)}) }; + } + const loaded = try e.add(class_ty, .{ .load = .{ .ptr = ptr, .@"align" = 4 } }); + const struct_name = e.dm.types.items[class_ty].@"struct".name; + const create = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.createHandleForLib.{s}", .{struct_name}), e.handle_ty, &.{ i32t, class_ty }, .nounwind_readonly); + const h = try e.callOp(create, e.handle_ty, &.{ try e.i32Const(160), loaded }); + if (!e.self_sm66()) return h; + const props_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.ResourceProperties", .elems = &.{ i32t, i32t } } }); + const annotate = try e.dxOp("dx.op.annotateHandle", e.handle_ty, &.{ i32t, e.handle_ty, props_ty }, .nounwind_readnone); + return e.callOp(annotate, e.handle_ty, &.{ try e.i32Const(216), h, try e.propertiesConst(res) }); + } + fn constIntOf(e: *Emitter, v: Value) ?i64 { if (v != .constant) return null; return switch (e.dm.constants.items[v.constant].kind) { @@ -5197,13 +5332,20 @@ const Emitter = struct { const f = &e.dm.functions.items[lf.func]; const name = try b.string(lf.name); const unmangled = try b.string(lf.unmangled); - // Resources whose globals the function loads, in table order. + // Resources whose globals the function loads (or indexes, for + // arrays), in table order. var used: std.ArrayList(u32) = .empty; - for (f.insts.items) |inst| if (inst.op == .load and inst.op.load.ptr == .global) { - if (res_index.get(inst.op.load.ptr.global)) |ri| { + for (f.insts.items) |inst| { + const ptr = switch (inst.op) { + .load => |l| l.ptr, + .gep => |g| g.ptr, + else => continue, + }; + if (ptr != .global) continue; + if (res_index.get(ptr.global)) |ri| { if (std.mem.indexOfScalar(u32, used.items, ri) == null) try used.append(e.arena, ri); } - }; + } std.mem.sort(u32, used.items, {}, std.sort.asc(u32)); const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref; const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref; diff --git a/src/dxil/libinfo.zig b/src/dxil/libinfo.zig index 10cdf13..e36c586 100644 --- a/src/dxil/libinfo.zig +++ b/src/dxil/libinfo.zig @@ -306,6 +306,11 @@ fn handleRes(m: *const module.Module, f: *const module.Function, o: Options, h: }, .load => |l| { if (l.ptr == .global) return o.globals[l.ptr.global]; + // An element of a resource array global. + if (l.ptr == .inst) switch (f.insts.items[l.ptr.inst].op) { + .gep => |g| if (g.ptr == .global) return o.globals[g.ptr.global], + else => {}, + }; return null; }, else => return null, diff --git a/src/dxil/mangle.zig b/src/dxil/mangle.zig index ffccf9b..58c2224 100644 --- a/src/dxil/mangle.zig +++ b/src/dxil/mangle.zig @@ -69,7 +69,11 @@ pub fn global(a: Allocator, t: *TypeTable, name: []const u8, ty: TypeId) Allocat var names: Names = .{}; try names.add(a, name); try out.print(a, "\x01?{s}@@3", .{name}); - try typeCode(a, t, ty, &out, &names); + // An array global: a pointer to its element. + if (t.get(ty) == .array) { + try out.appendSlice(a, "PA"); + try typeCode(a, t, t.get(ty).array.elem, &out, &names); + } else try typeCode(a, t, ty, &out, &names); try out.append(a, 'A'); return out.items; } @@ -137,7 +141,7 @@ fn typeCode(a: Allocator, t: *TypeTable, ty: TypeId, out: *std.ArrayList(u8), na var et = ty; while (t.get(et) == .array) : (et = t.get(et).array.elem) try dims.append(a, t.get(et).array.len); try out.append(a, 'Y'); - try number(a, dims.items.len - 1, out); + try number(a, dims.items.len, out); for (dims.items) |d| try number(a, d, out); try typeCode(a, t, et, out, names); }, diff --git a/src/dxil/module.zig b/src/dxil/module.zig index d624572..c107fd2 100644 --- a/src/dxil/module.zig +++ b/src/dxil/module.zig @@ -106,6 +106,9 @@ pub const Inst = struct { extractelement: struct { vec: Value, index: Value }, insertelement: struct { vec: Value, val: Value, index: Value }, }, + /// An attached metadata node (`kind` from Module.mdKind), as + /// `!dx.nonuniform` on a resource array's getelementptr. + md: ?struct { kind: u32, node: MdId } = null, }; pub const Function = struct { @@ -136,6 +139,8 @@ pub const Module = struct { globals: std.ArrayList(GlobalVar) = .empty, metadata: std.ArrayList(Metadata) = .empty, named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty, + /// Instruction metadata kinds, by id. + md_kinds: std.ArrayList([]const u8) = .empty, pub fn init(gpa: Allocator) Module { return .{ .arena = .init(gpa) }; @@ -250,6 +255,13 @@ pub const Module = struct { return @intCast(m.metadata.items.len - 1); } + /// The id of an instruction metadata kind. + pub fn mdKind(m: *Module, name: []const u8) !u32 { + for (m.md_kinds.items, 0..) |k, i| if (std.mem.eql(u8, k, name)) return @intCast(i); + try m.md_kinds.append(m.allocator(), try m.allocator().dupe(u8, name)); + return @intCast(m.md_kinds.items.len - 1); + } + pub fn addNamedMetadata(m: *Module, name: []const u8, nodes: []const MdId) !void { const a = m.allocator(); try m.named_metadata.append(a, .{ .name = try a.dupe(u8, name), .nodes = try a.dupe(MdId, nodes) }); @@ -270,6 +282,7 @@ const block_constants = 11; const block_function = 12; const block_value_symtab = 14; const block_metadata = 15; +const block_metadata_attachment = 16; const block_type = 17; const Encoder = struct { @@ -371,6 +384,12 @@ const Encoder = struct { } try e.writeConstants(); try e.writeMetadata(); + if (e.m.md_kinds.items.len != 0) { + // METADATA_KIND: [id, name...] + try w.enterBlock(block_metadata, 3); + for (e.m.md_kinds.items, 0..) |k, id| try w.recordString(6, &.{id}, k); + try w.endBlock(); + } try e.writeSymtab(); for (e.m.functions.items) |*f| { if (f.num_blocks != 0) try e.writeFunction(f); @@ -681,6 +700,17 @@ const Encoder = struct { } if (e.m.types.items[inst.ty] != .void) inst_id += 1; } + // METADATA_ATTACHMENT: [instruction index, (kind, node)...] + var any_md = false; + for (f.insts.items) |inst| any_md = any_md or inst.md != null; + if (any_md) { + try w.enterBlock(block_metadata_attachment, 3); + for (f.insts.items, 0..) |inst, k| if (inst.md) |md| { + try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node }); + try e.rec(11); + }; + try w.endBlock(); + } try w.endBlock(); } }; From dce6d0eadec621fa44069f34a1139c65b5f13432 Mon Sep 17 00:00:00 2001 From: peterino2 Date: Mon, 2 Nov 2026 00:22:23 -0800 Subject: [PATCH 7/8] DXIL: promote locals to SSA, elide by-value array copies Locals were left as allocas, so every access was a store or a reload. Glide's GlimmerProbeTrace came out as 2.3 MB of DXIL (DXC: 155 KB) that AMD's driver took over ten minutes to build into a pipeline, and the game stalled on a black screen. - promote.zig: SROA + mem2reg over the finished function. An alloca whose accesses are loads and stores through constant indices becomes one SSA variable per element, with phis at the iterated dominance frontiers. Trivial phis fold away, and dead instructions go. Locals read before they are written read zero, since the validator rejects reads of undef. - Dynamically indexed locals pin only what the index can reach. The emitter records each dynamic getelementptr's range (the indexed array's extent), and the rest of the local is still promoted. - A by-value array parameter that the callee only reads aliases the caller's storage when the argument was loaded from a local in the same block with no write since. This drops the per-call copies. - Declarations that lose their last call are pruned before writing, since the validator rejects unused external functions. On Glide's 400 DXIL compiles, total output goes from 34.5 MB to 6.8 MB (DXC: 6.1 MB), and GlimmerProbeTrace from 2.3 MB to 374 KB. Its pipeline now builds in about 5 s. All 400 objects pass DXC 1.8.2505's validator (checked with a copy built to claim validator 1.8), and Glide renders on zdxc. --- src/dxil/emit.zig | 169 ++++++++- src/dxil/promote.zig | 796 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 958 insertions(+), 7 deletions(-) create mode 100644 src/dxil/promote.zig diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index f33b9e3..cb0a22f 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -1,8 +1,9 @@ //! IR -> DXIL. Everything is inlined into the entry function while //! emitting (each call instantiates its callee); values are scalarized -//! (DXIL has no vectors); locals become flattened `[N x scalar]` allocas; -//! resources become handles created on entry. The result is a signed DXIL -//! container. +//! (DXIL has no vectors); locals become flattened `[N x scalar]` allocas, +//! which promote.zig turns into SSA values where they are not indexed +//! dynamically; resources become handles created on entry. The result is a +//! signed DXIL container. const std = @import("std"); const Allocator = std.mem.Allocator; @@ -21,6 +22,8 @@ const rdat = @import("rdat.zig"); const linalg_info = @import("linalg_info.zig"); const libinfo = @import("libinfo.zig"); const rootsig = @import("rootsig.zig"); +const promote = @import("promote.zig"); +const opt = @import("../ir/opt.zig"); const TypeId = types.TypeId; const TypeTable = types.TypeTable; @@ -102,6 +105,9 @@ const Ptr = struct { scalar_ty: DType, offset_const: u32 = 0, offset_dyn: ?Value = null, + /// The components `offset_dyn` can reach: the extent of the array (or + /// vector or matrix) it indexes. Null when not known. + dyn_range: ?[2]u32 = null, /// bools are stored as i32. bool_storage: bool = false, /// Mixed 32-bit component types share i32 storage (floats bitcast). @@ -149,6 +155,13 @@ const Frame = struct { rets: std.ArrayList(struct { block: u32, vals: []const Value }) = .empty, /// The resources a function returns (every return the same ones). ret_res: ?[]const Lowered = null, + /// Loads of locals: where from, and the block and write count when + /// read, so a call right after can pass the local itself. + load_srcs: std.AutoHashMapUnmanaged(u32, struct { ptr: Ptr, block: u32, writes: u32 }) = .empty, + /// By-value parameters passed as the caller's storage (see paramCopies). + param_ptrs: []const ?Ptr = &.{}, + /// paramCopies of the function, when some parameter is aliased. + param_copies: []const u32 = &.{}, }; const PInst = struct { inst: module.Inst, id: u32 }; @@ -214,6 +227,13 @@ const Emitter = struct { /// validator wants CheckAccessFullyMapped's operand to be one. status_vals: std.AutoHashMapUnmanaged(Value, void) = .empty, forwarded: std.AutoHashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }) = .empty, + /// Dynamically indexed getelementptrs into locals (by id) and the + /// components they can reach, for promote.run. + dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty, + /// Instructions emitted so far that may write memory. + writes: u32 = 0, + /// paramCopies per IR function. + param_copies: std.AutoHashMapUnmanaged(u32, []const u32) = .empty, uses_barycentrics: bool = false, uses_sampler_heap: bool = false, @@ -262,6 +282,13 @@ const Emitter = struct { fn add(e: *Emitter, ty: DType, op: @FieldType(module.Inst, "op")) Error!Value { const id = e.next_id; e.next_id += 1; + switch (op) { + .store, .atomicrmw, .cmpxchg => e.writes += 1, + .call => |c| if (!std.mem.startsWith(u8, e.dm.functions.items[c.callee].name, "dx.op.")) { + e.writes += 1; + }, + else => {}, + } try e.blocks.items[e.cur].append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id }); return .{ .inst = id }; } @@ -634,6 +661,9 @@ const Emitter = struct { return x.func < y.func; } }.lt); + if (try promote.pruneDeclarations(e.arena, &e.dm)) |index| for (funcs.items) |*lf| { + lf.func = index[lf.func]; + }; const bitcode = try e.writeLibraryModule(funcs.items); defer gpa.free(bitcode); return e.assembleLibrary(gpa, funcs.items, bitcode); @@ -1221,6 +1251,11 @@ const Emitter = struct { 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 (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap)); + var ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty; + var it = e.dyn_ranges.iterator(); + while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*); + e.dyn_ranges.clearRetainingCapacity(); + try promote.run(e.arena, &e.dm, func, &ranges); } /// Drops removable prologue instructions nothing uses (repeatedly: a @@ -1332,6 +1367,12 @@ const Emitter = struct { /// Emits function `fi` inline at the current block with `args`; returns /// its result components and leaves the current block after the call. fn inlineCall(e: *Emitter, fi: u32, args: []const Lowered) Error![]const Value { + return e.inlineCallAliased(fi, args, &.{}); + } + + /// `aliases[k]`, when set, is caller storage holding by-value argument + /// `k`, which the callee may read in place of a copy (see argAliases). + fn inlineCallAliased(e: *Emitter, fi: u32, args: []const Lowered, aliases: []const ?Ptr) Error![]const Value { const f = e.m.functions.items[fi]; var frame: Frame = .{ .f = f, @@ -1339,6 +1380,11 @@ const Emitter = struct { .params = args, .blocks = try e.arena.alloc(?u32, f.blocks.items.len), }; + for (aliases) |al| if (al != null) { + frame.param_ptrs = aliases; + frame.param_copies = try e.paramCopies(fi); + break; + }; @memset(frame.vals, .none); @memset(frame.blocks, null); const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and (fi == e.entry.wrapper or fi == e.entry.patch_wrapper); @@ -1368,6 +1414,87 @@ const Emitter = struct { return &.{}; } + /// Caller storage the by-value arguments of a call to `fi` can be read + /// from: an argument loaded from a local in the same block, with no + /// write since. Calls with out / inout arguments get none (the callee + /// could write the local through one while reading it through another). + fn argAliases(e: *Emitter, frame: *const Frame, fi: u32, refs: []const Ref) Error![]const ?Ptr { + const params = e.m.functions.items[fi].params; + for (params) |p| if (p.by_ref) return &.{}; + const out = try e.arena.alloc(?Ptr, refs.len); + for (refs, params, out) |r, p, *o| { + o.* = null; + if (e.t.get(p.ty) != .array) continue; + const src = frame.load_srcs.get(r.index()) orelse continue; + if (src.block == e.cur and src.writes == e.writes) o.* = src.ptr; + } + return out; + } + + /// For each instruction of IR function `fi`: the parameter a + /// `local_var` only ever holds a copy of (stored once, from that + /// by-value parameter, and otherwise only read), else maxInt. + fn paramCopies(e: *Emitter, fi: u32) Error![]const u32 { + const gop = try e.param_copies.getOrPut(e.arena, fi); + if (gop.found_existing) return gop.value_ptr.*; + const none = std.math.maxInt(u32); + const f = e.m.functions.items[fi]; + const n = f.insts.items.len; + // The local each pointer is into. + const root = try e.arena.alloc(u32, n); + @memset(root, none); + var changed = true; + while (changed) { + changed = false; + for (f.insts.items, 0..) |inst, k| { + const want: u32 = switch (inst.op) { + .local_var => @intCast(k), + .access => |x| root[x.base.index()], + else => none, + }; + if (want != root[k]) { + root[k] = want; + changed = true; + } + } + } + const out = try e.arena.alloc(u32, n); + @memset(out, none); + const ok = try e.arena.alloc(bool, n); + @memset(ok, true); + const Use = struct { + root: []const u32, + ok: []bool, + pub fn map(s: @This(), x: Ref) Ref { + if (x != .none and s.root[x.index()] != none) s.ok[s.root[x.index()]] = false; + return x; + } + }; + for (f.insts.items) |inst| switch (inst.op) { + .local_var => {}, + .load => {}, + .access => |x| for (x.indices) |ix| { + _ = (Use{ .root = root, .ok = ok }).map(ix); + }, + .store => |x| { + _ = (Use{ .root = root, .ok = ok }).map(x.value); + const l = root[x.ptr.index()]; + if (l == none) continue; + const v = f.inst(x.value).op; + if (x.ptr.index() == l and v == .param and !f.params[v.param].by_ref and out[l] == none) { + out[l] = v.param; + } else ok[l] = false; + }, + else => _ = try opt.mapOp(e.arena, inst.op, Use{ .root = root, .ok = ok }), + }; + // Terminators returning pointers do not occur. + for (out, ok) |*o, good| if (!good) { + o.* = none; + }; + gop.value_ptr.* = out; + return out; + } + /// A call of `[noinline]` function `fi` (module function `func`), as /// exportSignature passes values: out / inout values and structs /// through temporaries. @@ -1640,6 +1767,10 @@ const Emitter = struct { const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } }); return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } }; } + if (frame.param_copies.len > 0) { + const k = frame.param_copies[r.index()]; + if (k != std.math.maxInt(u32)) if (frame.param_ptrs[k]) |alias| return .{ .ptr = alias }; + } return .{ .ptr = try e.alloca(i.ty) }; }, .load => |p| switch (frame.vals[p.index()]) { @@ -1699,12 +1830,19 @@ const Emitter = struct { } return .{ .scalars = out }; }, - .ptr => |ptr| return e.loadPtr(ptr, i.ty), + .ptr => |ptr| { + if (ptr.addr_space == 0 and localRoot(f, p)) try frame.load_srcs.put(e.arena, r.index(), .{ .ptr = ptr, .block = e.cur, .writes = e.writes }); + return e.loadPtr(ptr, i.ty); + }, .typed => |tp| return e.typedLoad(tp, i.ty), .mesh => return e.unsupported("reading mesh shader outputs is not supported", .{}), else => return e.unsupported("internal: load from a non-pointer", .{}), }, .store => |s| { + if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) { + const k = f.inst(s.value).op.param; + if (frame.param_copies[s.ptr.index()] == k and frame.param_ptrs[k] != null) return .none; + }; if (frame.vals[s.ptr.index()] == .rq_local) { // A copy of a query is the same query. const v = frame.vals[s.value.index()]; @@ -1830,6 +1968,7 @@ const Emitter = struct { } else { const idx = (try e.scalars(frame, x))[0]; const scaled = if (s == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(s) } }); + if (ptr.offset_dyn == null) ptr.dyn_range = .{ ptr.offset_const, ptr.offset_const + try e.flatCount(cur) }; ptr.offset_dyn = if (ptr.offset_dyn) |d| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = scaled } }) else scaled; } cur = elem; @@ -1964,7 +2103,7 @@ const Emitter = struct { if (e.lib_calls.get(c.func)) |func| return e.libCall(frame, c.func, func, c.args); const args = try e.arena.alloc(Lowered, c.args.len); for (c.args, args) |a, *o| o.* = frame.vals[a.index()]; - const res = try e.inlineCall(c.func, args); + const res = try e.inlineCallAliased(c.func, args, try e.argAliases(frame, c.func, c.args)); // Functions returning resources (or structs of them). if (isResourceType(e.t, i.ty) and !isRayQuery(e.t, i.ty)) { const rr = e.last_ret_res orelse return e.unsupported("a function returning a resource with no return value", .{}); @@ -2094,6 +2233,7 @@ const Emitter = struct { const konst: ?u32 = if (xi.op == .constant) @intCast(xi.op.constant.int) else null; var data_off: u32 = 0; var data_dyn: ?Value = null; + var data_extent: u32 = 0; switch (e.t.get(cur)) { .@"struct" => |st| { const k = konst.?; @@ -2114,6 +2254,7 @@ const Emitter = struct { const idx = (try e.scalars(frame, x))[0]; const n = try e.flatCount(arr.elem); data_dyn = if (n == 1) idx else try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .mul, .lhs = idx, .rhs = try e.i32Const(n) } }); + data_extent = try e.flatCount(cur); } cur = arr.elem; }, @@ -2122,7 +2263,10 @@ const Emitter = struct { if (data) |*d| switch (d.*) { .ptr => |*ptr| { ptr.offset_const += data_off; - if (data_dyn) |dd| ptr.offset_dyn = if (ptr.offset_dyn) |old| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = old, .rhs = dd } }) else dd; + if (data_dyn) |dd| { + if (ptr.offset_dyn == null) ptr.dyn_range = .{ ptr.offset_const, ptr.offset_const + data_extent }; + ptr.offset_dyn = if (ptr.offset_dyn) |old| try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = old, .rhs = dd } }) else dd; + } }, .typed => try path.append(e.arena, (try e.scalars(frame, x))[0]), else => {}, @@ -2300,7 +2444,9 @@ const Emitter = struct { var idx = try e.i32Const(ptr.offset_const + c); if (ptr.offset_dyn) |d| idx = try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = idx } }); const pt = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } }); - return e.add(pt, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), idx }) } }); + const gep = try e.add(pt, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), idx }) } }); + if (ptr.offset_dyn != null) if (ptr.dyn_range) |r| try e.dyn_ranges.put(e.arena, gep.inst, r); + return gep; } fn convertScalar(e: *Emitter, v: Value, from: Scalar, to: Scalar) Error!Value { @@ -5501,6 +5647,7 @@ const Emitter = struct { try dm.addNamedMetadata("dx.shaderModel", &.{sm}); if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r}); try dm.addNamedMetadata("dx.entryPoints", &.{entry_md}); + _ = try promote.pruneDeclarations(e.arena, dm); return dm.writeBitcode(dm.arena.child_allocator); } @@ -5700,3 +5847,11 @@ fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool { } return seen; } + +/// Whether pointer `p` is into a function's own local (not a global or a +/// parameter's storage). +fn localRoot(f: *const ir.Function, p: Ref) bool { + var x = p; + while (f.inst(x).op == .access) x = f.inst(x).op.access.base; + return f.inst(x).op == .local_var; +} diff --git a/src/dxil/promote.zig b/src/dxil/promote.zig new file mode 100644 index 0000000..560bd54 --- /dev/null +++ b/src/dxil/promote.zig @@ -0,0 +1,796 @@ +//! Promotes locals from memory to SSA values, as LLVM's SROA and mem2reg do +//! for dxc. The emitter gives every local a flattened `[N x scalar]` alloca +//! (or a scalar one); an alloca whose every access is a load or store, +//! directly or through a getelementptr with constant indices, becomes one +//! SSA variable per element, with phis where control flow merges. Locals +//! indexed dynamically stay in memory, but only the components the dynamic +//! index can reach (`dyn`, from the emitter: the indexed array's extent); +//! the rest of such a local is still promoted. Locals used any other way +//! stay in memory. +//! +//! The phis go at the iterated dominance frontiers of the stores (Cytron et +//! al.), dominators by Cooper, Harvey and Kennedy's iteration. Phis whose +//! inputs are all one value, and phis nothing reads, are removed again. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const module = @import("module.zig"); + +const Value = module.Value; +const Inst = module.Inst; +const TypeId = module.TypeId; + +const none = std.math.maxInt(u32); + +const Role = enum { load_ptr, store_ptr, gep_base, other }; + +const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child; + +/// Visits each operand of `inst` (with the way it is used) through +/// `ctx.visit(value, role) Value`. With `write`, the results replace the +/// operands, in newly allocated slices where the operands are slices. +fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void { + const S = struct { + fn one(c: anytype, v: *Value, role: Role) void { + const r = c.visit(v.*, role); + if (write) v.* = r; + } + fn many(al: Allocator, c: anytype, vs: *[]const Value) Allocator.Error!void { + if (!write) { + for (vs.*) |v| _ = c.visit(v, .other); + return; + } + const out = try al.alloc(Value, vs.len); + for (vs.*, out) |v, *o| o.* = c.visit(v, .other); + vs.* = out; + } + }; + switch (inst.op) { + .ret => |*v| if (v.*) |*x| S.one(ctx, x, .other), + .br => |*b| if (b.cond) |*c| S.one(ctx, c, .other), + .@"switch" => |*sw| S.one(ctx, &sw.cond, .other), + .call => |*c| try S.many(a, ctx, &c.args), + .binop => |*b| { + S.one(ctx, &b.lhs, .other); + S.one(ctx, &b.rhs, .other); + }, + .cast => |*c| S.one(ctx, &c.val, .other), + .cmp => |*c| { + S.one(ctx, &c.lhs, .other); + S.one(ctx, &c.rhs, .other); + }, + .select => |*s| { + S.one(ctx, &s.cond, .other); + S.one(ctx, &s.t, .other); + S.one(ctx, &s.f, .other); + }, + .extractvalue => |*x| S.one(ctx, &x.agg, .other), + .phi => |*p| { + if (!write) { + for (p.incoming) |in| _ = ctx.visit(in.val, .other); + } else { + const out = try a.alloc(Edge, p.incoming.len); + for (p.incoming, out) |in, *o| o.* = .{ .val = ctx.visit(in.val, .other), .block = in.block }; + p.incoming = out; + } + }, + .alloca => |*x| S.one(ctx, &x.size, .other), + .load => |*x| S.one(ctx, &x.ptr, .load_ptr), + .store => |*x| { + S.one(ctx, &x.ptr, .store_ptr); + S.one(ctx, &x.val, .other); + }, + .gep => |*x| { + S.one(ctx, &x.ptr, .gep_base); + try S.many(a, ctx, &x.indices); + }, + .atomicrmw => |*x| { + S.one(ctx, &x.ptr, .other); + S.one(ctx, &x.val, .other); + }, + .cmpxchg => |*x| { + S.one(ctx, &x.ptr, .other); + S.one(ctx, &x.cmp, .other); + S.one(ctx, &x.new, .other); + }, + .@"unreachable" => {}, + .extractelement => |*x| { + S.one(ctx, &x.vec, .other); + S.one(ctx, &x.index, .other); + }, + .insertelement => |*x| { + S.one(ctx, &x.vec, .other); + S.one(ctx, &x.val, .other); + S.one(ctx, &x.index, .other); + }, + } +} + +fn isTerminator(inst: Inst) bool { + return switch (inst.op) { + .ret, .br, .@"switch", .@"unreachable" => true, + else => false, + }; +} + +fn isScalar(m: *const module.Module, ty: TypeId) bool { + return switch (m.types.items[ty]) { + .half, .float, .double, .int => true, + else => false, + }; +} + +/// `dyn` maps the dynamically indexed getelementptrs into locals to the +/// 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 { + const f = &m.functions.items[func]; + const insts = f.insts.items; + const n: u32 = @intCast(insts.len); + const nb = f.num_blocks; + if (n == 0 or nb == 0) return; + + // Blocks: instruction ranges, successors and predecessors (one entry + // per edge, so a switch's repeated target counts once per case). + const block_start = try a.alloc(u32, nb + 1); + const block_of = try a.alloc(u32, n); + { + var b: u32 = 0; + block_start[0] = 0; + for (insts, 0..) |inst, i| { + if (b >= nb) return; // not the block layout this pass expects + block_of[i] = b; + if (isTerminator(inst)) { + b += 1; + block_start[b] = @intCast(i + 1); + } + } + if (b != nb) return; + } + const succ_off = try a.alloc(u32, nb + 1); + var succs: std.ArrayList(u32) = .empty; + for (0..nb) |b| { + succ_off[b] = @intCast(succs.items.len); + switch (insts[block_start[b + 1] - 1].op) { + .br => |br| { + try succs.append(a, br.then); + if (br.@"else") |e| try succs.append(a, e); + }, + .@"switch" => |sw| { + try succs.append(a, sw.default); + for (sw.cases) |c| try succs.append(a, c.block); + }, + else => {}, + } + } + succ_off[nb] = @intCast(succs.items.len); + const pred_off = try a.alloc(u32, nb + 1); + @memset(pred_off, 0); + for (succs.items) |s| pred_off[s + 1] += 1; + for (1..nb + 1) |b| pred_off[b] += pred_off[b - 1]; + const preds = try a.alloc(u32, succs.items.len); + { + const fill = try a.dupe(u32, pred_off[0..nb]); + for (0..nb) |b| for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| { + preds[fill[s]] = @intCast(b); + fill[s] += 1; + }; + } + + // Reverse postorder from the entry; unreachable blocks stay `none`. + const rpo_index = try a.alloc(u32, nb); + @memset(rpo_index, none); + const rpo = try a.alloc(u32, nb); + var nr: u32 = 0; + { + const post = try a.alloc(u32, nb); + var np: u32 = 0; + const seen = try a.alloc(bool, nb); + @memset(seen, false); + const Frame = struct { b: u32, next: u32 }; + var stack: std.ArrayList(Frame) = .empty; + try stack.append(a, .{ .b = 0, .next = succ_off[0] }); + seen[0] = true; + while (stack.items.len > 0) { + const top = &stack.items[stack.items.len - 1]; + if (top.next < succ_off[top.b + 1]) { + const s = succs.items[top.next]; + top.next += 1; + if (!seen[s]) { + seen[s] = true; + try stack.append(a, .{ .b = s, .next = succ_off[s] }); + } + } else { + post[np] = top.b; + np += 1; + _ = stack.pop(); + } + } + for (0..np) |k| { + rpo[k] = post[np - 1 - k]; + rpo_index[rpo[k]] = @intCast(k); + } + nr = np; + } + + // Immediate dominators. + const idom = try a.alloc(u32, nb); + @memset(idom, none); + idom[0] = 0; + { + var changed = true; + while (changed) { + changed = false; + for (rpo[1..nr]) |b| { + var new: u32 = none; + for (preds[pred_off[b]..pred_off[b + 1]]) |p| { + if (idom[p] == none) continue; + if (new == none) { + new = p; + continue; + } + var x = p; + var y = new; + while (x != y) { + while (rpo_index[x] > rpo_index[y]) x = idom[x]; + while (rpo_index[y] > rpo_index[x]) y = idom[y]; + } + new = x; + } + if (new != idom[b]) { + idom[b] = new; + changed = true; + } + } + } + } + + // Dominance frontiers. + const df = try a.alloc(std.ArrayList(u32), nb); + @memset(df, .empty); + for (rpo[0..nr]) |b| { + const ps = preds[pred_off[b]..pred_off[b + 1]]; + if (ps.len < 2) continue; + for (ps) |p| { + if (rpo_index[p] == none) continue; + var r = p; + while (r != idom[b]) { + const l = &df[r]; + if (l.items.len == 0 or l.items[l.items.len - 1] != b) try l.append(a, b); + r = idom[r]; + } + } + } + + // Candidate allocas: arrays of scalars and scalars. `var_base[i]` is + // the variable of an alloca's element 0, `none` if it stays in memory. + const var_base = try a.alloc(u32, n); + @memset(var_base, none); + const elem_ty = try a.alloc(TypeId, n); + const direct = try a.alloc(bool, n); + for (insts, 0..) |inst, i| switch (inst.op) { + .alloca => |x| switch (m.types.items[x.elem]) { + .array => |arr| if (isScalar(m, arr.elem) and arr.len > 0) { + var_base[i] = 0; + elem_ty[i] = arr.elem; + direct[i] = false; + }, + else => if (isScalar(m, x.elem)) { + var_base[i] = 0; + elem_ty[i] = x.elem; + direct[i] = true; + }, + }, + else => {}, + }; + // getelementptrs of candidates: the alloca and the element they + // address (`none` for a dynamic index, which pins its range). + const gep_alloca = try a.alloc(u32, n); + @memset(gep_alloca, none); + const gep_k = try a.alloc(u32, n); + const Scan = struct { + insts: []const Inst, + var_base: []u32, + direct: []const bool, + gep_alloca: []const u32, + + fn visit(s: *@This(), v: Value, role: Role) Value { + if (v != .inst) return v; + const i = v.inst; + if (s.var_base[i] != none and s.insts[i].op == .alloca) { + const ok = switch (role) { + .gep_base => !s.direct[i], + .load_ptr, .store_ptr => s.direct[i], + .other => false, + }; + if (!ok) s.var_base[i] = none; + } else if (s.gep_alloca[i] != none and role != .load_ptr and role != .store_ptr) { + s.var_base[s.gep_alloca[i]] = none; + } + return v; + } + }; + for (insts, 0..) |inst, i| switch (inst.op) { + .gep => |g| if (g.ptr == .inst and var_base[g.ptr.inst] != none and insts[g.ptr.inst].op == .alloca) { + const al = g.ptr.inst; + if (direct[al]) { + var_base[al] = none; + continue; + } + const k = constIndex(m, g.indices, m.types.items[insts[al].op.alloca.elem].array.len); + if (k) |kk| { + gep_alloca[i] = al; + gep_k[i] = kk; + } else if (dyn.contains(@intCast(i)) and g.indices.len == 2 and constInt(m, g.indices[0]) == 0) { + gep_alloca[i] = al; + gep_k[i] = none; + } else var_base[al] = none; + }, + else => {}, + }; + { + var scan: Scan = .{ .insts = insts, .var_base = var_base, .direct = direct, .gep_alloca = gep_alloca }; + for (insts) |*inst| try operands(false, a, inst, &scan); + } + // Loads and stores must move whole elements of the element type. + for (insts) |inst| { + const ptr, const ty = switch (inst.op) { + .load => |x| .{ x.ptr, inst.ty }, + .store => |x| .{ x.ptr, typeOf(m, f, x.val) }, + else => continue, + }; + if (ptr != .inst) continue; + const al = if (gep_alloca[ptr.inst] != none) gep_alloca[ptr.inst] else ptr.inst; + if (var_base[al] != none and insts[al].op == .alloca and ty != elem_ty[al]) var_base[al] = none; + } + + // Variables. + var nv: u32 = 0; + for (insts, 0..) |inst, i| { + if (inst.op != .alloca or var_base[i] == none) continue; + var_base[i] = nv; + nv += if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len); + } + if (nv == 0) return; + const var_ty = try a.alloc(TypeId, nv); + for (insts, 0..) |inst, i| { + if (inst.op != .alloca or var_base[i] == none) continue; + const len: u32 = if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len); + @memset(var_ty[var_base[i]..][0..len], elem_ty[i]); + } + // Components a dynamic index can reach stay in memory, and so does + // their alloca. + const pinned = try a.alloc(bool, nv); + @memset(pinned, false); + const keep = try a.alloc(bool, n); + @memset(keep, false); + for (insts, 0..) |inst, i| { + if (inst.op != .gep or gep_alloca[i] == none or gep_k[i] != none) continue; + const al = gep_alloca[i]; + if (var_base[al] == none) continue; + const len: u32 = @intCast(m.types.items[insts[al].op.alloca.elem].array.len); + const r = dyn.get(@intCast(i)).?; + const lo = @min(r[0], len); + const hi = @min(r[1], len); + @memset(pinned[var_base[al] + lo .. var_base[al] + hi], true); + keep[al] = true; + } + // The variable an instruction loads or stores, or `none`. + const access = try a.alloc(u32, n); + @memset(access, none); + for (insts, 0..) |inst, i| { + const ptr = switch (inst.op) { + .load => |x| x.ptr, + .store => |x| x.ptr, + else => continue, + }; + if (ptr != .inst) continue; + const p = ptr.inst; + if (gep_alloca[p] != none and var_base[gep_alloca[p]] != none) { + if (gep_k[p] != none and !pinned[var_base[gep_alloca[p]] + gep_k[p]]) access[i] = var_base[gep_alloca[p]] + gep_k[p]; + } else if (insts[p].op == .alloca and var_base[p] != none) { + access[i] = var_base[p]; + } + } + + // A variable needs phis unless all its accesses are in one block and + // the first is a store. Collect the blocks that store the others. + const first_block = try a.alloc(u32, nv); + @memset(first_block, none); + const global = try a.alloc(bool, nv); + @memset(global, false); + for (insts, 0..) |inst, i| { + const v = access[i]; + if (v == none) continue; + if (first_block[v] == none) { + first_block[v] = block_of[i]; + if (inst.op == .load) global[v] = true; + } else if (first_block[v] != block_of[i]) global[v] = true; + } + const Def = struct { v: u32, b: u32 }; + var defs: std.ArrayList(Def) = .empty; + for (insts, 0..) |inst, i| { + const v = access[i]; + if (v == none or inst.op != .store or !global[v] or rpo_index[block_of[i]] == none) continue; + try defs.append(a, .{ .v = v, .b = block_of[i] }); + } + std.sort.pdq(Def, defs.items, {}, struct { + fn lt(_: void, x: Def, y: Def) bool { + return if (x.v != y.v) x.v < y.v else x.b < y.b; + } + }.lt); + + // Phis at the iterated dominance frontiers. + var phi_var: std.ArrayList(u32) = .empty; + var phi_block: std.ArrayList(u32) = .empty; + { + const has_phi = try a.alloc(u32, nb); + @memset(has_phi, none); + const queued = try a.alloc(u32, nb); + @memset(queued, none); + var work: std.ArrayList(u32) = .empty; + var k: usize = 0; + while (k < defs.items.len) { + const v = defs.items[k].v; + work.clearRetainingCapacity(); + while (k < defs.items.len and defs.items[k].v == v) : (k += 1) { + const b = defs.items[k].b; + if (queued[b] != v) { + queued[b] = v; + try work.append(a, b); + } + } + while (work.pop()) |b| for (df[b].items) |y| { + if (has_phi[y] == v) continue; + has_phi[y] = v; + try phi_var.append(a, v); + try phi_block.append(a, y); + if (queued[y] != v) { + queued[y] = v; + try work.append(a, y); + } + }; + } + } + const np: u32 = @intCast(phi_var.items.len); + // Phis per block, and their incoming edges (filled while renaming). + const bphi_off = try a.alloc(u32, nb + 1); + @memset(bphi_off, 0); + for (phi_block.items) |b| bphi_off[b + 1] += 1; + for (1..nb + 1) |b| bphi_off[b] += bphi_off[b - 1]; + const bphis = try a.alloc(u32, np); + { + const fill = try a.dupe(u32, bphi_off[0..nb]); + for (phi_block.items, 0..) |b, j| { + bphis[fill[b]] = @intCast(j); + fill[b] += 1; + } + } + const incoming = try a.alloc([]Edge, np); + const filled = try a.alloc(u32, np); + @memset(filled, 0); + for (incoming, phi_block.items) |*in, b| in.* = try a.alloc(Edge, pred_off[b + 1] - pred_off[b]); + + // Renaming, over the dominator tree. A load's replacement goes to + // `repl`; phi `j` is the value `.{ .inst = n + j }` until rebuilt. + // A local read before any store reads zero: the validator rejects + // instructions that read undef. + var zeros: std.AutoHashMapUnmanaged(TypeId, Value) = .empty; + const Zero = struct { + fn get(al: Allocator, mm: *module.Module, cache: *std.AutoHashMapUnmanaged(TypeId, Value), ty: TypeId) Allocator.Error!Value { + const gop = try cache.getOrPut(al, ty); + if (!gop.found_existing) gop.value_ptr.* = try mm.constant(.{ .ty = ty, .kind = switch (mm.types.items[ty]) { + .int => .{ .int = 0 }, + else => .{ .float_bits = 0 }, + } }); + return gop.value_ptr.*; + } + }; + const repl = try a.alloc(?Value, n + np); + @memset(repl, null); + const cur = try a.alloc(Value, nv); + for (cur, var_ty) |*c, t| c.* = try Zero.get(a, m, &zeros, t); + { + const child_off = try a.alloc(u32, nb + 1); + @memset(child_off, 0); + for (rpo[1..nr]) |b| child_off[idom[b] + 1] += 1; + for (1..nb + 1) |b| child_off[b] += child_off[b - 1]; + const children = try a.alloc(u32, nr); + { + const fill = try a.dupe(u32, child_off[0..nb]); + for (rpo[1..nr]) |b| { + children[fill[idom[b]]] = b; + fill[idom[b]] += 1; + } + } + const Undo = struct { v: u32, old: Value }; + var log: std.ArrayList(Undo) = .empty; + const Visit = struct { b: u32, mark: u32, enter: bool }; + var stack: std.ArrayList(Visit) = .empty; + try stack.append(a, .{ .b = 0, .mark = 0, .enter = true }); + while (stack.pop()) |top| { + if (!top.enter) { + while (log.items.len > top.mark) { + const u = log.pop().?; + cur[u.v] = u.old; + } + continue; + } + const b = top.b; + try stack.append(a, .{ .b = b, .mark = @intCast(log.items.len), .enter = false }); + for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| { + const v = phi_var.items[j]; + try log.append(a, .{ .v = v, .old = cur[v] }); + cur[v] = .{ .inst = n + j }; + } + for (block_start[b]..block_start[b + 1]) |i| { + const v = access[i]; + if (v == none) continue; + switch (insts[i].op) { + .load => repl[i] = cur[v], + .store => |x| { + try log.append(a, .{ .v = v, .old = cur[v] }); + cur[v] = resolve(repl, x.val); + }, + else => unreachable, + } + } + for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| for (bphis[bphi_off[s]..bphi_off[s + 1]]) |j| { + incoming[j][filled[j]] = .{ .val = cur[phi_var.items[j]], .block = b }; + filled[j] += 1; + }; + for (children[child_off[b]..child_off[b + 1]]) |c| try stack.append(a, .{ .b = c, .mark = 0, .enter = true }); + } + } + // Edges from unreachable blocks bring zero; loads there read zero. + for (0..np) |j| { + const b = phi_block.items[j]; + for (preds[pred_off[b]..pred_off[b + 1]]) |p| { + if (rpo_index[p] != none) continue; + incoming[j][filled[j]] = .{ .val = try Zero.get(a, m, &zeros, var_ty[phi_var.items[j]]), .block = p }; + filled[j] += 1; + } + } + for (insts, 0..) |inst, i| { + if (access[i] != none and inst.op == .load and repl[i] == null) + repl[i] = try Zero.get(a, m, &zeros, var_ty[access[i]]); + } + + // Phis whose inputs (besides themselves) are one value become it. + const removed_phi = try a.alloc(bool, np); + @memset(removed_phi, false); + { + var changed = true; + while (changed) { + changed = false; + for (0..np) |j| { + if (removed_phi[j]) continue; + const self: Value = .{ .inst = n + @as(u32, @intCast(j)) }; + var same: ?Value = null; + var trivial = true; + for (incoming[j]) |in| { + const x = resolve(repl, in.val); + if (std.meta.eql(x, self)) continue; + if (same) |s| { + if (!std.meta.eql(s, x)) { + trivial = false; + break; + } + } else same = x; + } + if (!trivial) continue; + repl[n + j] = same orelse try Zero.get(a, m, &zeros, var_ty[phi_var.items[j]]); + removed_phi[j] = true; + changed = true; + } + } + } + + // The instructions that go: promoted allocas, their getelementptrs, + // loads and stores. + const removed = try a.alloc(bool, n); + for (insts, 0..) |inst, i| removed[i] = switch (inst.op) { + .alloca => var_base[i] != none and !keep[i], + .gep => gep_alloca[i] != none and var_base[gep_alloca[i]] != none and gep_k[i] != none and !pinned[var_base[gep_alloca[i]] + gep_k[i]], + .load, .store => access[i] != none, + else => false, + }; + + // What stays: instructions with effects, and what they read, + // transitively; new phis likewise. (The loads promotion leaves dead, + // such as copies of arguments never read, go too.) + const live = try a.alloc(bool, n + np); + @memset(live, false); + { + var work: std.ArrayList(u32) = .empty; + const Mark = struct { + repl: []const ?Value, + live: []bool, + removed: []const bool, + work: *std.ArrayList(u32), + a: Allocator, + failed: bool = false, + + fn visit(s: *@This(), v: Value, _: Role) Value { + const x = resolve(s.repl, v); + if (x == .inst and !s.live[x.inst] and !(x.inst < s.removed.len and s.removed[x.inst])) { + s.live[x.inst] = true; + s.work.append(s.a, x.inst) catch { + s.failed = true; + }; + } + return v; + } + }; + var mark: Mark = .{ .repl = repl, .live = live, .removed = removed, .work = &work, .a = a }; + for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst)) { + live[i] = true; + try work.append(a, @intCast(i)); + }; + while (work.pop()) |x| { + if (x < n) { + var inst = insts[x]; + try operands(false, a, &inst, &mark); + } else for (incoming[x - n]) |in| { + _ = mark.visit(in.val, .other); + } + } + if (mark.failed) return error.OutOfMemory; + } + + // New indices: in each block the existing phis, then the new ones, + // then the rest. + const index = try a.alloc(u32, n + np); + @memset(index, none); + var count: u32 = 0; + for (0..nb) |b| { + var i = block_start[b]; + while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) { + index[i] = count; + count += 1; + }; + for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| if (live[n + j]) { + index[n + j] = count; + count += 1; + }; + while (i < block_start[b + 1]) : (i += 1) if (live[i]) { + index[i] = count; + count += 1; + }; + } + const Map = struct { + repl: []const ?Value, + index: []const u32, + fn visit(s: *@This(), v: Value, _: Role) Value { + const x = resolve(s.repl, v); + return if (x == .inst) .{ .inst = s.index[x.inst] } else x; + } + }; + var map: Map = .{ .repl = repl, .index = index }; + const ma = m.allocator(); + var out: std.ArrayList(Inst) = .empty; + try out.ensureTotalCapacityPrecise(ma, count); + for (0..nb) |b| { + var i = block_start[b]; + while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) { + var inst = insts[i]; + try operands(true, ma, &inst, &map); + out.appendAssumeCapacity(inst); + }; + for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| if (live[n + j]) { + const edges = try ma.alloc(Edge, incoming[j].len); + for (incoming[j], edges) |in, *e| e.* = .{ .val = map.visit(in.val, .other), .block = in.block }; + out.appendAssumeCapacity(.{ .ty = var_ty[phi_var.items[j]], .op = .{ .phi = .{ .incoming = edges } } }); + }; + while (i < block_start[b + 1]) : (i += 1) if (live[i]) { + var inst = insts[i]; + try operands(true, ma, &inst, &map); + out.appendAssumeCapacity(inst); + }; + } + f.insts = out; +} + +/// Instructions that must stay even when nothing reads their result. +fn hasEffects(m: *const module.Module, inst: Inst) bool { + return switch (inst.op) { + .ret, .br, .@"switch", .@"unreachable", .store, .atomicrmw, .cmpxchg => true, + .call => |c| switch (m.functions.items[c.callee].attrs) { + .nounwind_readnone, .nounwind_readonly => false, + else => true, + }, + else => false, + }; +} + +/// `v` with replaced loads and phis followed to their final value. +fn resolve(repl: []const ?Value, v: Value) Value { + var x = v; + while (x == .inst) { + const r = repl[x.inst] orelse break; + x = r; + } + return x; +} + +/// Element `k` of `getelementptr [len x T], %a, 0, k`, or null. +fn constIndex(m: *const module.Module, indices: []const Value, len: u64) ?u32 { + if (indices.len != 2) return null; + const first = constInt(m, indices[0]) orelse return null; + const k = constInt(m, indices[1]) orelse return null; + if (first != 0 or k < 0 or k >= len) return null; + return @intCast(k); +} + +fn constInt(m: *const module.Module, v: Value) ?i64 { + if (v != .constant) return null; + return switch (m.constants.items[v.constant].kind) { + .int => |x| x, + else => null, + }; +} + +fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) TypeId { + return switch (v) { + .inst => |i| f.insts.items[i].ty, + .constant => |c| m.constants.items[c].ty, + .arg => |k| m.types.items[f.ty].function.params[k], + .global => |g| m.globals.items[g].ptr_ty, + .function => none, + }; +} + +/// Drops the function declarations nothing calls or refers to any more +/// (dead code removal can take a dx.op's last call, and the validator +/// rejects unused external functions), renumbering the other functions. +/// Run last: indices the emitter holds go stale. Returns the new index of +/// each old function (`none` for dropped ones), or null if none went. +pub fn pruneDeclarations(a: Allocator, m: *module.Module) Allocator.Error!?[]const u32 { + const funcs = m.functions.items; + const used = try a.alloc(bool, funcs.len); + for (funcs, used) |f, *u| u.* = f.num_blocks > 0; + const Use = struct { + used: []bool, + fn visit(s: *@This(), v: Value, _: Role) Value { + if (v == .function) s.used[v.function] = true; + return v; + } + }; + var use: Use = .{ .used = used }; + for (funcs) |f| for (f.insts.items) |*inst| { + if (inst.op == .call) used[inst.op.call.callee] = true; + try operands(false, a, inst, &use); + }; + for (m.metadata.items) |md| if (md == .value and md.value.val == .function) { + used[md.value.val.function] = true; + }; + if (std.mem.indexOfScalar(bool, used, false) == null) return null; + + const index = try a.alloc(u32, funcs.len); + var count: u32 = 0; + for (used, index) |u, *x| { + x.* = if (u) count else none; + if (u) count += 1; + } + const Map = struct { + index: []const u32, + fn visit(s: *@This(), v: Value, _: Role) Value { + return if (v == .function) .{ .function = s.index[v.function] } else v; + } + }; + var map: Map = .{ .index = index }; + const ma = m.allocator(); + for (funcs) |*f| for (f.insts.items) |*inst| { + try operands(true, ma, inst, &map); + if (inst.op == .call) inst.op.call.callee = index[inst.op.call.callee]; + }; + for (m.metadata.items) |*md| if (md.* == .value and md.value.val == .function) { + md.value.val = .{ .function = index[md.value.val.function] }; + }; + var k: usize = 0; + for (funcs, used) |f, u| if (u) { + funcs[k] = f; + k += 1; + }; + m.functions.shrinkRetainingCapacity(k); + return index; +} From 4666275a0bedd617e40825c54e44c2fffa7736ff Mon Sep 17 00:00:00 2001 From: peterino2 Date: Mon, 2 Nov 2026 01:13:16 -0800 Subject: [PATCH 8/8] DXIL: fold promoted values, pass constant buffer structs in place GlimmerProbeTrace (Glide) still came out at 374 KB of DXIL against dxc's 155 KB, with 130 allocas against 40. Most of the remainder: by-value struct parameters copied out of the constant buffer at every call (GlimmerGroundParams and GlimmerSpanParams, 32 i32s each), then indexed dynamically, which pinned each copy in memory. - Arguments loaded from a constant buffer are passed as the constant buffer place itself, structs as well as arrays (not with matrices, whose constant buffer access is narrower than a local's). Locals still alias only within a block with no write since. The alias now comes first in local_var lowering, so the skipped parameter store always matches. - Peepholes on promoted values: bitcast round trips (int/float mixing locals store i32s), constant integer arithmetic and comparisons, identities, selects on a constant. A constant out-of-bounds array index this exposes (on a path that cannot run) becomes 0, since the validator rejects it. - Inlined callees' array locals return to a per-type pool on return, for later callees to reuse. - -Od and -zdxc-no-opt skip promotion, aliasing and reuse, as they skip the SPIR-V IR passes. GlimmerProbeTrace: 374 KB to 191 KB, 21 allocas, 282 bitcasts (from 7198). Its pipeline builds in 3.6 s on an RX 9070 XT (was 5.1 s). All of Glide's 400 DXIL compiles: 5.91 MB (dxc: 6.11 MB), 7.1x faster than dxc. All pass dxc 1.8.2505's validator, and Glide renders. --- src/compile.zig | 2 +- src/dxil/emit.zig | 109 +++++++++++++++++++++-------- src/dxil/promote.zig | 160 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 243 insertions(+), 28 deletions(-) diff --git a/src/compile.zig b/src/compile.zig index 077a92a..8abe890 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -531,7 +531,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { 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; }; - const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags) catch |err| switch (err) { + const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) { error.Unsupported => { try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); return error.CompileFailed; diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index cb0a22f..bf01a9f 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -34,10 +34,13 @@ const Value = module.Value; pub const Error = Allocator.Error || error{Unsupported}; -pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics) Error![]u8 { +/// `optimize` (off for -Od and -zdxc-no-opt) promotes locals to SSA values, +/// passes arrays to callees that only read them in place and reuses +/// inlined callees' arrays. +pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error![]u8 { var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); - var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags }; + var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = optimize }; defer e.dm.deinit(); // Native 16-bit types are laid out at their own size. if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64"; @@ -155,13 +158,16 @@ const Frame = struct { rets: std.ArrayList(struct { block: u32, vals: []const Value }) = .empty, /// The resources a function returns (every return the same ones). ret_res: ?[]const Lowered = null, - /// Loads of locals: where from, and the block and write count when - /// read, so a call right after can pass the local itself. - load_srcs: std.AutoHashMapUnmanaged(u32, struct { ptr: Ptr, block: u32, writes: u32 }) = .empty, - /// By-value parameters passed as the caller's storage (see paramCopies). - param_ptrs: []const ?Ptr = &.{}, + /// Loads of locals and constant buffers: the place (a `.ptr` or + /// `.cbuf`), and the block and write count when read, so a call right + /// after can pass the place itself. + load_srcs: std.AutoHashMapUnmanaged(u32, struct { src: Lowered, block: u32, writes: u32 }) = .empty, + /// By-value parameters passed as the caller's place (see paramCopies). + param_srcs: []const ?Lowered = &.{}, /// paramCopies of the function, when some parameter is aliased. param_copies: []const u32 = &.{}, + /// Array locals of an inlined callee, back to the pool on return. + arrays: std.ArrayList(struct { ty: TypeId, ptr: Ptr }) = .empty, }; const PInst = struct { inst: module.Inst, id: u32 }; @@ -230,6 +236,11 @@ const Emitter = struct { /// Dynamically indexed getelementptrs into locals (by id) and the /// components they can reach, for promote.run. dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty, + /// See `emit`. + optimize: bool = true, + /// Arrays of inlined callees that have returned, by type, for later + /// callees' locals of that type (per function). + array_pool: std.AutoHashMapUnmanaged(TypeId, std.ArrayList(Ptr)) = .empty, /// Instructions emitted so far that may write memory. writes: u32 = 0, /// paramCopies per IR function. @@ -1255,7 +1266,8 @@ const Emitter = struct { var it = e.dyn_ranges.iterator(); while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*); e.dyn_ranges.clearRetainingCapacity(); - try promote.run(e.arena, &e.dm, func, &ranges); + e.array_pool.clearRetainingCapacity(); + if (e.optimize) try promote.run(e.arena, &e.dm, func, &ranges); } /// Drops removable prologue instructions nothing uses (repeatedly: a @@ -1370,9 +1382,10 @@ const Emitter = struct { return e.inlineCallAliased(fi, args, &.{}); } - /// `aliases[k]`, when set, is caller storage holding by-value argument - /// `k`, which the callee may read in place of a copy (see argAliases). - fn inlineCallAliased(e: *Emitter, fi: u32, args: []const Lowered, aliases: []const ?Ptr) Error![]const Value { + /// `aliases[k]`, when set, is the caller's place holding by-value + /// argument `k`, which the callee may read in place of a copy (see + /// argAliases). + fn inlineCallAliased(e: *Emitter, fi: u32, args: []const Lowered, aliases: []const ?Lowered) Error![]const Value { const f = e.m.functions.items[fi]; var frame: Frame = .{ .f = f, @@ -1381,7 +1394,7 @@ const Emitter = struct { .blocks = try e.arena.alloc(?u32, f.blocks.items.len), }; for (aliases) |al| if (al != null) { - frame.param_ptrs = aliases; + frame.param_srcs = aliases; frame.param_copies = try e.paramCopies(fi); break; }; @@ -1398,6 +1411,14 @@ const Emitter = struct { try e.emitBlock(&frame, @intCast(bi)); } e.last_ret_res = frame.ret_res; + // The callee's arrays are dead now: later callees can have them + // (with no values forwarded from what they held). + if (frame.arrays.items.len > 0) e.forwarded.clearRetainingCapacity(); + for (frame.arrays.items) |x| { + const gop = try e.array_pool.getOrPut(e.arena, x.ty); + if (!gop.found_existing) gop.value_ptr.* = .empty; + try gop.value_ptr.append(e.arena, x.ptr); + } if (frame.cont) |cont| { e.cur = cont; if (f.ret == TypeTable.void_type or frame.rets.items.len == 0) return &.{}; @@ -1414,19 +1435,33 @@ const Emitter = struct { return &.{}; } - /// Caller storage the by-value arguments of a call to `fi` can be read - /// from: an argument loaded from a local in the same block, with no - /// write since. Calls with out / inout arguments get none (the callee - /// could write the local through one while reading it through another). - fn argAliases(e: *Emitter, frame: *const Frame, fi: u32, refs: []const Ref) Error![]const ?Ptr { + /// Places the by-value array and struct arguments of a call to `fi` can + /// be read from: a constant buffer they were loaded from (none with + /// matrices, whose constant buffer access is narrower than a local's), + /// or a local loaded in the same block with no write since. Calls with + /// out / inout arguments get no locals (the callee could write one + /// through them while reading it through another). + fn argAliases(e: *Emitter, frame: *const Frame, fi: u32, refs: []const Ref) Error![]const ?Lowered { const params = e.m.functions.items[fi].params; - for (params) |p| if (p.by_ref) return &.{}; - const out = try e.arena.alloc(?Ptr, refs.len); + var by_ref = false; + for (params) |p| by_ref = by_ref or p.by_ref; + const out = try e.arena.alloc(?Lowered, refs.len); for (refs, params, out) |r, p, *o| { o.* = null; - if (e.t.get(p.ty) != .array) continue; + if (p.by_ref) continue; + switch (e.t.get(p.ty)) { + .array, .@"struct" => if (e.holdsResources(p.ty)) continue, + else => continue, + } const src = frame.load_srcs.get(r.index()) orelse continue; - if (src.block == e.cur and src.writes == e.writes) o.* = src.ptr; + switch (src.src) { + .cbuf => if (!e.containsMatrix(p.ty)) { + o.* = src.src; + }, + else => if (!by_ref and src.block == e.cur and src.writes == e.writes) { + o.* = src.src; + }, + } } return out; } @@ -1741,6 +1776,12 @@ const Emitter = struct { return .{ .handle = ri }; }, .local_var => { + // (First: the store of the parameter is skipped whenever + // there is an alias.) + if (frame.param_copies.len > 0) { + const k = frame.param_copies[r.index()]; + if (k != std.math.maxInt(u32)) if (frame.param_srcs[k]) |alias| return alias; + } if (e.payload_local) |pl| if (pl.func == f and pl.inst == r.index()) { const dty = try e.memoryType(i.ty); const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } }); @@ -1767,9 +1808,11 @@ const Emitter = struct { const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } }); return .{ .typed = .{ .base = base, .dty = dty, .addr_space = 0, .ty = i.ty } }; } - if (frame.param_copies.len > 0) { - const k = frame.param_copies[r.index()]; - if (k != std.math.maxInt(u32)) if (frame.param_ptrs[k]) |alias| return .{ .ptr = alias }; + if (e.optimize and frame.cont != null and e.t.get(i.ty) == .array) { + const pooled = if (e.array_pool.getPtr(i.ty)) |l| l.pop() else null; + const ptr = pooled orelse try e.alloca(i.ty); + try frame.arrays.append(e.arena, .{ .ty = i.ty, .ptr = ptr }); + return .{ .ptr = ptr }; } return .{ .ptr = try e.alloca(i.ty) }; }, @@ -1801,6 +1844,7 @@ const Emitter = struct { return .{ .scalars = try e.textureLoad(res, mip, tx.coords, null, i.ty) }; }, .cbuf => |c| { + if (c.dyn_comp == null) try frame.load_srcs.put(e.arena, r.index(), .{ .src = .{ .cbuf = c }, .block = e.cur, .writes = e.writes }); const dc = c.dyn_comp orelse return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty); const whole = (try e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, c.vec)).scalars; return .{ .scalars = try e.arena.dupe(Value, &.{try e.pickComponent(whole, dc, i.ty)}) }; @@ -1831,7 +1875,7 @@ const Emitter = struct { return .{ .scalars = out }; }, .ptr => |ptr| { - if (ptr.addr_space == 0 and localRoot(f, p)) try frame.load_srcs.put(e.arena, r.index(), .{ .ptr = ptr, .block = e.cur, .writes = e.writes }); + if (ptr.addr_space == 0 and localRoot(f, p)) try frame.load_srcs.put(e.arena, r.index(), .{ .src = .{ .ptr = ptr }, .block = e.cur, .writes = e.writes }); return e.loadPtr(ptr, i.ty); }, .typed => |tp| return e.typedLoad(tp, i.ty), @@ -1841,7 +1885,7 @@ const Emitter = struct { .store => |s| { if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) { const k = f.inst(s.value).op.param; - if (frame.param_copies[s.ptr.index()] == k and frame.param_ptrs[k] != null) return .none; + if (frame.param_copies[s.ptr.index()] == k and frame.param_srcs[k] != null) return .none; }; if (frame.vals[s.ptr.index()] == .rq_local) { // A copy of a query is the same query. @@ -2103,7 +2147,7 @@ const Emitter = struct { if (e.lib_calls.get(c.func)) |func| return e.libCall(frame, c.func, func, c.args); const args = try e.arena.alloc(Lowered, c.args.len); for (c.args, args) |a, *o| o.* = frame.vals[a.index()]; - const res = try e.inlineCallAliased(c.func, args, try e.argAliases(frame, c.func, c.args)); + const res = try e.inlineCallAliased(c.func, args, if (e.optimize) try e.argAliases(frame, c.func, c.args) else &.{}); // Functions returning resources (or structs of them). if (isResourceType(e.t, i.ty) and !isRayQuery(e.t, i.ty)) { const rr = e.last_ret_res orelse return e.unsupported("a function returning a resource with no return value", .{}); @@ -4734,6 +4778,17 @@ const Emitter = struct { return dty; } + fn containsMatrix(e: *Emitter, ty: TypeId) bool { + return switch (e.t.get(ty)) { + .matrix => true, + .array => |a| e.containsMatrix(a.elem), + .@"struct" => |st| for (st.fields.items) |fld| { + if (e.containsMatrix(fld.type)) break true; + } else false, + else => false, + }; + } + fn containsLinAlg(e: *Emitter, ty: TypeId) bool { return switch (e.t.get(ty)) { .linalg => true, diff --git a/src/dxil/promote.zig b/src/dxil/promote.zig index 560bd54..6bbe8ef 100644 --- a/src/dxil/promote.zig +++ b/src/dxil/promote.zig @@ -585,6 +585,15 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM } } + // Peepholes on what promotion exposes, in instruction order so they + // cascade: bitcast round trips (locals mixing ints and floats store + // i32s), constant integer arithmetic and comparisons, identities, and + // selects on a constant. + for (insts, 0..) |inst, i| { + if (repl[i] != null) continue; + repl[i] = try simplify(m, f, repl, n, phi_var.items, var_ty, inst); + } + // The instructions that go: promoted allocas, their getelementptrs, // loads and stores. const removed = try a.alloc(bool, n); @@ -684,12 +693,163 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM while (i < block_start[b + 1]) : (i += 1) if (live[i]) { var inst = insts[i]; try operands(true, ma, &inst, &map); + if (inst.op == .gep) try clampIndex(m, &inst.op.gep); out.appendAssumeCapacity(inst); }; } f.insts = out; } +/// An index into an array that folding made a constant out of range (on +/// a path that cannot run: the access would be undefined) becomes 0, as +/// the validator rejects constant out-of-bounds accesses. +fn clampIndex(m: *module.Module, g: *@FieldType(@FieldType(Inst, "op"), "gep")) Allocator.Error!void { + if (g.indices.len != 2) return; + const len = switch (m.types.items[g.elem]) { + .array => |arr| arr.len, + else => return, + }; + const k = constInt(m, g.indices[1]) orelse return; + if (k >= 0 and k < len) return; + const ix = try m.allocator().dupe(Value, g.indices); + ix[1] = try m.constant(.{ .ty = m.constants.items[g.indices[1].constant].ty, .kind = .{ .int = 0 } }); + g.indices = ix; +} + +/// A simpler value for `inst`, or null. +fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value, n: u32, phi_var: []const u32, var_ty: []const TypeId, inst: Inst) Allocator.Error!?Value { + const S = struct { + fn ty(mm: *const module.Module, ff: *const module.Function, nn: u32, pv: []const u32, vt: []const TypeId, v: Value) TypeId { + if (v == .inst and v.inst >= nn) return vt[pv[v.inst - nn]]; + return typeOf(mm, ff, v); + } + fn intWidth(mm: *const module.Module, t: TypeId) ?u32 { + return switch (mm.types.items[t]) { + .int => |w| w, + else => null, + }; + } + /// `v` as a `w`-bit pattern. + fn bits(v: i64, w: u32) u64 { + const u: u64 = @bitCast(v); + return if (w >= 64) u else u & ((@as(u64, 1) << @intCast(w)) - 1); + } + /// A `w`-bit pattern as stored: 0 / 1 for i1, sign-extended above. + fn stored(p: u64, w: u32) i64 { + if (w == 1) return @intCast(p & 1); + if (w >= 64) return @bitCast(p); + const sh: u6 = @intCast(64 - w); + return @as(i64, @bitCast(p << sh)) >> sh; + } + }; + switch (inst.op) { + .cast => |c| { + if (c.op != .bitcast) return null; + const x = resolve(repl, c.val); + if (x == .inst and x.inst < n) { + const inner = f.insts.items[x.inst].op; + if (inner == .cast and inner.cast.op == .bitcast) { + const src = resolve(repl, inner.cast.val); + if (S.ty(m, f, n, phi_var, var_ty, src) == inst.ty) return src; + } + } + if (x == .constant) { + const k = m.constants.items[x.constant].kind; + const w: u32 = switch (m.types.items[inst.ty]) { + .int => |iw| iw, + .half => 16, + .float => 32, + .double => 64, + else => return null, + }; + const p: u64 = switch (k) { + .int => |v| S.bits(v, w), + .float_bits => |b| b, + else => return null, + }; + return try m.constant(.{ .ty = inst.ty, .kind = switch (m.types.items[inst.ty]) { + .int => .{ .int = S.stored(p, w) }, + else => .{ .float_bits = p }, + } }); + } + return null; + }, + .binop => |b| { + const w = S.intWidth(m, inst.ty) orelse return null; + const l = resolve(repl, b.lhs); + const r = resolve(repl, b.rhs); + const lc = constInt(m, l); + const rc = constInt(m, r); + if (lc != null and rc != null) { + const x = S.bits(lc.?, w); + const y = S.bits(rc.?, w); + const sx = S.stored(x, w); + const sy = S.stored(y, w); + const p: u64 = switch (b.op) { + .add => x +% y, + .sub => x -% y, + .mul => x *% y, + .@"and" => x & y, + .@"or" => x | y, + .xor => x ^ y, + .shl => if (y < w) x << @intCast(y) else return null, + .lshr => if (y < w) x >> @intCast(y) else return null, + .ashr => if (y < w) @bitCast(sx >> @intCast(y)) else return null, + .udiv => if (y != 0) x / y else return null, + .urem => if (y != 0) x % y else return null, + .sdiv => if (sy != 0 and !(sy == -1 and sx == std.math.minInt(i64))) @bitCast(@divTrunc(sx, sy)) else return null, + .srem => if (sy != 0 and sy != -1) @bitCast(@rem(sx, sy)) else return null, + }; + return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = S.stored(S.bits(@bitCast(p), w), w) } }); + } + if (rc) |y| switch (b.op) { + .add, .sub, .@"or", .xor, .shl, .lshr, .ashr => if (y == 0) return l, + .mul, .udiv, .sdiv => if (S.bits(y, w) == 1) return l, + .@"and" => if (S.bits(y, w) == S.bits(-1, w)) return l, + else => {}, + }; + if (lc) |x| switch (b.op) { + .add, .@"or", .xor => if (x == 0) return r, + .mul => if (S.bits(x, w) == 1) return r, + .@"and" => if (S.bits(x, w) == S.bits(-1, w)) return r, + else => {}, + }; + return null; + }, + .cmp => |c| { + if (c.pred < 32 or c.pred > 41) return null; // integer predicates only + const l = resolve(repl, c.lhs); + const r = resolve(repl, c.rhs); + const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null; + const x = S.bits(constInt(m, l) orelse return null, w); + const y = S.bits(constInt(m, r) orelse return null, w); + const sx = S.stored(x, w); + const sy = S.stored(y, w); + const t = switch (c.pred) { + 32 => x == y, + 33 => x != y, + 34 => x > y, + 35 => x >= y, + 36 => x < y, + 37 => x <= y, + 38 => sx > sy, + 39 => sx >= sy, + 40 => sx < sy, + else => sx <= sy, + }; + return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } }); + }, + .select => |sl| { + const t = resolve(repl, sl.t); + const fv = resolve(repl, sl.f); + if (std.meta.eql(t, fv)) return t; + const c = constInt(m, resolve(repl, sl.cond)) orelse return null; + return if (c != 0) t else fv; + }, + else => return null, + } +} + /// Instructions that must stay even when nothing reads their result. fn hasEffects(m: *const module.Module, inst: Inst) bool { return switch (inst.op) {