diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 72e2110..ed7310a 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -89,6 +89,8 @@ const Lowered = union(enum) { /// A local assigned different elements of one resource array (index /// into Emitter.res_index_locals): it holds the element's index. res_index_local: u32, + /// A work graph node input or output, or a node's records. + node: NodeVal, /// A RayQuery local (index into Emitter.rq_locals) and a query handle. rq_local: u32, ray_query: Value, @@ -121,6 +123,11 @@ const Lowered = union(enum) { }, }; +/// A node object: its handle (%dx.types.NodeHandle for outputs, +/// %dx.types.NodeRecordHandle for records), annotated with `flags` +/// (NodeIOFlags) and the record's size. +const NodeVal = struct { kind: types.NodeKind, handle: Value, record: TypeId, flags: u32, size: u32 }; + /// Pointer into a flattened local: alloca `base` of `[n x scalar]`, at /// component `offset_const` (+ `offset_dyn` if dynamic). const Ptr = struct { @@ -727,6 +734,8 @@ const Emitter = struct { /// Graphics entries: signatures; entry properties of the stage. sigs: ?module.MdId = null, stage_props: []const ?module.MdId = &.{}, + /// Groupshared memory the entry uses (bytes). + groupshared: u32 = 0, }; /// Input qualifier (0 in, 1 out, 2 inout), component type and @@ -750,6 +759,7 @@ const Emitter = struct { .callable => 12, .mesh => 13, .amplification => 14, + .node => 15, }; } @@ -779,7 +789,7 @@ const Emitter = struct { var units: std.ArrayList(Unit) = .empty; for (m.entries.items, 0..) |entry, k| { switch (entry.stage) { - .compute, .raygeneration, .intersection, .anyhit, .closesthit, .miss, .callable, .vertex, .pixel, .geometry, .hull, .domain, .mesh, .amplification => {}, + .compute, .raygeneration, .intersection, .anyhit, .closesthit, .miss, .callable, .vertex, .pixel, .geometry, .hull, .domain, .mesh, .amplification, .node => {}, else => return e.unsupported("{s} shaders in libraries are not supported yet", .{@tagName(entry.stage)}), } try units.append(e.arena, .{ .order = m.functions.items[entry.func].decl_order, .kind = .entry, .index = @intCast(k) }); @@ -855,6 +865,7 @@ const Emitter = struct { try e.libHandles(); _ = try e.inlineCall(entry.wrapper, &.{}); try e.finish(lf.func); + lf.groupshared = e.groupshared_bytes; var pc_func: ?LibFunc = null; if (entry.patch_wrapper) |pw| { // The patch constant function: a function of its own. @@ -1390,7 +1401,7 @@ const Emitter = struct { switch (e.entry.stage) { // (Library functions record the use; their callers decide.) .pixel, .library => {}, - .compute, .mesh, .amplification => if (e.profile.minor < 6) return e.unsupported("derivatives outside pixel shaders need shader model 6.6", .{}), + .compute, .mesh, .amplification, .node => if (e.profile.minor < 6) return e.unsupported("derivatives outside pixel shaders need shader model 6.6", .{}), else => return e.unsupported("derivatives are not available in {s} shaders", .{@tagName(e.entry.stage)}), } if (e.entry.stage == .mesh or e.entry.stage == .amplification) e.uses_mesh_derivatives = true; @@ -2233,6 +2244,7 @@ const Emitter = struct { .constant => |c| return e.list(&.{try e.constant(i.ty, c)}), .param => |p| return frame.params[p], .spec_constant => return e.unsupported("specialization constants outside SPIR-V", .{}), + .node_io => |x| return e.nodeIo(x), .spirv_inst => return e.unsupported("inline SPIR-V outside SPIR-V", .{}), .ray_incoming => |k| { // The shader's payload / attribute / parameter argument. @@ -2472,10 +2484,12 @@ const Emitter = struct { if (frame.vals[s.ptr.index()] == .res_local) { const slot = &e.res_locals.items[frame.vals[s.ptr.index()].res_local]; const h = frame.vals[s.value.index()]; - if (h != .handle and h != .res_array) return e.unsupported("resources not tied to a global are not supported yet", .{}); + if (h != .handle and h != .res_array and h != .node) return e.unsupported("resources not tied to a global are not supported yet", .{}); // Selecting between resources at run time has no // handle-based lowering here; one assignment is fine. - if (slot.*) |old| if (!std.meta.eql(old, h)) return e.unsupported("assigning different resources to one variable is not supported yet (in '{s}')", .{frame.f.name}); + // (Node objects: again, where every assignment is in + // one block.) + if (slot.*) |old| if (!std.meta.eql(old, h) and !(h == .node and storesInOneBlock(f, s.ptr))) return e.unsupported("assigning different resources to one variable is not supported yet (in '{s}')", .{frame.f.name}); slot.* = h; return .none; } @@ -2515,6 +2529,17 @@ const Emitter = struct { }, .access => |a| { if (frame.vals[a.base.index()] == .mesh) return e.meshAccess(frame, frame.vals[a.base.index()].mesh, a.indices); + if (frame.vals[a.base.index()] == .node) { + const nv = frame.vals[a.base.index()].node; + const idx = (try e.scalars(frame, a.indices[0]))[0]; + if (nv.kind.outputElement()) |k| { + if (a.indices.len > 1) return e.unsupported("indexing a node output", .{}); + return .{ .node = try e.nodeIndex(nv, k, idx) }; + } + const tp = try e.nodeRecordPtr(nv, idx); + if (a.indices.len == 1) return .{ .typed = tp }; + return .{ .typed = try e.typedAccess(frame, tp, a.indices[1..]) }; + } if (frame.vals[a.base.index()] == .typed) { var tp = frame.vals[a.base.index()].typed; var path: std.ArrayList(Value) = .empty; @@ -2798,6 +2823,7 @@ const Emitter = struct { fn resCount(e: *Emitter, ty: TypeId) u32 { return switch (e.t.get(ty)) { .resource, .sampler => if (isRayQuery(e.t, ty)) 0 else 1, + .node => 1, .array => |a| a.len * e.resCount(a.elem), .@"struct" => |st| blk: { var n: u32 = 0; @@ -2844,7 +2870,7 @@ const Emitter = struct { return switch (v) { .agg => |a| a, .scalars => |vals| if (e.resCount(ty) == 0) .{ .vals = vals, .res = &.{} } else e.unsupported("this value with resources is not supported yet", .{}), - .handle, .res_array => .{ .vals = &.{}, .res = try e.arena.dupe(Lowered, &.{v}) }, + .handle, .res_array, .node => .{ .vals = &.{}, .res = try e.arena.dupe(Lowered, &.{v}) }, .none => .{ .vals = &.{}, .res = &.{} }, else => e.unsupported("this value with resources is not supported yet", .{}), }; @@ -3276,18 +3302,28 @@ const Emitter = struct { } // SM 6.8's Barrier(memory types or a UAV, semantics): the // arguments as they are (as dxc). + if (eq(u8, name, "GetRemainingRecursionLevels") and args.len == 0) { + const i32t = try e.dm.intType(32); + const fn_i = try e.dxOp("dx.op.getRemainingRecursionLevels", i32t, &.{i32t}, .nounwind_readonly); + return e.list(&.{try e.callOp(fn_i, i32t, &.{try e.i32Const(253)})}); + } if (eq(u8, name, "Barrier") and args.len == 2) { const i32t = try e.dm.intType(32); const sem = (try e.scalars(frame, args[1]))[0]; switch (frame.vals[args[0].index()]) { .handle => |h| { - const fn_i = try e.dxOp("dx.op.barrierByMemoryHandle", try e.voidTy(), &.{ i32t, e.handle_ty, i32t }, .nounwind); + const fn_i = try e.dxOp("dx.op.barrierByMemoryHandle", try e.voidTy(), &.{ i32t, e.handle_ty, i32t }, .noduplicate_nounwind); _ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(245), e.resources.items[h].handle, sem }); }, .scalars => |m| { - const fn_i = try e.dxOp("dx.op.barrierByMemoryType", try e.voidTy(), &.{ i32t, i32t, i32t }, .nounwind); + const fn_i = try e.dxOp("dx.op.barrierByMemoryType", try e.voidTy(), &.{ i32t, i32t, i32t }, .noduplicate_nounwind); _ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(244), m[0], sem }); }, + .node => |nv| { + const nt = try e.nodeTypes(); + const fn_i = try e.dxOp("dx.op.barrierByNodeRecordHandle", try e.voidTy(), &.{ i32t, nt.record_handle, i32t }, .noduplicate_nounwind); + _ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(246), nv.handle, sem }); + }, else => return e.unsupported("Barrier on this object is not supported yet", .{}), } return .none; @@ -3656,23 +3692,37 @@ const Emitter = struct { } /// Interlocked*(dest, value(s) [, out original]) on groupshared memory, - /// buffer elements and texels. + /// node records, buffer elements and texels. (The *FloatBitwise + /// compares: on the floats' bits.) fn atomic(e: *Emitter, frame: *Frame, name: []const u8, args: []const Ref) Error!Lowered { const eq = std.mem.eql; const op_name = name["Interlocked".len..]; const dest_ty = frame.f.inst(args[0]).ty; - const dc = e.compOf(dest_ty); + const float_bits = std.mem.endsWith(u8, op_name, "FloatBitwise"); + const dc: Scalar = if (float_bits and e.compOf(dest_ty) == .float) .uint else e.compOf(dest_ty); const wide = dc.size() == 8 and !dc.isFloat() and (frame.vals[args[0].index()] == .buf or frame.vals[args[0].index()] == .texel); if ((dc.size() != 4 and !wide) or dc.isFloat()) return e.unsupported("'{s}' on '{s}' is not supported yet", .{ name, try e.t.format(e.arena, dest_ty) }); const i32t = try e.dm.intType(32); const is_cmp = std.mem.startsWith(u8, op_name, "Compare"); - const has_orig = (is_cmp and eq(u8, op_name, "CompareExchange")) or (!is_cmp and args.len == 3); - const val = (try e.scalars(frame, args[if (is_cmp) 2 else 1]))[0]; - const cmp = if (is_cmp) (try e.scalars(frame, args[1]))[0] else null; + const has_orig = (is_cmp and std.mem.startsWith(u8, op_name, "CompareExchange")) or (!is_cmp and args.len == 3); + const val = try e.atomicOperand(float_bits, (try e.scalars(frame, args[if (is_cmp) 2 else 1]))[0]); + const cmp = if (is_cmp) try e.atomicOperand(float_bits, (try e.scalars(frame, args[1]))[0]) else null; const orig: Value = switch (frame.vals[args[0].index()]) { - .ptr => |p| blk: { - if (p.addr_space != 3) return e.unsupported("'{s}' on this variable is not supported yet", .{name}); - const ptr = try e.elementPtr(p, 0); + .ptr, .typed => blk: { + const tag = std.meta.activeTag(frame.vals[args[0].index()]); + var ptr = if (tag == .ptr) p: { + const p = frame.vals[args[0].index()].ptr; + if (p.addr_space != 3) return e.unsupported("'{s}' on this variable is not supported yet", .{name}); + break :p try e.elementPtr(p, 0); + } else p: { + const tp = frame.vals[args[0].index()].typed; + if (tp.addr_space != 6) return e.unsupported("'{s}' on this variable is not supported yet", .{name}); + break :p try e.typedScalarPtr(tp, &.{}, try e.scalarTy(memScalar(e.compOf(dest_ty)))); + }; + if (float_bits) { + const as: u32 = if (tag == .ptr) 3 else 6; + ptr = try e.add(try e.dm.getType(.{ .pointer = .{ .elem = i32t, .addr_space = as } }), .{ .cast = .{ .op = .bitcast, .val = ptr } }); + } if (cmp) |cv| { const pair = try e.dm.getType(.{ .@"struct" = .{ .name = "", .elems = &.{ i32t, try e.dm.intType(1) } } }); const r = try e.add(pair, .{ .cmpxchg = .{ .ptr = ptr, .cmp = cv, .new = val } }); @@ -3697,10 +3747,25 @@ const Emitter = struct { }, else => return e.unsupported("'{s}' on this destination is not supported yet", .{name}), }; - if (has_orig) try e.storePtr(try e.outPtr(frame, args[args.len - 1]), &.{orig}, frame.f.inst(args[args.len - 1]).ty); + const out_ty = frame.f.inst(args[args.len - 1]).ty; + const orig_val = if (float_bits and e.compOf(out_ty) == .float) try e.add(try e.dm.getType(.float), .{ .cast = .{ .op = .bitcast, .val = orig } }) else orig; + if (has_orig) try e.storePtr(try e.outPtr(frame, args[args.len - 1]), &.{orig_val}, out_ty); return .none; } + /// An atomic's value: a float's bits for the *FloatBitwise compares + /// (constants folded). + fn atomicOperand(e: *Emitter, float_bits: bool, v: Value) Error!Value { + if (!float_bits) return v; + const i32t = try e.dm.intType(32); + if (v == .constant) switch (e.dm.constants.items[v.constant].kind) { + .float_bits => |b| return e.i32Const(@as(i32, @bitCast(@as(u32, @truncate(b))))), + else => {}, + }; + if (e.dm.types.items[try e.valueType(v)] != .float) return v; + return e.add(i32t, .{ .cast = .{ .op = .bitcast, .val = v } }); + } + /// dx.op.atomicBinOp / atomicCompareExchange at `coords` (padded with /// undef to three). fn resourceAtomic(e: *Emitter, res: Resource, coords: []const Value, op_name: []const u8, dc: Scalar, val: Value, cmp: ?Value) Error!Value { @@ -4403,6 +4468,7 @@ const Emitter = struct { } fn method(e: *Emitter, frame: *Frame, name: []const u8, res_ref: Ref, arg_refs: []const Ref, ty: TypeId) Error!Lowered { + if (frame.vals[res_ref.index()] == .node) return e.nodeMethod(frame, frame.vals[res_ref.index()].node, name, arg_refs); if (frame.vals[res_ref.index()] == .ray_query) return e.rayQueryMethod(frame, frame.vals[res_ref.index()].ray_query, name, arg_refs, ty); const res = try e.resourceOf(frame, res_ref); const kind = e.resourceKind(res.*); @@ -5361,7 +5427,7 @@ const Emitter = struct { fn inputAt(e: *Emitter, k: u32, ty: TypeId, vertex: ?u32) Error!Lowered { const entry = e.entry; - if (entry.stage == .compute or entry.stage == .mesh or entry.stage == .amplification) return e.computeInput(k, ty); + if (entry.stage == .compute or entry.stage == .mesh or entry.stage == .amplification or entry.stage == .node) return e.computeInput(k, ty); const el = entry.inputs.items[k]; const se = if (e.in_elem[k]) |ei| &e.sig_in[ei] else return e.systemValueInput(el.semantic, ty); if (se.interpretation == .shadow) return e.systemValueInput(el.semantic, ty); @@ -5801,6 +5867,252 @@ const Emitter = struct { } } + // ---- Work graph nodes ------------------------------------------------ + + const NodeTypes = struct { handle: DType, record_handle: DType, info: DType, record_info: DType }; + + fn nodeTypes(e: *Emitter) Error!NodeTypes { + const i8p = try e.dm.ptrType(try e.dm.intType(8)); + const i32t = try e.dm.intType(32); + return .{ + .handle = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeHandle", .elems = &.{i8p} } }), + .record_handle = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeRecordHandle", .elems = &.{i8p} } }), + .info = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeInfo", .elems = &.{ i32t, i32t } } }), + .record_info = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.NodeRecordInfo", .elems = &.{ i32t, i32t } } }), + }; + } + + /// A record type's size and alignment (0, 0 for empty inputs and + /// outputs). + fn recordLayout(e: *Emitter, record: TypeId) Error![2]u32 { + if (record == TypeTable.void_type) return .{ 0, 0 }; + return e.memLayout(record); + } + + /// annotateNodeHandle / annotateNodeRecordHandle of `raw`. + fn annotateNode(e: *Emitter, nv: NodeVal, raw: Value) Error!Value { + const nt = try e.nodeTypes(); + const i32t = try e.dm.intType(32); + // (Inputs, empty ones too, and output records: record handles.) + const outputs = !nv.kind.isInput() and !nv.kind.hasRecords(); + const info_ty = if (outputs) nt.info else nt.record_info; + const hty = if (outputs) nt.handle else nt.record_handle; + const f0 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = nv.flags } }); + const f1 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = nv.size } }); + const props = try e.dm.constant(.{ .ty = info_ty, .kind = .{ .aggregate = try e.arena.dupe(module.ConstId, &.{ f0.constant, f1.constant }) } }); + const fn_i = if (outputs) + try e.dxOp("dx.op.annotateNodeHandle", hty, &.{ i32t, hty, info_ty }, .nounwind_readnone) + else + try e.dxOp("dx.op.annotateNodeRecordHandle", hty, &.{ i32t, hty, info_ty }, .nounwind_readnone); + return e.callOp(fn_i, hty, &.{ try e.i32Const(if (outputs) 249 else 251), raw, props }); + } + + /// The node shader's input or output `x.index`: its handle, created + /// and annotated. + fn nodeIo(e: *Emitter, x: @FieldType(ir.Op, "node_io")) Error!Lowered { + const info = e.entry.node orelse return e.unsupported("node objects outside node shaders", .{}); + const io = if (x.output) info.outputs[x.index] else info.inputs[x.index]; + const nt = try e.nodeTypes(); + const i32t = try e.dm.intType(32); + var nv: NodeVal = .{ .kind = io.kind, .handle = undefined, .record = io.record, .flags = io.kind.ioFlags() | io.extra_flags, .size = (try e.recordLayout(io.record))[0] }; + const raw = if (x.output) + try e.callOp(try e.dxOp("dx.op.createNodeOutputHandle", nt.handle, &.{ i32t, i32t }, .nounwind_readnone), nt.handle, &.{ try e.i32Const(247), try e.i32Const(x.index) }) + else + try e.callOp(try e.dxOp("dx.op.createNodeInputRecordHandle", nt.record_handle, &.{ i32t, i32t }, .nounwind_readnone), nt.record_handle, &.{ try e.i32Const(250), try e.i32Const(x.index) }); + nv.handle = try e.annotateNode(nv, raw); + return .{ .node = nv }; + } + + /// Output `idx` of an outputs array (annotated as the array). + fn nodeIndex(e: *Emitter, nv: NodeVal, kind: types.NodeKind, idx: Value) Error!NodeVal { + const nt = try e.nodeTypes(); + const i32t = try e.dm.intType(32); + const fn_i = try e.dxOp("dx.op.indexNodeHandle", nt.handle, &.{ i32t, nt.handle, i32t }, .nounwind_readnone); + const raw = try e.callOp(fn_i, nt.handle, &.{ try e.i32Const(248), nv.handle, idx }); + var out = nv; + out.handle = try e.annotateNode(nv, raw); + out.kind = kind; + return out; + } + + /// Record `idx` of a node object, in node record memory. + fn nodeRecordPtr(e: *Emitter, nv: NodeVal, idx: Value) Error!@FieldType(Lowered, "typed") { + if (nv.record == TypeTable.void_type) return e.unsupported("records of an empty node input or output", .{}); + const nt = try e.nodeTypes(); + const i32t = try e.dm.intType(32); + const dty = try e.memoryType(nv.record); + const sname = switch (e.dm.types.items[dty]) { + .@"struct" => |st| st.name, + else => return e.unsupported("node records of type '{s}'", .{try e.t.format(e.arena, nv.record)}), + }; + const pty = try e.dm.getType(.{ .pointer = .{ .elem = dty, .addr_space = 6 } }); + const fn_i = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.getNodeRecordPtr.{s}", .{sname}), pty, &.{ i32t, nt.record_handle, i32t }, .nounwind_readnone); + const base = try e.callOp(fn_i, pty, &.{ try e.i32Const(239), nv.handle, idx }); + return .{ .base = base, .dty = dty, .addr_space = 6, .ty = nv.record }; + } + + /// Methods of node objects. + fn nodeMethod(e: *Emitter, frame: *Frame, nv: NodeVal, name: []const u8, arg_refs: []const Ref) Error!Lowered { + const eq = std.mem.eql; + const nt = try e.nodeTypes(); + const i32t = try e.dm.intType(32); + const i1t = try e.dm.intType(1); + const void_ty = try e.voidTy(); + if (eq(u8, name, "IsValid")) { + const fn_i = try e.dxOp("dx.op.nodeOutputIsValid", i1t, &.{ i32t, nt.handle }, .nounwind_readonly); + return e.list(&.{try e.callOp(fn_i, i1t, &.{ try e.i32Const(252), nv.handle })}); + } + if (eq(u8, name, "GetThreadNodeOutputRecords") or eq(u8, name, "GetGroupNodeOutputRecords")) { + const per_thread = eq(u8, name, "GetThreadNodeOutputRecords"); + const n = (try e.scalars(frame, arg_refs[0]))[0]; + const fn_i = try e.dxOp("dx.op.allocateNodeOutputRecords", nt.record_handle, &.{ i32t, nt.handle, i32t, i1t }, .nounwind); + const pt = try e.dm.constant(.{ .ty = i1t, .kind = .{ .int = @intFromBool(per_thread) } }); + const raw = try e.callOp(fn_i, nt.record_handle, &.{ try e.i32Const(238), nv.handle, n, pt }); + const kind: types.NodeKind = if (per_thread) .thread_output_records else .group_output_records; + var out: NodeVal = .{ .kind = kind, .handle = undefined, .record = nv.record, .flags = kind.ioFlags(), .size = nv.size }; + out.handle = try e.annotateNode(out, raw); + return .{ .node = out }; + } + if (eq(u8, name, "GroupIncrementOutputCount") or eq(u8, name, "ThreadIncrementOutputCount")) { + const n = (try e.scalars(frame, arg_refs[0]))[0]; + const fn_i = try e.dxOp("dx.op.incrementOutputCount", void_ty, &.{ i32t, nt.handle, i32t, i1t }, .nounwind); + const pt = try e.dm.constant(.{ .ty = i1t, .kind = .{ .int = @intFromBool(eq(u8, name, "ThreadIncrementOutputCount")) } }); + _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(240), nv.handle, n, pt }); + return .none; + } + if (eq(u8, name, "OutputComplete")) { + const fn_i = try e.dxOp("dx.op.outputComplete", void_ty, &.{ i32t, nt.record_handle }, .nounwind); + _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(241), nv.handle }); + return .none; + } + if (eq(u8, name, "Count")) { + const fn_i = try e.dxOp("dx.op.getInputRecordCount", i32t, &.{ i32t, nt.record_handle }, .nounwind_readonly); + return e.list(&.{try e.callOp(fn_i, i32t, &.{ try e.i32Const(242), nv.handle })}); + } + if (eq(u8, name, "FinishedCrossGroupSharing")) { + const fn_i = try e.dxOp("dx.op.finishedCrossGroupSharing", i1t, &.{ i32t, nt.record_handle }, .nounwind); + return e.list(&.{try e.callOp(fn_i, i1t, &.{ try e.i32Const(243), nv.handle })}); + } + return e.unsupported("node method '{s}' is not supported yet", .{name}); + } + + /// A node shader's entry properties (before its thread group size), + /// in dxc's order. + fn nodeProps(e: *Emitter, entry: ir.Entry, n: ir.NodeInfo, props: *std.ArrayList(?module.MdId)) Error!void { + const dm = &e.dm; + const I = struct { + fn f(m: *module.Module, v: i64) !?module.MdId { + return try m.mdI32(v); + } + }.f; + const i1t = try dm.intType(1); + const mdTrue = try dm.mdValue(i1t, try dm.constant(.{ .ty = i1t, .kind = .{ .int = 1 } })); + try props.appendSlice(e.arena, &.{ try I(dm, 13), try I(dm, @backingInt(n.launch)) }); + if (entry.wave_size[0] != 0) { + const ws = entry.wave_size; + if (e.profile.minor >= 8) { + try props.appendSlice(e.arena, &.{ try I(dm, 23), try dm.mdNode(&.{ try I(dm, ws[0]), try I(dm, ws[1]), try I(dm, ws[2]) }) }); + } else try props.appendSlice(e.arena, &.{ try I(dm, 11), try dm.mdNode(&.{try I(dm, ws[0])}) }); + } + if (n.is_program_entry) try props.appendSlice(e.arena, &.{ try I(dm, 14), mdTrue }); + try props.appendSlice(e.arena, &.{ try I(dm, 15), try dm.mdNode(&.{ try dm.mdString(n.id.name), try I(dm, n.id.index) }) }); + try props.appendSlice(e.arena, &.{ try I(dm, 16), try I(dm, if (n.local_root_arguments_table_index) |x| @as(i64, x) else -1) }); + if (n.share_input_of) |s| try props.appendSlice(e.arena, &.{ try I(dm, 17), try dm.mdNode(&.{ try dm.mdString(s.name), try I(dm, s.index) }) }); + const grid = struct { + fn f(m: *module.Module, g: ?[3]u32) !?module.MdId { + const v = g orelse return null; + if (v[0] == 0 and v[1] == 0 and v[2] == 0) return null; + return try m.mdNode(&.{ try m.mdI32(v[0]), try m.mdI32(v[1]), try m.mdI32(v[2]) }); + } + }.f; + if (try grid(dm, n.dispatch_grid)) |g| try props.appendSlice(e.arena, &.{ try I(dm, 18), g }); + if (try grid(dm, n.max_dispatch_grid)) |g| try props.appendSlice(e.arena, &.{ try I(dm, 22), g }); + if (n.max_recursion_depth) |d| if (d != 0) try props.appendSlice(e.arena, &.{ try I(dm, 19), try I(dm, d) }); + if (n.inputs.len > 0) { + var l: std.ArrayList(?module.MdId) = .empty; + for (n.inputs) |io| try l.append(e.arena, try e.nodeIoProps(io)); + try props.appendSlice(e.arena, &.{ try I(dm, 20), try dm.mdNode(l.items) }); + } + if (n.outputs.len > 0) { + var l: std.ArrayList(?module.MdId) = .empty; + for (n.outputs) |io| try l.append(e.arena, try e.nodeIoProps(io)); + try props.appendSlice(e.arena, &.{ try I(dm, 21), try dm.mdNode(l.items) }); + } + } + + /// One node input's / output's properties. + fn nodeIoProps(e: *Emitter, io: ir.NodeIo) Error!?module.MdId { + const dm = &e.dm; + var l: std.ArrayList(?module.MdId) = .empty; + try l.appendSlice(e.arena, &.{ try dm.mdI32(1), try dm.mdI32(io.kind.ioFlags() | io.extra_flags) }); + const lay = try e.recordLayout(io.record); + if (lay[0] != 0) { + var r: std.ArrayList(?module.MdId) = .empty; + try r.appendSlice(e.arena, &.{ try dm.mdI32(0), try dm.mdI32(lay[0]) }); + if (try e.dispatchGridField(io.record, 0)) |g| { + try r.appendSlice(e.arena, &.{ try dm.mdI32(1), try dm.mdNode(&.{ try dm.mdI32(g.offset), try dm.mdI32(g.comp), try dm.mdI32(g.count) }) }); + } + try r.appendSlice(e.arena, &.{ try dm.mdI32(2), try dm.mdI32(lay[1]) }); + try l.appendSlice(e.arena, &.{ try dm.mdI32(2), try dm.mdNode(r.items) }); + } + const i1t = try dm.intType(1); + if (!io.kind.isInput()) { + try l.appendSlice(e.arena, &.{ try dm.mdI32(3), try dm.mdI32(io.max_records orelse 0) }); + if (io.array_size) |a| if (a != 0) try l.appendSlice(e.arena, &.{ try dm.mdI32(5), try dm.mdI32(@as(i32, @bitCast(a))) }); + if (io.max_records_shared_with) |s| try l.appendSlice(e.arena, &.{ try dm.mdI32(4), try dm.mdI32(s) }); + if (io.allow_sparse_nodes) try l.appendSlice(e.arena, &.{ try dm.mdI32(6), try dm.mdValue(i1t, try dm.constant(.{ .ty = i1t, .kind = .{ .int = 1 } })) }); + if (io.output_id) |id| try l.appendSlice(e.arena, &.{ try dm.mdI32(0), try dm.mdNode(&.{ try dm.mdString(id.name), try dm.mdI32(id.index) }) }); + } else if (io.max_records) |m| if (m != 0) try l.appendSlice(e.arena, &.{ try dm.mdI32(3), try dm.mdI32(m) }); + return try dm.mdNode(l.items); + } + + /// SV_DispatchGrid in a record: byte offset, component type (U32 5, + /// U16 3) and component count. + const DispatchGrid = struct { offset: u32, comp: u32, count: u32 }; + + fn dispatchGridField(e: *Emitter, ty: TypeId, base: u32) Error!?DispatchGrid { + const st = switch (e.t.get(ty)) { + .@"struct" => |s| s, + else => return null, + }; + var off: u32 = 0; + for (st.fields.items) |fld| { + const fl = try e.memLayout(fld.type); + off = std.mem.alignForward(u32, off, fl[1]); + if (fld.semantic) |sem| if (std.ascii.eqlIgnoreCase(sem, "SV_DispatchGrid")) { + const count: u32 = switch (e.t.get(fld.type)) { + .vector => |v| v.len, + .array => |a| a.len, + else => 1, + }; + const scalar_size = fl[0] / count; + return .{ .offset = base + off, .comp = if (scalar_size == 2) 3 else 5, .count = count }; + }; + if (e.t.get(fld.type) == .@"struct") if (try e.dispatchGridField(fld.type, base + off)) |g| return g; + off += fl[0]; + } + return null; + } + + /// `tp` indexed by `indices` (struct members by constant index). + fn typedAccess(e: *Emitter, frame: *Frame, start: @FieldType(Lowered, "typed"), indices: []const Ref) Error!@FieldType(Lowered, "typed") { + var tp = start; + var path: std.ArrayList(Value) = .empty; + try path.appendSlice(e.arena, tp.path); + for (indices) |x| { + try path.append(e.arena, (try e.scalars(frame, x))[0]); + tp.ty = switch (e.t.get(tp.ty)) { + .@"struct" => |st| st.fields.items[@intCast(frame.f.inst(x).op.constant.int)].type, + .array => |arr| arr.elem, + .vector => |v| try e.t.scalar(v.elem), + .matrix => |mt| try e.t.vector(mt.elem, mt.cols), + else => return e.unsupported("indexing this member is not supported yet", .{}), + }; + } + tp.path = path.items; + return tp; + } + fn typedScalarPtr(e: *Emitter, tp: @FieldType(Lowered, "typed"), sub: []const Value, st: DType) Error!Value { const idx = try e.arena.alloc(Value, 1 + tp.path.len + sub.len); idx[0] = try e.i32Const(0); @@ -6731,6 +7043,78 @@ const Emitter = struct { return @intCast(n); } + /// A node shader's RDAT NodeShaderInfo (as dxc's AddShaderNodeInfo). + fn rdatNode(e: *Emitter, b: *rdat.Builder, entry: ir.Entry, n: ir.NodeInfo, groupshared: u32) Error!u32 { + const rec = struct { + fn f(bb: *rdat.Builder, t: rdat.Ext, words: []const u32) !u32 { + return bb.record(t, std.mem.sliceAsBytes(words)); + } + }.f; + var attrs: std.ArrayList(u32) = .empty; + // NodeFuncAttribKind: ID 1, NumThreads 2, ShareInputOf 3, + // DispatchGrid 4, MaxRecursionDepth 5, LocalRootArgumentsTableIndex + // 6, MaxDispatchGrid 7. + const id = try rec(b, .node_ids, &.{ try b.string(n.id.name), n.id.index }); + try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 1, id })); + const nt = entry.num_threads; + if (nt[0] != 0 or nt[1] != 0 or nt[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 2, try b.array(&nt) })); + if (n.local_root_arguments_table_index) |x| try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 6, x })); + if (n.share_input_of) |s| { + const sid = try rec(b, .node_ids, &.{ try b.string(s.name), s.index }); + try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 3, sid })); + } + if (n.dispatch_grid) |g| if (g[0] != 0 or g[1] != 0 or g[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 4, try b.array(&g) })); + if (n.max_recursion_depth) |d| if (d != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 5, d })); + if (n.max_dispatch_grid) |g| if (g[0] != 0 or g[1] != 0 or g[2] != 0) try attrs.append(e.arena, try rec(b, .node_func_attribs, &.{ 7, try b.array(&g) })); + const func_attrs = try b.array(attrs.items); + const inputs = try e.rdatIoNodes(b, n.inputs); + const outputs = try e.rdatIoNodes(b, n.outputs); + return rec(b, .node_shaders, &.{ @backingInt(n.launch), groupshared, func_attrs, outputs, inputs }); + } + + /// The IONode records of node inputs or outputs (an index array). + fn rdatIoNodes(e: *Emitter, b: *rdat.Builder, ios: []const ir.NodeIo) Error!u32 { + const rec = struct { + fn f(bb: *rdat.Builder, t: rdat.Ext, words: []const u32) !u32 { + return bb.record(t, std.mem.sliceAsBytes(words)); + } + }.f; + var nodes: std.ArrayList(u32) = .empty; + for (ios) |io| { + // NodeAttribKind: OutputID 1, MaxRecords 2, MaxRecordsSharedWith + // 3, RecordSizeInBytes 4, RecordDispatchGrid 5, OutputArraySize + // 6, AllowSparseNodes 7, RecordAlignmentInBytes 8. + var attrs: std.ArrayList(u32) = .empty; + if (!io.kind.isInput()) { + const oid = io.output_id orelse ir.NodeId{ .name = "" }; + const id = try rec(b, .node_ids, &.{ try b.string(oid.name), oid.index }); + try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 1, id })); + try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 6, io.array_size orelse 0 })); + if (io.max_records orelse 0 != 0) { + try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 2, io.max_records.? })); + } else if (io.max_records_shared_with) |s| { + try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 3, s })); + } + if (io.allow_sparse_nodes) try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 7, 1 })); + } else if (io.max_records orelse 0 != 0) { + try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 2, io.max_records.? })); + } + const lay = try e.recordLayout(io.record); + if (lay[0] != 0) { + try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 4, lay[0] })); + if (try e.dispatchGridField(io.record, 0)) |g| { + // ByteOffset (u16), then components (bits 0..1) and + // component type (from bit 2). + try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 5, g.offset | ((g.count & 3) | (g.comp << 2)) << 16 })); + } + if (lay[1] != 0) try attrs.append(e.arena, try rec(b, .node_io_attribs, &.{ 8, lay[1] })); + } + const arr = try b.array(attrs.items); + try nodes.append(e.arena, try rec(b, .io_nodes, &.{ io.kind.ioFlags() | io.extra_flags, arr })); + } + return b.array(nodes.items); + } + /// The library container: feature info, runtime data (RDAT) and the /// program. fn assembleLibrary(e: *Emitter, gpa: Allocator, funcs: []const LibFunc, bitcode: []const u8) Error![]u8 { @@ -6788,6 +7172,12 @@ const Emitter = struct { .cbuffers = func_cbuffers.items, }); const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref; + var shader_flags: u16 = 0; + const node_info = if (lf.stage == .node) blk: { + const n = lf.entry.node.?; + if (n.is_program_entry) shader_flags |= 1; + break :blk try e.rdatNode(&b, lf.entry, n, lf.groupshared); + } else rdat.null_ref; const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref; const kind = shaderKind(lf.stage); try b.addFunction(.{ @@ -6804,6 +7194,8 @@ const Emitter = struct { // (RDAT: 0 where none is specified.) .min_wave_lanes = @intCast(lf.entry.wave_size[0]), .max_wave_lanes = @intCast(if (lf.entry.wave_size[1] != 0) lf.entry.wave_size[1] else lf.entry.wave_size[0]), + .shader_flags = shader_flags, + .raw_shader_ref = node_info, .extended_properties = props, }); } @@ -6877,6 +7269,11 @@ const Emitter = struct { } }.f; 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]) }); + if (entry.node) |n| { + try e.nodeProps(entry, n, props); + try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads }); + return; + } if (entry.stage == .compute) try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads }); // WaveSize: a value (tag 11) before SM 6.8, a range with a // preferred size after (tag 23; zeros where not given). @@ -7188,15 +7585,29 @@ fn gsTopology(g: ir.GeometryInfo) u32 { return 1; } +/// Resources, samplers and (handles too) work graph node objects. fn isResourceType(t: *TypeTable, ty: TypeId) bool { return switch (t.get(ty)) { - .resource, .sampler => true, + .resource, .sampler, .node => true, else => false, }; } const isRayQuery = @import("../ir/lower.zig").isRayQuery; +/// Whether the stores to local `ptr` are all in one block of `f`. +fn storesInOneBlock(f: *const ir.Function, ptr: Ref) bool { + var found: ?usize = null; + for (f.blocks.items, 0..) |blk, bi| for (blk.insts.items) |r| switch (f.inst(r).op) { + .store => |x| if (x.ptr == ptr) { + if (found) |b| if (b != bi) return false; + found = bi; + }, + else => {}, + }; + return true; +} + fn reachableBlocks(a: Allocator, f: *const ir.Function) Allocator.Error![]bool { return reachableBlocksTaken(a, f, &.{}); } diff --git a/src/dxil/module.zig b/src/dxil/module.zig index cd414ed..cd5b2fa 100644 --- a/src/dxil/module.zig +++ b/src/dxil/module.zig @@ -106,7 +106,7 @@ const ConstantContext = struct { pub const Linkage = enum(u32) { external = 0, internal = 3 }; /// Attribute group for function declarations (e.g. dx.op functions). -pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind }; +pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind, noinline_nounwind, noduplicate_nounwind }; pub const Value = union(enum) { /// Index into Module.globals (a pointer to the variable). @@ -671,12 +671,19 @@ const Encoder = struct { } fn writeAttributes(e: *Encoder) !void { - // Groups 1..5 match FnAttrs order; each applies to the function (index 0xFFFFFFFF). - // Attribute kinds: noinline = 14, noreturn = 17, nounwind = 18, - // readnone = 20, readonly = 21. + // Groups 1..6 match FnAttrs order; each applies to the function (index 0xFFFFFFFF). + // Attribute kinds: noduplicate = 12, noinline = 14, noreturn = 17, + // nounwind = 18, readnone = 20, readonly = 21. const w = &e.w; try w.enterBlock(block_paramattr_group, 3); - const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 } }; + const all = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 }, &.{ 14, 18 }, &.{ 12, 18 } }; + // noduplicate (the SM 6.8 barriers) only when used: the rest of + // the modules are as they were. + var n: usize = 5; + for (e.m.functions.items) |f| { + if (f.attrs == .noduplicate_nounwind) n = 6; + } + const groups = all[0..n]; for (groups, 1..) |kinds, id| { try e.push(id); try e.push(0xFFFFFFFF); diff --git a/src/dxil/rdat.zig b/src/dxil/rdat.zig index 6716a2d..63ae585 100644 --- a/src/dxil/rdat.zig +++ b/src/dxil/rdat.zig @@ -5,8 +5,9 @@ //! Layout: a header (version, part count), part offsets, then each //! non-empty part as (type, size) and its 4-byte aligned contents. Parts //! come in the order dxc adds them: strings, resources, functions, index -//! arrays, raw bytes, subobjects, then the record tables of the extended -//! function properties (SM 6.10 linear algebra). +//! arrays, raw bytes, subobjects, then the other record tables: work graph +//! nodes (validator 1.8+) and the extended function properties (SM 6.10 +//! linear algebra). const std = @import("std"); const Allocator = std.mem.Allocator; @@ -46,9 +47,14 @@ pub const Function = struct { extended_properties: u32 = null_ref, }; -/// The extended function property tables, in part order (part types -/// 13..20). +/// The other record tables, by part type: work graph nodes (7..11) and +/// the extended function properties (13..20). pub const Ext = enum(u32) { + node_ids = 7, + node_io_attribs, + node_func_attribs, + io_nodes, + node_shaders, properties = 13, shapes, constructions, @@ -61,8 +67,10 @@ pub const Ext = enum(u32) { /// Record size in bytes. pub fn stride(t: Ext) usize { return switch (t) { + .node_shaders => 20, .shapes => 12, .properties, .constructions, .wave_multiplies, .group_multiplies => 8, + .node_ids, .node_io_attribs, .node_func_attribs, .io_nodes => 8, .thread_matvec, .outer_products, .accumulate_stores => 4, }; } @@ -77,7 +85,8 @@ pub const Builder = struct { functions: std.ArrayList([14]u32) = .empty, raw: std.ArrayList(u8) = .empty, subobjects: std.ArrayList([6]u32) = .empty, - ext: [8]std.ArrayList(u8) = @splat(.empty), + /// By part type, from 7. + ext: [14]std.ArrayList(u8) = @splat(.empty), pub fn init(gpa: Allocator) Allocator.Error!Builder { var b: Builder = .{ .gpa = gpa }; @@ -134,7 +143,7 @@ pub const Builder = struct { /// (record deduplication, validator 1.7+). pub fn record(b: *Builder, t: Ext, rec: []const u8) Allocator.Error!u32 { std.debug.assert(rec.len == t.stride()); - const tab = &b.ext[@backingInt(t) - 13]; + const tab = &b.ext[@backingInt(t) - 7]; var at: usize = 0; while (at < tab.items.len) : (at += rec.len) { if (std.mem.eql(u8, tab.items[at..][0..rec.len], rec)) return @intCast(at / rec.len); @@ -182,8 +191,12 @@ pub const Builder = struct { try tables.append(b.gpa, t); try parts.append(b.gpa, .{ .ty = 6, .data = t }); } - for (b.ext, 13..) |rows, ty| if (rows.items.len > 0) { - const stride = @as(Ext, @fromBackingInt(@intCast(ty))).stride(); + // (dxc's table order: the node function attributes before the + // I/O attributes.) + const order = [_]u32{ 7, 9, 8, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20 }; + for (order) |ty| if (b.ext[ty - 7].items.len > 0) { + const rows = b.ext[ty - 7]; + const stride = @as(Ext, @fromBackingInt(ty)).stride(); const t = try table(b.gpa, stride / 4, rows.items, rows.items.len / stride); try tables.append(b.gpa, t); try parts.append(b.gpa, .{ .ty = @intCast(ty), .data = t }); diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 57da522..60aa17d 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -38,7 +38,8 @@ pub const BlockId = enum(u32) { }; /// Where a pointer points. -pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray }; +/// (`node`: a work graph node record.) +pub const Space = enum { none, function, private, groupshared, resource, input, output, cbuffer, mesh, ray, node }; /// Ray tracing shader storage an entry receives: the incoming payload, /// the hit attributes and the incoming callable data. @@ -72,6 +73,9 @@ pub const Constant = union(enum) { pub const Op = union(enum) { /// A scalar constant (or a vector of one constant, splatted). constant: Constant, + /// A node shader's input (`output` false) or its output `index`: the + /// node object (Entry.node's inputs / outputs). + node_io: struct { output: bool, index: u32 }, /// The function's `n`th parameter (a pointer for out / inout). param: u32, /// Pointer to a module global (resource, groupshared, static). @@ -356,6 +360,8 @@ pub const Stage = enum { mesh, amplification, library, + /// Work graph nodes (SM 6.8 libraries). + node, raygeneration, intersection, anyhit, @@ -409,6 +415,45 @@ pub const OutputTopology = enum(u8) { point = 1, line = 2, triangle_cw = 3, tria pub const MeshOutput = enum { vertices, primitives, indices }; +/// A node shader's properties (`[Shader("node")]`), from its attributes. +pub const NodeInfo = struct { + launch: Launch = .broadcasting, + is_program_entry: bool = false, + /// `[NodeID("name", index)]`; by default the function's name, 0. + id: NodeId, + local_root_arguments_table_index: ?u32 = null, + share_input_of: ?NodeId = null, + dispatch_grid: ?[3]u32 = null, + max_dispatch_grid: ?[3]u32 = null, + max_recursion_depth: ?u32 = null, + inputs: []const NodeIo = &.{}, + outputs: []const NodeIo = &.{}, + + /// NodeLaunchType. + pub const Launch = enum(u32) { broadcasting = 1, coalescing = 2, thread = 3 }; +}; + +pub const NodeId = struct { name: []const u8, index: u32 = 0 }; + +/// One node input or output: a parameter of a node object type. +pub const NodeIo = struct { + kind: types.NodeKind, + /// The record type (void for empty inputs / outputs). + record: TypeId, + /// I/O flags beyond the kind: TrackRWInputSharing 0x100, + /// GloballyCoherent 0x200. + extra_flags: u32 = 0, + /// Outputs: `[NodeID]`, by default the parameter's name, 0. + output_id: ?NodeId = null, + max_records: ?u32 = null, + /// Outputs: the index of the output whose records these share. + max_records_shared_with: ?u32 = null, + /// Output arrays: `[NodeArraySize(n)]`, or maxInt for + /// `[UnboundedSparseNodes]`. + array_size: ?u32 = null, + allow_sparse_nodes: bool = false, +}; + pub const MeshInfo = struct { max_vertices: u32 = 0, max_primitives: u32 = 0, @@ -442,6 +487,8 @@ pub const Entry = struct { geometry: GeometryInfo = .{}, tess: TessInfo = .{}, mesh: MeshInfo = .{}, + /// Node shaders. + node: ?NodeInfo = null, inputs: std.ArrayList(SigElement) = .empty, outputs: std.ArrayList(SigElement) = .empty, /// Patch constants: written by the hull shader's patch constant @@ -661,6 +708,7 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo .float => |v| try w.print("const {d}", .{v}), }, .param => |p| try w.print("param {d}", .{p}), + .node_io => |x| try w.print("node_{s} {d}", .{ if (x.output) "output" else "input", x.index }), .global => |g| try w.print("global @{d}", .{g}), .local_var => try w.writeAll("local_var"), .load => |p| try w.print("load %{d}", .{p.index()}), diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 6eae6a7..a9c82fd 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -73,11 +73,21 @@ pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module { /// The stage a `[shader("...")]` attribute names. fn stageNamed(name: []const u8) ?ir.Stage { const names = [_]struct { []const u8, ir.Stage }{ - .{ "vertex", .vertex }, .{ "pixel", .pixel }, .{ "geometry", .geometry }, - .{ "hull", .hull }, .{ "domain", .domain }, .{ "compute", .compute }, - .{ "mesh", .mesh }, .{ "amplification", .amplification }, .{ "raygeneration", .raygeneration }, - .{ "intersection", .intersection }, .{ "anyhit", .anyhit }, .{ "closesthit", .closesthit }, - .{ "miss", .miss }, .{ "callable", .callable }, + .{ "node", .node }, + .{ "vertex", .vertex }, + .{ "pixel", .pixel }, + .{ "geometry", .geometry }, + .{ "hull", .hull }, + .{ "domain", .domain }, + .{ "compute", .compute }, + .{ "mesh", .mesh }, + .{ "amplification", .amplification }, + .{ "raygeneration", .raygeneration }, + .{ "intersection", .intersection }, + .{ "anyhit", .anyhit }, + .{ "closesthit", .closesthit }, + .{ "miss", .miss }, + .{ "callable", .callable }, }; for (names) |t| if (std.ascii.eqlIgnoreCase(name, t[0])) return t[1]; return null; @@ -1070,6 +1080,13 @@ const Lowerer = struct { const idx = try l.indexValue(x.index, bt.resource.kind.indexDims()); return l.b.add(.{ .op = .{ .res_load = .{ .res = res, .index = idx } }, .ty = try l.concrete(e.ty) }); } + if (bt == .node) { + if (bt.node.kind.isArray()) return l.b.load(try l.nodeRecordPtr(e)); + // An output of an outputs array: the node object. + const obj = try l.rvalue(x.base); + const idx = try l.converted(x.index, try t.scalar(.uint)); + return l.b.add(.{ .op = .{ .access = .{ .base = obj, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty }); + } if (isAddressable(l.s, x.base)) return l.b.load(try l.lvalue(e)); const base = try l.rvalue(x.base); if (l.s.evalInt(x.index)) |k| return l.b.add(.{ .op = .{ .extract = .{ .agg = base, .index = @intCast(k) } }, .ty = try l.concrete(e.ty) }); @@ -1377,6 +1394,7 @@ const Lowerer = struct { fn call(l: *Lowerer, e: *ast.Expr, callee: *ast.Expr, args: []const *ast.Expr) Error!Ref { const r = l.s.resolution(e) orelse return l.fail(e, "this call"); const ret_ty = try l.concrete(e.ty); + if (r == .node_record) return l.b.load(try l.nodeRecordPtr(e)); switch (r) { .function => |f| { if (!f.defined and hasAttr(f.decl.attrs, "vk::ext_instruction")) return l.spirvInstCall(e, f, args, ret_ty); @@ -1754,7 +1772,22 @@ const Lowerer = struct { return l.b.add(.{ .op = .{ .global = g }, .ty = glob.ty, .ptr = glob.space }); } + /// A node record: `obj.Get()`, `obj.Get(i)` or `obj[i]` (an element + /// of the node object, in node record memory). + fn nodeRecordPtr(l: *Lowerer, e: *ast.Expr) Error!Ref { + const t = l.types(); + const obj_expr, const index: ?*ast.Expr = switch (e.kind) { + .call => |c| .{ c.callee.kind.member.base, if (c.args.len > 0) c.args[0] else null }, + .index => |x| .{ x.base, x.index }, + else => return l.fail(e, "this node record"), + }; + const obj = try l.rvalue(obj_expr); + const idx = if (index) |i| try l.converted(i, try t.scalar(.uint)) else try l.b.constInt(try t.scalar(.uint), 0); + return l.b.add(.{ .op = .{ .access = .{ .base = obj, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = .node }); + } + fn lvalue(l: *Lowerer, e: *ast.Expr) Error!Ref { + if (l.s.resolution(e)) |r| if (r == .node_record) return l.nodeRecordPtr(e); const t = l.types(); // A resource inside a global struct: its own global. if (e.kind == .member or e.kind == .index) if (l.uniformPath(e)) |up| if (layout.isOpaque(t, e.ty)) return l.leafGlobal(up.v, up.path, e.ty); @@ -2421,6 +2454,97 @@ const Lowerer = struct { entry.patch_wrapper = wrapper; } + /// A node shader's properties: its attributes and its node object + /// parameters (inputs, then outputs, in parameter order). + fn nodeInfo(l: *Lowerer, f: *const semamod.Function) Error!ir.NodeInfo { + const eqi = std.ascii.eqlIgnoreCase; + var info: ir.NodeInfo = .{ .id = .{ .name = f.name } }; + for (f.decl.attrs) |a| { + if (eqi(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) { + const v = try stringContents(l.arena, a.args[0].kind.string_lit); + if (eqi(v, "coalescing")) info.launch = .coalescing else if (eqi(v, "thread")) info.launch = .thread else info.launch = .broadcasting; + } else if (eqi(a.name, "nodeisprogramentry")) { + info.is_program_entry = true; + } else if (eqi(a.name, "nodeid")) { + if (try l.nodeId(a)) |id| info.id = id; + } else if (eqi(a.name, "nodelocalrootargumentstableindex") and a.args.len == 1) { + info.local_root_arguments_table_index = l.attrUint(a.args[0]); + } else if (eqi(a.name, "nodeshareinputof")) { + info.share_input_of = try l.nodeId(a); + } else if (eqi(a.name, "nodedispatchgrid") and a.args.len == 3) { + info.dispatch_grid = .{ l.attrUint(a.args[0]), l.attrUint(a.args[1]), l.attrUint(a.args[2]) }; + } else if (eqi(a.name, "nodemaxdispatchgrid") and a.args.len == 3) { + info.max_dispatch_grid = .{ l.attrUint(a.args[0]), l.attrUint(a.args[1]), l.attrUint(a.args[2]) }; + } else if (eqi(a.name, "nodemaxrecursiondepth") and a.args.len == 1) { + info.max_recursion_depth = l.attrUint(a.args[0]); + } + } + var inputs: std.ArrayList(ir.NodeIo) = .empty; + var outputs: std.ArrayList(ir.NodeIo) = .empty; + var out_names: std.ArrayList([]const u8) = .empty; + // MaxRecordsSharedWith names a later output too: resolved after. + var shared: std.ArrayList(struct { out: usize, name: []const u8 }) = .empty; + for (f.decl.params, f.params) |pd, p| { + const nt = switch (l.s.types.get(p.type)) { + .node => |x| x, + else => continue, + }; + var io: ir.NodeIo = .{ .kind = nt.kind, .record = nt.elem }; + if (pd.quals.globallycoherent) io.extra_flags |= 0x200; + if (nt.elem != TypeTable.void_type and l.trackRwInputSharing(nt.elem)) io.extra_flags |= 0x100; + if (!nt.kind.isInput()) io.output_id = .{ .name = pd.name }; + for (pd.attrs) |a| { + if (eqi(a.name, "maxrecords") and a.args.len == 1) { + io.max_records = l.attrUint(a.args[0]); + } else if (eqi(a.name, "nodeid")) { + if (try l.nodeId(a)) |id| io.output_id = id; + } else if (eqi(a.name, "nodearraysize") and a.args.len == 1) { + io.array_size = l.attrUint(a.args[0]); + } else if (eqi(a.name, "unboundedsparsenodes")) { + io.array_size = std.math.maxInt(u32); + io.allow_sparse_nodes = true; + } else if (eqi(a.name, "allowsparsenodes")) { + io.allow_sparse_nodes = true; + } else if (eqi(a.name, "maxrecordssharedwith") and a.args.len == 1 and a.args[0].kind == .name) { + try shared.append(l.arena, .{ .out = outputs.items.len, .name = a.args[0].kind.name.last() }); + } + } + if (nt.kind.isInput()) { + try inputs.append(l.arena, io); + } else { + try outputs.append(l.arena, io); + try out_names.append(l.arena, pd.name); + } + } + for (shared.items) |sh| { + for (out_names.items, 0..) |n, k| if (std.mem.eql(u8, n, sh.name)) { + outputs.items[sh.out].max_records_shared_with = @intCast(k); + }; + } + info.inputs = inputs.items; + info.outputs = outputs.items; + return info; + } + + /// `[NodeID("name"[, index])]`, `[NodeShareInputOf(...)]`. + fn nodeId(l: *Lowerer, a: ast.Attribute) Error!?ir.NodeId { + if (a.args.len < 1 or a.args[0].kind != .string_lit) return null; + return .{ .name = try stringContents(l.arena, a.args[0].kind.string_lit), .index = if (a.args.len > 1) l.attrUint(a.args[1]) else 0 }; + } + + fn attrUint(l: *Lowerer, e: *const ast.Expr) u32 { + return @intCast(std.math.clamp(l.s.evalInt(e) orelse 0, 0, std.math.maxInt(u32))); + } + + /// A record struct declared `[NodeTrackRWInputSharing]`. + fn trackRwInputSharing(l: *Lowerer, record: TypeId) bool { + const info = switch (l.s.types.get(record)) { + .@"struct" => |s| s, + else => return false, + }; + return l.s.structHasAttr(info, "nodetrackrwinputsharing"); + } + 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, .ext = try l.spirvExt(f.decl.attrs) }; @@ -2461,14 +2585,25 @@ const Lowerer = struct { } }; if (opts.stage == .amplification) entry.mesh.payload = l.mesh_payload; + if (opts.stage == .node) entry.node = try l.nodeInfo(f); 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; + var node_in: u32 = 0; + var node_out: u32 = 0; for (f.decl.params, f.params, 0..) |pd, p, i| { if (l.s.types.get(p.type) == .stream) continue; n_args += 1; const q = pd.quals; + if (l.s.types.get(p.type) == .node) { + const output = !l.s.types.get(p.type).node.kind.isInput(); + const index = if (output) node_out else node_in; + if (output) node_out += 1 else node_in += 1; + args[i] = try l.b.add(.{ .op = .{ .node_io = .{ .output = output, .index = index } }, .ty = p.type }); + locals[i] = args[i]; + continue; + } if (opts.stage == .mesh and (q.vertices or q.indices or q.primitives) and l.s.types.get(p.type) == .array) { // Output arrays: stores through them write the outputs. const arr = l.s.types.get(p.type).array; @@ -2844,6 +2979,7 @@ fn signExtend(v: u64, bits: u8) i64 { /// Whether `e` designates storage (a variable, or a part of one) rather /// than a temporary such as an operator call's result. fn isAddressable(s: *const Sema, e: *const ast.Expr) bool { + if (s.resolution(e)) |r| if (r == .node_record) return true; return switch (e.kind) { .name, .this => true, .member => |m| isAddressable(s, m.base), diff --git a/src/ir/opt.zig b/src/ir/opt.zig index def9e96..d135021 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -181,7 +181,7 @@ fn mapRefs(a: Allocator, xs: []const Ref, ctx: anytype) Allocator.Error![]const /// `op` with every operand passed through `ctx.map`. pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { return switch (op) { - .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => op, + .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef, .node_io => 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) } }, @@ -227,7 +227,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { /// allocating. pub fn eachOperand(op: Op, ctx: anytype) void { switch (op) { - .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef => {}, + .constant, .param, .global, .local_var, .input, .input_vertex, .emit, .cut, .patch_input, .output_vertex, .mesh_output, .mesh_payload, .ray_incoming, .spec_constant, .undef, .node_io => {}, .load => |p| ctx.use(p), .store => |x| { ctx.use(x.ptr); diff --git a/src/sema/intrinsics.zig b/src/sema/intrinsics.zig index a00d7d7..415c6e5 100644 --- a/src/sema/intrinsics.zig +++ b/src/sema/intrinsics.zig @@ -221,6 +221,7 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: [] .resource => |r| r.elem, .stream => |s| s.elem, .patch => |p| p.elem, + .node => |x| x.elem, else => TypeTable.error_type, } else TypeTable.error_type; @@ -321,6 +322,12 @@ fn paramType( // Non-numeric classes. const base = if (cs.special == .none) cs.base else s.base; + // NodeOutput's Get{Thread,Group}NodeOutputRecords: records of the + // output's record type. + if (i == 0 and obj_elem != TypeTable.error_type) { + const records: ?types.NodeKind = if (std.mem.eql(u8, base, "ThreadNodeOutputRecords")) .thread_output_records else if (std.mem.eql(u8, base, "GroupNodeOutputRecords")) .group_output_records else null; + if (records) |k| return try t.intern(.{ .node = .{ .kind = k, .elem = obj_elem } }); + } if (!std.mem.eql(u8, base, "void") and !isNumericClass(base)) { // Objects (samplers are checked) and classes zdxc does not model // (HitObject, node records, LinAlg...): unconstrained. diff --git a/src/sema/sema.zig b/src/sema/sema.zig index e09ab50..9fa2d52 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -89,6 +89,9 @@ pub const Resolution = union(enum) { /// A bitfield member (`this_bitfield`: named without `this.`). bitfield: types.Bitfield, this_bitfield: types.Bitfield, + /// A node object's record: `Get()`, `Get(i)` or `[i]` (lowered as an + /// element of the object). + node_record, }; pub const Param = struct { @@ -1352,6 +1355,18 @@ pub const Sema = struct { // Any other builtin object (RayQuery, node records, vk:: types...). // vk::ext_result_id: a T (an inline instruction's result). if (eql(n, "ext_result_id") and args.len == 1) return try s.typeArg(args[0]) orelse TypeTable.error_type; + // Work graph node objects: their record type. + if (types.NodeKind.named(n)) |kind| { + var elem: TypeId = TypeTable.void_type; + if (kind.templated()) { + if (args.len == 0) { + s.err(t.loc, "'{s}' requires a record type template argument", .{n}); + return TypeTable.error_type; + } + elem = try s.typeArg(args[0]) orelse return TypeTable.error_type; + } + return s.types.intern(.{ .node = .{ .kind = kind, .elem = elem } }); + } if (isOtherBuiltinObject(n)) { var elem: TypeId = TypeTable.void_type; if (eql(n, "RayQuery")) { @@ -1548,6 +1563,15 @@ pub const Sema = struct { // ------------------------------------------------------------------ // Constant evaluation (array sizes, case labels, template arguments) + /// Whether struct `info` was declared with attribute `name` (any case). + pub fn structHasAttr(s: *const Sema, info: *const types.StructInfo, name: []const u8) bool { + _ = s; + const ss: *const StructSema = @ptrCast(@alignCast(info.sema orelse return false)); + if (ss.decl.kind != .@"struct") return false; + for (ss.decl.kind.@"struct".attrs) |a| if (std.ascii.eqlIgnoreCase(a.name, name)) return true; + return false; + } + pub fn evalInt(s: *Sema, e: *const ast.Expr) ?i64 { return switch (s.evalConst(e) orelse return null) { .int => |v| v, @@ -2166,6 +2190,13 @@ pub const Sema = struct { if (last_shader) |kept| { if (!eql(kept, stage)) s.err(a.loc, "shader attribute type '{s}' conflicts with shader attribute type '{s}'", .{ stage, kept }); } else last_shader = stage; + } else if (std.ascii.eqlIgnoreCase(a.name, "nodelaunch") and a.args.len == 1 and a.args[0].kind == .string_lit) { + // (Exactly these: dxc compares case-sensitively.) + const lit = a.args[0].kind.string_lit; + const v = if (lit.len >= 2) lit[1 .. lit.len - 1] else lit; + if (!eql(v, "broadcasting") and !eql(v, "coalescing") and !eql(v, "thread")) { + s.err(a.args[0].loc, "attribute 'NodeLaunch' must have one of these values: broadcasting,coalescing,thread", .{}); + } } else if (std.ascii.eqlIgnoreCase(a.name, "wavesize")) { if (last_wavesize) |kept| { var same = kept.args.len == a.args.len; @@ -3554,6 +3585,17 @@ pub const Sema = struct { return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } }; }, .stream, .patch => return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } }, + .node => |x| { + // Get: the record (records objects); the rest from the + // intrinsics table. + const known = (eql(name, "Get") and x.kind.hasRecords()) or + if (methodNamespace(s.types.get(b.ty))) |ns| s.intrinsic_db.hasMethod(ns, name) else false; + if (!known) { + s.err(name_loc, "no member named '{s}' in '{s}'", .{ name, s.typeName(b.ty) }); + return err_typed; + } + return .{ .ty = TypeTable.error_type, .callee = .{ .method = .{ .object = b.ty, .name = name, .object_lvalue = b.lvalue } } }; + }, else => { s.err(name_loc, "member reference base type '{s}' is not a structure", .{s.typeName(b.ty)}); return err_typed; @@ -3597,6 +3639,16 @@ pub const Sema = struct { }; return .{ .ty = try s.types.vector(m.elem, m.cols), .lvalue = b.lvalue, .read_only = b.read_only }; }, + .node => |x| { + // Records of a records array; an output of an outputs array. + if (x.kind.isArray()) { + s.record(e, .node_record); + return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() }; + } + if (x.kind.outputElement()) |k| return rvalue(try s.types.intern(.{ .node = .{ .kind = k, .elem = x.elem } })); + s.err(e.loc, "type '{s}' does not provide a subscript operator", .{s.typeName(b.ty)}); + return err_typed; + }, .resource => |r| { if (r.kind.indexDims() == 0 or r.elem == TypeTable.void_type) { if (r.kind == .other) return err_typed; @@ -3724,6 +3776,25 @@ pub const Sema = struct { if (sym != .functions) return err_typed; return rvalue(s.resolveUserCall(e, sym.functions, arg_types, callee)); }, + .node => |x| if (eql(m.name, "Get")) { + // The record (`Get(i)`: of several). + const most: usize = if (x.kind.isArray()) 1 else 0; + if (arg_types.len > most) { + s.err(e.loc, "too many arguments to function call, expected at most {d}, have {d}", .{ most, arg_types.len }); + return err_typed; + } + if (arg_types.len == 1 and s.conversionCost(arg_types[0].ty, try s.types.scalar(.uint)) == null) { + s.err(e.loc, "no matching member function for call to 'Get'", .{}); + return err_typed; + } + s.record(e, .node_record); + return .{ .ty = x.elem, .lvalue = true, .read_only = !x.kind.writable() }; + } else { + const ns = methodNamespace(s.types.get(m.object)) orelse return err_typed; + const r = try s.intrinsic_db.resolve(s, e.loc, ns, m.name, m.object, arg_types, null); + if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params, .object = m.object } }); + return rvalue(r.ret); + }, else => { var explicit: ?TypeId = null; if (template_args.len > 0) explicit = try s.typeArg(template_args[0]); @@ -4328,6 +4399,15 @@ fn methodNamespace(t: types.Type) ?[]const u8 { .constant_buffer, .texture_buffer, .raytracing_acceleration_structure => null, .other => if (std.mem.eql(u8, r.name, "RayQuery")) "RayQueryMethods" else if (std.mem.eql(u8, r.name, "SubpassInput")) "VkSubpassInputMethods" else if (std.mem.eql(u8, r.name, "SubpassInputMS")) "VkSubpassInputMSMethods" else null, }, + .node => |x| switch (x.kind) { + .empty_input => "EmptyNodeInputMethods", + .rw_dispatch_input => "RWDispatchNodeInputRecordMethods", + .group_input, .rw_group_input => "GroupNodeInputRecordsMethods", + .output => "NodeOutputMethods", + .empty_output => "EmptyNodeOutputMethods", + .thread_output_records, .group_output_records => "GroupOrThreadNodeOutputRecordsMethods", + else => null, + }, else => null, }; } diff --git a/src/sema/types.zig b/src/sema/types.zig index 839484a..05fe61b 100644 --- a/src/sema/types.zig +++ b/src/sema/types.zig @@ -527,6 +527,110 @@ pub const Type = union(enum) { /// `__builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(c, m, n, use, /// scope)]]` (SM 6.10): an opaque matrix handle. linalg: LinAlgMatrix, + /// A work graph node input, output or output record object + /// (`DispatchNodeInputRecord`, `NodeOutput`, ...): `elem` is the + /// record type (void for the empty ones). + node: struct { kind: NodeKind, elem: TypeId }, +}; + +/// Work graph node object types, as DXC's NodeIOKind. +pub const NodeKind = enum { + dispatch_input, + rw_dispatch_input, + group_input, + rw_group_input, + thread_input, + rw_thread_input, + empty_input, + output, + output_array, + empty_output, + empty_output_array, + thread_output_records, + group_output_records, + + pub const names = [_]struct { []const u8, NodeKind }{ + .{ "DispatchNodeInputRecord", .dispatch_input }, .{ "RWDispatchNodeInputRecord", .rw_dispatch_input }, + .{ "GroupNodeInputRecords", .group_input }, .{ "RWGroupNodeInputRecords", .rw_group_input }, + .{ "ThreadNodeInputRecord", .thread_input }, .{ "RWThreadNodeInputRecord", .rw_thread_input }, + .{ "EmptyNodeInput", .empty_input }, .{ "NodeOutput", .output }, + .{ "NodeOutputArray", .output_array }, .{ "EmptyNodeOutput", .empty_output }, + .{ "EmptyNodeOutputArray", .empty_output_array }, .{ "ThreadNodeOutputRecords", .thread_output_records }, + .{ "GroupNodeOutputRecords", .group_output_records }, + }; + + pub fn named(n: []const u8) ?NodeKind { + for (names) |e| if (std.mem.eql(u8, e[0], n)) return e[1]; + return null; + } + + pub fn name(k: NodeKind) []const u8 { + for (names) |e| if (e[1] == k) return e[0]; + unreachable; + } + + /// NodeIOFlags: input 0x1, output 0x2, read-write 0x4, empty 0x8, + /// array 0x10; record granularity thread 0x20, group 0x40, dispatch + /// 0x60. + pub fn ioFlags(k: NodeKind) u32 { + return switch (k) { + .dispatch_input => 0x61, + .rw_dispatch_input => 0x65, + .group_input => 0x41, + .rw_group_input => 0x45, + .thread_input => 0x21, + .rw_thread_input => 0x25, + .empty_input => 0x9, + .output => 0x6, + .output_array => 0x16, + .empty_output => 0xA, + .empty_output_array => 0x1A, + .thread_output_records => 0x26, + .group_output_records => 0x46, + }; + } + + pub fn isInput(k: NodeKind) bool { + return k.ioFlags() & 1 != 0; + } + + /// Objects holding records (Get and, for the group ones, indexing). + pub fn hasRecords(k: NodeKind) bool { + return switch (k) { + .dispatch_input, .rw_dispatch_input, .group_input, .rw_group_input, .thread_input, .rw_thread_input, .thread_output_records, .group_output_records => true, + else => false, + }; + } + + /// Several records: `Get(i)` and `[i]` (dxc's IsArray). + pub fn isArray(k: NodeKind) bool { + return switch (k) { + .group_input, .rw_group_input, .thread_output_records, .group_output_records => true, + else => false, + }; + } + + /// An array of outputs: `[i]` is one. + pub fn outputElement(k: NodeKind) ?NodeKind { + return switch (k) { + .output_array => .output, + .empty_output_array => .empty_output, + else => null, + }; + } + + /// Records that may be written. + pub fn writable(k: NodeKind) bool { + return k.ioFlags() & 4 != 0 and k.hasRecords(); + } + + /// Whether the type takes a record type argument. + pub fn templated(k: NodeKind) bool { + return switch (k) { + .empty_input, .empty_output, .empty_output_array => false, + else => true, + }; + } }; pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u32 }; @@ -597,6 +701,7 @@ pub const TypeTable = struct { .texture_view => |v| .{ .tag = 14, .a = v.texture, .b = @backingInt(v.kind) }, .linalg => |x| .{ .tag = 16, .a = (@as(u64, x.comp) << 32) | x.m, .b = (@as(u64, x.n) << 32) | (@as(u64, x.use) << 16) | x.scope }, .spirv => |x| .{ .tag = 15, .a = (@as(u64, x.opcode) << 32) | x.size, .b = std.hash.Wyhash.hash(x.alignment, std.mem.sliceAsBytes(x.operands)) }, + .node => |x| .{ .tag = 17, .a = @backingInt(x.kind), .b = x.elem }, }; } @@ -778,6 +883,7 @@ pub const TypeTable = struct { .triangle => "TriangleStream", }, try t.format(gpa, s.elem), ""), .patch => |p| templateName(gpa, if (p.output) "OutputPatch" else "InputPatch", try t.format(gpa, p.elem), try std.fmt.allocPrint(gpa, ", {d}", .{p.count})), + .node => |x| if (x.kind.templated()) templateName(gpa, x.kind.name(), try t.format(gpa, x.elem), "") else x.kind.name(), .descriptor_heap => |h| if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap", .dynamic_resource => "", .texture_view => |v| std.fmt.allocPrint(gpa, "{s}::{s}", .{ try t.format(gpa, v.texture), switch (v.kind) { diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index d250bf1..c64105c 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -1089,6 +1089,7 @@ const Emitter = struct { .miss => 5317, .callable => 5318, .library => return e.unsupported("library targets are not supported", .{}), + .node => return e.unsupported("work graph nodes are not supported in SPIR-V", .{}), }; const wrapper = e.func_ids[entry.wrapper]; const name = if (e.m.entries.items.len == 1) e.vk.entry_name orelse entry.name else entry.name; @@ -2385,6 +2386,7 @@ const Emitter = struct { const ri = r.index(); switch (i.op) { .constant, .param, .local_var => {}, + .node_io => return e.unsupported("work graph nodes are not supported in SPIR-V", .{}), .spec_constant => |k| e.vals[ri] = try e.specConstant(k), .spirv_inst => |x| e.vals[ri] = try e.spirvInst(x, i.ty), .ray_incoming => |k| e.vals[ri] = try e.rayVar(switch (k) {