diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 9ac0367..02a3986 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -116,6 +116,8 @@ const Emitter = struct { diags: *diag.Diagnostics, main_fn: u32 = 0, + /// Hull shaders: the patch constant function. + pc_fn: ?u32 = null, /// Instructions per block, in creation order, with provisional ids. blocks: std.ArrayList(std.ArrayList(PInst)) = .empty, prologue: std.ArrayList(PInst) = .empty, @@ -141,6 +143,9 @@ const Emitter = struct { sig_in: []signature.Element = &.{}, sig_out: []signature.Element = &.{}, + /// Patch constants (hull output, domain input). + sig_pc: []signature.Element = &.{}, + pc_elem: []?u32 = &.{}, /// IR entry input / output index -> signature element; null for system /// values read with an intrinsic instead. in_elem: []?u32 = &.{}, @@ -285,7 +290,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, .geometry => {}, + .compute, .vertex, .pixel, .geometry, .hull, .domain => {}, else => return e.unsupported("{s} shaders are not supported yet", .{@tagName(entry.stage)}), } const void_ty = try e.voidTy(); @@ -299,7 +304,21 @@ const Emitter = struct { e.cur = try e.newBlock(); try e.createHandles(); _ = try e.inlineCall(entry.wrapper, &.{}); - try e.finish(); + try e.finish(e.main_fn); + if (entry.patch_wrapper) |pw| { + // The patch constant function is a function of its own. + e.blocks = .empty; + e.prologue = .empty; + e.next_id = 0; + e.private_globals = .empty; + e.nonuniform = .empty; + const name = m.functions.items[pw].name; + e.pc_fn = try e.dm.addFunction(.{ .name = name[0 .. name.len - ".wrapper".len], .ty = fn_ty, .num_blocks = 1 }); + e.cur = try e.newBlock(); + try e.createHandles(); + _ = try e.inlineCall(pw, &.{}); + try e.finish(e.pc_fn.?); + } const bitcode = try e.writeModule(entry); defer gpa.free(bitcode); @@ -507,7 +526,7 @@ const Emitter = struct { /// Assigns final instruction indices: prologue first, then blocks in /// creation order. - fn finish(e: *Emitter) Error!void { + fn finish(e: *Emitter, func: u32) Error!void { const map = try e.arena.alloc(u32, e.next_id); var n: u32 = 0; for (e.prologue.items) |pi| { @@ -518,7 +537,7 @@ const Emitter = struct { map[pi.id] = n; n += 1; }; - const f = &e.dm.functions.items[e.main_fn]; + const f = &e.dm.functions.items[func]; f.num_blocks = @intCast(e.blocks.items.len); const remap = struct { fn v(mp: []const u32, x: Value) Value { @@ -605,7 +624,7 @@ const Emitter = struct { }; @memset(frame.vals, .none); @memset(frame.blocks, null); - const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and fi == e.m.entry.?.wrapper; + const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and (fi == e.m.entry.?.wrapper or fi == e.m.entry.?.patch_wrapper); if (!is_entry) frame.cont = try e.newBlock(); // The callee's entry continues the current block. frame.blocks[0] = e.cur; @@ -979,6 +998,12 @@ const Emitter = struct { try e.output(frame, o.element, o.value); return .none; }, + .patch_input => |k| return e.patchInput(k, i.ty), + .patch_output => |o| { + try e.patchOutput(frame, o.element, o.value); + return .none; + }, + .output_vertex => |x| return e.outputControlPoint(x.element, i.ty, x.vertex), .phi => return e.unsupported("phi", .{}), } } @@ -2428,11 +2453,13 @@ const Emitter = struct { // Signatures fn buildSignatures(e: *Emitter, entry: ir.Entry) Error!void { - 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 }, + const points: [3]?signature.SigPoint = switch (entry.stage) { + .vertex => .{ .vs_in, .vs_out, null }, + .pixel => .{ .ps_in, .ps_out, null }, + .geometry => .{ .gs_v_in, .gs_out, null }, + .hull => .{ .hs_cp_in, .hs_cp_out, .pc_out }, + .domain => .{ .ds_cp_in, .ds_out, .ds_in }, + else => .{ null, null, null }, }; e.in_elem = try e.arena.alloc(?u32, entry.inputs.items.len); @memset(e.in_elem, null); @@ -2442,6 +2469,9 @@ const Emitter = struct { @memset(e.out_split, 0); if (points[0]) |sp| e.sig_in = try e.buildSignature(entry.inputs.items, sp, e.in_elem, null); if (points[1]) |sp| e.sig_out = try e.buildSignature(entry.outputs.items, sp, e.out_elem, e.out_split); + e.pc_elem = try e.arena.alloc(?u32, entry.patch_constants.items.len); + @memset(e.pc_elem, null); + if (points[2]) |sp| e.sig_pc = try e.buildSignature(entry.patch_constants.items, sp, e.pc_elem, null); } fn buildSignature(e: *Emitter, els: []const ir.SigElement, sp: signature.SigPoint, map: []?u32, split: ?[]u32) Error![]signature.Element { @@ -2450,7 +2480,7 @@ const Emitter = struct { const kind = signature.kindByName(el.semantic); if (kind == .invalid) return e.unsupported("semantic '{s}' is not supported yet", .{el.semantic}); // 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 esp: signature.SigPoint = if (sp == .gs_v_in and !el.per_vertex) .gs_in else if (sp == .hs_cp_in and !el.per_vertex) .hs_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" }), @@ -2509,7 +2539,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 or sp == .gs_in) return .undefined; + if (sp == .vs_in or sp == .ps_out or sp == .gs_in or sp == .pc_out or sp == .ds_in) return .undefined; var m: signature.InterpMode = if (q.nointerpolation) .constant else if (q.sample) @@ -2607,6 +2637,7 @@ const Emitter = struct { .{ .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" }, + .{ .kind = .output_control_point_id, .op = 107, .fname = "dx.op.outputControlPointID.i32" }, }; const out = try e.arena.alloc(Value, try e.flatCount(ty)); if (kind == .cull_primitive) { @@ -2615,6 +2646,15 @@ const Emitter = struct { } if (kind == .view_id) e.uses_view_id = true; if (kind == .inner_coverage) e.uses_inner_coverage = true; + if (kind == .domain_location) { + const ft = try e.dm.getType(.float); + const fn_i = try e.dxOp("dx.op.domainLocation.f32", ft, &.{ i32t, try e.dm.intType(8) }, .nounwind_readnone); + for (out, 0..) |*o, c| { + const v = try e.callOp(fn_i, ft, &.{ try e.i32Const(105), try e.dm.constInt(8, @intCast(c)) }); + o.* = try e.convertScalar(v, .float, e.compOf(ty)); + } + return .{ .scalars = out }; + } for (svs) |sv| if (sv.kind == kind) { const fn_i = try e.dxOp(sv.fname, i32t, &.{i32t}, .nounwind_readnone); const v = try e.callOp(fn_i, i32t, &.{try e.i32Const(sv.op)}); @@ -2676,6 +2716,64 @@ const Emitter = struct { } } + /// A domain shader's patch constant (or a system value read with its + /// own intrinsic). + fn patchInput(e: *Emitter, k: u32, ty: TypeId) Error!Lowered { + const el = e.m.entry.?.patch_constants.items[k]; + const se = if (e.pc_elem[k]) |ei| &e.sig_pc[ei] else return e.systemValueInput(el.semantic, ty); + const i32t = try e.dm.intType(32); + const i8t = try e.dm.intType(8); + 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.loadPatchConstant.{s}", .{e.overloadName(vt)}), vt, &.{ i32t, i32t, i32t, i8t }, .nounwind_readnone); + const out = try e.arena.alloc(Value, try e.flatCount(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(104), try e.i32Const(se.id), try e.i32Const(rc[0]), try e.dm.constInt(8, rc[1]) }); + o.* = try e.convertScalar(v, via, e.compOf(ty)); + se.usage |= @as(u8, 1) << @intCast(rc[1]); + } + return .{ .scalars = out }; + } + + /// A patch constant written by the hull shader's patch constant + /// function. + fn patchOutput(e: *Emitter, frame: *Frame, k: u32, value: Ref) Error!void { + const el = e.m.entry.?.patch_constants.items[k]; + const se = if (e.pc_elem[k]) |ei| &e.sig_pc[ei] else return e.unsupported("patch constant '{s}' is not supported yet", .{el.semantic}); + const vals = try e.scalars(frame, value); + const i32t = try e.dm.intType(32); + const i8t = try e.dm.intType(8); + const void_ty = try e.voidTy(); + 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.storePatchConstant.{s}", .{e.overloadName(vt)}), void_ty, &.{ i32t, i32t, i32t, i8t, vt }, .nounwind); + for (vals, 0..) |v, c| { + const rc = try e.sigComponent(el.ty, el.row_major, @intCast(c)); + _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(106), try e.i32Const(se.id), try e.i32Const(rc[0]), try e.dm.constInt(8, rc[1]), try e.convertScalar(v, e.compOf(el.ty), via) }); + se.usage |= @as(u8, 1) << @intCast(rc[1]); + } + } + + /// An output control point of the hull shader, read by its patch + /// constant function. + fn outputControlPoint(e: *Emitter, k: u32, ty: TypeId, point: u32) Error!Lowered { + const el = e.m.entry.?.outputs.items[k]; + const se = if (e.out_elem[k]) |ei| &e.sig_out[ei] else return e.unsupported("output '{s}' is not supported yet", .{el.semantic}); + const i32t = try e.dm.intType(32); + const i8t = try e.dm.intType(8); + 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.loadOutputControlPoint.{s}", .{e.overloadName(vt)}), vt, &.{ i32t, i32t, i32t, i8t, i32t }, .nounwind_readnone); + const out = try e.arena.alloc(Value, try e.flatCount(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(103), try e.i32Const(se.id), try e.i32Const(rc[0]), try e.dm.constInt(8, rc[1]), try e.i32Const(point) }); + o.* = try e.convertScalar(v, via, e.compOf(ty)); + } + return .{ .scalars = out }; + } + fn computeInput(e: *Emitter, k: u32, ty: TypeId) Error!Lowered { const el = e.m.entry.?.inputs.items[k]; const eqi = std.ascii.eqlIgnoreCase; @@ -2859,10 +2957,31 @@ const Emitter = struct { 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 }); } + if (entry.stage == .hull) { + // HS state: patch constant function, control point counts, + // domain, partitioning, output primitive, max tess factor. + const ts = entry.tess; + const pc_ty = dm.functions.items[e.pc_fn.?].ty; + const ft = try dm.getType(.float); + const state = try dm.mdNode(&.{ + try dm.mdValue(try dm.ptrType(pc_ty), .{ .function = e.pc_fn.? }), + try mdI32(dm, ts.input_control_points), + try mdI32(dm, ts.output_control_points), + try mdI32(dm, @intFromEnum(ts.domain)), + try mdI32(dm, @intFromEnum(ts.partitioning)), + try mdI32(dm, @intFromEnum(ts.output_topology)), + try dm.mdValue(ft, try dm.constant(.{ .ty = ft, .kind = .{ .float_bits = @as(u32, @bitCast(ts.max_tess_factor)) } })), + }); + try props.appendSlice(e.arena, &.{ try mdI32(dm, 3), state }); + } + if (entry.stage == .domain) { + const state = try dm.mdNode(&.{ try mdI32(dm, @intFromEnum(entry.tess.domain)), try mdI32(dm, entry.tess.input_control_points) }); + try props.appendSlice(e.arena, &.{ try mdI32(dm, 2), 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) { - sigs = try dm.mdNode(&.{ try e.signatureMetadata(e.sig_in), try e.signatureMetadata(e.sig_out), null }); + if (e.sig_in.len + e.sig_out.len + e.sig_pc.len > 0) { + sigs = try dm.mdNode(&.{ try e.signatureMetadata(e.sig_in), try e.signatureMetadata(e.sig_out), try e.signatureMetadata(e.sig_pc) }); } const main_ty = dm.functions.items[e.main_fn].ty; const fn_ref = try dm.mdValue(try dm.ptrType(main_ty), .{ .function = e.main_fn }); @@ -2951,10 +3070,26 @@ const Emitter = struct { if (el.kind == .position) stage_info[12] = 1; // OutputPositionPresent } } + if (entry.stage == .hull) { + const ts = entry.tess; + std.mem.writeInt(u32, stage_info[0..4], ts.input_control_points, .little); + std.mem.writeInt(u32, stage_info[4..8], ts.output_control_points, .little); + std.mem.writeInt(u32, stage_info[8..12], @intFromEnum(ts.domain), .little); + std.mem.writeInt(u32, stage_info[12..16], @intFromEnum(ts.output_topology), .little); + } + if (entry.stage == .domain) { + std.mem.writeInt(u32, stage_info[0..4], entry.tess.input_control_points, .little); + for (e.sig_out) |el| { + if (el.kind == .position) stage_info[4] = 1; // OutputPositionPresent + } + std.mem.writeInt(u32, stage_info[8..12], @intFromEnum(entry.tess.domain), .little); + } const kind: shader.ShaderKind = switch (entry.stage) { .vertex => .vertex, .pixel => .pixel, .geometry => .geometry, + .hull => .hull, + .domain => .domain, else => .compute, }; const psv = try shader.psv(gpa, .{ @@ -2965,24 +3100,32 @@ const Emitter = struct { .resources = binds.items, .inputs = e.sig_in, .outputs = e.sig_out, + .patch_constants = e.sig_pc, .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); + const domain: signature.Domain = if (entry.stage == .hull or entry.stage == .domain) @enumFromInt(@intFromEnum(entry.tess.domain)) else .undefined; + const isg1 = try signature.programSignature(gpa, e.sig_in, true, domain); defer gpa.free(isg1); - const osg1 = try signature.programSignature(gpa, e.sig_out, false); + const osg1 = try signature.programSignature(gpa, e.sig_out, false, domain); defer gpa.free(osg1); + const psg1 = try signature.programSignature(gpa, e.sig_pc, entry.stage == .domain, domain); + defer gpa.free(psg1); var sfi0: [8]u8 = @splat(0); std.mem.writeInt(u64, &sfi0, featureInfo(e.shaderFlags()), .little); - const parts = [_]container.Part{ + var parts: std.ArrayList(container.Part) = .empty; + try parts.appendSlice(e.arena, &.{ .{ .fourcc = container.fourcc("SFI0"), .data = &sfi0 }, .{ .fourcc = container.fourcc("ISG1"), .data = isg1 }, .{ .fourcc = container.fourcc("OSG1"), .data = osg1 }, + }); + if (entry.stage == .hull or entry.stage == .domain) try parts.append(e.arena, .{ .fourcc = container.fourcc("PSG1"), .data = psg1 }); + try parts.appendSlice(e.arena, &.{ .{ .fourcc = container.fourcc("PSV0"), .data = psv }, .{ .fourcc = container.fourcc("DXIL"), .data = dxil_part }, - }; - return container.assemble(gpa, &parts); + }); + return container.assemble(gpa, parts.items); } }; diff --git a/src/dxil/shader.zig b/src/dxil/shader.zig index 3c483f0..690bcae 100644 --- a/src/dxil/shader.zig +++ b/src/dxil/shader.zig @@ -145,6 +145,7 @@ pub const PsvInfo = struct { resources: []const ResourceBind = &.{}, inputs: []const signature.Element = &.{}, outputs: []const signature.Element = &.{}, + patch_constants: []const signature.Element = &.{}, groupshared_bytes: u32 = 0, max_vertex_count: u16 = 0, }; @@ -161,6 +162,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 { const in_vectors = signature.vectorsUsed(info.inputs, 0); var out_vectors: [4]u32 = undefined; for (&out_vectors, 0..) |*v, s| v.* = signature.vectorsUsed(info.outputs, @intCast(s)); + const pc_vectors = signature.vectorsUsed(info.patch_constants, 0); try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4) // PSVRuntimeInfo0 @@ -169,8 +171,11 @@ 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, @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) }); + // (The MaxVertexCount union holds SigPatchConstOrPrimVectors for hull + // and domain shaders.) + const union16: u16 = if (info.kind == .hull or info.kind == .domain) @intCast(pc_vectors) else info.max_vertex_count; + try buf.appendSlice(gpa, &.{ @backingInt(info.kind), 0, @truncate(union16), @truncate(union16 >> 8) }); + try buf.appendSlice(gpa, &.{ @intCast(info.inputs.len), @intCast(info.outputs.len), @intCast(info.patch_constants.len), @intCast(in_vectors) }); for (out_vectors) |v| try buf.append(gpa, @intCast(v)); // PSVRuntimeInfo2 for (info.num_threads) |t| try w(&buf, gpa, t); @@ -184,7 +189,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 { defer indices.deinit(gpa); var records: std.ArrayList(u8) = .empty; defer records.deinit(gpa); - for ([_][]const signature.Element{ info.inputs, info.outputs }) |els| for (els) |e| { + for ([_][]const signature.Element{ info.inputs, info.outputs, info.patch_constants }) |els| for (els) |e| { var name_off: u32 = 0; if (e.kind == .arbitrary and e.name.len > 0) { name_off = @intCast(strings.items.len); @@ -228,7 +233,7 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 { try buf.appendSlice(gpa, strings.items); try w(&buf, gpa, @intCast(indices.items.len)); for (indices.items) |v| try w(&buf, gpa, v); - if (info.inputs.len + info.outputs.len > 0) { + if (info.inputs.len + info.outputs.len + info.patch_constants.len > 0) { try w(&buf, gpa, 16); // sizeof(PSVSignatureElement0) try buf.appendSlice(gpa, records.items); } @@ -237,14 +242,20 @@ pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 { // (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); - } + if (in_vectors > 0 and ov > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, ov) * 4); } + // Inputs to patch constants (hull), patch constants to outputs + // (domain). + if (info.kind == .hull and pc_vectors > 0 and in_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(in_vectors, pc_vectors) * 4); + if (info.kind == .domain and out_vectors[0] > 0 and pc_vectors > 0) try buf.appendNTimes(gpa, 0, tableDwords(pc_vectors, out_vectors[0]) * 4); return buf.toOwnedSlice(gpa); } +/// PSVComputeInputOutputTableDwords. +fn tableDwords(in_vectors: u32, out_vectors: u32) u32 { + return ((out_vectors + 7) >> 3) * in_vectors * 4; +} + test "profile parsing" { const p = Profile.parse("cs_6_6").?; try std.testing.expectEqual(ShaderKind.compute, p.kind); diff --git a/src/dxil/signature.zig b/src/dxil/signature.zig index d5a5d94..0d7507e 100644 --- a/src/dxil/signature.zig +++ b/src/dxil/signature.zig @@ -75,55 +75,79 @@ pub const Interpretation = enum(u8) { na, sv, sgv, arb, not_in_sig, not_packed, pub const SigPoint = enum { vs_in, vs_out, + pc_in, + hs_in, + hs_cp_in, + hs_cp_out, + pc_out, + ds_in, + ds_cp_in, + ds_out, gs_v_in, gs_in, gs_out, ps_in, ps_out, + cs_in, + ms_in, + ms_out, + ms_p_out, + as_in, fn packing(sp: SigPoint) enum { none, input_assembler, vertex, target } { return switch (sp) { .vs_in => .input_assembler, - .vs_out, .gs_v_in, .gs_out, .ps_in => .vertex, + .vs_out, .hs_cp_in, .hs_cp_out, .pc_out, .ds_in, .ds_cp_in, .ds_out, .gs_v_in, .gs_out, .ps_in, .ms_out, .ms_p_out => .vertex, .ps_out => .target, - .gs_in => .none, + .pc_in, .hs_in, .gs_in, .cs_in, .ms_in, .as_in => .none, }; } pub fn isInput(sp: SigPoint) bool { return switch (sp) { - .vs_in, .gs_v_in, .gs_in, .ps_in => true, + .vs_in, .pc_in, .hs_in, .hs_cp_in, .ds_in, .ds_cp_in, .gs_v_in, .gs_in, .ps_in, .cs_in, .ms_in, .as_in => true, else => false, }; } }; /// How `kind` is treated at `sp` in shader model 6.`minor` (dxc's -/// DxilSigPoint interpretation table, for the stages zdxc supports). +/// DxilSigPoint interpretation table). pub fn interpretation(kind: SemanticKind, sp: SigPoint, minor: u8) Interpretation { const I = Interpretation; - // Columns: vs_in, vs_out, gs_v_in, gs_in, gs_out, ps_in, ps_out. - const Row = [7]I; + // Columns: VSIn, VSOut, PCIn, HSIn, HSCPIn, HSCPOut, PCOut, DSIn, + // DSCPIn, DSOut, GSVIn, GSIn, GSOut, PSIn, PSOut, CSIn, MSIn, MSOut, + // MSPOut, ASIn. + const Row = [20]I; const na: I = .na; + const arb: I = .arb; + const sv: I = .sv; + const nis: I = .not_in_sig; + const cc: I = .clip_cull; const row: Row = switch (kind) { - .arbitrary => .{ .arb, .arb, .arb, na, .arb, .arb, na }, - .vertex_id => .{ .sv, na, na, na, na, na, na }, - .instance_id => .{ .sv, .arb, .arb, na, .arb, .arb, na }, - .position, .render_target_array_index, .viewport_array_index => .{ .arb, .sv, .sv, na, .sv, .sv, na }, - .clip_distance, .cull_distance => .{ .arb, .clip_cull, .clip_cull, na, .clip_cull, .clip_cull, na }, - .primitive_id => .{ na, na, na, .shadow, .sgv, .sgv, na }, - .gs_instance_id => .{ na, na, na, .not_in_sig, na, na, na }, - .sample_index => .{ na, na, na, na, na, .shadow, na }, - .is_front_face => .{ na, na, na, na, .sgv, .sgv, na }, - .coverage => .{ na, na, na, na, na, .not_in_sig, .not_packed }, - .inner_coverage => .{ na, na, na, na, na, .not_in_sig, na }, - .target => .{ na, na, na, na, na, na, .target }, - .depth, .depth_less_equal, .depth_greater_equal, .stencil_ref => .{ na, na, na, na, na, na, .not_packed }, - .view_id => if (minor >= 1) .{ .not_in_sig, na, na, .not_in_sig, na, .not_in_sig, na } else @splat(na), - .barycentrics => if (minor >= 1) .{ na, na, na, na, na, .not_packed, na } else @splat(na), - .shading_rate => if (minor >= 4) .{ na, .sv, .sv, na, .sv, .sv, na } else @splat(na), - .cull_primitive => .{ na, na, na, na, na, .not_in_sig, na }, - .start_vertex_location, .start_instance_location => if (minor >= 8) .{ .not_in_sig, na, na, na, na, na, na } else @splat(na), + .arbitrary => .{ arb, arb, na, na, arb, arb, arb, arb, arb, arb, arb, na, arb, arb, na, na, na, arb, arb, na }, + .vertex_id => .{ sv, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na }, + .instance_id => .{ sv, arb, na, na, arb, arb, na, na, arb, arb, arb, na, arb, arb, na, na, na, na, na, na }, + .position => .{ arb, sv, na, na, sv, sv, arb, arb, sv, sv, sv, na, sv, sv, na, na, na, sv, na, na }, + .render_target_array_index, .viewport_array_index => .{ arb, sv, na, na, sv, sv, arb, arb, sv, sv, sv, na, sv, sv, na, na, na, na, sv, na }, + .clip_distance, .cull_distance => .{ arb, cc, na, na, cc, cc, arb, arb, cc, cc, cc, na, cc, cc, na, na, na, cc, na, na }, + .output_control_point_id => .{ na, na, na, nis, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na }, + .domain_location => .{ na, na, na, na, na, na, na, nis, na, na, na, na, na, na, na, na, na, na, na, na }, + .primitive_id => .{ na, na, nis, nis, na, na, na, nis, na, na, na, .shadow, .sgv, .sgv, na, na, na, na, sv, na }, + .gs_instance_id => .{ na, na, na, na, na, na, na, na, na, na, na, nis, na, na, na, na, na, na, na, na }, + .sample_index => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, .shadow, na, na, na, na, na, na }, + .is_front_face => .{ na, na, na, na, na, na, na, na, na, na, na, na, .sgv, .sgv, na, na, na, na, na, na }, + .coverage => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, nis, .not_packed, na, na, na, na, na }, + .inner_coverage => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, nis, na, na, na, na, na, na }, + .target => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, na, .target, na, na, na, na, na }, + .depth, .depth_less_equal, .depth_greater_equal, .stencil_ref => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, na, .not_packed, na, na, na, na, na }, + .dispatch_thread_id, .group_id, .group_index, .group_thread_id => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, nis, nis, na, na, nis }, + .tess_factor, .inside_tess_factor => .{ na, na, na, na, na, na, .tess_factor, .tess_factor, na, na, na, na, na, na, na, na, na, na, na, na }, + .view_id => if (minor >= 1) .{ nis, na, nis, nis, na, na, na, nis, na, na, na, nis, na, nis, na, na, nis, na, na, na } else @splat(na), + .barycentrics => if (minor >= 1) .{ na, na, na, na, na, na, na, na, na, na, na, na, na, .not_packed, na, na, na, na, na, na } else @splat(na), + .shading_rate => if (minor >= 4) .{ na, sv, na, na, sv, sv, na, na, sv, sv, sv, na, sv, sv, na, na, na, na, sv, na } else @splat(na), + .cull_primitive => .{ na, na, na, na, na, na, na, na, na, na, na, na, na, nis, na, na, na, na, .not_packed, na }, + .start_vertex_location, .start_instance_location => if (minor >= 8) .{ nis, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na } else @splat(na), else => @splat(na), }; return row[@intFromEnum(sp)]; @@ -486,8 +510,21 @@ pub fn vectorsUsed(elements: []const Element, stream: u32) u32 { // ISG1 / OSG1 /// D3D system-value code of a semantic (DxilProgramSigSemantic). -fn systemValue(kind: SemanticKind) u32 { +pub const Domain = enum(u8) { undefined = 0, isoline = 1, tri = 2, quad = 3 }; + +fn systemValue(kind: SemanticKind, domain: Domain) u32 { return switch (kind) { + .tess_factor => switch (domain) { + .isoline => 16, // FinalLineDensityTessfactor (then Detail) + .tri => 13, + .quad => 11, + .undefined => 0, + }, + .inside_tess_factor => switch (domain) { + .tri => 14, + .quad => 12, + else => 0, + }, .arbitrary, .invalid => 0, .position => 1, .clip_distance => 2, @@ -515,7 +552,7 @@ fn systemValue(kind: SemanticKind) u32 { /// A DxilProgramSignature part (ISG1 or OSG1) for elements in the /// signature (not NotInSig ones). -pub fn programSignature(gpa: Allocator, elements: []const Element, is_input: bool) Allocator.Error![]u8 { +pub fn programSignature(gpa: Allocator, elements: []const Element, is_input: bool, domain: Domain) Allocator.Error![]u8 { const Rec = struct { stream: u32, name: u32, index: u32, sv: u32, comp: u32, reg: u32, mask: u8, rw: u8, min_prec: u32 }; var recs: std.ArrayList(Rec) = .empty; defer recs.deinit(gpa); @@ -540,9 +577,11 @@ pub fn programSignature(gpa: Allocator, elements: []const Element, is_input: boo if (e.start_row != null) usage <<= @intCast(e.start_col); const rw: u8 = if (is_input) usage else (usage ^ 0xF) & 0xF; var reg: u32 = e.start_row orelse 0xFFFFFFFF; + var sv = systemValue(e.kind, domain); for (e.indices) |idx| { - try recs.append(gpa, .{ .stream = e.stream, .name = name_off, .index = idx, .sv = systemValue(e.kind), .comp = e.comp.sigCompType(), .reg = reg, .mask = e.colsMask(), .rw = rw, .min_prec = e.comp.minPrecision() }); + try recs.append(gpa, .{ .stream = e.stream, .name = name_off, .index = idx, .sv = sv, .comp = e.comp.sigCompType(), .reg = reg, .mask = e.colsMask(), .rw = rw, .min_prec = e.comp.minPrecision() }); if (e.start_row != null) reg += 1; + if (sv == 16) sv = 15; // isoline: density, then detail } } std.sort.insertion(Rec, recs.items, {}, struct { diff --git a/src/ir/ir.zig b/src/ir/ir.zig index d5a65b7..11dd974 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -110,6 +110,12 @@ pub const Op = union(enum) { /// A per-vertex input (geometry shaders): element, vertex index. input_vertex: struct { element: u32, vertex: u32 }, output: struct { element: u32, value: Ref }, + /// Hull / domain shaders: a patch constant read (domain) or written + /// (hull patch constant function), and a hull output control point + /// read back by the patch constant function. + patch_input: u32, + patch_output: struct { element: u32, value: Ref }, + output_vertex: struct { element: u32, vertex: u32 }, /// Geometry shaders: emit the vertex written to the outputs of a stream, /// or end its strip. emit: u32, @@ -221,6 +227,21 @@ pub const GeometryInfo = struct { streams: [4]?enum { point, line, triangle } = .{ null, null, null, null }, }; +pub const Domain = enum(u8) { isoline = 1, tri = 2, quad = 3 }; +pub const Partitioning = enum(u8) { integer = 1, pow2 = 2, fractional_odd = 3, fractional_even = 4 }; +pub const OutputTopology = enum(u8) { point = 1, line = 2, triangle_cw = 3, triangle_ccw = 4 }; + +pub const TessInfo = struct { + domain: Domain = .tri, + partitioning: Partitioning = .integer, + output_topology: OutputTopology = .triangle_cw, + /// Control points per input patch (hull: InputPatch; domain: + /// OutputPatch). + input_control_points: u32 = 0, + output_control_points: u32 = 0, + max_tess_factor: f32 = 64, +}; + pub const Entry = struct { /// The function the entry wraps (the HLSL entry, in memory form). func: u32, @@ -228,8 +249,16 @@ pub const Entry = struct { stage: Stage, num_threads: [3]u32 = .{ 1, 1, 1 }, geometry: GeometryInfo = .{}, + tess: TessInfo = .{}, inputs: std.ArrayList(SigElement) = .empty, outputs: std.ArrayList(SigElement) = .empty, + /// Patch constants: written by the hull shader's patch constant + /// function, read by the domain shader. + patch_constants: std.ArrayList(SigElement) = .empty, + /// Hull shaders: the wrapper of the patch constant function (no + /// parameters; reads inputs and output control points, writes patch + /// constants). + patch_wrapper: ?u32 = null, /// The wrapper with no parameters that reads `inputs`, calls `func` /// and writes `outputs`. wrapper: u32 = 0, @@ -392,6 +421,9 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo }, .input_vertex => |x| try w.print("input {d} vertex {d}", .{ x.element, x.vertex }), .emit => |k| try w.print("emit stream {d}", .{k}), + .patch_input => |k| try w.print("patch input {d}", .{k}), + .patch_output => |x| try w.print("patch output {d} = %{d}", .{ x.element, x.value.index() }), + .output_vertex => |x| try w.print("output {d} vertex {d}", .{ x.element, x.vertex }), .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() }), diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 92ff2a9..fd6d3f6 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -69,6 +69,11 @@ const Lowerer = struct { early_outputs: std.ArrayList(ir.SigElement) = .empty, streams: std.ArrayList(Stream) = .empty, entry_fn: ?*const semamod.Function = null, + /// Entry inputs / outputs go to the patch constants (domain shader + /// inputs other than control points; hull patch constant outputs). + patch_io: bool = false, + /// Per-vertex reads come from the hull shader's output control points. + vertex_from_outputs: bool = false, /// The current method's object pointer. this_ptr: Ref = .none, ret_ty: TypeId = TypeTable.void_type, @@ -93,7 +98,7 @@ const Lowerer = struct { if (isMethod(f)) try params.append(l.arena, .{ .name = "this", .ty = try l.s.types.intern(.{ .@"struct" = f.owner.? }), .by_ref = true }); 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 }); + try params.append(l.arena, .{ .name = p.name, .ty = l.irType(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); @@ -101,6 +106,15 @@ const Lowerer = struct { return i; } + /// The IR type of a value of Sema type `ty`: InputPatch / OutputPatch + /// are arrays of control points. + fn irType(l: *Lowerer, ty: TypeId) TypeId { + return switch (l.s.types.get(ty)) { + .patch => |p| l.s.types.array(p.elem, p.count) catch ty, + else => ty, + }; + } + fn drain(l: *Lowerer) Error!void { while (l.pending.pop()) |f| try l.lowerFunction(f); } @@ -126,10 +140,11 @@ const Lowerer = struct { } for (f.params, 0..) |p, i| { 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 }); + const pty = l.irType(p.type); + const pv = try l.b.add(.{ .op = .{ .param = ir_index }, .ty = pty, .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 }); + const local = try l.b.add(.{ .op = .local_var, .ty = pty, .ptr = .function }); try l.b.store(local, pv); break :blk local; }; @@ -1284,6 +1299,25 @@ const Lowerer = struct { return r; } + fn addInput(l: *Lowerer, entry: *ir.Entry, el: ir.SigElement) Error!Ref { + if (l.patch_io) { + try entry.patch_constants.append(l.arena, el); + return l.b.add(.{ .op = .{ .patch_input = @intCast(entry.patch_constants.items.len - 1) }, .ty = el.ty }); + } + try entry.inputs.append(l.arena, el); + return l.b.add(.{ .op = .{ .input = @intCast(entry.inputs.items.len - 1) }, .ty = el.ty }); + } + + fn addOutput(l: *Lowerer, entry: *ir.Entry, el: ir.SigElement, value: Ref) Error!void { + if (l.patch_io) { + try entry.patch_constants.append(l.arena, el); + _ = try l.b.add(.{ .op = .{ .patch_output = .{ .element = @intCast(entry.patch_constants.items.len - 1), .value = value } }, .ty = TypeTable.void_type }); + return; + } + try entry.outputs.append(l.arena, el); + _ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = value } }, .ty = TypeTable.void_type }); + } + /// An entry input of type `ty`: one signature element, or for structs /// without a semantic one per field (recursively). fn entryInput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, semantic: ?[]const u8, attrs: SigAttrs, loc: ast.Loc, what: []const u8) Error!Ref { @@ -1292,10 +1326,7 @@ const Lowerer = struct { var el = sigElement(sem, ty); return l.structInput(entry, ty, el.semantic, &el.semantic_index, attrs); }; - if (semantic) |sem| { - try entry.inputs.append(l.arena, withAttrs(sigElement(sem, ty), attrs)); - return l.b.add(.{ .op = .{ .input = @intCast(entry.inputs.items.len - 1) }, .ty = ty }); - } + if (semantic) |sem| return l.addInput(entry, withAttrs(sigElement(sem, ty), attrs)); switch (l.s.types.get(ty)) { .@"struct" => |st| { const parts = try l.arena.alloc(Ref, st.fields.items.len); @@ -1317,9 +1348,8 @@ const Lowerer = struct { p.* = try l.structInput(entry, fld.type, name, index, attrs.field(fld)); continue; } - try entry.inputs.append(l.arena, withAttrs(.{ .semantic = name, .semantic_index = index.*, .ty = fld.type, .system_value = std.ascii.startsWithIgnoreCase(name, "SV_") }, attrs.field(fld))); + p.* = try l.addInput(entry, withAttrs(.{ .semantic = name, .semantic_index = index.*, .ty = fld.type, .system_value = std.ascii.startsWithIgnoreCase(name, "SV_") }, attrs.field(fld))); index.* += 1; - p.* = try l.b.add(.{ .op = .{ .input = @intCast(entry.inputs.items.len - 1) }, .ty = fld.type }); } return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty }); } @@ -1332,9 +1362,8 @@ const Lowerer = struct { try l.structOutput(entry, fld.type, name, index, v, attrs.field(fld)); continue; } - try entry.outputs.append(l.arena, withAttrs(.{ .semantic = name, .semantic_index = index.*, .ty = fld.type, .system_value = std.ascii.startsWithIgnoreCase(name, "SV_") }, attrs.field(fld))); + try l.addOutput(entry, withAttrs(.{ .semantic = name, .semantic_index = index.*, .ty = fld.type, .system_value = std.ascii.startsWithIgnoreCase(name, "SV_") }, attrs.field(fld)), v); index.* += 1; - _ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = v } }, .ty = TypeTable.void_type }); } } @@ -1343,11 +1372,7 @@ const Lowerer = struct { var el = sigElement(sem, ty); return l.structOutput(entry, ty, el.semantic, &el.semantic_index, value, attrs); }; - if (semantic) |sem| { - try entry.outputs.append(l.arena, withAttrs(sigElement(sem, ty), attrs)); - _ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = value } }, .ty = TypeTable.void_type }); - return; - } + if (semantic) |sem| return l.addOutput(entry, withAttrs(sigElement(sem, ty), attrs), value); switch (l.s.types.get(ty)) { .@"struct" => |st| for (st.fields.items, 0..) |fld, k| { const v = try l.b.add(.{ .op = .{ .extract = .{ .agg = value, .index = @intCast(k) } }, .ty = fld.type }); @@ -1477,6 +1502,11 @@ const Lowerer = struct { 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 { + if (lw.vertex_from_outputs) { + const r = try lw.b.add(.{ .op = .{ .output_vertex = .{ .element = nx.*, .vertex = vx } }, .ty = el.ty }); + nx.* += 1; + return r; + } var e2 = el; e2.per_vertex = true; if (reg) try en.inputs.append(lw.arena, e2); @@ -1521,6 +1551,128 @@ const Lowerer = struct { return l.b.add(.{ .op = .{ .construct = parts }, .ty = to }); } + /// `[domain(...)]`, `[partitioning(...)]` and the other hull / domain + /// attributes. + fn tessAttributes(l: *Lowerer, f: *const semamod.Function, entry: *ir.Entry) void { + for (f.decl.attrs) |a| { + const name = a.name; + const eqi = std.ascii.eqlIgnoreCase; + const str: []const u8 = if (a.args.len == 1 and a.args[0].kind == .string_lit) blk: { + const lit = a.args[0].kind.string_lit; + break :blk if (lit.len >= 2) lit[1 .. lit.len - 1] else lit; + } else ""; + if (eqi(name, "domain")) { + entry.tess.domain = std.meta.stringToEnum(ir.Domain, str) orelse entry.tess.domain; + } else if (eqi(name, "partitioning")) { + entry.tess.partitioning = std.meta.stringToEnum(ir.Partitioning, str) orelse entry.tess.partitioning; + } else if (eqi(name, "outputtopology")) { + entry.tess.output_topology = std.meta.stringToEnum(ir.OutputTopology, str) orelse entry.tess.output_topology; + } else if (eqi(name, "outputcontrolpoints") and a.args.len == 1) { + entry.tess.output_control_points = @intCast(@max(0, l.s.evalInt(a.args[0]) orelse 0)); + } else if (eqi(name, "maxtessfactor") and a.args.len == 1) { + if (l.s.evalConst(a.args[0])) |c| entry.tess.max_tess_factor = switch (c) { + .float => |x| @floatCast(x), + .int => |x| @floatFromInt(x), + .bool => |x| @floatFromInt(@intFromBool(x)), + }; + } + } + } + + /// Reads the control points of a patch parameter (registering their + /// elements when `register`) and stores them into `local`. + fn storeControlPoints(l: *Lowerer, entry: *ir.Entry, local: Ref, pty: TypeId, pd: ast.VarDecl, first: u32, register: bool) Error!void { + const patch = l.s.types.get(pty).patch; + if (!l.vertex_from_outputs) entry.tess.input_control_points = patch.count; + const points = try l.arena.alloc(Ref, patch.count); + for (points, 0..) |*v, k| { + var next = first; + v.* = try l.vertexIn(entry, patch.elem, semanticOf(pd.semantics), paramAttrs(pd.quals), @intCast(k), register and k == 0, &next, null, pd.name_loc); + } + try l.b.store(local, try l.b.add(.{ .op = .{ .construct = points }, .ty = l.irType(pty) })); + } + + fn writesTessFactor(l: *Lowerer, f: *const semamod.Function) bool { + if (f.ret != TypeTable.void_type and l.hasTessFactor(f.ret, semanticOf(f.decl.ret_semantics))) return true; + for (f.decl.params, f.params) |pd, p| { + if (p.dir != .in and l.hasTessFactor(p.type, semanticOf(pd.semantics))) return true; + } + return false; + } + + /// An SV_TessFactor array in `ty` (dxc's HasTessFactorSemanticRecurse). + fn hasTessFactor(l: *Lowerer, ty: TypeId, semantic: ?[]const u8) bool { + switch (l.s.types.get(ty)) { + .@"struct" => |st| { + for (st.fields.items) |fld| if (l.hasTessFactor(fld.type, fld.semantic)) return true; + return false; + }, + .array => { + const sem = semantic orelse return false; + return std.ascii.eqlIgnoreCase(sigElement(sem, ty).semantic, "SV_TessFactor"); + }, + else => return false, + } + } + + /// The hull shader's patch constant function, wrapped like the entry: + /// reads control points (the entry's inputs and outputs), writes the + /// patch constants. + fn patchConstantWrapper(l: *Lowerer, f: *const semamod.Function, entry: *ir.Entry, cp_first: ?u32) Error!void { + const name: []const u8 = for (f.decl.attrs) |a| { + if (std.ascii.eqlIgnoreCase(a.name, "patchconstantfunc") and a.args.len == 1 and a.args[0].kind == .string_lit) { + const lit = a.args[0].kind.string_lit; + break if (lit.len >= 2) lit[1 .. lit.len - 1] else lit; + } + } else { + l.unsupported(f.loc, "hull shader without a patch constant function", .{}); + return error.Unsupported; + }; + // Among overloads, the one that can be a patch constant function + // (writes a tess factor array), as dxc. + const pcf = for (l.s.all_functions.items) |g| { + if (g.owner == null and g.defined and std.mem.eql(u8, g.name, name) and l.writesTessFactor(g)) break g; + } else { + l.unsupported(f.loc, "patch constant function '{s}' has no definition", .{name}); + return error.Unsupported; + }; + const pci = try l.functionIndex(pcf); + try l.drain(); + const wrapper = try l.m.addFunction(.{ .name = try std.fmt.allocPrint(l.arena, "{s}.wrapper", .{name}), .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, pcf.params.len); + const locals = try l.arena.alloc(Ref, pcf.params.len); + for (pcf.decl.params, pcf.params, 0..) |pd, p, i| { + locals[i] = try l.b.add(.{ .op = .local_var, .ty = l.irType(p.type), .ptr = .function }); + if (l.s.types.get(p.type) == .patch) { + if (l.s.types.get(p.type).patch.output) { + // The entry's output control points, read back. + l.vertex_from_outputs = true; + defer l.vertex_from_outputs = false; + try l.storeControlPoints(entry, locals[i], p.type, pd, 0, false); + } else { + const first = cp_first orelse @as(u32, @intCast(entry.inputs.items.len)); + try l.storeControlPoints(entry, locals[i], p.type, pd, first, cp_first == null); + } + args[i] = try l.b.load(locals[i]); + continue; + } + if (p.dir != .out) try l.b.store(locals[i], try l.entryInput(entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), pd.name_loc, pd.name)); + args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i]; + } + const ret = try l.b.add(.{ .op = .{ .call = .{ .func = pci, .args = args } }, .ty = pcf.ret }); + l.patch_io = true; + defer l.patch_io = false; + if (pcf.ret != TypeTable.void_type) try l.entryOutput(entry, pcf.ret, semanticOf(pcf.decl.ret_semantics), paramAttrs(pcf.decl.quals), ret, pcf.loc, "return value"); + for (pcf.decl.params, pcf.params, 0..) |pd, p, i| { + if (p.dir == .in) continue; + try l.entryOutput(entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), try l.b.load(locals[i]), pd.name_loc, pd.name); + } + l.b.terminate(.{ .ret = .none }); + entry.patch_wrapper = wrapper; + } + 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 }; @@ -1549,11 +1701,31 @@ 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; + const tess = opts.stage == .hull or opts.stage == .domain; + if (tess) l.tessAttributes(f, &entry); + // Hull shaders: where the control point inputs start. + var cp_first: ?u32 = null; 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 }); + locals[i] = try l.b.add(.{ .op = .local_var, .ty = l.irType(p.type), .ptr = .function }); const q = pd.quals; + if (tess and l.s.types.get(p.type) == .patch) { + // Control points: one value per point of the patch. + const first: u32 = @intCast(entry.inputs.items.len); + cp_first = first; + try l.storeControlPoints(&entry, locals[i], p.type, pd, first, true); + args[i] = try l.b.load(locals[i]); + continue; + } + if (opts.stage == .domain and p.dir != .out) { + // Everything else a domain shader reads is per patch. + l.patch_io = true; + defer l.patch_io = false; + try l.b.store(locals[i], try l.entryInput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), pd.name_loc, pd.name)); + args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i]; + continue; + } 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; @@ -1587,6 +1759,11 @@ const Lowerer = struct { } l.b.terminate(.{ .ret = .none }); entry.wrapper = wrapper; + if (opts.stage == .hull) { + // Output control points are arrays over the patch. + for (entry.outputs.items) |*el| el.per_vertex = true; + try l.patchConstantWrapper(f, &entry, cp_first); + } // 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; diff --git a/src/ir/opt.zig b/src/ir/opt.zig index 7148b99..fc6e21c 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const /// `op` with every operand passed through `ctx.map`. fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { return switch (op) { - .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut => op, + .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex => 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) } }, @@ -202,6 +202,7 @@ fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { .res_store => |x| .{ .res_store = .{ .res = ctx.map(x.res), .index = ctx.map(x.index), .value = ctx.map(x.value) } }, .method => |x| .{ .method = .{ .name = x.name, .res = ctx.map(x.res), .args = try mapRefs(a, x.args, ctx) } }, .output => |x| .{ .output = .{ .element = x.element, .value = ctx.map(x.value) } }, + .patch_output => |x| .{ .patch_output = .{ .element = x.element, .value = ctx.map(x.value) } }, .phi => |ps| blk: { const out = try a.alloc(@typeInfo(@TypeOf(ps)).pointer.child, ps.len); for (ps, out) |p, *o| o.* = .{ .value = ctx.map(p.value), .block = p.block }; diff --git a/src/sema/sema.zig b/src/sema/sema.zig index dd7d752..9134da2 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -1126,7 +1126,7 @@ pub const Sema = struct { return null; } - fn evalConst(s: *Sema, e: *const ast.Expr) ?Const { + pub fn evalConst(s: *Sema, e: *const ast.Expr) ?Const { return switch (e.kind) { .int_lit => |t| .{ .int = parseIntLiteral(t) orelse return null }, .float_lit => |t| .{ .float = parseFloatLiteral(t) orelse return null }, diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index e3e8143..f7b5294 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -28,6 +28,7 @@ const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, o const Capability = enum(u32) { shader = 1, geometry = 2, + tessellation = 3, float16 = 9, float64 = 10, int64 = 11, @@ -134,13 +135,20 @@ const Emitter = struct { /// Entry inputs / outputs: interface variable and its value type. inputs: []Interface = &.{}, outputs: []Interface = &.{}, + patches: []Interface = &.{}, interface_ids: std.ArrayList(Id) = .empty, // Per function. vals: []Id = &.{}, f: *const ir.Function = undefined, - const Interface = struct { var_id: Id, ty: TypeId }; + const Interface = struct { + var_id: Id, + ty: TypeId, + /// TessLevelOuter / TessLevelInner: float[4] / float[2] builtins + /// holding a shorter array (or a scalar), accessed element-wise. + tess_level: bool = false, + }; const LayoutKey = struct { TypeId, layout.Rules, bool }; const PtrLayout = struct { rules: layout.Rules, row_major: bool }; @@ -539,6 +547,23 @@ const Emitter = struct { } else 27; try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, out_mode }); }, + .hull => { + const ts = entry.tess; + try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, domainMode(ts.domain) }); + try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, switch (ts.partitioning) { + .integer, .pow2 => 1, // SpacingEqual + .fractional_even => 2, + .fractional_odd => 3, + } }); + switch (ts.output_topology) { + .triangle_cw => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 4 }), // VertexOrderCw + .triangle_ccw => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 5 }), // VertexOrderCcw + .point => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 10 }), // PointMode + .line => {}, + } + try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 26, ts.output_control_points }); // OutputVertices + }, + .domain => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, domainMode(entry.tess.domain) }), .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")) { @@ -552,6 +577,14 @@ const Emitter = struct { } } + fn domainMode(d: ir.Domain) u32 { + return switch (d) { + .tri => 22, // Triangles + .quad => 24, // Quads + .isoline => 25, // Isolines + }; + } + fn emitGlobals(e: *Emitter) Error!void { const m = e.m; e.global_vars = try e.arena.alloc(Id, m.globals.items.len); @@ -732,6 +765,13 @@ const Emitter = struct { 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 (stage == .hull or stage == .domain) { + if (eq(n, "SV_TessFactor")) return .{ .id = 11, .ty = try t.array(try t.scalar(.float), 4) }; // TessLevelOuter + if (eq(n, "SV_InsideTessFactor")) return .{ .id = 12, .ty = try t.array(try t.scalar(.float), 2) }; // TessLevelInner + if (input and eq(n, "SV_PrimitiveID")) return .{ .id = 7, .ty = uint1 }; // PrimitiveId + } + if (stage == .domain and input and eq(n, "SV_DomainLocation")) return .{ .id = 13, .ty = try t.vector(.float, 3) }; // TessCoord + if (stage == .hull and input and eq(n, "SV_OutputControlPointID")) return .{ .id = 8, .ty = uint1 }; // InvocationId 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; @@ -740,30 +780,47 @@ const Emitter = struct { 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; + e.patches = try e.arena.alloc(Interface, entry.patch_constants.items.len); + if (entry.stage == .hull or entry.stage == .domain) try e.cap(.tessellation); + // Variables needing a Location, assigned once all exist. + const Located = struct { var_id: Id, key: []const u8, count: u32, input: bool, target: ?u32 }; + var located: std.ArrayList(Located) = .empty; + const lists = [_][]const ir.SigElement{ entry.inputs.items, entry.outputs.items, entry.patch_constants.items }; + const ifaces = [_][]Interface{ e.inputs, e.outputs, e.patches }; + for (lists, ifaces, 0..) |els, out, li| { + const patch = li == 2; + const input = if (patch) entry.stage == .domain else li == 0; for (els, out) |el, *iface| { const bi = try e.builtinFor(el, input, entry.stage); // bool is not allowed in located interface variables. 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. + // Per-vertex values are arrays over the primitive / patch. const vty = ty; - if (el.per_vertex) ty = try e.t.array(ty, entry.geometry.input_vertices); + if (el.per_vertex) ty = try e.t.array(ty, switch (entry.stage) { + .geometry => entry.geometry.input_vertices, + .hull => if (input) entry.tess.input_control_points else entry.tess.output_control_points, + else => entry.tess.input_control_points, + }); const sc: StorageClass = if (input) .input else .output; + if (bi != null and input and !el.per_vertex) { + // One variable per input builtin, shared by its uses. + iface.* = .{ .var_id = try e.builtinInput(bi.?.id, ty), .ty = vty, .tess_level = bi.?.id == 11 or bi.?.id == 12 }; + if (iface.tess_level) try e.b.emit(.annotations, .decorate, &.{ iface.var_id, 15 }); // Patch + continue; + } 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 (patch) try e.b.emit(.annotations, .decorate, &.{ var_id, 15 }); // Patch 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 - location[dir] = @max(location[dir], loc) + try e.locationCount(ty); + const key = if (el.semantic_index > 0) try std.fmt.allocPrint(e.arena, "{s}{d}", .{ el.semantic, el.semantic_index }) else el.semantic; + const target: ?u32 = if (std.ascii.eqlIgnoreCase(el.semantic, "SV_Target")) el.semantic_index else null; + try located.append(e.arena, .{ .var_id = var_id, .key = key, .count = try e.locationCount(vty), .input = input, .target = target }); // Interpolation (as dxc: pixel inputs and vertex // outputs; integers are always flat). if ((input and entry.stage == .pixel) or (!input and entry.stage == .vertex)) { @@ -788,10 +845,30 @@ const Emitter = struct { } 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 = vty }; + iface.* = .{ .var_id = var_id, .ty = vty, .tess_level = bi != null and (bi.?.id == 11 or bi.?.id == 12) }; try e.interface_ids.append(e.arena, var_id); } } + // Locations in declaration order, except hull outputs and domain + // inputs (control points and patch constants together), which + // dxc orders by semantic so the two stages agree. + for ([_]bool{ true, false }) |input| { + var vars: std.ArrayList(Located) = .empty; + for (located.items) |x| if (x.input == input) try vars.append(e.arena, x); + if ((!input and entry.stage == .hull) or (input and entry.stage == .domain)) { + std.sort.insertion(Located, vars.items, {}, struct { + fn lt(_: void, a: Located, b: Located) bool { + return std.mem.order(u8, a.key, b.key) == .lt; + } + }.lt); + } + var next: u32 = 0; + for (vars.items) |x| { + const loc = x.target orelse next; + try e.b.emit(.annotations, .decorate, &.{ x.var_id, 30, loc }); // Location + next = @max(next, loc) + x.count; + } + } } /// Locations an interface variable occupies: one per array element and @@ -886,7 +963,25 @@ const Emitter = struct { } 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()]}), + .ret => |v| if (v == .none) { + if (e.hullEpilogue(fn_id)) |pw| { + // After the control points: the patch constant + // function, once per patch. + const uint_ty = try e.t.scalar(.uint); + try e.b.emit(.functions, .control_barrier, &.{ try e.constUint(2), try e.constUint(4), try e.constUint(0) }); + const id = try e.op1(.load, uint_ty, &.{try e.builtinInput(8, uint_ty)}); + const first = try e.op1(.i_equal, try e.t.scalar(.bool), &.{ id, try e.constUint(0) }); + const then_l = e.b.newId(); + const merge_l = e.b.newId(); + try e.b.emit(.functions, .selection_merge, &.{ merge_l, 0 }); + try e.b.emit(.functions, .branch_conditional, &.{ first, then_l, merge_l }); + try e.b.emit(.functions, .label, &.{then_l}); + _ = try e.op1(.function_call, TypeTable.void_type, &.{pw}); + try e.b.emit(.functions, .branch, &.{merge_l}); + try e.b.emit(.functions, .label, &.{merge_l}); + } + 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| { @@ -901,6 +996,14 @@ const Emitter = struct { try e.b.emit(.functions, .function_end, &.{}); } + /// For the hull shader's entry wrapper: the patch constant wrapper it + /// calls before returning. + fn hullEpilogue(e: *Emitter, fn_id: Id) ?Id { + const entry = e.m.entry.?; + if (entry.stage != .hull or fn_id != e.func_ids[entry.wrapper]) return null; + return e.func_ids[entry.patch_wrapper orelse return null]; + } + /// Scalars, 1-vectors and 1x1 matrices (all a SPIR-V scalar). fn isScalarLike(e: *Emitter, ty: TypeId) bool { return switch (e.t.get(ty)) { @@ -1349,6 +1452,13 @@ const Emitter = struct { 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); }, + .patch_input => |k| e.vals[ri] = try e.loadInterface(e.patches[k], .input, i.ty), + .patch_output => |o| try e.storeInterface(e.patches[o.element], f.inst(o.value).ty, e.val(o.value)), + .output_vertex => |x| { + const iface = e.outputs[x.element]; + const ptr = try e.opRaw(.access_chain, try e.pointerType(.output, 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) { @@ -1358,12 +1468,46 @@ const Emitter = struct { .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 }); + if (e.m.entry.?.outputs.items[o.element].per_vertex) { + // Hull output control points: this invocation's element. + const id = try e.op1(.load, try e.t.scalar(.uint), &.{try e.builtinInput(8, try e.t.scalar(.uint))}); + const ptr = try e.opRaw(.access_chain, try e.pointerType(.output, try e.typeId(iface.ty)), &.{ iface.var_id, id }); + try e.b.emit(.functions, .store, &.{ ptr, v }); + } else try e.b.emit(.functions, .store, &.{ iface.var_id, v }); }, .phi => return e.unsupported("phi", .{}), } } + /// Reads an interface variable as a value of type `ty`. + fn loadInterface(e: *Emitter, iface: Interface, sc: StorageClass, ty: TypeId) Error!Id { + if (!iface.tess_level) return e.reshape(try e.op1(.load, iface.ty, &.{iface.var_id}), iface.ty, ty); + const ft = try e.t.scalar(.float); + const n: u32 = if (e.t.get(ty) == .array) e.t.get(ty).array.len else 1; + const parts = try e.arena.alloc(Id, n); + for (parts, 0..) |*p, k| { + const ptr = try e.opRaw(.access_chain, try e.pointerType(sc, try e.typeId(ft)), &.{ iface.var_id, try e.constUint(@intCast(k)) }); + p.* = try e.op1(.load, ft, &.{ptr}); + } + if (e.t.get(ty) != .array) return parts[0]; + return e.op1(.composite_construct, ty, parts); + } + + /// Writes value `v` of type `ty` to an output interface variable. + fn storeInterface(e: *Emitter, iface: Interface, ty: TypeId, v: Id) Error!void { + if (!iface.tess_level) { + try e.b.emit(.functions, .store, &.{ iface.var_id, try e.reshape(v, ty, iface.ty) }); + return; + } + const ft = try e.t.scalar(.float); + const n: u32 = if (e.t.get(ty) == .array) e.t.get(ty).array.len else 1; + for (0..n) |k| { + const ptr = try e.opRaw(.access_chain, try e.pointerType(.output, try e.typeId(ft)), &.{ iface.var_id, try e.constUint(@intCast(k)) }); + const x = if (e.t.get(ty) == .array) try e.op1(.composite_extract, ft, &.{ v, @intCast(k) }) else v; + try e.b.emit(.functions, .store, &.{ ptr, x }); + } + } + /// 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(); @@ -2009,7 +2153,10 @@ const Emitter = struct { const v = e.b.newId(); try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(.input, try e.typeId(ty)), v, @backingInt(StorageClass.input) }); try e.b.emit(.annotations, .decorate, &.{ v, 11, builtin }); // BuiltIn - if (e.m.entry.?.stage == .pixel and !e.t.component(ty).?.isFloat()) try e.b.emit(.annotations, .decorate, &.{ v, 14 }); // Flat + var et = ty; + while (e.t.get(et) == .array) et = e.t.get(et).array.elem; + const c = e.t.component(et).?; + if (e.m.entry.?.stage == .pixel and !c.isFloat() and c != .bool) try e.b.emit(.annotations, .decorate, &.{ v, 14 }); // Flat try e.interface_ids.append(e.arena, v); try e.builtin_inputs.put(e.arena, builtin, v); return v;