Compare commits

..

No commits in common. "0aee714ae2b6206ea7724abc39c7ce24762691b1" and "01a66d456a2b33431a1ea408a923ca9976f4b7ff" have entirely different histories.

10 changed files with 12 additions and 1392 deletions

View File

@ -187,8 +187,6 @@ 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.
@ -221,7 +219,6 @@ 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,
@ -496,6 +493,10 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
if (profile == null) return ctx.fail("missing -T <profile>", .{});
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 => {
@ -504,18 +505,6 @@ 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);
try zdxc.ir.ssa.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 });

View File

@ -1965,7 +1965,6 @@ 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", .{}),
}
}

View File

@ -1,418 +0,0 @@
//! 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).
//!
//! 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
//! 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).
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 => {},
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;
// Shapes from the original bodies (inlining a function's callees does
// not change how it returns).
const shapes = try a.alloc(?Shape, n);
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);
}
/// 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 (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;
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 .keep;
// A loop header keeps its instructions (its back edges target it).
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);
// 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 };
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| {
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);
}
}
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;
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
// 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);
@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: []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, .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[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()]));
}
};
// 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, mp.map(r));
}
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, .selection_control = src.selection_control };
}
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;
}

View File

@ -141,9 +141,6 @@ 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 {
@ -180,12 +177,8 @@ 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,
@ -215,8 +208,6 @@ 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,
@ -712,7 +703,6 @@ 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() });

View File

@ -565,7 +565,6 @@ 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);
@ -598,7 +597,7 @@ const Lowerer = struct {
l.b.terminate(.{ .br = target.cont });
},
.discard => l.b.terminate(.discard),
.@"switch" => |x| try l.switchStmt(x, st.attrs),
.@"switch" => |x| try l.switchStmt(x),
.case, .default => {
l.unsupported(st.loc, "case labels outside a switch body", .{});
return error.Unsupported;
@ -608,16 +607,7 @@ 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.
/// `[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 {
fn switchStmt(l: *Lowerer, x: @FieldType(ast.Stmt.Kind, "switch")) Error!void {
if (x.cond_decl) |d| try l.localDecl(d);
const t = l.types();
var cond_ty = x.cond.ty;
@ -658,7 +648,6 @@ 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 });

View File

@ -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, .undef => op,
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant => 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,68 +223,6 @@ 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 {
@ -734,7 +672,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, .selection_control = src.selection_control };
f.blocks.items[nb] = .{ .insts = insts, .term = term, .merge = mg };
}
entries[iter] = bmap.get(body).?;
conts[iter] = bmap.get(cont).?;

View File

@ -1,811 +0,0 @@
//! 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;
}
}
}

View File

@ -29,7 +29,6 @@ pub const Extra = enum {
zdxc_ast,
zdxc_sema,
zdxc_ir,
zdxc_no_opt,
job,
fcolor_diagnostics,
fno_color_diagnostics,
@ -43,7 +42,6 @@ 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 = "<job.json>", .help = "Compile every shader a JSON job file lists, in one process, on all cores (see docs/batch.md)" },
.{ .id = .fcolor_diagnostics, .spelling = "fcolor-diagnostics", .help = "Always use colors in diagnostics" },
.{ .id = .fno_color_diagnostics, .spelling = "fno-color-diagnostics", .help = "Never use colors in diagnostics" },

View File

@ -35,8 +35,6 @@ 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 ssa = @import("ir/ssa.zig");
};
pub const sema = struct {

View File

@ -226,13 +226,6 @@ 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
@ -952,7 +945,6 @@ 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, &.{});
}
@ -992,7 +984,7 @@ const Emitter = struct {
try e.entryPoint(entry);
}
for (m.functions.items, e.func_ids) |f, id| {
if (!f.dead and !e.hasResourceParams(f)) try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{});
if (!e.hasResourceParams(f)) try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{});
}
}
@ -2138,13 +2130,10 @@ 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 });
@ -2199,21 +2188,8 @@ const Emitter = struct {
for (blk.insts.items) |r| try e.emitInst(r);
switch (blk.merge) {
.none => {},
// [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.
.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,
} }),
.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 }),
}
switch (blk.term) {
.none, .@"unreachable" => try e.b.emit(.functions, .@"unreachable", &.{}),
@ -2247,22 +2223,9 @@ 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 {
@ -2947,22 +2910,7 @@ const Emitter = struct {
try e.b.emit(.functions, .store, &.{ ptr, v });
} else try e.b.emit(.functions, .store, &.{ iface.var_id, v });
},
.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;
},
.phi => return e.unsupported("phi", .{}),
}
}