IR, AST lowering and a SPIR-V backend

- src/ir/ir.zig: typed values in a structured CFG (selection / loop
  headers name their merge and continue blocks), memory-form locals,
  functions kept, plus a text dump (-zdxc-ir).
- src/ir/lower.zig: lowers the entry point and everything it reaches
  from the AST and Sema's new resolutions (variables, call targets,
  intrinsic overloads, struct fields): statements, structured loops and
  selections, short-circuit operators, implicit conversions, copy-in /
  copy-out arguments, swizzle stores, resource reads and writes, and a
  parameterless entry wrapper over the stage inputs and outputs.
- src/spirv/emit.zig: IR -> SPIR-V with dxc's conventions (BufferBlock
  structured buffers with std430 strides, default register bindings,
  stage builtins, GLSL.std.450 intrinsics, structured merges).
- test/oracle/codegen.sh: compiles every dxc-valid corpus file and
  validates the output: 281 files produce SPIR-V spirv-val accepts, 0
  invalid; the rest report the construct not supported yet.
This commit is contained in:
Peter Li 2026-10-31 04:54:45 -07:00
parent d5d6b3578a
commit c9b458a3b4
9 changed files with 2438 additions and 18 deletions

379
src/ir/ir.zig Normal file
View File

@ -0,0 +1,379 @@
//! zdxc IR: typed values in a control-flow graph that keeps its structure
//! (selection and loop headers name their merge and continue blocks), shared
//! by the DXIL and SPIR-V backends.
//!
//! Lowering produces memory form: locals and parameters live in `local_var`
//! storage accessed by `load` / `store`, as dxc's SPIR-V backend emits them.
//! Functions and calls are kept (SPIR-V wants real functions); the DXIL
//! backend inlines, promotes memory to SSA values and scalarizes.
//!
//! Value types are Sema's TypeTable ids (scalars, vectors, matrices,
//! arrays, structs, resources). A value whose `ptr` space is not `.none` is
//! a pointer to storage of that type.
const std = @import("std");
const Allocator = std.mem.Allocator;
const types = @import("../sema/types.zig");
pub const TypeId = types.TypeId;
pub const TypeTable = types.TypeTable;
/// An instruction result within a function.
pub const Ref = enum(u32) {
none = std.math.maxInt(u32),
_,
pub fn index(r: Ref) u32 {
return @backingInt(r);
}
};
pub const BlockId = enum(u32) {
none = std.math.maxInt(u32),
_,
pub fn index(b: BlockId) u32 {
return @backingInt(b);
}
};
/// Where a pointer points.
pub const Space = enum { none, function, private, groupshared, resource, input, output };
pub const BinaryOp = enum {
add,
sub,
mul,
div,
rem,
shl,
shr,
bit_and,
bit_or,
bit_xor,
log_and,
log_or,
};
pub const CmpOp = enum { eq, ne, lt, le, gt, ge };
pub const UnaryOp = enum { neg, not, bit_not };
pub const Constant = union(enum) {
/// Integer or bool bits, sign-extended for signed types.
int: i64,
float: f64,
};
pub const Op = union(enum) {
/// A scalar constant (or a vector of one constant, splatted).
constant: Constant,
/// The function's `n`th parameter (a pointer for out / inout).
param: u32,
/// Pointer to a module global (resource, groupshared, static).
global: u32,
/// Function-local storage of the result type (result is a pointer).
local_var,
load: Ref,
store: struct { ptr: Ref, value: Ref },
/// Pointer to a member / element of the storage `base` points at.
access: struct { base: Ref, indices: []const Ref },
binary: struct { op: BinaryOp, lhs: Ref, rhs: Ref },
unary: struct { op: UnaryOp, operand: Ref },
cmp: struct { op: CmpOp, lhs: Ref, rhs: Ref },
/// Component-wise numeric conversion to the result type (same shape).
convert: Ref,
/// Bit reinterpretation (asuint, asfloat, ...).
bitcast: Ref,
/// Scalar replicated to the result vector / matrix.
splat: Ref,
/// Constant component / member / element.
extract: struct { agg: Ref, index: u32 },
insert: struct { agg: Ref, value: Ref, index: u32 },
/// Vector / matrix / struct / array from its components.
construct: []const Ref,
/// Vector components picked by index (swizzles, truncation).
shuffle: struct { vec: Ref, components: []const u8 },
select: struct { cond: Ref, t: Ref, f: Ref },
call: struct { func: u32, args: []const Ref },
/// A math / bit / derivative intrinsic by HLSL name (`sqrt`, `mad`, ...).
intrinsic: struct { name: []const u8, args: []const Ref },
/// `resource[index]` read and write (structured / typed / raw buffers,
/// textures).
res_load: struct { res: Ref, index: Ref },
res_store: struct { res: Ref, index: Ref, value: Ref },
/// A builtin method call on a resource (`Load`, `Sample`, ...).
method: struct { name: []const u8, res: Ref, args: []const Ref },
/// An entry-point input / output element (index into the entry's
/// signature).
input: u32,
output: struct { element: u32, value: Ref },
phi: []const struct { value: Ref, block: BlockId },
};
pub const Inst = struct {
op: Op,
ty: TypeId,
/// Non-`none` when the result is a pointer to `ty` storage.
ptr: Space = .none,
};
pub const Terminator = union(enum) {
/// Not yet terminated (lowering in progress).
none,
ret: Ref,
br: BlockId,
cond_br: struct { cond: Ref, then: BlockId, @"else": BlockId },
@"switch": struct { value: Ref, default: BlockId, cases: []const struct { value: i64, block: BlockId } },
/// After `discard`, or where control cannot reach.
@"unreachable",
discard,
};
/// Structured control flow: a header block names where its construct
/// merges and (for loops) where iterations continue.
pub const Merge = union(enum) {
none,
selection: BlockId,
loop: struct { merge: BlockId, @"continue": BlockId },
};
pub const Block = struct {
insts: std.ArrayList(Ref) = .empty,
term: Terminator = .none,
merge: Merge = .none,
};
pub const Param = struct {
name: []const u8,
ty: TypeId,
/// out / inout: passed as a pointer to caller storage.
by_ref: bool,
};
pub const Function = struct {
name: []const u8,
params: []const Param,
ret: TypeId,
insts: std.ArrayList(Inst) = .empty,
blocks: std.ArrayList(Block) = .empty,
pub fn inst(f: *const Function, r: Ref) Inst {
return f.insts.items[r.index()];
}
pub fn block(f: *Function, b: BlockId) *Block {
return &f.blocks.items[b.index()];
}
};
pub const Binding = struct {
/// Register class: 'b', 't', 'u', 's' (0: none given).
class: u8 = 0,
index: u32 = 0,
space: u32 = 0,
explicit: bool = false,
};
pub const Global = struct {
name: []const u8,
ty: TypeId,
space: Space,
binding: Binding = .{},
};
pub const Stage = enum { vertex, pixel, geometry, hull, domain, compute, library };
/// One entry-point input or output (a semantic on a parameter, field or
/// the return value).
pub const SigElement = struct {
semantic: []const u8,
semantic_index: u32,
ty: TypeId,
system_value: bool,
};
pub const Entry = struct {
/// The function the entry wraps (the HLSL entry, in memory form).
func: u32,
name: []const u8,
stage: Stage,
num_threads: [3]u32 = .{ 1, 1, 1 },
inputs: std.ArrayList(SigElement) = .empty,
outputs: std.ArrayList(SigElement) = .empty,
/// The wrapper with no parameters that reads `inputs`, calls `func`
/// and writes `outputs`.
wrapper: u32 = 0,
};
pub const Module = struct {
arena: Allocator,
types: *TypeTable,
globals: std.ArrayList(Global) = .empty,
/// By pointer: lowering appends callees while building a caller.
functions: std.ArrayList(*Function) = .empty,
entry: ?Entry = null,
pub fn addFunction(m: *Module, f: Function) !u32 {
const p = try m.arena.create(Function);
p.* = f;
try m.functions.append(m.arena, p);
return @intCast(m.functions.items.len - 1);
}
};
/// Appends instructions to a function at a current block.
pub const Builder = struct {
m: *Module,
f: *Function,
cur: BlockId = .none,
pub fn newBlock(b: *Builder) !BlockId {
try b.f.blocks.append(b.m.arena, .{});
return @fromBackingInt(@intCast(b.f.blocks.items.len - 1));
}
pub fn setBlock(b: *Builder, blk: BlockId) void {
b.cur = blk;
}
/// The current block is still open (no terminator yet).
pub fn open(b: *Builder) bool {
return b.cur != .none and b.f.block(b.cur).term == .none;
}
pub fn add(b: *Builder, inst: Inst) !Ref {
try b.f.insts.append(b.m.arena, inst);
const r: Ref = @fromBackingInt(@intCast(b.f.insts.items.len - 1));
// Instructions after a terminator (dead code) go to a fresh block.
if (!b.open()) b.cur = try b.newBlock();
try b.f.block(b.cur).insts.append(b.m.arena, r);
return r;
}
pub fn terminate(b: *Builder, t: Terminator) void {
if (!b.open()) return;
b.f.block(b.cur).term = t;
}
pub fn constInt(b: *Builder, ty: TypeId, v: i64) !Ref {
return b.add(.{ .op = .{ .constant = .{ .int = v } }, .ty = ty });
}
pub fn constFloat(b: *Builder, ty: TypeId, v: f64) !Ref {
return b.add(.{ .op = .{ .constant = .{ .float = v } }, .ty = ty });
}
pub fn load(b: *Builder, ptr: Ref) !Ref {
const p = b.f.inst(ptr);
return b.add(.{ .op = .{ .load = ptr }, .ty = p.ty });
}
pub fn store(b: *Builder, ptr: Ref, value: Ref) !void {
_ = try b.add(.{ .op = .{ .store = .{ .ptr = ptr, .value = value } }, .ty = TypeTable.void_type });
}
};
/// Prints a module in a readable text form (for `-zdxc-ir` and tests).
pub fn dump(m: *const Module, w: *std.Io.Writer) !void {
for (m.globals.items, 0..) |g, i| {
try w.print("global @{d} {s}: {s} {s}", .{ i, g.name, @tagName(g.space), try m.types.format(m.arena, g.ty) });
if (g.binding.class != 0) try w.print(" : register({c}{d}, space{d})", .{ g.binding.class, g.binding.index, g.binding.space });
try w.writeByte('\n');
}
for (m.functions.items, 0..) |f, fi| {
try w.print("fn @{d} {s}(", .{ fi, f.name });
for (f.params, 0..) |p, i| {
if (i > 0) try w.writeAll(", ");
try w.print("{s}{s}: {s}", .{ if (p.by_ref) "ref " else "", p.name, try m.types.format(m.arena, p.ty) });
}
try w.print(") -> {s} {{\n", .{try m.types.format(m.arena, f.ret)});
for (f.blocks.items, 0..) |blk, bi| {
try w.print("b{d}:", .{bi});
switch (blk.merge) {
.none => {},
.selection => |mb| try w.print(" ; selection merge b{d}", .{mb.index()}),
.loop => |l| try w.print(" ; loop merge b{d} continue b{d}", .{ l.merge.index(), l.@"continue".index() }),
}
try w.writeByte('\n');
for (blk.insts.items) |r| try dumpInst(m, f, r, w);
try w.writeAll(" ");
switch (blk.term) {
.none => try w.writeAll("<open>"),
.ret => |v| if (v == .none) try w.writeAll("ret") else try w.print("ret %{d}", .{v.index()}),
.br => |t| try w.print("br b{d}", .{t.index()}),
.cond_br => |c| try w.print("br %{d}, b{d}, b{d}", .{ c.cond.index(), c.then.index(), c.@"else".index() }),
.@"switch" => |sw| {
try w.print("switch %{d} default b{d}", .{ sw.value.index(), sw.default.index() });
for (sw.cases) |c| try w.print(", {d}: b{d}", .{ c.value, c.block.index() });
},
.@"unreachable" => try w.writeAll("unreachable"),
.discard => try w.writeAll("discard"),
}
try w.writeByte('\n');
}
try w.writeAll("}\n");
}
}
fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !void {
const inst = f.inst(r);
try w.writeAll(" ");
if (inst.ty != TypeTable.void_type) {
try w.print("%{d}: {s}{s} = ", .{ r.index(), if (inst.ptr != .none) "*" else "", try m.types.format(m.arena, inst.ty) });
}
switch (inst.op) {
.constant => |c| switch (c) {
.int => |v| try w.print("const {d}", .{v}),
.float => |v| try w.print("const {d}", .{v}),
},
.param => |p| try w.print("param {d}", .{p}),
.global => |g| try w.print("global @{d}", .{g}),
.local_var => try w.writeAll("local_var"),
.load => |p| try w.print("load %{d}", .{p.index()}),
.store => |s| try w.print("store %{d}, %{d}", .{ s.ptr.index(), s.value.index() }),
.access => |a| {
try w.print("access %{d}", .{a.base.index()});
for (a.indices) |i| try w.print(", %{d}", .{i.index()});
},
.binary => |b| try w.print("{s} %{d}, %{d}", .{ @tagName(b.op), b.lhs.index(), b.rhs.index() }),
.unary => |u| try w.print("{s} %{d}", .{ @tagName(u.op), u.operand.index() }),
.cmp => |c| try w.print("cmp.{s} %{d}, %{d}", .{ @tagName(c.op), c.lhs.index(), c.rhs.index() }),
.convert => |x| try w.print("convert %{d}", .{x.index()}),
.bitcast => |x| try w.print("bitcast %{d}", .{x.index()}),
.splat => |x| try w.print("splat %{d}", .{x.index()}),
.extract => |x| try w.print("extract %{d}, {d}", .{ x.agg.index(), x.index }),
.insert => |x| try w.print("insert %{d}, %{d}, {d}", .{ x.agg.index(), x.value.index(), x.index }),
.construct => |xs| {
try w.writeAll("construct");
for (xs, 0..) |x, i| try w.print("{s} %{d}", .{ if (i > 0) "," else "", x.index() });
},
.shuffle => |s| {
try w.print("shuffle %{d}", .{s.vec.index()});
for (s.components) |c| try w.print(", {d}", .{c});
},
.select => |s| try w.print("select %{d}, %{d}, %{d}", .{ s.cond.index(), s.t.index(), s.f.index() }),
.call => |c| {
try w.print("call @{d}", .{c.func});
for (c.args) |a| try w.print(", %{d}", .{a.index()});
},
.intrinsic => |c| {
try w.print("{s}", .{c.name});
for (c.args, 0..) |a, i| try w.print("{s} %{d}", .{ if (i > 0) "," else "", a.index() });
},
.res_load => |x| try w.print("res_load %{d}[%{d}]", .{ x.res.index(), x.index.index() }),
.res_store => |x| try w.print("res_store %{d}[%{d}], %{d}", .{ x.res.index(), x.index.index(), x.value.index() }),
.method => |x| {
try w.print("%{d}.{s}(", .{ x.res.index(), x.name });
for (x.args, 0..) |a, i| try w.print("{s}%{d}", .{ if (i > 0) ", " else "", a.index() });
try w.writeByte(')');
},
.input => |i| try w.print("input {d}", .{i}),
.output => |o| try w.print("output {d}, %{d}", .{ o.element, o.value.index() }),
.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() });
},
}
try w.writeByte('\n');
}

831
src/ir/lower.zig Normal file
View File

@ -0,0 +1,831 @@
//! Lowers a checked translation unit (AST plus Sema's types and
//! resolutions) to memory-form IR: the entry function, everything it
//! reaches, the globals it uses, and a parameterless wrapper that reads the
//! entry's inputs and writes its outputs.
const std = @import("std");
const Allocator = std.mem.Allocator;
const ast = @import("../front/ast.zig");
const ir = @import("ir.zig");
const semamod = @import("../sema/sema.zig");
const types = @import("../sema/types.zig");
const table = @import("intrinsics_table");
const Sema = semamod.Sema;
const Variable = semamod.Variable;
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
const Scalar = types.Scalar;
const Ref = ir.Ref;
const BlockId = ir.BlockId;
pub const Options = struct {
entry: []const u8,
stage: ir.Stage,
};
pub const Error = Allocator.Error || error{Unsupported};
/// Lowers the entry point and what it reaches. Constructs the lowering does
/// not handle yet fail with `error.Unsupported` after reporting why.
pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module {
var l: Lowerer = .{ .arena = arena, .s = s, .m = .{ .arena = arena, .types = &s.types } };
const entry_fn = for (s.all_functions.items) |f| {
if (f.owner == null and f.defined and std.mem.eql(u8, f.name, opts.entry)) break f;
} else {
l.unsupported(.none, "missing entry point definition", .{});
return error.Unsupported;
};
const main = try l.functionIndex(entry_fn);
try l.drain();
try l.buildEntry(entry_fn, main, opts);
return l.m;
}
const Lowerer = struct {
arena: Allocator,
s: *Sema,
m: ir.Module,
funcs: std.AutoHashMapUnmanaged(*const semamod.Function, u32) = .empty,
pending: std.ArrayList(*const semamod.Function) = .empty,
globals: std.AutoHashMapUnmanaged(*const Variable, u32) = .empty,
// Per function.
b: ir.Builder = undefined,
vars: std.AutoHashMapUnmanaged(*const Variable, Ref) = .empty,
loops: std.ArrayList(struct { brk: BlockId, cont: BlockId }) = .empty,
ret_ty: TypeId = TypeTable.void_type,
fn unsupported(l: *Lowerer, loc: ast.Loc, comptime fmt: []const u8, args: anytype) void {
_ = l.s.diags.report(.{ .severity = .@"error", .loc = loc }, "code generation: " ++ fmt, args);
}
fn types(l: *Lowerer) *TypeTable {
return &l.s.types;
}
// ------------------------------------------------------------------
// Functions
/// The IR function for a Sema function, queued for lowering on first use.
fn functionIndex(l: *Lowerer, f: *const semamod.Function) Error!u32 {
if (l.funcs.get(f)) |i| return i;
const params = try l.arena.alloc(ir.Param, f.params.len);
for (f.params, params) |p, *out| out.* = .{ .name = p.name, .ty = p.type, .by_ref = p.dir != .in };
const i = try l.m.addFunction(.{ .name = f.name, .params = params, .ret = f.ret });
try l.funcs.put(l.arena, f, i);
try l.pending.append(l.arena, f);
return i;
}
fn drain(l: *Lowerer) Error!void {
while (l.pending.pop()) |f| try l.lowerFunction(f);
}
fn lowerFunction(l: *Lowerer, f: *const semamod.Function) Error!void {
const func = l.m.functions.items[l.funcs.get(f).?];
const body = f.decl.body orelse {
l.unsupported(f.loc, "function '{s}' has no definition", .{f.name});
return error.Unsupported;
};
l.b = .{ .m = &l.m, .f = func };
l.vars = .empty;
l.loops = .empty;
l.ret_ty = f.ret;
l.b.setBlock(try l.b.newBlock());
// Parameters: by-value ones get local storage, out / inout ones
// are the caller's pointers.
for (f.params, 0..) |p, i| {
const pv = try l.b.add(.{ .op = .{ .param = @intCast(i) }, .ty = p.type, .ptr = if (p.dir != .in) .function else .none });
const storage = if (p.dir != .in) pv else blk: {
const local = try l.b.add(.{ .op = .local_var, .ty = p.type, .ptr = .function });
try l.b.store(local, pv);
break :blk local;
};
if (i < f.param_vars.len) if (f.param_vars[i]) |v| try l.vars.put(l.arena, v, storage);
}
try l.stmts(body.kind.compound);
if (l.b.open()) {
if (f.ret != TypeTable.void_type) {
l.b.terminate(.@"unreachable");
} else l.b.terminate(.{ .ret = .none });
}
}
// ------------------------------------------------------------------
// Globals
fn globalIndex(l: *Lowerer, v: *const Variable) Error!u32 {
if (l.globals.get(v)) |i| return i;
const space: ir.Space = switch (v.storage) {
.groupshared => .groupshared,
.global_static, .constant => if (l.s.types.get(v.type) == .resource or l.s.types.get(v.type) == .sampler) .resource else .private,
.global_uniform, .cbuffer => {
l.unsupported(v.loc, "constant buffer variable '{s}' is not supported yet", .{v.name});
return error.Unsupported;
},
else => unreachable,
};
var binding: ir.Binding = .{};
if (v.decl) |d| for (d.semantics) |sem| {
if (sem.kind != .register) continue;
binding = parseBinding(sem.values);
};
try l.m.globals.append(l.arena, .{ .name = v.name, .ty = v.type, .space = space, .binding = binding });
const i: u32 = @intCast(l.m.globals.items.len - 1);
try l.globals.put(l.arena, v, i);
return i;
}
// ------------------------------------------------------------------
// Statements
fn stmts(l: *Lowerer, list: []const *ast.Stmt) Error!void {
for (list) |st| try l.stmt(st);
}
fn stmt(l: *Lowerer, st: *const ast.Stmt) Error!void {
switch (st.kind) {
.compound => |list| try l.stmts(list),
.empty => {},
.expr => |e| _ = try l.rvalue(e),
.decl => |decls| for (decls) |d| try l.localDecl(d),
.@"return" => |v| {
if (v != null and v.?.ty == TypeTable.void_type) {
_ = try l.rvalue(v.?);
l.b.terminate(.{ .ret = .none });
} else if (v) |e| {
const val = try l.converted(e, l.ret_ty);
l.b.terminate(.{ .ret = val });
} else l.b.terminate(.{ .ret = .none });
},
.@"if" => |x| {
if (x.cond_decl) |d| try l.localDecl(d);
const cond = try l.condition(x.cond);
const then_b = try l.b.newBlock();
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.terminate(.{ .cond_br = .{ .cond = cond, .then = then_b, .@"else" = else_b } });
l.b.setBlock(then_b);
try l.stmt(x.then);
l.b.terminate(.{ .br = merge });
if (x.@"else") |e| {
l.b.setBlock(else_b);
try l.stmt(e);
l.b.terminate(.{ .br = merge });
}
l.b.setBlock(merge);
},
.@"for" => |x| {
if (x.init) |i| try l.stmt(i);
try l.loop(x.cond, x.inc, x.body, false);
},
.@"while" => |x| {
if (x.cond_decl != null) {
l.unsupported(st.loc, "declarations in while conditions are not supported yet", .{});
return error.Unsupported;
}
try l.loop(x.cond, null, x.body, false);
},
.do_while => |x| try l.loop(x.cond, null, x.body, true),
.@"break" => {
const target = l.loops.getLast();
l.b.terminate(.{ .br = target.brk });
},
.@"continue" => {
const target = l.loops.getLast();
l.b.terminate(.{ .br = target.cont });
},
.discard => l.b.terminate(.discard),
.@"switch", .case, .default => {
l.unsupported(st.loc, "switch statements are not supported yet", .{});
return error.Unsupported;
},
}
}
/// header (loop merge) -> cond -> body -> continue (inc) -> header.
/// `do` loops test at the end of the continue block.
fn loop(l: *Lowerer, cond: ?*ast.Expr, inc: ?*ast.Expr, body: *const ast.Stmt, do_while: bool) Error!void {
const header = try l.b.newBlock();
const body_b = try l.b.newBlock();
const cont = try l.b.newBlock();
const merge = try l.b.newBlock();
l.b.terminate(.{ .br = header });
l.b.setBlock(header);
l.b.f.block(header).merge = .{ .loop = .{ .merge = merge, .@"continue" = cont } };
if (!do_while and cond != null) {
const check = try l.b.newBlock();
l.b.terminate(.{ .br = check });
l.b.setBlock(check);
const c = try l.condition(cond.?);
l.b.terminate(.{ .cond_br = .{ .cond = c, .then = body_b, .@"else" = merge } });
} else l.b.terminate(.{ .br = body_b });
try l.loops.append(l.arena, .{ .brk = merge, .cont = cont });
l.b.setBlock(body_b);
try l.stmt(body);
l.b.terminate(.{ .br = cont });
_ = l.loops.pop();
l.b.setBlock(cont);
if (inc) |e| _ = try l.rvalue(e);
if (do_while and cond != null) {
const c = try l.condition(cond.?);
l.b.terminate(.{ .cond_br = .{ .cond = c, .then = header, .@"else" = merge } });
} else l.b.terminate(.{ .br = header });
l.b.setBlock(merge);
}
fn localDecl(l: *Lowerer, d: *const ast.Decl) Error!void {
switch (d.kind) {
.@"var" => |*v| {
const variable = l.s.decl_vars.get(v) orelse return;
if (variable.storage == .local_static) {
l.unsupported(d.loc, "static locals are not supported yet", .{});
return error.Unsupported;
}
const local = try l.b.add(.{ .op = .local_var, .ty = variable.type, .ptr = .function });
try l.vars.put(l.arena, variable, local);
if (v.init) |init_e| {
if (init_e.kind == .init_list) {
const val = try l.initList(init_e, variable.type);
try l.b.store(local, val);
} else try l.b.store(local, try l.converted(init_e, variable.type));
}
},
.typedef, .@"struct", .@"enum", .static_assert, .pragma => {},
else => {
l.unsupported(d.loc, "this local declaration is not supported yet", .{});
return error.Unsupported;
},
}
}
fn condition(l: *Lowerer, e: *ast.Expr) Error!Ref {
return l.converted(e, try l.types().scalar(.bool));
}
// ------------------------------------------------------------------
// Expressions
fn concrete(l: *Lowerer, ty: TypeId) Error!TypeId {
const c = l.types().component(ty) orelse return ty;
if (!c.isLiteral()) return ty;
return l.types().withComponent(ty, c.concrete());
}
/// `e` converted to `target` (implicit conversion rules: component
/// conversion, scalar splat, vector truncation).
fn converted(l: *Lowerer, e: *ast.Expr, target: TypeId) Error!Ref {
const v = try l.rvalue(e);
return l.convert(v, target);
}
fn convert(l: *Lowerer, v: Ref, target: TypeId) Error!Ref {
const t = l.types();
const inst = l.b.f.inst(v);
if (inst.ty == target) return v;
const fs = t.shape(inst.ty) orelse return v; // objects, structs: same type
const ts = t.shape(target) orelse return v;
const tc = t.component(target).?;
// Constants convert at compile time.
if (inst.op == .constant and fs.count() == 1) {
const scalar_ty = try t.scalar(tc);
const c = inst.op.constant;
const k = if (tc.isFloat())
try l.b.constFloat(scalar_ty, switch (c) {
.int => |i| @floatFromInt(i),
.float => |f| f,
})
else if (tc == .bool)
try l.b.constInt(scalar_ty, switch (c) {
.int => |i| @intFromBool(i != 0),
.float => |f| @intFromBool(f != 0),
})
else
try l.b.constInt(scalar_ty, switch (c) {
.int => |i| i,
.float => |f| if (std.math.isFinite(f)) @intFromFloat(@trunc(f)) else 0,
});
if (ts.count() == 1 and ts.kind == .scalar) return k;
return l.b.add(.{ .op = .{ .splat = k }, .ty = target });
}
// Shape first, in the source component type.
var cur = v;
if (fs.count() == 1 and ts.count() > 1) {
const sc = if (fs.kind == .scalar) cur else try l.b.add(.{ .op = .{ .extract = .{ .agg = cur, .index = 0 } }, .ty = try t.scalar(t.component(inst.ty).?) });
const conv = try l.convert(sc, try t.scalar(tc));
return l.b.add(.{ .op = .{ .splat = conv }, .ty = target });
}
if (ts.kind == .scalar and fs.kind != .scalar) {
cur = try l.b.add(.{ .op = .{ .extract = .{ .agg = cur, .index = 0 } }, .ty = try t.scalar(t.component(inst.ty).?) });
} else if (ts.kind == .vector and fs.kind == .vector and ts.cols < fs.cols) {
const comps = try l.arena.alloc(u8, ts.cols);
for (comps, 0..) |*c, i| c.* = @intCast(i);
cur = try l.b.add(.{ .op = .{ .shuffle = .{ .vec = cur, .components = comps } }, .ty = try t.vector(t.component(inst.ty).?, ts.cols) });
} else if (fs.kind != ts.kind or fs.rows != ts.rows or fs.cols != ts.cols) {
if (!(fs.count() == 1 and ts.count() == 1)) {
l.unsupported(.none, "conversion from '{s}' to '{s}' is not supported yet", .{ l.s.typeName(inst.ty), l.s.typeName(target) });
return error.Unsupported;
}
if (fs.kind != .scalar) cur = try l.b.add(.{ .op = .{ .extract = .{ .agg = cur, .index = 0 } }, .ty = try t.scalar(t.component(inst.ty).?) });
}
const cur_ty = l.b.f.inst(cur).ty;
if (cur_ty == target) return cur;
const same_shape_target = try t.withComponent(cur_ty, tc);
if (same_shape_target != cur_ty) cur = try l.b.add(.{ .op = .{ .convert = cur }, .ty = same_shape_target });
if (same_shape_target != target) {
// float1 <-> float
if (ts.kind == .scalar) return l.b.add(.{ .op = .{ .extract = .{ .agg = cur, .index = 0 } }, .ty = target });
return l.b.add(.{ .op = .{ .construct = try l.arena.dupe(Ref, &.{cur}) }, .ty = target });
}
return cur;
}
fn rvalue(l: *Lowerer, e: *ast.Expr) Error!Ref {
const t = l.types();
switch (e.kind) {
.int_lit => |text| {
const ty = try l.concrete(e.ty);
return l.b.constInt(ty, semamod.parseIntLiteral(text) orelse 0);
},
.float_lit => |text| {
const ty = try l.concrete(e.ty);
return l.b.constFloat(ty, semamod.parseFloatLiteral(text) orelse 0);
},
.bool_lit => |b| return l.b.constInt(try t.scalar(.bool), @intFromBool(b)),
.name => {
const r = l.s.resolution(e) orelse return l.fail(e, "this name");
switch (r) {
.variable => return l.b.load(try l.lvalue(e)),
.enumerator => |v| return l.b.constInt(try l.concrete(e.ty), v),
else => return l.fail(e, "this name"),
}
},
.binary => |x| return l.binary(e, x.op, x.lhs, x.rhs),
.unary => |x| return l.unary(e, x.op, x.operand),
.assign => |x| {
const lt = x.lhs.ty;
var value: Ref = undefined;
if (x.op == .assign) {
value = try l.converted(x.rhs, lt);
} else {
const old = try l.rvalue(x.lhs);
const rhs = try l.rvalue(x.rhs);
const bop = std.meta.stringToEnum(ast.BinaryOp, @tagName(x.op)).?;
const res = try l.arith(bop, old, rhs, lt, x.lhs.ty, x.rhs.ty);
value = try l.convert(res, lt);
}
try l.storeTo(x.lhs, value);
return value;
},
.conditional => |x| {
const ty = try l.concrete(e.ty);
const tmp = try l.b.add(.{ .op = .local_var, .ty = ty, .ptr = .function });
const cond = try l.condition(x.cond);
const then_b = try l.b.newBlock();
const else_b = try l.b.newBlock();
const merge = try l.b.newBlock();
l.b.f.block(l.b.cur).merge = .{ .selection = merge };
l.b.terminate(.{ .cond_br = .{ .cond = cond, .then = then_b, .@"else" = else_b } });
l.b.setBlock(then_b);
try l.b.store(tmp, try l.converted(x.then, ty));
l.b.terminate(.{ .br = merge });
l.b.setBlock(else_b);
try l.b.store(tmp, try l.converted(x.@"else", ty));
l.b.terminate(.{ .br = merge });
l.b.setBlock(merge);
return l.b.load(tmp);
},
.call => |c| return l.call(e, c.callee, c.args),
.construct => |c| return l.construct(e, try l.concrete(e.ty), c.args),
.cast => |c| {
const v = try l.rvalue(c.operand);
return l.convertExplicit(v, try l.concrete(e.ty));
},
.member => |m| return l.member(e, m.base, m.name),
.index => |x| {
const bt = t.get(x.base.ty);
if (bt == .resource) {
const res = try l.rvalue(x.base);
const idx = try l.indexValue(x.index, bt.resource.kind.indexDims());
return l.b.add(.{ .op = .{ .res_load = .{ .res = res, .index = idx } }, .ty = try l.concrete(e.ty) });
}
if (isAddressable(x.base)) return l.b.load(try l.lvalue(e));
const base = try l.rvalue(x.base);
if (l.s.evalInt(x.index)) |k| return l.b.add(.{ .op = .{ .extract = .{ .agg = base, .index = @intCast(k) } }, .ty = try l.concrete(e.ty) });
// Dynamic index into a value: spill to storage.
const tmp = try l.b.add(.{ .op = .local_var, .ty = l.b.f.inst(base).ty, .ptr = .function });
try l.b.store(tmp, base);
const idx = try l.converted(x.index, try t.scalar(.uint));
const p = try l.b.add(.{ .op = .{ .access = .{ .base = tmp, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = try l.concrete(e.ty), .ptr = .function });
return l.b.load(p);
},
.sizeof_type, .sizeof_expr, .is_same => {
if (l.s.evalInt(e)) |v| return l.b.constInt(try l.concrete(e.ty), v);
return l.fail(e, "this expression");
},
.this, .init_list, .string_lit => return l.fail(e, "this expression"),
}
}
fn fail(l: *Lowerer, e: *const ast.Expr, comptime what: []const u8) Error {
l.unsupported(e.loc, what ++ " is not supported yet", .{});
return error.Unsupported;
}
/// Index for `resource[i]`: uint, or uintN for multi-dimensional
/// resources.
fn indexValue(l: *Lowerer, e: *ast.Expr, dims: u8) Error!Ref {
const t = l.types();
const ty = if (dims <= 1) try t.scalar(.uint) else try t.vector(.uint, dims);
return l.converted(e, ty);
}
fn binary(l: *Lowerer, e: *ast.Expr, op: ast.BinaryOp, lhs: *ast.Expr, rhs: *ast.Expr) Error!Ref {
const t = l.types();
switch (op) {
.comma => {
_ = try l.rvalue(lhs);
return l.rvalue(rhs);
},
.log_and, .log_or => {
// Short-circuit (HLSL 2021: scalar operands).
const bool_ty = try t.scalar(.bool);
const tmp = try l.b.add(.{ .op = .local_var, .ty = bool_ty, .ptr = .function });
const a = try l.condition(lhs);
try l.b.store(tmp, a);
const rhs_b = try l.b.newBlock();
const merge = try l.b.newBlock();
l.b.f.block(l.b.cur).merge = .{ .selection = merge };
l.b.terminate(.{ .cond_br = .{ .cond = a, .then = if (op == .log_and) rhs_b else merge, .@"else" = if (op == .log_and) merge else rhs_b } });
l.b.setBlock(rhs_b);
try l.b.store(tmp, try l.condition(rhs));
l.b.terminate(.{ .br = merge });
l.b.setBlock(merge);
return l.b.load(tmp);
},
else => {},
}
const a = try l.rvalue(lhs);
const b = try l.rvalue(rhs);
return l.arith(op, a, b, try l.concrete(e.ty), lhs.ty, rhs.ty);
}
/// `a op b` with Sema's operand types and the expression's result type
/// (bool-shaped for comparisons).
fn arith(l: *Lowerer, op: ast.BinaryOp, a: Ref, b: Ref, result_ty: TypeId, a_ty: TypeId, b_ty: TypeId) Error!Ref {
const t = l.types();
const cmp: ?ir.CmpOp = switch (op) {
.eq => .eq,
.ne => .ne,
.lt => .lt,
.le => .le,
.gt => .gt,
.ge => .ge,
else => null,
};
// The computation type: the result type, or for comparisons the
// combined operand type in the result's shape.
var comp_ty = result_ty;
if (cmp != null) {
const c = Scalar.combine(t.component(a_ty).?, t.component(b_ty).?);
comp_ty = try t.withComponent(result_ty, if (c.isLiteral()) c.concrete() else c);
}
if (op == .shl or op == .shr) {
const av = try l.convert(a, comp_ty);
const bv = try l.convert(b, comp_ty);
return l.b.add(.{ .op = .{ .binary = .{ .op = if (op == .shl) .shl else .shr, .lhs = av, .rhs = bv } }, .ty = comp_ty });
}
const av = try l.convert(a, comp_ty);
const bv = try l.convert(b, comp_ty);
if (cmp) |c| return l.b.add(.{ .op = .{ .cmp = .{ .op = c, .lhs = av, .rhs = bv } }, .ty = result_ty });
const bop: ir.BinaryOp = switch (op) {
.add => .add,
.sub => .sub,
.mul => .mul,
.div => .div,
.rem => .rem,
.bit_and => .bit_and,
.bit_or => .bit_or,
.bit_xor => .bit_xor,
else => unreachable,
};
return l.b.add(.{ .op = .{ .binary = .{ .op = bop, .lhs = av, .rhs = bv } }, .ty = comp_ty });
}
fn unary(l: *Lowerer, e: *ast.Expr, op: ast.UnaryOp, operand: *ast.Expr) Error!Ref {
const t = l.types();
const ty = try l.concrete(e.ty);
switch (op) {
.plus => return l.converted(operand, ty),
.minus => return l.b.add(.{ .op = .{ .unary = .{ .op = .neg, .operand = try l.converted(operand, ty) } }, .ty = ty }),
.bit_not => return l.b.add(.{ .op = .{ .unary = .{ .op = .bit_not, .operand = try l.converted(operand, ty) } }, .ty = ty }),
.not => return l.b.add(.{ .op = .{ .unary = .{ .op = .not, .operand = try l.converted(operand, ty) } }, .ty = ty }),
.pre_inc, .pre_dec, .post_inc, .post_dec => {
const old = try l.rvalue(operand);
const vty = l.b.f.inst(old).ty;
const one = try l.convert(try l.b.constInt(try t.scalar(.int), 1), vty);
const new = try l.b.add(.{ .op = .{ .binary = .{ .op = if (op == .pre_inc or op == .post_inc) .add else .sub, .lhs = old, .rhs = one } }, .ty = vty });
try l.storeTo(operand, new);
return if (op == .pre_inc or op == .pre_dec) new else old;
},
}
}
fn convertExplicit(l: *Lowerer, v: Ref, target: TypeId) Error!Ref {
// Explicit casts additionally allow truncation to fewer components,
// which `convert` already performs.
return l.convert(v, target);
}
fn construct(l: *Lowerer, e: *ast.Expr, ty: TypeId, args: []const *ast.Expr) Error!Ref {
const t = l.types();
const comp = t.component(ty) orelse return l.fail(e, "this constructor");
const scalar_ty = try t.scalar(comp);
var comps: std.ArrayList(Ref) = .empty;
for (args) |a| {
const v = try l.rvalue(a);
const vt = l.b.f.inst(v).ty;
const n = t.componentCount(vt) orelse return l.fail(a, "this constructor argument");
if (t.get(vt) == .scalar or t.get(vt) == .@"enum") {
try comps.append(l.arena, try l.convert(v, scalar_ty));
} else {
const ec = try t.scalar(t.component(vt).?);
for (0..n) |i| {
const x = try l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = @intCast(i) } }, .ty = ec });
try comps.append(l.arena, try l.convert(x, scalar_ty));
}
}
}
if (t.get(ty) == .scalar) return comps.items[0];
if (comps.items.len == 1) return l.b.add(.{ .op = .{ .splat = comps.items[0] }, .ty = ty });
return l.b.add(.{ .op = .{ .construct = comps.items }, .ty = ty });
}
fn initList(l: *Lowerer, e: *ast.Expr, ty: TypeId) Error!Ref {
const t = l.types();
if (t.shape(ty) == null) return l.fail(e, "this initializer list");
// Flatten the list's scalars into a constructor of `ty`.
var flat: std.ArrayList(*ast.Expr) = .empty;
try flattenList(l.arena, e, &flat);
return l.construct(e, ty, flat.items);
}
fn member(l: *Lowerer, e: *ast.Expr, base: *ast.Expr, name: []const u8) Error!Ref {
const t = l.types();
const bt = t.get(base.ty);
switch (bt) {
.scalar, .vector => {
const v = try l.rvalue(base);
const comps = swizzleComponents(name) orelse return l.fail(e, "this swizzle");
const ty = try l.concrete(e.ty);
if (bt == .scalar) {
if (comps.len == 1) return v;
return l.b.add(.{ .op = .{ .splat = v }, .ty = ty });
}
if (comps.len == 1) return l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = comps[0] } }, .ty = ty });
return l.b.add(.{ .op = .{ .shuffle = .{ .vec = v, .components = comps } }, .ty = ty });
},
.@"struct" => {
if (isAddressable(base)) return l.b.load(try l.lvalue(e));
const v = try l.rvalue(base);
const r = l.s.resolution(e) orelse return l.fail(e, "this member");
return l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = r.field } }, .ty = e.ty });
},
else => return l.fail(e, "this member access"),
}
}
fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref {
const r = l.s.resolution(e) orelse return l.fail(e, "this call");
const ret_ty = try l.concrete(e.ty);
switch (r) {
.function => |f| {
const fi = try l.functionIndex(f);
const vals = try l.arena.alloc(Ref, args.len);
const temps = try l.arena.alloc(Ref, args.len);
for (args, f.params, 0..) |a, p, i| {
if (p.dir == .in) {
vals[i] = try l.converted(a, p.type);
} else {
// Copy-in / copy-out through a temporary.
temps[i] = try l.b.add(.{ .op = .local_var, .ty = p.type, .ptr = .function });
if (p.dir == .inout) try l.b.store(temps[i], try l.converted(a, p.type));
vals[i] = temps[i];
}
}
const res = try l.b.add(.{ .op = .{ .call = .{ .func = fi, .args = vals } }, .ty = ret_ty });
for (args, f.params, 0..) |a, p, i| {
if (p.dir == .in) continue;
const back = try l.b.load(temps[i]);
try l.storeTo(a, try l.convert(back, a.ty));
}
return res;
},
.intrinsic => |it| {
const name = table.intrinsics[it.index].name;
if (it.object) |_| {
const obj = callee.kind.member.base;
const res = try l.rvalue(obj);
const vals = try l.arena.alloc(Ref, args.len);
for (args, 0..) |a, i| vals[i] = try l.converted(a, try l.concrete(it.params[i]));
return l.b.add(.{ .op = .{ .method = .{ .name = name, .res = res, .args = vals } }, .ty = ret_ty });
}
const spec = table.intrinsics[it.index];
const vals = try l.arena.alloc(Ref, args.len);
for (args, 0..) |a, i| {
if (i < spec.params.len and spec.params[i].qual != .in) {
return l.fail(a, "out arguments of intrinsics");
}
vals[i] = try l.converted(a, try l.concrete(it.params[i]));
}
return l.b.add(.{ .op = .{ .intrinsic = .{ .name = name, .args = vals } }, .ty = ret_ty });
},
else => return l.fail(e, "this call"),
}
}
/// Pointer to the storage `e` designates.
fn lvalue(l: *Lowerer, e: *ast.Expr) Error!Ref {
const t = l.types();
switch (e.kind) {
.name => {
const r = l.s.resolution(e) orelse return l.fail(e, "this name");
if (r != .variable) return l.fail(e, "this name");
const v = r.variable;
if (l.vars.get(v)) |p| return p;
switch (v.storage) {
.local, .param, .local_static => return l.fail(e, "this variable"),
else => {},
}
const g = try l.globalIndex(v);
const glob = l.m.globals.items[g];
return l.b.add(.{ .op = .{ .global = g }, .ty = glob.ty, .ptr = glob.space });
},
.member => |m| {
const r = l.s.resolution(e) orelse return l.fail(e, "this member");
if (r != .field) return l.fail(e, "this member");
const base = try l.lvalue(m.base);
const idx = try l.b.constInt(try t.scalar(.uint), r.field);
return l.b.add(.{ .op = .{ .access = .{ .base = base, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = l.b.f.inst(base).ptr });
},
.index => |x| {
const base = try l.lvalue(x.base);
const idx = try l.converted(x.index, try t.scalar(.uint));
return l.b.add(.{ .op = .{ .access = .{ .base = base, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = l.b.f.inst(base).ptr });
},
.cast => |c| return l.lvalue(c.operand),
else => return l.fail(e, "this assignment target"),
}
}
/// Stores `value` (already of `lhs`'s type) into what `lhs` designates.
fn storeTo(l: *Lowerer, lhs: *ast.Expr, value: Ref) Error!void {
const t = l.types();
switch (lhs.kind) {
.index => |x| if (t.get(x.base.ty) == .resource) {
const res = try l.rvalue(x.base);
const idx = try l.indexValue(x.index, t.get(x.base.ty).resource.kind.indexDims());
_ = try l.b.add(.{ .op = .{ .res_store = .{ .res = res, .index = idx, .value = value } }, .ty = TypeTable.void_type });
return;
},
.member => |m| if (t.get(m.base.ty) == .vector or t.get(m.base.ty) == .scalar) {
// Swizzle store: read, replace the named components, write.
const comps = swizzleComponents(m.name) orelse return error.Unsupported;
if (t.get(m.base.ty) == .scalar) return l.storeTo(m.base, value);
var whole = try l.rvalue(m.base);
const ec = try t.scalar(t.component(m.base.ty).?);
for (comps, 0..) |c, i| {
const part = if (comps.len == 1) value else try l.b.add(.{ .op = .{ .extract = .{ .agg = value, .index = @intCast(i) } }, .ty = ec });
whole = try l.b.add(.{ .op = .{ .insert = .{ .agg = whole, .value = part, .index = c } }, .ty = m.base.ty });
}
return l.storeTo(m.base, whole);
},
else => {},
}
try l.b.store(try l.lvalue(lhs), value);
}
// ------------------------------------------------------------------
// Entry point
fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void {
var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage };
for (f.decl.attrs) |a| {
if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) {
for (a.args, 0..) |arg, i| entry.num_threads[i] = @intCast(@max(1, l.s.evalInt(arg) orelse 1));
}
}
const wrapper = try l.m.addFunction(.{ .name = opts.entry, .params = &.{}, .ret = TypeTable.void_type });
l.b = .{ .m = &l.m, .f = l.m.functions.items[wrapper] };
l.b.setBlock(try l.b.newBlock());
const args = try l.arena.alloc(Ref, f.params.len);
const locals = try l.arena.alloc(Ref, f.params.len);
for (f.decl.params, f.params, 0..) |pd, p, i| {
const sem = semanticOf(pd.semantics) orelse {
l.unsupported(pd.name_loc, "entry parameter '{s}' needs a semantic", .{pd.name});
return error.Unsupported;
};
locals[i] = try l.b.add(.{ .op = .local_var, .ty = p.type, .ptr = .function });
if (p.dir != .out) {
try entry.inputs.append(l.arena, sigElement(sem, p.type));
const v = try l.b.add(.{ .op = .{ .input = @intCast(entry.inputs.items.len - 1) }, .ty = p.type });
try l.b.store(locals[i], v);
}
args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i];
}
const ret = try l.b.add(.{ .op = .{ .call = .{ .func = main, .args = args } }, .ty = f.ret });
if (f.ret != TypeTable.void_type) {
const sem = semanticOf(f.decl.ret_semantics) orelse {
l.unsupported(f.loc, "entry return value needs a semantic", .{});
return error.Unsupported;
};
try entry.outputs.append(l.arena, sigElement(sem, f.ret));
_ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = ret } }, .ty = TypeTable.void_type });
}
for (f.decl.params, f.params, 0..) |pd, p, i| {
if (p.dir == .in) continue;
try entry.outputs.append(l.arena, sigElement(semanticOf(pd.semantics).?, p.type));
const v = try l.b.load(locals[i]);
_ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = v } }, .ty = TypeTable.void_type });
}
l.b.terminate(.{ .ret = .none });
entry.wrapper = wrapper;
// The HLSL entry keeps its name with a prefix (as dxc's SPIR-V).
l.m.functions.items[main].name = try std.fmt.allocPrint(l.arena, "src.{s}", .{opts.entry});
l.m.entry = entry;
}
};
fn semanticOf(sems: []const ast.Semantic) ?[]const u8 {
for (sems) |sem| if (sem.kind == .semantic) return sem.values[0];
return null;
}
/// `SV_Target1` -> name `SV_Target`, index 1.
fn sigElement(semantic: []const u8, ty: TypeId) ir.SigElement {
var end = semantic.len;
while (end > 0 and std.ascii.isDigit(semantic[end - 1])) end -= 1;
const index = std.fmt.parseInt(u32, semantic[end..], 10) catch 0;
return .{
.semantic = semantic[0..end],
.semantic_index = index,
.ty = ty,
.system_value = std.ascii.startsWithIgnoreCase(semantic, "SV_"),
};
}
/// `register(t3, space1)` -> class 't', index 3, space 1.
fn parseBinding(values: []const []const u8) ir.Binding {
var b: ir.Binding = .{};
for (values) |v| {
if (std.mem.startsWith(u8, v, "space")) {
b.space = std.fmt.parseInt(u32, v[5..], 10) catch 0;
} else if (v.len > 0 and std.mem.indexOfScalar(u8, "bcistu", std.ascii.toLower(v[0])) != null) {
const end = std.mem.indexOfScalar(u8, v, '[') orelse v.len;
b.class = std.ascii.toLower(v[0]);
b.index = std.fmt.parseInt(u32, v[1..end], 10) catch 0;
b.explicit = true;
}
}
return b;
}
/// `xyzw` / `rgba` swizzle -> component indices.
fn swizzleComponents(name: []const u8) ?[]const u8 {
if (name.len == 0 or name.len > 4) return null;
const static = struct {
var buf: [16][4]u8 = undefined;
var next: usize = 0;
};
const out = &static.buf[static.next % 16];
static.next += 1;
for (name, 0..) |c, i| {
out[i] = switch (c) {
'x', 'r' => 0,
'y', 'g' => 1,
'z', 'b' => 2,
'w', 'a' => 3,
else => return null,
};
}
return out[0..name.len];
}
fn isAddressable(e: *const ast.Expr) bool {
return switch (e.kind) {
.name => true,
.member => |m| isAddressable(m.base),
.index => |x| isAddressable(x.base),
else => false,
};
}
fn flattenList(a: Allocator, e: *ast.Expr, out: *std.ArrayList(*ast.Expr)) Allocator.Error!void {
if (e.kind == .init_list) {
for (e.kind.init_list) |item| try flattenList(a, item, out);
} else try out.append(a, e);
}

View File

@ -30,6 +30,7 @@ const Options = struct {
parse: bool = false,
dump_ast: bool = false,
sema: bool = false,
dump_ir: 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.
@ -93,6 +94,7 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std
opts.dump_ast = true;
},
.zdxc_sema => opts.sema = true,
.zdxc_ir => opts.dump_ir = true,
.fcolor_diagnostics => opts.color = true,
.fno_color_diagnostics => opts.color = false,
},
@ -234,6 +236,7 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
.enable_16bit = opts.enable_16bit,
});
var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null;
if (try pp.enterMainFile(input)) {
if (opts.preprocess) {
try front.pp_print.print(&pp, &out.writer);
@ -252,6 +255,21 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
.root = opts.entry,
});
try sema.checkUnit(tu);
if (!opts.sema and !diags.hasErrors() and profile != null and !is_lib) {
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {
.vertex => .vertex,
.pixel => .pixel,
.geometry => .geometry,
.hull => .hull,
.domain => .domain,
.compute => .compute,
else => .library,
};
module = zdxc.ir.lower.lowerUnit(arena, &sema, .{ .entry = opts.entry, .stage = stage }) catch |e| switch (e) {
error.Unsupported => null,
else => |x| return x,
};
}
}
}
}
@ -267,6 +285,25 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
}
if (opts.parse or opts.sema) return;
if (profile == null) return cli.fail("missing -T <profile>", .{});
if (module) |*m| {
if (opts.dump_ir) {
try zdxc.ir.ir.dump(m, stdout);
return;
}
if (opts.spirv) {
const bytes = zdxc.spirv.emit.emit(arena, m, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return error.CompileFailed;
},
else => |x| return x,
};
const path = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = bytes });
return;
}
}
return cli.fail("code generation is not implemented yet: the input was checked but no output was written (use -zdxc-empty for a placeholder shader)", .{});
}

View File

@ -28,6 +28,7 @@ pub const Extra = enum {
zdxc_parse,
zdxc_ast,
zdxc_sema,
zdxc_ir,
fcolor_diagnostics,
fno_color_diagnostics,
};
@ -39,6 +40,7 @@ const extra_options = [_]struct { id: Extra, spelling: []const u8, help: []const
.{ .id = .zdxc_parse, .spelling = "zdxc-parse", .help = "Preprocess and parse the input, reporting syntax errors only (development)" },
.{ .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 = .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

@ -23,6 +23,11 @@ pub const dxil = struct {
pub const shader = @import("dxil/shader.zig");
};
pub const ir = struct {
pub const ir = @import("ir/ir.zig");
pub const lower = @import("ir/lower.zig");
};
pub const sema = struct {
pub const types = @import("sema/types.zig");
pub const intrinsics = @import("sema/intrinsics.zig");
@ -31,6 +36,7 @@ pub const sema = struct {
pub const spirv = struct {
pub const builder = @import("spirv/builder.zig");
pub const emit = @import("spirv/emit.zig");
};
pub const version = "0.0.0";

View File

@ -72,32 +72,38 @@ pub const Db = struct {
/// Resolve a call; reports a diagnostic and returns the error type when
/// no overload matches. `sema` is the calling Sema (for conversions and
/// diagnostics); `object` is the method's object type, if any.
pub fn resolve(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !TypeId {
/// A resolved intrinsic call: the table entry and its concrete
/// parameter types (the argument's type where the table leaves a
/// parameter unconstrained).
pub const Resolved = struct { ret: TypeId, index: u16 = 0, params: []const TypeId = &.{}, ok: bool = false };
pub fn resolve(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
const cands = try db.candidates(sema.arena, ns, name);
if (cands.len == 0) {
if (object) |o| {
sema.err(loc, "no member named '{s}' in '{s}'", .{ name, sema.typeName(o) });
} else sema.err(loc, "use of undeclared identifier '{s}'", .{name});
return TypeTable.error_type;
return .{ .ret = TypeTable.error_type };
}
var best: ?Match = null;
for (cands) |ci| {
const m = try matchOne(sema, &table.intrinsics[ci], object, args, explicit) orelse continue;
var m = try matchOne(sema, &table.intrinsics[ci], object, args, explicit) orelse continue;
m.index = ci;
if (best == null or m.cost < best.?.cost) best = m;
}
// vk::static_pointer_cast / reinterpret_pointer_cast return a
// BufferPointer of the template argument: not modelled yet.
if (best != null and (std.mem.eql(u8, name, "static_pointer_cast") or std.mem.eql(u8, name, "reinterpret_pointer_cast"))) return TypeTable.error_type;
if (best != null and (std.mem.eql(u8, name, "static_pointer_cast") or std.mem.eql(u8, name, "reinterpret_pointer_cast"))) return .{ .ret = TypeTable.error_type };
const m = best orelse {
sema.err(loc, "no matching function for call to '{s}'", .{name});
return TypeTable.error_type;
return .{ .ret = TypeTable.error_type };
};
for (args, 0..) |a, i| {
if (i < m.out_params.len and m.out_params[i] and !a.lvalue) {
sema.err(a.loc, "cannot bind non-lvalue argument to out parameter", .{});
}
}
return m.ret;
return .{ .ret = m.ret, .index = m.index, .params = m.params, .ok = true };
}
};
@ -105,6 +111,8 @@ const Match = struct {
ret: TypeId,
cost: u32,
out_params: []const bool,
index: u16 = 0,
params: []const TypeId = &.{},
};
const Layout = struct { rows: u8, cols: u8, kind: TypeTable.Shape };
@ -179,6 +187,7 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
var cost: u32 = 0;
const out_params = try sema.arena.alloc(bool, args.len);
@memset(out_params, false);
const param_types = try sema.arena.alloc(TypeId, args.len);
// Parameter types, checked against the arguments.
for (args, 0..) |a, ai| {
@ -187,6 +196,7 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
const s = specs[i];
out_params[ai] = s.qual == .out or s.qual == .inout or s.qual == .ref;
const pt = try paramType(sema, specs, i, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null;
param_types[ai] = if (pt == TypeTable.error_type) a.ty else pt;
if (pt == TypeTable.error_type) continue; // unconstrained object / unknown class
const c = sema.conversionCost(a.ty, pt) orelse return null;
cost += c;
@ -194,7 +204,8 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
// Return type.
const ret = try paramType(sema, specs, 0, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null;
return .{ .ret = ret, .cost = cost, .out_params = out_params };
for (args[@min(args.len, it.params.len)..], @min(args.len, it.params.len)..) |a, ai| param_types[ai] = a.ty; // varargs
return .{ .ret = ret, .cost = cost, .out_params = out_params, .params = param_types };
}
/// The concrete type of spec `i`, or null if the arguments cannot fit.

View File

@ -47,6 +47,24 @@ pub const Variable = struct {
read_only: bool,
/// Initializer of `static const` / `const` variables, for constants.
init: ?*ast.Expr = null,
/// The declaration (globals, locals): register bindings, semantics.
decl: ?*const ast.VarDecl = null,
/// Position among the function's parameters (storage == .param).
param_index: u32 = 0,
};
/// What an expression refers to, recorded by Sema for lowering
/// (`Expr.info` is an index into `Sema.resolutions` plus one).
pub const Resolution = union(enum) {
variable: *Variable,
enumerator: i64,
/// A call to a user function or method.
function: *Function,
/// A call to an intrinsic or builtin method (`object` is the method's
/// object type).
intrinsic: struct { index: u16, params: []const TypeId, object: ?TypeId = null },
/// A struct field (member expression).
field: u32,
};
pub const Param = struct {
@ -69,6 +87,9 @@ pub const Function = struct {
owner: ?*types.StructInfo = null,
/// Functions called from the body (call graph for recursion checks).
callees: std.ArrayList(*Function) = .empty,
/// The parameters' variables, created when the body is checked
/// (null for unnamed parameters).
param_vars: []?*Variable = &.{},
};
pub const FuncSet = struct {
@ -134,6 +155,9 @@ pub const Sema = struct {
typedef_attrs: std.StringHashMapUnmanaged(TypeAttrs) = .empty,
/// Type attributes of the last resolveType result.
last_attrs: TypeAttrs = .{},
resolutions: std.ArrayList(Resolution) = .empty,
/// Variable of each checked variable declaration (for lowering).
decl_vars: std.AutoHashMapUnmanaged(*const ast.VarDecl, *Variable) = .empty,
loop_depth: u32 = 0,
switch_depth: u32 = 0,
intrinsic_db: intrinsics.Db,
@ -1323,8 +1347,10 @@ pub const Sema = struct {
.loc = v.name_loc,
.read_only = read_only,
.init = v.init,
.decl = v,
};
try s.declare(v.name, .{ .variable = variable }, v.name_loc);
try s.decl_vars.put(s.arena, v, variable);
// Unsized arrays take their size from the initializer.
if (v.init) |init_e| if (!is_auto) {
if (s.types.get(ty) == .array and s.types.get(ty).array.len == 0 and init_e.kind == .init_list) {
@ -1449,10 +1475,13 @@ pub const Sema = struct {
defer s.current_fn = saved_fn;
_ = try s.pushScope(.function);
defer s.popScope();
for (f.params, params) |p, pp| {
func.param_vars = try s.arena.alloc(?*Variable, params.len);
@memset(func.param_vars, null);
for (f.params, params, 0..) |*p, pp, pi| {
if (p.name.len == 0) continue;
const pv = try s.arena.create(Variable);
pv.* = .{ .name = p.name, .type = pp.type, .quals = p.quals, .storage = .param, .loc = p.name_loc, .read_only = p.quals.@"const" };
pv.* = .{ .name = p.name, .type = pp.type, .quals = p.quals, .storage = .param, .loc = p.name_loc, .read_only = p.quals.@"const", .decl = p, .param_index = @intCast(pi) };
func.param_vars[pi] = pv;
try s.declare(p.name, .{ .variable = pv }, p.name_loc);
}
// The body's top-level block shares the parameter scope.
@ -1580,6 +1609,16 @@ pub const Sema = struct {
// ------------------------------------------------------------------
// Expressions
fn record(s: *Sema, e: *ast.Expr, r: Resolution) void {
s.resolutions.append(s.arena, r) catch return;
e.info = @intCast(s.resolutions.items.len);
}
/// The resolution Sema recorded for `e`, if any.
pub fn resolution(s: *const Sema, e: *const ast.Expr) ?Resolution {
return if (e.info == 0) null else s.resolutions.items[e.info - 1];
}
fn setType(e: *ast.Expr, t: Typed) Typed {
e.ty = t.ty;
return t;
@ -1693,7 +1732,10 @@ pub const Sema = struct {
fn nameExpr(s: *Sema, e: *ast.Expr, n: ast.Name) Allocator.Error!Typed {
if (s.lookupName(n)) |sym| switch (sym) {
.variable => |v| return .{ .ty = v.type, .lvalue = true, .read_only = v.read_only },
.variable => |v| {
s.record(e, .{ .variable = v });
return .{ .ty = v.type, .lvalue = true, .read_only = v.read_only };
},
.functions => |set| return .{ .ty = TypeTable.error_type, .callee = .{ .functions = set } },
.enumerator => |en| return rvalue(en.type),
.type => |t| return .{ .ty = TypeTable.error_type, .callee = .{ .type = t } },
@ -2002,7 +2044,6 @@ pub const Sema = struct {
}
fn memberExpr(s: *Sema, e: *ast.Expr, base: *ast.Expr, name: []const u8, name_loc: Loc) Allocator.Error!Typed {
_ = e;
const b = try s.expr(base);
if (b.ty == TypeTable.error_type) return err_typed;
switch (s.types.get(b.ty)) {
@ -2036,7 +2077,10 @@ pub const Sema = struct {
while (fi > 0) {
fi -= 1;
const f = info.fields.items[fi];
if (std.mem.eql(u8, f.name, name)) return .{ .ty = f.type, .lvalue = b.lvalue, .read_only = b.read_only };
if (std.mem.eql(u8, f.name, name)) {
s.record(e, .{ .field = @intCast(fi) });
return .{ .ty = f.type, .lvalue = b.lvalue, .read_only = b.read_only };
}
}
if (info.sema) |p| {
const ss: *StructSema = @ptrCast(@alignCast(p));
@ -2223,7 +2267,9 @@ pub const Sema = struct {
.intrinsic => |name| {
var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
return rvalue(try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit));
const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit);
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } });
return rvalue(r.ret);
},
.method => |m| {
switch (s.types.get(m.object)) {
@ -2237,7 +2283,9 @@ pub const Sema = struct {
var explicit: ?TypeId = null;
if (template_args.len > 0) explicit = try s.typeArg(template_args[0]);
const ns = methodNamespace(s.types.get(m.object)) orelse return err_typed;
return rvalue(try s.intrinsic_db.resolve(s, e.loc, ns, m.name, m.object, arg_types, explicit));
const r = try s.intrinsic_db.resolve(s, e.loc, ns, m.name, m.object, arg_types, explicit);
if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params, .object = m.object } });
return rvalue(r.ret);
},
}
},
@ -2300,8 +2348,8 @@ pub const Sema = struct {
s.err(a.loc, "cannot bind non-lvalue argument to {s} parameter", .{if (f.params[i].dir == .out) "out" else "inout"});
}
}
_ = e;
if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {};
s.record(e, .{ .function = f });
return f.ret;
}
@ -2542,7 +2590,7 @@ pub fn parseIntLiteral(text: []const u8) ?i64 {
return @bitCast(v);
}
fn parseFloatLiteral(text: []const u8) ?f64 {
pub fn parseFloatLiteral(text: []const u8) ?f64 {
if (std.mem.indexOf(u8, text, ".#INF") != null) return std.math.inf(f64);
var end = text.len;
while (end > 0 and std.mem.indexOfScalar(u8, "fFhHlL", text[end - 1]) != null) end -= 1;

View File

@ -6,20 +6,145 @@ const Allocator = std.mem.Allocator;
pub const Id = u32;
/// Opcodes used so far. Will be replaced by tables generated from
/// vendor/spirv grammar JSON.
/// SPIR-V opcodes (unified1 core grammar numbering).
pub const Op = enum(u16) {
undef = 1,
source = 3,
name = 5,
member_name = 6,
extension = 10,
ext_inst_import = 11,
ext_inst = 12,
memory_model = 14,
entry_point = 15,
execution_mode = 16,
capability = 17,
type_void = 19,
type_bool = 20,
type_int = 21,
type_float = 22,
type_vector = 23,
type_matrix = 24,
type_image = 25,
type_sampler = 26,
type_sampled_image = 27,
type_array = 28,
type_runtime_array = 29,
type_struct = 30,
type_pointer = 32,
type_function = 33,
constant_true = 41,
constant_false = 42,
constant = 43,
constant_composite = 44,
constant_null = 46,
function = 54,
function_parameter = 55,
function_end = 56,
function_call = 57,
variable = 59,
load = 61,
store = 62,
access_chain = 65,
decorate = 71,
member_decorate = 72,
vector_extract_dynamic = 77,
vector_insert_dynamic = 78,
vector_shuffle = 79,
composite_construct = 80,
composite_extract = 81,
composite_insert = 82,
sampled_image = 86,
image_sample_implicit_lod = 87,
image_sample_explicit_lod = 88,
image_fetch = 95,
image_read = 98,
image_write = 99,
image_query_size_lod = 103,
image_query_size = 104,
image_query_levels = 106,
convert_f_to_u = 109,
convert_f_to_s = 110,
convert_s_to_f = 111,
convert_u_to_f = 112,
u_convert = 113,
s_convert = 114,
f_convert = 115,
bitcast = 124,
s_negate = 126,
f_negate = 127,
i_add = 128,
f_add = 129,
i_sub = 130,
f_sub = 131,
i_mul = 132,
f_mul = 133,
u_div = 134,
s_div = 135,
f_div = 136,
u_mod = 137,
s_rem = 138,
s_mod = 139,
f_rem = 140,
f_mod = 141,
vector_times_scalar = 142,
matrix_times_scalar = 143,
vector_times_matrix = 144,
matrix_times_vector = 145,
matrix_times_matrix = 146,
dot = 148,
any = 154,
all = 155,
is_nan = 156,
is_inf = 157,
logical_equal = 164,
logical_not_equal = 165,
logical_or = 166,
logical_and = 167,
logical_not = 168,
select = 169,
i_equal = 170,
i_not_equal = 171,
u_greater_than = 172,
s_greater_than = 173,
u_greater_than_equal = 174,
s_greater_than_equal = 175,
u_less_than = 176,
s_less_than = 177,
u_less_than_equal = 178,
s_less_than_equal = 179,
f_ord_equal = 180,
f_ord_not_equal = 182,
f_unord_not_equal = 183,
f_ord_less_than = 184,
f_ord_greater_than = 186,
f_ord_less_than_equal = 188,
f_ord_greater_than_equal = 190,
shift_right_logical = 194,
shift_right_arithmetic = 195,
shift_left_logical = 196,
bitwise_or = 197,
bitwise_xor = 198,
bitwise_and = 199,
not_ = 200,
bit_reverse = 204,
bit_count = 205,
dpdx = 207,
dpdy = 208,
fwidth = 209,
control_barrier = 224,
memory_barrier = 225,
phi = 245,
loop_merge = 246,
selection_merge = 247,
label = 248,
branch = 249,
branch_conditional = 250,
@"switch" = 251,
kill = 252,
@"return" = 253,
return_value = 254,
@"unreachable" = 255,
};
pub const Section = enum {

981
src/spirv/emit.zig Normal file
View File

@ -0,0 +1,981 @@
//! IR -> SPIR-V (Vulkan). Follows dxc's conventions: the HLSL entry is a
//! function called from a parameterless wrapper that loads the stage
//! inputs; resources use dxc's default register-to-binding mapping
//! (binding = register number, descriptor set = register space).
const std = @import("std");
const Allocator = std.mem.Allocator;
const ir = @import("../ir/ir.zig");
const types = @import("../sema/types.zig");
const builder = @import("builder.zig");
const diag = @import("../diag.zig");
const Builder = builder.Builder;
const Id = builder.Id;
const Op = builder.Op;
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
const Scalar = types.Scalar;
const Ref = ir.Ref;
pub const Error = Allocator.Error || error{Unsupported};
/// SPIR-V storage classes.
const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, output = 3, workgroup = 4, private = 6, function = 7, storage_buffer = 12 };
const Capability = enum(u32) { shader = 1, float16 = 9, float64 = 10, int64 = 11, int16 = 22, sampled_buffer = 46, image_buffer = 47, storage_image_extended_formats = 49, image_query = 50 };
pub fn emit(gpa: Allocator, m: *const ir.Module, diags: *diag.Diagnostics) Error![]u8 {
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
var e: Emitter = .{ .arena = arena_state.allocator(), .b = .init(gpa), .m = m, .t = m.types, .diags = diags };
defer e.b.deinit();
try e.module();
return e.b.finish(builder.spv_1_0);
}
const Emitter = struct {
arena: Allocator,
b: Builder,
m: *const ir.Module,
t: *TypeTable,
diags: *diag.Diagnostics,
value_types: std.AutoHashMapUnmanaged(TypeId, Id) = .empty,
pointer_types: std.AutoHashMapUnmanaged(struct { StorageClass, Id }, Id) = .empty,
function_types: std.StringHashMapUnmanaged(Id) = .empty,
constants: std.AutoHashMapUnmanaged(struct { Id, u64 }, Id) = .empty,
capabilities: std.AutoArrayHashMapUnmanaged(Capability, void) = .empty,
glsl: Id = 0,
void_id: Id = 0,
func_ids: []Id = &.{},
/// Per global: the OpVariable and, for buffers, the element pointer
/// type.
global_vars: []Id = &.{},
buffer_elem_ptr: []Id = &.{},
/// Entry inputs / outputs: interface variable and its value type.
inputs: []Interface = &.{},
outputs: []Interface = &.{},
interface_ids: std.ArrayList(Id) = .empty,
// Per function.
vals: []Id = &.{},
f: *const ir.Function = undefined,
const Interface = struct { var_id: Id, ty: TypeId };
fn unsupported(e: *Emitter, comptime fmt: []const u8, args: anytype) Error {
_ = e.diags.report(.{ .severity = .@"error", .loc = .none }, "SPIR-V code generation: " ++ fmt, args);
return error.Unsupported;
}
fn cap(e: *Emitter, c: Capability) !void {
try e.capabilities.put(e.arena, c, {});
}
// ------------------------------------------------------------------
// Types and constants
fn scalarType(e: *Emitter, s: Scalar) Error!Id {
return e.typeId(try e.t.scalar(storageScalar(s)));
}
/// The SPIR-V representation of an HLSL scalar: min-precision and
/// non-native 16-bit `half` use 32-bit types.
fn storageScalar(s: Scalar) Scalar {
return switch (s) {
.min16int, .min12int, .literal_int, .int8_4packed => .int,
.min16uint, .uint8_4packed => .uint,
.half, .min16float, .min10float, .literal_float => .float,
else => s,
};
}
fn typeId(e: *Emitter, ty: TypeId) Error!Id {
if (e.value_types.get(ty)) |id| return id;
const id: Id = switch (e.t.get(ty)) {
.void => blk: {
const id = e.b.newId();
try e.b.emit(.types_globals, .type_void, &.{id});
break :blk id;
},
.scalar => |s| blk: {
const st = storageScalar(s);
if (st != s) break :blk try e.typeId(try e.t.scalar(st));
const id = e.b.newId();
switch (s) {
.bool => try e.b.emit(.types_globals, .type_bool, &.{id}),
.int => try e.b.emit(.types_globals, .type_int, &.{ id, 32, 1 }),
.uint => try e.b.emit(.types_globals, .type_int, &.{ id, 32, 0 }),
.int16, .uint16 => {
try e.cap(.int16);
try e.b.emit(.types_globals, .type_int, &.{ id, 16, @intFromBool(s == .int16) });
},
.int64, .uint64 => {
try e.cap(.int64);
try e.b.emit(.types_globals, .type_int, &.{ id, 64, @intFromBool(s == .int64) });
},
.float => try e.b.emit(.types_globals, .type_float, &.{ id, 32 }),
.float16 => {
try e.cap(.float16);
try e.b.emit(.types_globals, .type_float, &.{ id, 16 });
},
.double => {
try e.cap(.float64);
try e.b.emit(.types_globals, .type_float, &.{ id, 64 });
},
else => unreachable,
}
break :blk id;
},
.vector => |v| blk: {
// vector<T, 1> is a plain T (SPIR-V has no 1-vectors).
if (v.len == 1) break :blk try e.scalarType(v.elem);
const elem = try e.scalarType(v.elem);
const id = e.b.newId();
try e.b.emit(.types_globals, .type_vector, &.{ id, elem, v.len });
break :blk id;
},
.array => |a| blk: {
const elem = try e.typeId(a.elem);
const len = try e.constUint(a.len);
const id = e.b.newId();
try e.b.emit(.types_globals, .type_array, &.{ id, elem, len });
break :blk id;
},
else => return e.unsupported("type '{s}' is not supported yet", .{try e.t.format(e.arena, ty)}),
};
try e.value_types.put(e.arena, ty, id);
return id;
}
fn pointerType(e: *Emitter, sc: StorageClass, pointee: Id) Error!Id {
if (e.pointer_types.get(.{ sc, pointee })) |id| return id;
const id = e.b.newId();
try e.b.emit(.types_globals, .type_pointer, &.{ id, @backingInt(sc), pointee });
try e.pointer_types.put(e.arena, .{ sc, pointee }, id);
return id;
}
fn functionType(e: *Emitter, ret: Id, params: []const Id) Error!Id {
var key: std.ArrayList(u8) = .empty;
try key.print(e.arena, "{d},", .{ret});
for (params) |p| try key.print(e.arena, "{d},", .{p});
if (e.function_types.get(key.items)) |id| return id;
const id = e.b.newId();
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ id, ret });
try ops.appendSlice(e.arena, params);
try e.b.emit(.types_globals, .type_function, ops.items);
try e.function_types.put(e.arena, key.items, id);
return id;
}
fn constBits(e: *Emitter, ty_id: Id, bits: u64, words: u32) Error!Id {
if (e.constants.get(.{ ty_id, bits })) |id| return id;
const id = e.b.newId();
if (words == 2) {
try e.b.emit(.types_globals, .constant, &.{ ty_id, id, @truncate(bits), @truncate(bits >> 32) });
} else try e.b.emit(.types_globals, .constant, &.{ ty_id, id, @truncate(bits) });
try e.constants.put(e.arena, .{ ty_id, bits }, id);
return id;
}
fn constUint(e: *Emitter, v: u64) Error!Id {
return e.constBits(try e.scalarType(.uint), v, 1);
}
fn constInt(e: *Emitter, v: i64) Error!Id {
return e.constBits(try e.scalarType(.int), @as(u32, @bitCast(@as(i32, @truncate(v)))), 1);
}
/// A scalar constant of HLSL type `ty`.
fn constant(e: *Emitter, ty: TypeId, c: ir.Constant) Error!Id {
const s = storageScalar(e.t.component(ty).?);
const ty_id = try e.scalarType(s);
switch (s) {
.bool => {
const v = switch (c) {
.int => |i| i != 0,
.float => |f| f != 0,
};
if (e.constants.get(.{ ty_id, @intFromBool(v) })) |id| return id;
const id = e.b.newId();
try e.b.emit(.types_globals, if (v) .constant_true else .constant_false, &.{ ty_id, id });
try e.constants.put(e.arena, .{ ty_id, @intFromBool(v) }, id);
return id;
},
.float => return e.constBits(ty_id, @as(u32, @bitCast(@as(f32, @floatCast(floatOf(c))))), 1),
.double => return e.constBits(ty_id, @bitCast(floatOf(c)), 2),
.float16 => return e.constBits(ty_id, @as(u16, @bitCast(@as(f16, @floatCast(floatOf(c))))), 1),
.int64, .uint64 => return e.constBits(ty_id, @bitCast(intOf(c)), 2),
.int16, .uint16 => return e.constBits(ty_id, @as(u16, @truncate(@as(u64, @bitCast(intOf(c))))), 1),
else => return e.constBits(ty_id, @as(u32, @truncate(@as(u64, @bitCast(intOf(c))))), 1),
}
}
fn floatOf(c: ir.Constant) f64 {
return switch (c) {
.int => |i| @floatFromInt(i),
.float => |f| f,
};
}
fn intOf(c: ir.Constant) i64 {
return switch (c) {
.int => |i| i,
.float => |f| @intFromFloat(@trunc(f)),
};
}
// ------------------------------------------------------------------
// Module
fn module(e: *Emitter) Error!void {
const m = e.m;
const entry = m.entry orelse return e.unsupported("no entry point", .{});
try e.b.emit(.debug_names, .source, &.{ 5, 600 }); // HLSL
e.void_id = try e.typeId(TypeTable.void_type);
try e.cap(.shader);
e.func_ids = try e.arena.alloc(Id, m.functions.items.len);
for (e.func_ids) |*id| id.* = e.b.newId();
try e.emitGlobals();
try e.emitInterface(entry);
for (m.functions.items, 0..) |f, fi| try e.emitFunction(f, @intCast(fi));
for (e.capabilities.keys()) |c| try e.b.emit(.capabilities, .capability, &.{@backingInt(c)});
if (e.glsl != 0) try e.b.emitWithString(.ext_inst_imports, .ext_inst_import, &.{e.glsl}, "GLSL.std.450", &.{});
try e.b.emit(.memory_model, .memory_model, &.{ 0, 1 }); // Logical GLSL450
const model: u32 = switch (entry.stage) {
.vertex => 0,
.hull => 1,
.domain => 2,
.geometry => 3,
.pixel => 4,
.compute => 5,
.library => return e.unsupported("library targets are not supported", .{}),
};
const wrapper = e.func_ids[entry.wrapper];
try e.b.emitWithString(.entry_points, .entry_point, &.{ model, wrapper }, entry.name, e.interface_ids.items);
switch (entry.stage) {
.compute => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 17, entry.num_threads[0], entry.num_threads[1], entry.num_threads[2] }),
.pixel => {
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 7 }); // OriginUpperLeft
for (entry.outputs.items) |o| if (std.ascii.eqlIgnoreCase(o.semantic, "SV_Depth")) {
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 12 }); // DepthReplacing
};
},
else => {},
}
for (m.functions.items, e.func_ids) |f, id| try e.b.emitWithString(.debug_names, .name, &.{id}, f.name, &.{});
}
fn emitGlobals(e: *Emitter) Error!void {
const m = e.m;
e.global_vars = try e.arena.alloc(Id, m.globals.items.len);
e.buffer_elem_ptr = try e.arena.alloc(Id, m.globals.items.len);
@memset(e.buffer_elem_ptr, 0);
// Registers without an explicit binding take the next free one.
var used: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty;
for (m.globals.items) |g| if (g.binding.explicit) try used.put(e.arena, .{ g.binding.space, g.binding.index }, {});
var next_free: u32 = 0;
for (m.globals.items, 0..) |g, gi| {
switch (g.space) {
.resource => {
const r = switch (e.t.get(g.ty)) {
.resource => |r| r,
else => return e.unsupported("global '{s}' of type '{s}' is not supported yet", .{ g.name, try e.t.format(e.arena, g.ty) }),
};
const var_id = e.b.newId();
switch (r.kind) {
.structured_buffer, .rw_structured_buffer, .byte_address_buffer, .rw_byte_address_buffer => {
var elem_ty = if (r.kind == .byte_address_buffer or r.kind == .rw_byte_address_buffer) try e.t.scalar(.uint) else r.elem;
// Buffers hold bools as uints.
if (e.t.component(elem_ty) == .bool) elem_ty = try e.t.withComponent(elem_ty, .uint);
const elem = try e.typeId(elem_ty);
const layout = try e.std430(elem_ty);
const rt = e.b.newId();
try e.b.emit(.types_globals, .type_runtime_array, &.{ rt, elem });
try e.b.emit(.annotations, .decorate, &.{ rt, 6, layout.size }); // ArrayStride
const st = e.b.newId();
try e.b.emit(.types_globals, .type_struct, &.{ st, rt });
try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 35, 0 }); // Offset 0
if (!r.kind.isWritable()) try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 24 }); // NonWritable
try e.b.emit(.annotations, .decorate, &.{ st, 3 }); // BufferBlock
try e.b.emitWithString(.debug_names, .name, &.{st}, try std.fmt.allocPrint(e.arena, "type.{s}.{s}", .{ r.name, try e.typeLabel(elem_ty) }), &.{});
const ptr = try e.pointerType(.uniform, st);
try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(StorageClass.uniform) });
e.buffer_elem_ptr[gi] = try e.pointerType(.uniform, elem);
},
else => return e.unsupported("resource type '{s}' is not supported yet", .{r.name}),
}
var binding = g.binding.index;
if (!g.binding.explicit) {
while (used.contains(.{ g.binding.space, next_free })) next_free += 1;
binding = next_free;
try used.put(e.arena, .{ g.binding.space, binding }, {});
}
try e.b.emit(.annotations, .decorate, &.{ var_id, 34, g.binding.space }); // DescriptorSet
try e.b.emit(.annotations, .decorate, &.{ var_id, 33, binding }); // Binding
try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{});
e.global_vars[gi] = var_id;
},
.groupshared, .private => {
const ty = try e.typeId(g.ty);
const sc: StorageClass = if (g.space == .groupshared) .workgroup else .private;
const ptr = try e.pointerType(sc, ty);
const var_id = e.b.newId();
try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(sc) });
try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{});
e.global_vars[gi] = var_id;
},
else => return e.unsupported("global '{s}' is not supported yet", .{g.name}),
}
}
}
/// `float`, `v4float`: dxc's type names inside buffer type names.
fn typeLabel(e: *Emitter, ty: TypeId) Error![]const u8 {
return switch (e.t.get(ty)) {
.scalar => |s| storageScalar(s).name(),
.vector => |v| std.fmt.allocPrint(e.arena, "v{d}{s}", .{ v.len, storageScalar(v.elem).name() }),
else => e.t.format(e.arena, ty),
};
}
const Layout = struct { size: u32, alignment: u32 };
fn std430(e: *Emitter, ty: TypeId) Error!Layout {
return switch (e.t.get(ty)) {
.scalar => |s| .{ .size = storageScalar(s).size(), .alignment = storageScalar(s).size() },
.vector => |v| blk: {
const s = storageScalar(v.elem).size();
const n: u32 = if (v.len == 3) 4 else v.len;
break :blk .{ .size = s * v.len, .alignment = s * n };
},
else => e.unsupported("buffer elements of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
};
}
// ------------------------------------------------------------------
// Entry interface
const Builtin = struct { id: u32, ty: TypeId };
fn builtinFor(e: *Emitter, el: ir.SigElement, input: bool, stage: ir.Stage) Error!?Builtin {
const t = e.t;
const n = el.semantic;
const uint3 = try t.vector(.uint, 3);
const uint1 = try t.scalar(.uint);
const float4 = try t.vector(.float, 4);
const eq = std.ascii.eqlIgnoreCase;
// Builtins exist only for some stages and directions; elsewhere a
// system value is an ordinary located variable (as in dxc).
if (stage == .compute and input) {
if (eq(n, "SV_DispatchThreadID")) return .{ .id = 28, .ty = uint3 }; // GlobalInvocationId
if (eq(n, "SV_GroupID")) return .{ .id = 26, .ty = uint3 }; // WorkgroupId
if (eq(n, "SV_GroupThreadID")) return .{ .id = 27, .ty = uint3 }; // LocalInvocationId
if (eq(n, "SV_GroupIndex")) return .{ .id = 29, .ty = uint1 }; // LocalInvocationIndex
}
if (stage == .vertex and input) {
if (eq(n, "SV_VertexID")) return .{ .id = 42, .ty = uint1 }; // VertexIndex
if (eq(n, "SV_InstanceID")) return .{ .id = 43, .ty = uint1 }; // InstanceIndex
}
if (eq(n, "SV_Position")) {
if (stage == .pixel and input) return .{ .id = 15, .ty = float4 }; // FragCoord
if (!(stage == .vertex and input) and !(stage == .pixel)) return .{ .id = 0, .ty = float4 }; // Position
}
if (stage == .pixel and input and eq(n, "SV_IsFrontFace")) return .{ .id = 17, .ty = try t.scalar(.bool) }; // FrontFacing
if (stage == .pixel and !input and eq(n, "SV_Depth")) return .{ .id = 22, .ty = try t.scalar(.float) }; // FragDepth
if (eq(n, "SV_Target") or eq(n, "SV_VertexID") or eq(n, "SV_InstanceID") or eq(n, "SV_Position")) return null;
if (el.system_value) return e.unsupported("system value '{s}' is not supported yet", .{n});
return null;
}
fn emitInterface(e: *Emitter, entry: ir.Entry) Error!void {
e.inputs = try e.arena.alloc(Interface, entry.inputs.items.len);
e.outputs = try e.arena.alloc(Interface, entry.outputs.items.len);
var location: [2]u32 = .{ 0, 0 };
for ([_][]const ir.SigElement{ entry.inputs.items, entry.outputs.items }, 0..) |els, dir| {
const input = dir == 0;
const out = if (input) e.inputs else e.outputs;
for (els, out) |el, *iface| {
const bi = try e.builtinFor(el, input, entry.stage);
// bool is not allowed in located interface variables.
const ty = if (bi) |x| x.ty else if (e.t.component(el.ty) == .bool) try e.t.withComponent(el.ty, .uint) else el.ty;
const sc: StorageClass = if (input) .input else .output;
const ptr = try e.pointerType(sc, try e.typeId(ty));
const var_id = e.b.newId();
try e.b.emit(.types_globals, .variable, &.{ ptr, var_id, @backingInt(sc) });
if (bi) |x| {
try e.b.emit(.annotations, .decorate, &.{ var_id, 11, x.id }); // BuiltIn
} else {
const loc = if (std.ascii.eqlIgnoreCase(el.semantic, "SV_Target")) el.semantic_index else location[dir];
try e.b.emit(.annotations, .decorate, &.{ var_id, 30, loc }); // Location
location[dir] = @max(location[dir], loc) + try e.locationCount(ty);
// Integer fragment inputs cannot be interpolated.
if (input and entry.stage == .pixel and !e.t.component(ty).?.isFloat()) {
try e.b.emit(.annotations, .decorate, &.{ var_id, 14 }); // Flat
}
}
const name = try std.fmt.allocPrint(e.arena, "{s}.var.{s}{d}", .{ if (input) "in" else "out", el.semantic, el.semantic_index });
try e.b.emitWithString(.debug_names, .name, &.{var_id}, name, &.{});
iface.* = .{ .var_id = var_id, .ty = ty };
try e.interface_ids.append(e.arena, var_id);
}
}
}
/// Locations an interface variable occupies: one per array element and
/// matrix row; 64-bit 3- and 4-vectors take two.
fn locationCount(e: *Emitter, ty: TypeId) Error!u32 {
return switch (e.t.get(ty)) {
.array => |a| a.len * try e.locationCount(a.elem),
.matrix => |m| m.rows * (if (m.elem.size() == 8 and m.cols > 2) @as(u32, 2) else 1),
.vector => |v| if (v.elem.size() == 8 and v.len > 2) 2 else 1,
else => 1,
};
}
// ------------------------------------------------------------------
// Functions
fn emitFunction(e: *Emitter, f: *const ir.Function, fi: u32) Error!void {
e.f = f;
e.vals = try e.arena.alloc(Id, f.insts.items.len);
@memset(e.vals, 0);
const ret = try e.typeId(f.ret);
const params = try e.arena.alloc(Id, f.params.len);
for (f.params, params) |p, *out| {
const t = try e.typeId(p.ty);
out.* = if (p.by_ref) try e.pointerType(.function, t) else t;
}
const fn_ty = try e.functionType(ret, params);
try e.b.emit(.functions, .function, &.{ ret, e.func_ids[fi], 0, fn_ty });
const param_ids = try e.arena.alloc(Id, f.params.len);
for (params, param_ids) |p, *id| {
id.* = e.b.newId();
try e.b.emit(.functions, .function_parameter, &.{ p, id.* });
}
for (f.params, param_ids) |p, id| try e.b.emitWithString(.debug_names, .name, &.{id}, p.name, &.{});
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();
// 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),
.param => |p| e.vals[i] = param_ids[p],
else => {},
};
for (order, 0..) |bi, oi| {
try e.b.emit(.functions, .label, &.{labels[bi]});
if (oi == 0) {
// OpVariables must open the first block.
for (f.insts.items, 0..) |inst, i| if (inst.op == .local_var) {
const ptr = try e.pointerType(.function, try e.typeId(inst.ty));
e.vals[i] = e.b.newId();
try e.b.emit(.functions, .variable, &.{ ptr, e.vals[i], @backingInt(StorageClass.function) });
};
}
const blk = f.blocks.items[bi];
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 }),
.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", &.{}),
.ret => |v| if (v == .none) try e.b.emit(.functions, .@"return", &.{}) else try e.b.emit(.functions, .return_value, &.{e.vals[v.index()]}),
.br => |t| try e.b.emit(.functions, .branch, &.{labels[t.index()]}),
.cond_br => |c| try e.b.emit(.functions, .branch_conditional, &.{ e.vals[c.cond.index()], labels[c.then.index()], labels[c.@"else".index()] }),
.@"switch" => |sw| {
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ e.vals[sw.value.index()], labels[sw.default.index()] });
for (sw.cases) |c| try ops.appendSlice(e.arena, &.{ @truncate(@as(u64, @bitCast(c.value))), labels[c.block.index()] });
try e.b.emit(.functions, .@"switch", ops.items);
},
.discard => try e.b.emit(.functions, .kill, &.{}),
}
}
try e.b.emit(.functions, .function_end, &.{});
}
/// Scalars and 1-component vectors (both a SPIR-V scalar).
fn isScalarLike(e: *Emitter, ty: TypeId) bool {
return switch (e.t.get(ty)) {
.scalar, .@"enum" => true,
.vector => |v| v.len == 1,
else => false,
};
}
fn val(e: *Emitter, r: Ref) Id {
return e.vals[r.index()];
}
fn compOf(e: *Emitter, ty: TypeId) Scalar {
return storageScalar(e.t.component(ty) orelse .int);
}
fn emitInst(e: *Emitter, r: Ref) Error!void {
const f = e.f;
const i = f.inst(r);
const ri = r.index();
switch (i.op) {
.constant, .param, .local_var => {},
.global => |g| e.vals[ri] = e.global_vars[g],
.load => |p| {
// Resources stay as their variables (accessed by chains).
if (i.ptr == .none and (e.t.get(i.ty) == .resource or e.t.get(i.ty) == .sampler)) {
e.vals[ri] = e.val(p);
return;
}
e.vals[ri] = try e.op1(.load, i.ty, &.{e.val(p)});
},
.store => |s| try e.b.emit(.functions, .store, &.{ e.val(s.ptr), e.val(s.value) }),
.access => |a| {
const sc: StorageClass = switch (i.ptr) {
.function => .function,
.private => .private,
.groupshared => .workgroup,
else => return e.unsupported("access into this storage is not supported yet", .{}),
};
const ptr_ty = try e.pointerType(sc, try e.typeId(i.ty));
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ ptr_ty, 0, e.val(a.base) });
// Indices into 1-vectors (SPIR-V scalars) are dropped.
var cur = f.inst(a.base).ty;
for (a.indices) |x| {
const skip = e.isScalarLike(cur);
cur = switch (e.t.get(cur)) {
.array => |arr| arr.elem,
.vector => |v| try e.t.scalar(v.elem),
.matrix => |mt| try e.t.vector(mt.elem, mt.cols),
.@"struct" => |st| blk: {
const k = f.inst(x);
break :blk if (k.op == .constant) st.fields.items[@intCast(k.op.constant.int)].type else cur;
},
else => cur,
};
if (!skip) try ops.append(e.arena, e.val(x));
}
if (ops.items.len == 3) {
e.vals[ri] = e.val(a.base);
return;
}
e.vals[ri] = e.b.newId();
ops.items[1] = e.vals[ri];
try e.b.emit(.functions, .access_chain, ops.items);
},
.binary => |x| e.vals[ri] = try e.binary(x.op, i.ty, e.val(x.lhs), e.val(x.rhs)),
.unary => |x| {
const c = e.compOf(i.ty);
const op: Op = switch (x.op) {
.neg => if (c.isFloat()) .f_negate else .s_negate,
.not => .logical_not,
.bit_not => .not_,
};
e.vals[ri] = try e.op1(op, i.ty, &.{e.val(x.operand)});
},
.cmp => |x| {
const c = e.compOf(f.inst(x.lhs).ty);
const op: Op = if (c.isFloat()) switch (x.op) {
.eq => .f_ord_equal,
.ne => .f_unord_not_equal,
.lt => .f_ord_less_than,
.le => .f_ord_less_than_equal,
.gt => .f_ord_greater_than,
.ge => .f_ord_greater_than_equal,
} else if (c == .bool) switch (x.op) {
.eq => .logical_equal,
.ne => .logical_not_equal,
else => return e.unsupported("ordered comparison of bools", .{}),
} else if (c.isUnsigned()) switch (x.op) {
.eq => .i_equal,
.ne => .i_not_equal,
.lt => .u_less_than,
.le => .u_less_than_equal,
.gt => .u_greater_than,
.ge => .u_greater_than_equal,
} else switch (x.op) {
.eq => .i_equal,
.ne => .i_not_equal,
.lt => .s_less_than,
.le => .s_less_than_equal,
.gt => .s_greater_than,
.ge => .s_greater_than_equal,
};
e.vals[ri] = try e.op1(op, i.ty, &.{ e.val(x.lhs), e.val(x.rhs) });
},
.convert => |x| e.vals[ri] = try e.convert(e.val(x), f.inst(x).ty, i.ty),
.bitcast => |x| e.vals[ri] = try e.op1(.bitcast, i.ty, &.{e.val(x)}),
.splat => |x| {
const n = e.t.componentCount(i.ty).?;
if (n == 1) {
e.vals[ri] = e.val(x);
return;
}
const comps = try e.arena.alloc(u32, n);
@memset(comps, e.val(x));
e.vals[ri] = try e.op1(.composite_construct, i.ty, comps);
},
.extract => |x| {
if (e.isScalarLike(f.inst(x.agg).ty)) {
e.vals[ri] = e.val(x.agg);
return;
}
e.vals[ri] = try e.op1(.composite_extract, i.ty, &.{ e.val(x.agg), x.index });
},
.insert => |x| {
if (e.isScalarLike(i.ty)) {
e.vals[ri] = e.val(x.value);
return;
}
e.vals[ri] = try e.op1(.composite_insert, i.ty, &.{ e.val(x.value), e.val(x.agg), x.index });
},
.construct => |xs| {
if (xs.len == 1 and e.isScalarLike(i.ty)) {
e.vals[ri] = e.val(xs[0]);
return;
}
const ids = try e.arena.alloc(u32, xs.len);
for (xs, ids) |x, *id| id.* = e.val(x);
e.vals[ri] = try e.op1(.composite_construct, i.ty, ids);
},
.shuffle => |x| {
const v = e.val(x.vec);
if (e.isScalarLike(f.inst(x.vec).ty)) {
if (x.components.len == 1) {
e.vals[ri] = v;
} else {
const comps = try e.arena.alloc(u32, x.components.len);
@memset(comps, v);
e.vals[ri] = try e.op1(.composite_construct, i.ty, comps);
}
return;
}
if (x.components.len == 1) {
e.vals[ri] = try e.op1(.composite_extract, i.ty, &.{ v, x.components[0] });
return;
}
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ v, v });
for (x.components) |c| try ops.append(e.arena, c);
e.vals[ri] = try e.op1(.vector_shuffle, i.ty, ops.items);
},
.select => |x| e.vals[ri] = try e.op1(.select, i.ty, &.{ e.val(x.cond), e.val(x.t), e.val(x.f) }),
.call => |c| {
var ops: std.ArrayList(u32) = .empty;
try ops.append(e.arena, e.func_ids[c.func]);
for (c.args) |a| try ops.append(e.arena, e.val(a));
e.vals[ri] = try e.op1(.function_call, i.ty, ops.items);
},
.intrinsic => |c| e.vals[ri] = try e.intrinsic(c.name, i.ty, c.args),
.res_load => |x| {
const ptr = try e.bufferElement(x.res, x.index);
if (e.t.component(i.ty) == .bool) {
const stored = try e.t.withComponent(i.ty, .uint);
const raw = try e.op1(.load, stored, &.{ptr});
e.vals[ri] = try e.convert(raw, stored, i.ty);
} else e.vals[ri] = try e.op1(.load, i.ty, &.{ptr});
},
.res_store => |x| {
const ptr = try e.bufferElement(x.res, x.index);
var v = e.val(x.value);
const vt = f.inst(x.value).ty;
if (e.t.component(vt) == .bool) v = try e.convert(v, vt, try e.t.withComponent(vt, .uint));
try e.b.emit(.functions, .store, &.{ ptr, v });
},
.method => |x| return e.unsupported("method '{s}' is not supported yet", .{x.name}),
.input => |k| {
const iface = e.inputs[k];
const loaded = try e.op1(.load, iface.ty, &.{iface.var_id});
e.vals[ri] = try e.reshape(loaded, iface.ty, i.ty);
},
.output => |o| {
const iface = e.outputs[o.element];
const v = try e.reshape(e.val(o.value), f.inst(o.value).ty, iface.ty);
try e.b.emit(.functions, .store, &.{ iface.var_id, v });
},
.phi => return e.unsupported("phi", .{}),
}
}
/// Emits `op` with a result of HLSL type `ty`; returns the result id.
fn op1(e: *Emitter, op: Op, ty: TypeId, operands: []const u32) Error!Id {
const id = e.b.newId();
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ try e.typeId(ty), id });
try ops.appendSlice(e.arena, operands);
try e.b.emit(.functions, op, ops.items);
return id;
}
/// Pointer to `buffer[index]` (structured / byte-address buffers).
fn bufferElement(e: *Emitter, res: Ref, index: Ref) Error!Id {
const g = e.globalOf(res) orelse return e.unsupported("resources not tied to a global are not supported yet", .{});
const elem_ptr = e.buffer_elem_ptr[g];
if (elem_ptr == 0) return e.unsupported("indexing this resource is not supported yet", .{});
const id = e.b.newId();
try e.b.emit(.functions, .access_chain, &.{ elem_ptr, id, e.global_vars[g], try e.constInt(0), e.val(index) });
return id;
}
/// The global a resource value comes from (`load (global g)`).
fn globalOf(e: *Emitter, r: Ref) ?u32 {
const i = e.f.inst(r);
return switch (i.op) {
.global => |g| g,
.load => |p| e.globalOf(p),
else => null,
};
}
/// Interface values whose builtin type differs from the declared one
/// (`uint i : SV_DispatchThreadID` reads component x of a uint3).
fn reshape(e: *Emitter, v: Id, from: TypeId, to: TypeId) Error!Id {
if (from == to) return v;
const fs = e.t.shape(from).?;
const ts = e.t.shape(to).?;
var cur = v;
var cur_ty = from;
if (ts.count() < fs.count()) {
const ct = e.t.component(from).?;
if (ts.count() == 1) {
cur_ty = try e.t.scalar(ct);
cur = try e.op1(.composite_extract, cur_ty, &.{ cur, 0 });
} else {
cur_ty = try e.t.vector(ct, ts.cols);
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ cur, cur });
for (0..ts.cols) |c| try ops.append(e.arena, @intCast(c));
cur = try e.op1(.vector_shuffle, cur_ty, ops.items);
}
} else if (ts.count() > fs.count()) {
return e.unsupported("widening interface values is not supported yet", .{});
}
if (cur_ty != to) cur = try e.convert(cur, cur_ty, try e.t.withComponent(cur_ty, e.t.component(to).?));
return cur;
}
fn convert(e: *Emitter, v: Id, from: TypeId, to: TypeId) Error!Id {
const fc = e.compOf(from);
const tc = e.compOf(to);
if (fc == tc) return v;
if (tc == .bool) {
const zero = try e.splatConst(from, .{ .int = 0 });
return e.op1(if (fc.isFloat()) .f_ord_not_equal else .i_not_equal, to, &.{ v, zero });
}
if (fc == .bool) {
const one = try e.splatConst(to, .{ .int = 1 });
const zero = try e.splatConst(to, .{ .int = 0 });
return e.op1(.select, to, &.{ v, one, zero });
}
const op: Op = if (fc.isFloat() and tc.isFloat())
.f_convert
else if (fc.isFloat())
(if (tc.isUnsigned()) .convert_f_to_u else .convert_f_to_s)
else if (tc.isFloat())
(if (fc.isUnsigned()) .convert_u_to_f else .convert_s_to_f)
else if (fc.size() == tc.size())
.bitcast
else {
// Width change: zero- or sign-extend by the source's
// signedness into an integer of the target width and the
// source's signedness, then reinterpret.
const mid_c: Scalar = switch (tc.size()) {
2 => if (fc.isUnsigned()) .uint16 else .int16,
8 => if (fc.isUnsigned()) .uint64 else .int64,
else => if (fc.isUnsigned()) .uint else .int,
};
const mid = try e.t.withComponent(to, mid_c);
const ext = try e.op1(if (fc.isUnsigned()) .u_convert else .s_convert, mid, &.{v});
if (mid == to) return ext;
return e.op1(.bitcast, to, &.{ext});
};
return e.op1(op, to, &.{v});
}
/// A constant of `ty`'s component, splatted to its shape.
fn splatConst(e: *Emitter, ty: TypeId, c: ir.Constant) Error!Id {
const s = try e.constant(try e.t.scalar(e.t.component(ty).?), c);
const n = e.t.componentCount(ty).?;
if (e.isScalarLike(ty)) return s;
const id = e.b.newId();
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ try e.typeId(ty), id });
for (0..n) |_| try ops.append(e.arena, s);
try e.b.emit(.types_globals, .constant_composite, ops.items);
return id;
}
fn binary(e: *Emitter, op: ir.BinaryOp, ty: TypeId, a: Id, b: Id) Error!Id {
const c = e.compOf(ty);
const f = c.isFloat();
const u = c.isUnsigned();
const sop: Op = switch (op) {
.add => if (f) .f_add else .i_add,
.sub => if (f) .f_sub else .i_sub,
.mul => if (f) .f_mul else .i_mul,
.div => if (f) .f_div else if (u) .u_div else .s_div,
.rem => if (f) .f_rem else if (u) .u_mod else .s_rem,
.bit_and => if (c == .bool) .logical_and else .bitwise_and,
.bit_or => if (c == .bool) .logical_or else .bitwise_or,
.bit_xor => if (c == .bool) .logical_not_equal else .bitwise_xor,
.log_and => .logical_and,
.log_or => .logical_or,
.shl, .shr => {
// HLSL masks the shift amount to the bit width.
const mask = try e.splatConst(ty, .{ .int = @as(i64, c.size()) * 8 - 1 });
const amount = try e.op1(.bitwise_and, ty, &.{ b, mask });
const shop: Op = if (op == .shl) .shift_left_logical else if (u) .shift_right_logical else .shift_right_arithmetic;
return e.op1(shop, ty, &.{ a, amount });
},
};
return e.op1(sop, ty, &.{ a, b });
}
fn glslSet(e: *Emitter) Id {
if (e.glsl == 0) e.glsl = e.b.newId();
return e.glsl;
}
fn intrinsic(e: *Emitter, name: []const u8, ty: TypeId, args: []const Ref) Error!Id {
const ids = try e.arena.alloc(u32, args.len);
for (args, ids) |a, *id| id.* = e.val(a);
const arg_c = if (args.len > 0) e.compOf(e.f.inst(args[0]).ty) else e.compOf(ty);
const fl = arg_c.isFloat();
const un = arg_c.isUnsigned();
const Glsl = struct { name: []const u8, f: u32, s: u32 = 0, u: u32 = 0 };
const glsl_ops = [_]Glsl{
.{ .name = "round", .f = 2 }, .{ .name = "trunc", .f = 3 }, .{ .name = "abs", .f = 4, .s = 5, .u = 5 },
.{ .name = "sign", .f = 6, .s = 7 }, .{ .name = "floor", .f = 8 }, .{ .name = "ceil", .f = 9 },
.{ .name = "frac", .f = 10 }, .{ .name = "radians", .f = 11 }, .{ .name = "degrees", .f = 12 },
.{ .name = "sin", .f = 13 }, .{ .name = "cos", .f = 14 }, .{ .name = "tan", .f = 15 },
.{ .name = "asin", .f = 16 }, .{ .name = "acos", .f = 17 }, .{ .name = "atan", .f = 18 },
.{ .name = "sinh", .f = 19 }, .{ .name = "cosh", .f = 20 }, .{ .name = "tanh", .f = 21 },
.{ .name = "atan2", .f = 25 }, .{ .name = "pow", .f = 26 }, .{ .name = "exp", .f = 27 },
.{ .name = "log", .f = 28 }, .{ .name = "exp2", .f = 29 }, .{ .name = "log2", .f = 30 },
.{ .name = "sqrt", .f = 31 }, .{ .name = "rsqrt", .f = 32 }, .{ .name = "determinant", .f = 33 },
.{ .name = "min", .f = 37, .s = 39, .u = 38 }, .{ .name = "max", .f = 40, .s = 42, .u = 41 }, .{ .name = "clamp", .f = 43, .s = 45, .u = 44 },
.{ .name = "lerp", .f = 46 }, .{ .name = "step", .f = 48 }, .{ .name = "smoothstep", .f = 49 },
.{ .name = "mad", .f = 50 }, .{ .name = "ldexp", .f = 53 }, .{ .name = "length", .f = 66 },
.{ .name = "distance", .f = 67 }, .{ .name = "cross", .f = 68 }, .{ .name = "normalize", .f = 69 },
.{ .name = "faceforward", .f = 70 }, .{ .name = "reflect", .f = 71 }, .{ .name = "refract", .f = 72 },
};
const eqn = std.mem.eql;
if (eqn(u8, name, "sign")) {
// HLSL sign returns int; GLSL's FSign / SSign keep the type.
const at = e.f.inst(args[0]).ty;
const s = try e.op1(.ext_inst, at, &.{ e.glslSet(), if (fl) 6 else 7, ids[0] });
return e.convert(s, at, ty);
}
if ((eqn(u8, name, "countbits") or eqn(u8, name, "reversebits") or eqn(u8, name, "ddx") or eqn(u8, name, "ddy") or eqn(u8, name, "fwidth") or eqn(u8, name, "ddx_coarse") or eqn(u8, name, "ddy_coarse")) and arg_c.size() != 4) {
return e.unsupported("intrinsic '{s}' on {d}-bit types is not supported yet", .{ name, arg_c.size() * 8 });
}
for (glsl_ops) |g| if (std.mem.eql(u8, g.name, name)) {
if (std.mem.eql(u8, name, "mad") and !fl) {
const p = try e.op1(.i_mul, ty, &.{ ids[0], ids[1] });
return e.op1(.i_add, ty, &.{ p, ids[2] });
}
const op = if (fl) g.f else if (un) g.u else g.s;
if (op == 0) break;
var ops: std.ArrayList(u32) = .empty;
try ops.appendSlice(e.arena, &.{ e.glslSet(), op });
try ops.appendSlice(e.arena, ids);
return e.op1(.ext_inst, ty, ops.items);
};
if (std.mem.eql(u8, name, "saturate")) {
const zero = try e.splatConst(ty, .{ .float = 0 });
const one = try e.splatConst(ty, .{ .float = 1 });
return e.op1(.ext_inst, ty, &.{ e.glslSet(), 43, ids[0], zero, one });
}
if (std.mem.eql(u8, name, "dot") and fl) return e.op1(.dot, ty, ids);
if (std.mem.eql(u8, name, "ddx") or std.mem.eql(u8, name, "ddx_coarse")) return e.op1(.dpdx, ty, ids);
if (std.mem.eql(u8, name, "ddy") or std.mem.eql(u8, name, "ddy_coarse")) return e.op1(.dpdy, ty, ids);
if (std.mem.eql(u8, name, "fwidth")) return e.op1(.fwidth, ty, ids);
if (std.mem.eql(u8, name, "asuint") or std.mem.eql(u8, name, "asint") or std.mem.eql(u8, name, "asfloat")) {
if (args.len == 1) return e.op1(.bitcast, ty, ids);
}
if (std.mem.eql(u8, name, "countbits")) return e.op1(.bit_count, ty, ids);
if (std.mem.eql(u8, name, "reversebits")) return e.op1(.bit_reverse, ty, ids);
if (std.mem.eql(u8, name, "rcp")) {
const one = try e.splatConst(ty, .{ .float = 1 });
return e.op1(.f_div, ty, &.{ one, ids[0] });
}
if (std.mem.eql(u8, name, "GroupMemoryBarrierWithGroupSync")) {
// Workgroup execution and memory scope, AcquireRelease |
// WorkgroupMemory semantics.
try e.b.emit(.functions, .control_barrier, &.{ try e.constUint(2), try e.constUint(2), try e.constUint(0x108) });
return 0;
}
return e.unsupported("intrinsic '{s}' is not supported yet", .{name});
}
};
/// Blocks in an order where each block follows its dominators: reverse
/// post-order from the entry, then merge / continue targets that are not
/// reachable (they must still exist).
fn blockOrder(a: Allocator, f: *const ir.Function) Allocator.Error![]u32 {
const n = f.blocks.items.len;
const seen = try a.alloc(bool, n);
@memset(seen, false);
var post: std.ArrayList(u32) = .empty;
try dfs(a, f, 0, seen, &post);
var order: std.ArrayList(u32) = .empty;
var i = post.items.len;
while (i > 0) {
i -= 1;
try order.append(a, post.items[i]);
}
// Unreachable merge / continue targets.
var changed = true;
while (changed) {
changed = false;
for (order.items) |bi| {
const targets: [2]ir.BlockId = switch (f.blocks.items[bi].merge) {
.none => .{ .none, .none },
.selection => |m| .{ m, .none },
.loop => |l| .{ l.merge, l.@"continue" },
};
for (targets) |t| if (t != .none and !seen[t.index()]) {
var extra: std.ArrayList(u32) = .empty;
try dfs(a, f, t.index(), seen, &extra);
var j = extra.items.len;
while (j > 0) {
j -= 1;
try order.append(a, extra.items[j]);
}
changed = true;
break;
};
if (changed) break;
}
}
return order.items;
}
fn dfs(a: Allocator, f: *const ir.Function, b: u32, seen: []bool, post: *std.ArrayList(u32)) Allocator.Error!void {
seen[b] = true;
const blk = f.blocks.items[b];
var succ: std.ArrayList(u32) = .empty;
switch (blk.term) {
.br => |t| try succ.append(a, t.index()),
.cond_br => |c| try succ.appendSlice(a, &.{ c.then.index(), c.@"else".index() }),
.@"switch" => |sw| {
try succ.append(a, sw.default.index());
for (sw.cases) |c| try succ.append(a, c.block.index());
},
else => {},
}
for (succ.items) |s| if (!seen[s]) try dfs(a, f, s, seen, post);
try post.append(a, b);
}