Geometry shaders on both backends

Lowering: per-vertex inputs (point/line/triangle/lineadj/triangleadj
arrays), stream outputs registered per stream parameter in order, and
Append/RestartStrip from any function (streams are compile-time only and
drop out of IR signatures). [maxvertexcount] and [instance].

DXIL: GSVIn/GSIn/GSOut signatures (SV_PrimitiveID as a shadow element,
SV_GSInstanceID by intrinsic), vertex-indexed loadInput, emitStream /
cutStream, GS state metadata, PSV0 geometry info, MaxVertexCount and
per-stream dependency tables. SPIR-V: the Geometry execution model and
modes, arrayed per-vertex inputs, OpEmitVertex / OpEndPrimitive (stream
variants for several streams), and the PrimitiveId, InvocationId, Layer,
ViewportIndex and SampleId builtins (Flat on integer fragment builtins).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peter Li 2026-10-31 11:11:28 -07:00
parent 3daa1943b8
commit ddf0082220
9 changed files with 378 additions and 21 deletions

View File

@ -285,7 +285,7 @@ const Emitter = struct {
const m = e.m;
const entry = m.entry orelse return e.unsupported("no entry point", .{});
switch (entry.stage) {
.compute, .vertex, .pixel => {},
.compute, .vertex, .pixel, .geometry => {},
else => return e.unsupported("{s} shaders are not supported yet", .{@tagName(entry.stage)}),
}
const void_ty = try e.voidTy();
@ -968,6 +968,13 @@ const Emitter = struct {
},
.method => |x| return e.method(frame, x.name, x.res, x.args, i.ty),
.input => |k| return e.input(k, i.ty),
.input_vertex => |x| return e.inputAt(x.element, i.ty, x.vertex),
.emit, .cut => |stream| {
const i8t = try e.dm.intType(8);
const fn_i = try e.dxOp(if (i.op == .emit) "dx.op.emitStream" else "dx.op.cutStream", try e.voidTy(), &.{ try e.dm.intType(32), i8t }, .nounwind);
_ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(if (i.op == .emit) 97 else 98), try e.dm.constant(.{ .ty = i8t, .kind = .{ .int = stream } }) });
return .none;
},
.output => |o| {
try e.output(frame, o.element, o.value);
return .none;
@ -2424,6 +2431,7 @@ const Emitter = struct {
const points: [2]?signature.SigPoint = switch (entry.stage) {
.vertex => .{ .vs_in, .vs_out },
.pixel => .{ .ps_in, .ps_out },
.geometry => .{ .gs_v_in, .gs_out },
else => .{ null, null },
};
e.in_elem = try e.arena.alloc(?u32, entry.inputs.items.len);
@ -2441,7 +2449,9 @@ const Emitter = struct {
for (els, 0..) |el, k| {
const kind = signature.kindByName(el.semantic);
if (kind == .invalid) return e.unsupported("semantic '{s}' is not supported yet", .{el.semantic});
const interp = signature.interpretation(kind, sp, e.profile.minor);
// Geometry inputs that are not per vertex belong to GSIn.
const esp: signature.SigPoint = if (sp == .gs_v_in and !el.per_vertex) .gs_in else sp;
const interp = signature.interpretation(kind, esp, e.profile.minor);
switch (interp) {
.na => return e.unsupported("semantic '{s}' is not supported as this {s} yet", .{ el.semantic, if (sp.isInput()) "input" else "output" }),
.not_in_sig => continue,
@ -2481,7 +2491,8 @@ const Emitter = struct {
.kind = eff_kind,
.interpretation = interp,
.comp = comp,
.interp = interpMode(el.interp, sp, comp, eff_kind),
.interp = interpMode(el.interp, esp, comp, eff_kind),
.stream = el.stream,
.rows = shape.rows,
.cols = shape.cols,
.indices = indices,
@ -2498,7 +2509,7 @@ const Emitter = struct {
/// linear for floats and constant for the rest; SV_Position never
/// interpolates with perspective.
fn interpMode(q: types.Interp, sp: signature.SigPoint, comp: signature.CompType, kind: signature.SemanticKind) signature.InterpMode {
if (sp == .vs_in or sp == .ps_out) return .undefined;
if (sp == .vs_in or sp == .ps_out or sp == .gs_in) return .undefined;
var m: signature.InterpMode = if (q.nointerpolation)
.constant
else if (q.sample)
@ -2594,6 +2605,8 @@ const Emitter = struct {
.{ .kind = .view_id, .op = 138, .fname = "dx.op.viewID.i32" },
.{ .kind = .start_vertex_location, .op = 256, .fname = "dx.op.startVertexLocation.i32" },
.{ .kind = .start_instance_location, .op = 257, .fname = "dx.op.startInstanceLocation.i32" },
.{ .kind = .primitive_id, .op = 108, .fname = "dx.op.primitiveID.i32" },
.{ .kind = .gs_instance_id, .op = 100, .fname = "dx.op.gsInstanceID.i32" },
};
const out = try e.arena.alloc(Value, try e.flatCount(ty));
if (kind == .cull_primitive) {
@ -2612,6 +2625,10 @@ const Emitter = struct {
}
fn input(e: *Emitter, k: u32, ty: TypeId) Error!Lowered {
return e.inputAt(k, ty, null);
}
fn inputAt(e: *Emitter, k: u32, ty: TypeId, vertex: ?u32) Error!Lowered {
const entry = e.m.entry.?;
if (entry.stage == .compute) return e.computeInput(k, ty);
const el = entry.inputs.items[k];
@ -2622,12 +2639,12 @@ const Emitter = struct {
const via = sigScalar(se.comp);
const vt = try e.scalarTy(via);
const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.loadInput.{s}", .{e.overloadName(vt)}), vt, &.{ i32t, i32t, i32t, i8t, i32t }, .nounwind_readnone);
const undef = try e.dm.constant(.{ .ty = i32t, .kind = .undef });
const vx = if (vertex) |v| try e.i32Const(v) else try e.dm.constant(.{ .ty = i32t, .kind = .undef });
const out = try e.arena.alloc(Value, try e.flatCount(ty));
const to = e.compOf(ty);
for (out, 0..) |*o, c| {
const rc = try e.sigComponent(el.ty, el.row_major, @intCast(c));
const v = try e.callOp(fn_i, vt, &.{ try e.i32Const(4), try e.i32Const(se.id), try e.i32Const(rc[0]), try e.dm.constInt(8, rc[1]), undef });
const v = try e.callOp(fn_i, vt, &.{ try e.i32Const(4), try e.i32Const(se.id), try e.i32Const(rc[0]), try e.dm.constInt(8, rc[1]), vx });
o.* = try e.convertScalar(v, via, to);
se.usage |= @as(u8, 1) << @intCast(rc[1]);
}
@ -2835,6 +2852,13 @@ const Emitter = struct {
const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) });
try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads });
}
if (entry.stage == .geometry) {
// GS state: input primitive, max vertex count, stream mask,
// output topology, instance count.
const gsi = entry.geometry;
const state = try dm.mdNode(&.{ try mdI32(dm, @intFromEnum(gsi.input)), try mdI32(dm, gsi.max_vertex_count), try mdI32(dm, streamMask(gsi)), try mdI32(dm, gsTopology(gsi)), try mdI32(dm, gsi.instance_count) });
try props.appendSlice(e.arena, &.{ try mdI32(dm, 1), state });
}
const props_node = if (props.items.len > 0) try dm.mdNode(props.items) else null;
var sigs: ?module.MdId = null;
if (e.sig_in.len + e.sig_out.len > 0) {
@ -2918,9 +2942,19 @@ const Emitter = struct {
},
else => {},
}
if (entry.stage == .geometry) {
const gsi = entry.geometry;
std.mem.writeInt(u32, stage_info[0..4], @intFromEnum(gsi.input), .little);
std.mem.writeInt(u32, stage_info[4..8], gsTopology(gsi), .little);
std.mem.writeInt(u32, stage_info[8..12], streamMask(gsi), .little);
for (e.sig_out) |el| {
if (el.kind == .position) stage_info[12] = 1; // OutputPositionPresent
}
}
const kind: shader.ShaderKind = switch (entry.stage) {
.vertex => .vertex,
.pixel => .pixel,
.geometry => .geometry,
else => .compute,
};
const psv = try shader.psv(gpa, .{
@ -2932,6 +2966,7 @@ const Emitter = struct {
.inputs = e.sig_in,
.outputs = e.sig_out,
.groupshared_bytes = if (entry.stage == .compute) e.groupshared_bytes else 0,
.max_vertex_count = if (entry.stage == .geometry) @intCast(entry.geometry.max_vertex_count) else 0,
});
defer gpa.free(psv);
const isg1 = try signature.programSignature(gpa, e.sig_in, true);
@ -2951,6 +2986,24 @@ const Emitter = struct {
}
};
fn streamMask(g: ir.GeometryInfo) u32 {
var m: u32 = 0;
for (g.streams, 0..) |st, k| if (st != null) {
m |= @as(u32, 1) << @intCast(k);
};
return if (m == 0) 1 else m;
}
/// DXIL::PrimitiveTopology of the (first used) output stream.
fn gsTopology(g: ir.GeometryInfo) u32 {
for (g.streams) |st| if (st) |k| return switch (k) {
.point => 1,
.line => 3,
.triangle => 5,
};
return 1;
}
fn isResourceType(t: *TypeTable, ty: TypeId) bool {
return switch (t.get(ty)) {
.resource, .sampler => true,

View File

@ -146,6 +146,7 @@ pub const PsvInfo = struct {
inputs: []const signature.Element = &.{},
outputs: []const signature.Element = &.{},
groupshared_bytes: u32 = 0,
max_vertex_count: u16 = 0,
};
pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resources: []const ResourceBind) ![]u8 {
@ -168,7 +169,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount
// PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts,
// vector counts.
try buf.appendSlice(gpa, &.{ @backingInt(info.kind), 0, 0, 0 });
try buf.appendSlice(gpa, &.{ @backingInt(info.kind), 0, @truncate(info.max_vertex_count), @truncate(info.max_vertex_count >> 8) });
try buf.appendSlice(gpa, &.{ @intCast(info.inputs.len), @intCast(info.outputs.len), 0, @intCast(in_vectors) });
for (out_vectors) |v| try buf.append(gpa, @intCast(v));
// PSVRuntimeInfo2
@ -233,10 +234,14 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 {
}
// Input-to-output dependency table (no ViewID). Left empty: the
// validator only checks it against dx.viewIdState, which zdxc omits.
if (in_vectors > 0 and out_vectors[0] > 0) {
const dwords = ((out_vectors[0] + 7) >> 3) * in_vectors * 4;
// (One per output stream for geometry shaders.)
for (out_vectors, 0..) |ov, stream| {
if (stream > 0 and info.kind != .geometry) break;
if (in_vectors > 0 and ov > 0) {
const dwords = ((ov + 7) >> 3) * in_vectors * 4;
try buf.appendNTimes(gpa, 0, dwords * 4);
}
}
return buf.toOwnedSlice(gpa);
}

View File

@ -107,7 +107,13 @@ pub const Op = union(enum) {
/// An entry-point input / output element (index into the entry's
/// signature).
input: u32,
/// A per-vertex input (geometry shaders): element, vertex index.
input_vertex: struct { element: u32, vertex: u32 },
output: struct { element: u32, value: Ref },
/// Geometry shaders: emit the vertex written to the outputs of a stream,
/// or end its strip.
emit: u32,
cut: u32,
phi: []const struct { value: Ref, block: BlockId },
};
@ -197,6 +203,22 @@ pub const SigElement = struct {
interp: types.Interp = .{},
/// Matrices in the element are row_major (signature layout only).
row_major: bool = false,
/// Geometry shader output stream.
stream: u32 = 0,
/// One value per vertex of the input primitive (geometry shaders).
per_vertex: bool = false,
};
pub const Primitive = enum(u8) { point = 1, line = 2, triangle = 3, line_adj = 6, triangle_adj = 7 };
pub const GeometryInfo = struct {
input: Primitive = .triangle,
/// Vertices per input primitive.
input_vertices: u32 = 3,
max_vertex_count: u32 = 1,
instance_count: u32 = 1,
/// Output topology per stream (null: stream unused).
streams: [4]?enum { point, line, triangle } = .{ null, null, null, null },
};
pub const Entry = struct {
@ -205,6 +227,7 @@ pub const Entry = struct {
name: []const u8,
stage: Stage,
num_threads: [3]u32 = .{ 1, 1, 1 },
geometry: GeometryInfo = .{},
inputs: std.ArrayList(SigElement) = .empty,
outputs: std.ArrayList(SigElement) = .empty,
/// The wrapper with no parameters that reads `inputs`, calls `func`
@ -367,6 +390,9 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo
try w.print("{s}", .{c.name});
for (c.args, 0..) |a, i| try w.print("{s} %{d}", .{ if (i > 0) "," else "", a.index() });
},
.input_vertex => |x| try w.print("input {d} vertex {d}", .{ x.element, x.vertex }),
.emit => |k| try w.print("emit stream {d}", .{k}),
.cut => |k| try w.print("cut stream {d}", .{k}),
.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| {

View File

@ -38,12 +38,15 @@ pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module {
l.unsupported(.none, "missing entry point definition", .{});
return error.Unsupported;
};
if (opts.stage == .geometry) try l.registerStreams(entry_fn);
const main = try l.functionIndex(entry_fn);
try l.drain();
try l.buildEntry(entry_fn, main, opts);
return l.m;
}
const Stream = struct { param: u32, ty: TypeId, first: u32, kind: @FieldType(types.Type, "stream") };
const Lowerer = struct {
arena: Allocator,
s: *Sema,
@ -60,6 +63,11 @@ const Lowerer = struct {
b: ir.Builder = undefined,
vars: std.AutoHashMapUnmanaged(*const Variable, Ref) = .empty,
loops: std.ArrayList(struct { brk: BlockId, cont: BlockId }) = .empty,
/// Geometry shaders: output elements registered before lowering (by
/// stream parameter), and each stream's element layout.
early_outputs: std.ArrayList(ir.SigElement) = .empty,
streams: std.ArrayList(Stream) = .empty,
entry_fn: ?*const semamod.Function = null,
ret_ty: TypeId = TypeTable.void_type,
fn unsupported(l: *Lowerer, loc: ast.Loc, comptime fmt: []const u8, args: anytype) void {
@ -76,9 +84,13 @@ const Lowerer = struct {
/// 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 });
// Stream-output objects exist only at compile time: no parameter.
var params: std.ArrayList(ir.Param) = .empty;
for (f.params) |p| {
if (l.s.types.get(p.type) == .stream) continue;
try params.append(l.arena, .{ .name = p.name, .ty = p.type, .by_ref = p.dir != .in });
}
const i = try l.m.addFunction(.{ .name = f.name, .params = params.items, .ret = f.ret });
try l.funcs.put(l.arena, f, i);
try l.pending.append(l.arena, f);
return i;
@ -101,8 +113,11 @@ const Lowerer = struct {
l.b.setBlock(try l.b.newBlock());
// Parameters: by-value ones get local storage, out / inout ones
// are the caller's pointers.
var ir_index: u32 = 0;
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 });
if (l.s.types.get(p.type) == .stream) continue;
const pv = try l.b.add(.{ .op = .{ .param = ir_index }, .ty = p.type, .ptr = if (p.dir != .in) .function else .none });
ir_index += 1;
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);
@ -868,7 +883,10 @@ const Lowerer = struct {
{
const vals = try l.arena.alloc(Ref, args.len);
const temps = try l.arena.alloc(Ref, args.len);
var n_vals: usize = 0;
for (args, f.params, 0..) |a, p, i| {
if (l.s.types.get(p.type) == .stream) continue;
n_vals += 1;
if (p.dir == .in) {
vals[i] = try l.converted(a, p.type);
} else {
@ -878,9 +896,13 @@ const Lowerer = struct {
vals[i] = temps[i];
}
}
const res = try l.b.add(.{ .op = .{ .call = .{ .func = fi, .args = vals } }, .ty = ret_ty });
// (Stream arguments are dropped.)
var packed_vals: std.ArrayList(Ref) = .empty;
for (f.params, 0..) |p, i| if (l.s.types.get(p.type) != .stream) try packed_vals.append(l.arena, vals[i]);
std.debug.assert(packed_vals.items.len == n_vals);
const res = try l.b.add(.{ .op = .{ .call = .{ .func = fi, .args = packed_vals.items } }, .ty = ret_ty });
for (args, f.params, 0..) |a, p, i| {
if (p.dir == .in) continue;
if (p.dir == .in or l.s.types.get(p.type) == .stream) continue;
const back = try l.b.load(temps[i]);
try l.storeTo(a, try l.convert(back, a.ty));
}
@ -894,6 +916,9 @@ const Lowerer = struct {
.intrinsic => |it| {
const name = table.intrinsics[it.index].name;
const spec = table.intrinsics[it.index];
if (it.object) |_| if (l.s.types.get(callee.kind.member.base.ty) == .stream) {
return l.streamMethod(e, callee.kind.member.base, name, args);
};
if (it.object) |_| {
const obj = callee.kind.member.base;
const res = try l.rvalue(obj);
@ -1173,14 +1198,145 @@ const Lowerer = struct {
return inits;
}
/// One leaf at a time of a signature value of type `ty`: registers
/// elements into `list` (when non-null) or writes `value`'s leaves to
/// consecutive output elements starting at `next`.
fn streamOut(l: *Lowerer, list: ?*std.ArrayList(ir.SigElement), ty: TypeId, semantic: ?[]const u8, attrs: SigAttrs, value: ?Ref, next: *u32, stream: u32, numbered: ?*ir.SigElement, loc: ast.Loc) Error!void {
const t = l.types();
const leaf = struct {
fn f(lw: *Lowerer, lst: ?*std.ArrayList(ir.SigElement), el: ir.SigElement, v: ?Ref, nx: *u32) Error!void {
if (lst) |x| try x.append(lw.arena, el) else _ = try lw.b.add(.{ .op = .{ .output = .{ .element = nx.*, .value = v.? } }, .ty = TypeTable.void_type });
nx.* += 1;
}
}.f;
const part = struct {
fn f(lw: *Lowerer, v: ?Ref, k: usize, fty: TypeId) Error!?Ref {
return if (v) |x| try lw.b.add(.{ .op = .{ .extract = .{ .agg = x, .index = @intCast(k) } }, .ty = fty }) else null;
}
}.f;
if (numbered) |num| {
// A semantic on a struct numbers its leaves.
if (t.get(ty) == .@"struct") {
for (t.get(ty).@"struct".fields.items, 0..) |fld, k| try l.streamOut(list, fld.type, null, attrs.field(fld), try part(l, value, k, fld.type), next, stream, num, loc);
return;
}
var el = withAttrs(.{ .semantic = num.semantic, .semantic_index = num.semantic_index, .ty = ty, .system_value = num.system_value }, attrs);
el.stream = stream;
num.semantic_index += 1;
return leaf(l, list, el, value, next);
}
if (semantic) |sem| {
var el = withAttrs(sigElement(sem, ty), attrs);
el.stream = stream;
if (t.get(ty) == .@"struct") return l.streamOut(list, ty, null, attrs, value, next, stream, &el, loc);
return leaf(l, list, el, value, next);
}
if (t.get(ty) != .@"struct") {
l.unsupported(loc, "stream output elements need semantics", .{});
return error.Unsupported;
}
for (t.get(ty).@"struct".fields.items, 0..) |fld, k| try l.streamOut(list, fld.type, fld.semantic, attrs.field(fld), try part(l, value, k, fld.type), next, stream, null, loc);
}
/// Registers the output elements of each stream parameter of the entry
/// (in parameter order, as dxc).
fn registerStreams(l: *Lowerer, f: *const semamod.Function) Error!void {
l.entry_fn = f;
for (f.params, 0..) |p, i| {
const st = switch (l.s.types.get(p.type)) {
.stream => |st| st,
else => continue,
};
const k: u32 = @intCast(l.streams.items.len);
if (k >= 4) {
l.unsupported(f.loc, "more than four streams", .{});
return error.Unsupported;
}
var next: u32 = @intCast(l.early_outputs.items.len);
const first = next;
try l.streamOut(&l.early_outputs, st.elem, null, .{}, null, &next, k, null, f.decl.params[i].name_loc);
try l.streams.append(l.arena, .{ .param = @intCast(i), .ty = st.elem, .first = first, .kind = st });
}
}
/// `stream.Append(v)` / `stream.RestartStrip()`.
fn streamMethod(l: *Lowerer, e: *ast.Expr, obj: *ast.Expr, name: []const u8, args: []const *ast.Expr) Error!Ref {
if (l.streams.items.len == 0) return l.fail(e, "streams outside geometry shaders");
// Which stream: the entry's stream parameter named, or the only one.
var k: usize = 0;
if (l.streams.items.len > 1) {
const r = l.s.resolution(obj) orelse return l.fail(e, "this stream");
const ef = l.entry_fn.?;
k = for (l.streams.items, 0..) |sm, j| {
if (r == .variable and sm.param < ef.param_vars.len and ef.param_vars[sm.param] == r.variable) break j;
} else return l.fail(e, "selecting among several streams through a function parameter");
}
const sm = l.streams.items[k];
if (std.mem.eql(u8, name, "Append")) {
const v = try l.converted(args[0], sm.ty);
var next = sm.first;
try l.streamOut(null, sm.ty, null, .{}, v, &next, @intCast(k), null, e.loc);
_ = try l.b.add(.{ .op = .{ .emit = @intCast(k) }, .ty = TypeTable.void_type });
} else _ = try l.b.add(.{ .op = .{ .cut = @intCast(k) }, .ty = TypeTable.void_type });
return .none;
}
/// A per-vertex input value of type `ty` for `vertex`, registering its
/// elements when `register` (the first vertex).
fn vertexIn(l: *Lowerer, entry: *ir.Entry, ty: TypeId, semantic: ?[]const u8, attrs: SigAttrs, vertex: u32, register: bool, next: *u32, numbered: ?*ir.SigElement, loc: ast.Loc) Error!Ref {
const t = l.types();
const leaf = struct {
fn f(lw: *Lowerer, en: *ir.Entry, el: ir.SigElement, vx: u32, reg: bool, nx: *u32) Error!Ref {
var e2 = el;
e2.per_vertex = true;
if (reg) try en.inputs.append(lw.arena, e2);
const r = try lw.b.add(.{ .op = .{ .input_vertex = .{ .element = nx.*, .vertex = vx } }, .ty = el.ty });
nx.* += 1;
return r;
}
}.f;
if (numbered) |num| {
if (t.get(ty) == .@"struct") {
const st = t.get(ty).@"struct";
const parts = try l.arena.alloc(Ref, st.fields.items.len);
for (parts, st.fields.items) |*p, fld| p.* = try l.vertexIn(entry, fld.type, null, attrs.field(fld), vertex, register, next, num, loc);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
}
const el = withAttrs(.{ .semantic = num.semantic, .semantic_index = num.semantic_index, .ty = ty, .system_value = num.system_value }, attrs);
num.semantic_index += 1;
return leaf(l, entry, el, vertex, register, next);
}
if (semantic) |sem| {
var el = withAttrs(sigElement(sem, ty), attrs);
if (t.get(ty) == .@"struct") return l.vertexIn(entry, ty, null, attrs, vertex, register, next, &el, loc);
return leaf(l, entry, el, vertex, register, next);
}
if (t.get(ty) != .@"struct") {
l.unsupported(loc, "per-vertex inputs need semantics", .{});
return error.Unsupported;
}
const st = t.get(ty).@"struct";
const parts = try l.arena.alloc(Ref, st.fields.items.len);
for (parts, st.fields.items) |*p, fld| p.* = try l.vertexIn(entry, fld.type, fld.semantic, attrs.field(fld), vertex, register, next, null, loc);
return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty });
}
fn buildEntry(l: *Lowerer, f: *const semamod.Function, main: u32, opts: Options) Error!void {
const inits = try l.staticInits();
var entry: ir.Entry = .{ .func = main, .name = opts.entry, .stage = opts.stage };
entry.outputs = l.early_outputs;
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));
}
if (std.ascii.eqlIgnoreCase(a.name, "maxvertexcount") and a.args.len == 1) entry.geometry.max_vertex_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
if (std.ascii.eqlIgnoreCase(a.name, "instance") and a.args.len == 1) entry.geometry.instance_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
}
for (l.streams.items, 0..) |sm, k| entry.geometry.streams[k] = switch (sm.kind.kind) {
.point => .point,
.line => .line,
.triangle => .triangle,
};
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());
@ -1192,18 +1348,40 @@ const Lowerer = struct {
};
const args = try l.arena.alloc(Ref, f.params.len);
const locals = try l.arena.alloc(Ref, f.params.len);
var n_args: usize = 0;
for (f.decl.params, f.params, 0..) |pd, p, i| {
if (l.s.types.get(p.type) == .stream) continue;
n_args += 1;
locals[i] = try l.b.add(.{ .op = .local_var, .ty = p.type, .ptr = .function });
const q = pd.quals;
if (opts.stage == .geometry and (q.point or q.line or q.triangle or q.lineadj or q.triangleadj) and l.s.types.get(p.type) == .array) {
// Per-vertex inputs: one value per vertex of the primitive.
const arr = l.s.types.get(p.type).array;
entry.geometry.input = if (q.point) .point else if (q.line) .line else if (q.triangle) .triangle else if (q.lineadj) .line_adj else .triangle_adj;
entry.geometry.input_vertices = arr.len;
const first: u32 = @intCast(entry.inputs.items.len);
const verts = try l.arena.alloc(Ref, arr.len);
for (verts, 0..) |*v, vx| {
var next = first;
v.* = try l.vertexIn(&entry, arr.elem, semanticOf(pd.semantics), paramAttrs(pd.quals), @intCast(vx), vx == 0, &next, null, pd.name_loc);
}
try l.b.store(locals[i], try l.b.add(.{ .op = .{ .construct = verts }, .ty = p.type }));
args[i] = try l.b.load(locals[i]);
continue;
}
if (p.dir != .out) {
const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), pd.name_loc, pd.name);
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 });
var call_args: std.ArrayList(Ref) = .empty;
for (f.params, 0..) |p, i| if (l.s.types.get(p.type) != .stream) try call_args.append(l.arena, args[i]);
std.debug.assert(call_args.items.len == n_args);
const ret = try l.b.add(.{ .op = .{ .call = .{ .func = main, .args = call_args.items } }, .ty = f.ret });
if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), paramAttrs(f.decl.quals), ret, f.loc, "return value");
for (f.decl.params, f.params, 0..) |pd, p, i| {
if (p.dir == .in) continue;
if (p.dir == .in or l.s.types.get(p.type) == .stream) continue;
const v = try l.b.load(locals[i]);
try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), v, pd.name_loc, pd.name);
}

View File

@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const
/// `op` with every operand passed through `ctx.map`.
fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op {
return switch (op) {
.constant, .param, .global, .local_var, .input => op,
.constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut => op,
.load => |p| .{ .load = ctx.map(p) },
.store => |x| .{ .store = .{ .ptr = ctx.map(x.ptr), .value = ctx.map(x.value) } },
.access => |x| .{ .access = .{ .base = ctx.map(x.base), .indices = try mapRefs(a, x.indices, ctx) } },

View File

@ -190,6 +190,10 @@ pub const Op = enum(u16) {
group_non_uniform_bitwise_xor = 361,
group_non_uniform_quad_broadcast = 365,
group_non_uniform_quad_swap = 366,
emit_vertex = 218,
end_primitive = 219,
emit_stream_vertex = 220,
end_stream_primitive = 221,
};
pub const Section = enum {

View File

@ -27,6 +27,7 @@ const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, o
const Capability = enum(u32) {
shader = 1,
geometry = 2,
float16 = 9,
float64 = 10,
int64 = 11,
@ -35,6 +36,8 @@ const Capability = enum(u32) {
image_gather_extended = 25,
storage_image_multisample = 27,
sample_rate_shading = 35,
geometry_streams = 54,
multi_viewport = 57,
min_lod = 42,
sampled1d = 43,
image1d = 44,
@ -479,6 +482,7 @@ const Emitter = struct {
try e.b.emit(.debug_names, .source, &.{ 5, 600 }); // HLSL
e.void_id = try e.typeId(TypeTable.void_type);
try e.cap(.shader);
if (entry.stage == .geometry) try e.cap(.geometry);
e.func_ids = try e.arena.alloc(Id, m.functions.items.len);
for (e.func_ids) |*id| id.* = e.b.newId();
@ -516,6 +520,25 @@ const Emitter = struct {
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] }),
.geometry => {
const gsi = entry.geometry;
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 0, gsi.instance_count }); // Invocations
const in_mode: u32 = switch (gsi.input) {
.point => 19,
.line => 20,
.line_adj => 21,
.triangle => 22,
.triangle_adj => 23,
};
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, in_mode });
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 26, gsi.max_vertex_count }); // OutputVertices
const out_mode: u32 = if (gsi.streams[0]) |k| switch (k) {
.point => 27,
.line => 28,
.triangle => 29,
} else 27;
try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, out_mode });
},
.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")) {
@ -688,6 +711,26 @@ const Emitter = struct {
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 (input and (stage == .geometry or stage == .pixel) and eq(n, "SV_PrimitiveID")) {
try e.cap(.geometry);
return .{ .id = 7, .ty = uint1 }; // PrimitiveId
}
if (input and stage == .geometry and eq(n, "SV_GSInstanceID")) return .{ .id = 8, .ty = uint1 }; // InvocationId
if ((!input and stage == .geometry) or (input and stage == .pixel)) {
if (eq(n, "SV_RenderTargetArrayIndex")) {
try e.cap(.geometry);
return .{ .id = 9, .ty = uint1 }; // Layer
}
if (eq(n, "SV_ViewportArrayIndex")) {
try e.cap(.geometry);
try e.cap(.multi_viewport);
return .{ .id = 10, .ty = uint1 }; // ViewportIndex
}
}
if (input and stage == .pixel and eq(n, "SV_SampleIndex")) {
try e.cap(.sample_rate_shading);
return .{ .id = 18, .ty = uint1 }; // SampleId
}
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});
@ -704,13 +747,19 @@ const Emitter = struct {
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;
var ty = if (bi) |x| x.ty else if (e.t.component(el.ty) == .bool) try e.t.withComponent(el.ty, .uint) else el.ty;
// Geometry inputs per vertex are arrays over the primitive.
const vty = ty;
if (el.per_vertex) ty = try e.t.array(ty, entry.geometry.input_vertices);
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
if (input and entry.stage == .pixel and !e.t.component(x.ty).?.isFloat() and e.t.component(x.ty).? != .bool) {
try e.b.emit(.annotations, .decorate, &.{ var_id, 14 }); // Flat
}
} 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
@ -733,9 +782,13 @@ const Emitter = struct {
}
}
}
if (!input and entry.stage == .geometry and entry.geometry.streams[1] != null) {
try e.cap(.geometry_streams);
try e.b.emit(.annotations, .decorate, &.{ var_id, 29, el.stream }); // Stream
}
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 };
iface.* = .{ .var_id = var_id, .ty = vty };
try e.interface_ids.append(e.arena, var_id);
}
}
@ -1291,6 +1344,17 @@ const Emitter = struct {
const loaded = try e.op1(.load, iface.ty, &.{iface.var_id});
e.vals[ri] = try e.reshape(loaded, iface.ty, i.ty);
},
.input_vertex => |x| {
const iface = e.inputs[x.element];
const ptr = try e.opRaw(.access_chain, try e.pointerType(.input, try e.typeId(iface.ty)), &.{ iface.var_id, try e.constUint(x.vertex) });
e.vals[ri] = try e.reshape(try e.op1(.load, iface.ty, &.{ptr}), iface.ty, i.ty);
},
.emit, .cut => |stream| {
const multi = e.m.entry.?.geometry.streams[1] != null;
if (multi) {
try e.b.emit(.functions, if (i.op == .emit) .emit_stream_vertex else .end_stream_primitive, &.{try e.constUint(stream)});
} else try e.b.emit(.functions, if (i.op == .emit) .emit_vertex else .end_primitive, &.{});
},
.output => |o| {
const iface = e.outputs[o.element];
const v = try e.reshape(e.val(o.value), f.inst(o.value).ty, iface.ty);

13
test/dxil/geometry.hlsl Normal file
View File

@ -0,0 +1,13 @@
// PROFILE: gs_6_0
// Geometry shader: per-vertex inputs, shadow SV_PrimitiveID, streams.
// ZCHECK: @dx.op.emitStream(i32 97, i8 0)
// ZCHECK: @dx.op.cutStream(i32 98, i8 0)
// ZCHECK: @dx.op.gsInstanceID.i32(i32 100)
// ZCHECK: !{i32 3, i32 6, i32 1, i32 5, i32 2}
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
struct GSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; uint layer : SV_RenderTargetArrayIndex; };
[maxvertexcount(6)] [instance(2)]
void main(triangle VSOut input[3], uint pid : SV_PrimitiveID, uint iid : SV_GSInstanceID, inout TriangleStream<GSOut> stream) {
for (int k = 0; k < 3; k++) { GSOut o; o.pos = input[k].pos; o.uv = input[k].uv + pid; o.layer = iid; stream.Append(o); }
stream.RestartStrip();
}

14
test/spirv/geometry.hlsl Normal file
View File

@ -0,0 +1,14 @@
// PROFILE: gs_6_0
// Geometry shader: arrayed per-vertex inputs, emit and end primitive.
// ZCHECK: OpExecutionMode %main Invocations 2
// ZCHECK: OpExecutionMode %main OutputTriangleStrip
// ZCHECK: OpEmitVertex
// ZCHECK: OpEndPrimitive
// ZCHECK: BuiltIn InvocationId
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
struct GSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; uint layer : SV_RenderTargetArrayIndex; };
[maxvertexcount(6)] [instance(2)]
void main(triangle VSOut input[3], uint pid : SV_PrimitiveID, uint iid : SV_GSInstanceID, inout TriangleStream<GSOut> stream) {
for (int k = 0; k < 3; k++) { GSOut o; o.pos = input[k].pos; o.uv = input[k].uv + pid; o.layer = iid; stream.Append(o); }
stream.RestartStrip();
}