diff --git a/build.zig b/build.zig index 02ebd01..d281c48 100644 --- a/build.zig +++ b/build.zig @@ -73,6 +73,11 @@ pub fn build(b: *std.Build) void { oracle.setCwd(b.path(".")); oracle.has_side_effects = true; oracle_step.dependOn(&oracle.step); + const dxil_checks = b.addSystemCommand(&.{ "sh", "test/dxil/check.sh" }); + dxil_checks.addArtifactArg(exe); + dxil_checks.setCwd(b.path(".")); + dxil_checks.has_side_effects = true; + oracle_step.dependOn(&dxil_checks.step); const oracle_parse_step = b.step("oracle-parse", "Parse every dxc-valid corpus file with zdxc"); const oracle_parse = b.addSystemCommand(&.{ "sh", "test/oracle/parse.sh" }); diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index c541278..0b84506 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -14,6 +14,7 @@ const shader = @import("shader.zig"); const container = @import("container.zig"); const hash = @import("hash.zig"); const layout = @import("../ir/layout.zig"); +const signature = @import("signature.zig"); const TypeId = types.TypeId; const TypeTable = types.TypeTable; @@ -103,8 +104,23 @@ const Emitter = struct { resources: std.ArrayList(Resource) = .empty, resource_of_global: std.AutoHashMapUnmanaged(u32, u32) = .empty, + private_globals: std.AutoHashMapUnmanaged(u32, Ptr) = .empty, uses_double: bool = false, uses_int64: bool = false, + /// 16-bit min-precision values cross the signature. + uses_min_precision: bool = false, + uses_view_id: bool = false, + uses_inner_coverage: bool = false, + + sig_in: []signature.Element = &.{}, + sig_out: []signature.Element = &.{}, + /// IR entry input / output index -> signature element; null for system + /// values read with an intrinsic instead. + in_elem: []?u32 = &.{}, + out_elem: []?u32 = &.{}, + /// Rows of an SV_Target array split into one element per row (the + /// last row's element comes first, as in dxc); 0 if not split. + out_split: []u32 = &.{}, handle_ty: DType = 0, @@ -172,6 +188,7 @@ const Emitter = struct { } fn compOf(e: *Emitter, ty: TypeId) Scalar { + if (e.t.get(ty) == .array) return e.compOf(e.t.get(ty).array.elem); return storageScalar(e.t.component(ty) orelse .int); } @@ -240,7 +257,10 @@ const Emitter = struct { fn run(e: *Emitter, gpa: Allocator) Error![]u8 { const m = e.m; const entry = m.entry orelse return e.unsupported("no entry point", .{}); - if (entry.stage != .compute) return e.unsupported("only compute shaders are supported yet", .{}); + switch (entry.stage) { + .compute, .vertex, .pixel => {}, + else => return e.unsupported("{s} shaders are not supported yet", .{@tagName(entry.stage)}), + } const void_ty = try e.voidTy(); const fn_ty = try e.dm.fnType(void_ty, &.{}); e.main_fn = try e.dm.addFunction(.{ .name = entry.name, .ty = fn_ty, .num_blocks = 1 }); @@ -248,6 +268,7 @@ const Emitter = struct { e.handle_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.Handle", .elems = &.{i8p} } }); try e.collectResources(); + try e.buildSignatures(entry); e.cur = try e.newBlock(); try e.createHandles(); _ = try e.inlineCall(entry.wrapper, &.{}); @@ -547,7 +568,14 @@ const Emitter = struct { }, .none, .@"unreachable" => _ = try e.add(void_ty, .@"unreachable"), .@"switch" => return e.unsupported("switch", .{}), - .discard => return e.unsupported("discard", .{}), + .discard => { + // Like SPIR-V's OpKill: the invocation stops here. + const i32t = try e.dm.intType(32); + const i1t = try e.dm.intType(1); + const fn_i = try e.dxOp("dx.op.discard", void_ty, &.{ i32t, i1t }, .nounwind); + _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(82), try e.dm.constInt(1, 1) }); + _ = try e.add(void_ty, .{ .ret = null }); + }, } } @@ -558,6 +586,23 @@ const Emitter = struct { }; } + /// Flattened storage for a value of type `ty`, allocated on entry. + fn alloca(e: *Emitter, ty: TypeId) Error!Ptr { + const n = try e.flatCount(ty); + if (try e.mixedStorage(ty)) { + const st = try e.dm.intType(32); + const arr = try e.dm.getType(.{ .array = .{ .len = n, .elem = st } }); + const base = try e.addPrologue(try e.dm.ptrType(arr), .{ .alloca = .{ .elem = arr, .size = try e.i32Const(1) } }); + return .{ .base = base, .array_ty = arr, .scalar_ty = st, .mixed = true }; + } + const c = try e.uniformScalar(ty); + const store_c = if (c == .bool) Scalar.int else c; + const st = try e.scalarTy(store_c); + const arr = try e.dm.getType(.{ .array = .{ .len = n, .elem = st } }); + const base = try e.addPrologue(try e.dm.ptrType(arr), .{ .alloca = .{ .elem = arr, .size = try e.i32Const(1) } }); + return .{ .base = base, .array_ty = arr, .scalar_ty = st, .bool_storage = c == .bool }; + } + fn list(e: *Emitter, vals: []const Value) Error!Lowered { return .{ .scalars = try e.arena.dupe(Value, vals) }; } @@ -569,26 +614,18 @@ const Emitter = struct { .constant => |c| return e.list(&.{try e.constant(i.ty, c)}), .param => |p| return frame.params[p], .global => |g| { + // Static globals live in the entry function (everything is + // inlined into it). + if (e.m.globals.items[g].space == .private) { + const gop = try e.private_globals.getOrPut(e.arena, g); + if (!gop.found_existing) gop.value_ptr.* = try e.alloca(e.m.globals.items[g].ty); + return .{ .ptr = gop.value_ptr.* }; + } const ri = e.resource_of_global.get(g) orelse return e.unsupported("global '{s}' is not supported yet", .{e.m.globals.items[g].name}); if (e.resources.items[ri].class == .cbuffer) return .{ .cbuf = .{ .res = ri } }; return .{ .handle = ri }; }, - .local_var => { - const n = try e.flatCount(i.ty); - if (try e.mixedStorage(i.ty)) { - const st = try e.dm.intType(32); - const arr = try e.dm.getType(.{ .array = .{ .len = n, .elem = st } }); - const base = try e.addPrologue(try e.dm.ptrType(arr), .{ .alloca = .{ .elem = arr, .size = try e.i32Const(1) } }); - return .{ .ptr = .{ .base = base, .array_ty = arr, .scalar_ty = st, .mixed = true } }; - } - const c = try e.uniformScalar(i.ty); - const store_c = if (c == .bool) Scalar.int else c; - const st = try e.scalarTy(store_c); - const arr = try e.dm.getType(.{ .array = .{ .len = n, .elem = st } }); - const ptr_ty = try e.dm.ptrType(arr); - const base = try e.addPrologue(ptr_ty, .{ .alloca = .{ .elem = arr, .size = try e.i32Const(1) } }); - return .{ .ptr = .{ .base = base, .array_ty = arr, .scalar_ty = st, .bool_storage = c == .bool } }; - }, + .local_var => return .{ .ptr = try e.alloca(i.ty) }, .load => |p| switch (frame.vals[p.index()]) { .handle => |h| return .{ .handle = h }, .cbuf => |c| return e.cbufferLoad(c.res, c.offset, c.dyn_regs, c.row_major, i.ty), @@ -766,7 +803,10 @@ const Emitter = struct { }, .method => |x| return e.unsupported("method '{s}' is not supported yet", .{x.name}), .input => |k| return e.input(k, i.ty), - .output => return e.unsupported("stage outputs are not supported yet", .{}), + .output => |o| { + try e.output(frame, o.element, o.value); + return .none; + }, .phi => return e.unsupported("phi", .{}), } } @@ -802,7 +842,8 @@ const Emitter = struct { }; return switch (s) { .bool => e.dm.constant(.{ .ty = dt, .kind = .{ .int = @intFromBool(iv != 0) } }), - .float => e.dm.constant(.{ .ty = dt, .kind = .{ .float_bits = @as(u64, @bitCast(@as(f64, @as(f32, @floatCast(fv))))) } }), + // Bitcode stores a float constant as its own 32-bit pattern. + .float => e.dm.constant(.{ .ty = dt, .kind = .{ .float_bits = @as(u32, @bitCast(@as(f32, @floatCast(fv)))) } }), .double => e.dm.constant(.{ .ty = dt, .kind = .{ .float_bits = @bitCast(fv) } }), .float16 => e.dm.constant(.{ .ty = dt, .kind = .{ .float_bits = @as(u16, @bitCast(@as(f16, @floatCast(fv)))) } }), .uint, .uint16 => e.dm.constant(.{ .ty = dt, .kind = .{ .int = signExtend(iv, s.size()) } }), @@ -1126,6 +1167,42 @@ const Emitter = struct { _ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(80), try e.i32Const(flags) }); return .none; } + const Deriv = struct { name: []const u8, op: i64 }; + const derivs = [_]Deriv{ + .{ .name = "ddx", .op = 83 }, .{ .name = "ddx_coarse", .op = 83 }, .{ .name = "ddy", .op = 84 }, + .{ .name = "ddy_coarse", .op = 84 }, .{ .name = "ddx_fine", .op = 85 }, .{ .name = "ddy_fine", .op = 86 }, + }; + const is_deriv = eq(u8, name, "fwidth") or for (derivs) |d| { + if (eq(u8, name, d.name)) break true; + } else false; + if (is_deriv and e.m.entry.?.stage != .pixel) return e.unsupported("derivatives outside pixel shaders are not supported yet", .{}); + for (derivs) |d| if (eq(u8, name, d.name)) { + for (out, 0..) |*o, k| o.* = try e.unaryOp(d.op, "unary", a[0][k], at); + return .{ .scalars = out }; + }; + if (eq(u8, name, "fwidth")) { + // abs(ddx(x)) + abs(ddy(x)), coarse, as dxc. + for (out, 0..) |*o, k| { + const dx = try e.unaryOp(6, "unary", try e.unaryOp(83, "unary", a[0][k], at), at); + const dy = try e.unaryOp(6, "unary", try e.unaryOp(84, "unary", a[0][k], at), at); + o.* = try e.add(at, .{ .binop = .{ .op = .add, .lhs = dx, .rhs = dy } }); + } + return .{ .scalars = out }; + } + if (eq(u8, name, "clip")) { + // discard(any(x < 0)). + const i1t = try e.dm.intType(1); + const zero = try e.constant(try e.t.scalar(ac), .{ .float = 0 }); + var cond: ?Value = null; + for (a[0]) |x| { + const lt = try e.add(i1t, .{ .cmp = .{ .pred = 4, .lhs = x, .rhs = zero } }); // fcmp olt + cond = if (cond) |c| try e.add(i1t, .{ .binop = .{ .op = .@"or", .lhs = c, .rhs = lt } }) else lt; + } + const i32t = try e.dm.intType(32); + const fn_i = try e.dxOp("dx.op.discard", try e.voidTy(), &.{ i32t, i1t }, .nounwind); + _ = try e.callOp(fn_i, try e.voidTy(), &.{ try e.i32Const(82), cond.? }); + return .none; + } return e.unsupported("intrinsic '{s}' is not supported yet", .{name}); } @@ -1467,7 +1544,249 @@ 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 }, + else => .{ null, null }, + }; + e.in_elem = try e.arena.alloc(?u32, entry.inputs.items.len); + @memset(e.in_elem, null); + e.out_elem = try e.arena.alloc(?u32, entry.outputs.items.len); + @memset(e.out_elem, null); + e.out_split = try e.arena.alloc(u32, entry.outputs.items.len); + @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); + } + + fn buildSignature(e: *Emitter, els: []const ir.SigElement, sp: signature.SigPoint, map: []?u32, split: ?[]u32) Error![]signature.Element { + var out: std.ArrayList(signature.Element) = .empty; + for (els, 0..) |el, k| { + const kind = signature.kindByName(el.semantic); + if (kind == .invalid) return e.unsupported("semantic '{s}' is not supported yet", .{el.semantic}); + const interp = signature.interpretation(kind, sp, e.profile.minor); + switch (interp) { + .na => return e.unsupported("semantic '{s}' is not supported as this {s} yet", .{ el.semantic, if (sp.isInput()) "input" else "output" }), + .not_in_sig => continue, + else => {}, + } + const shape = try e.sigShape(el.ty, el.row_major); + var comp = try e.sigCompType(el.ty); + if (kind == .is_front_face and comp == .i1) comp = .u32; + if (comp == .f16 or comp == .i16 or comp == .u16) e.uses_min_precision = true; + const eff_kind: signature.SemanticKind = if (interp == .arb) .arbitrary else kind; + map[k] = @intCast(out.items.len); + if (kind == .target and shape.rows > 1) { + // One element per render target, last first (as dxc). + split.?[k] = shape.rows; + var r = shape.rows; + while (r > 0) { + r -= 1; + try out.append(e.arena, .{ + .id = @intCast(out.items.len), + .name = signature.canonicalName(kind), + .kind = kind, + .interpretation = interp, + .comp = comp, + .interp = .undefined, + .rows = 1, + .cols = shape.cols, + .indices = try e.arena.dupe(u32, &.{el.semantic_index + r}), + }); + } + continue; + } + const indices = try e.arena.alloc(u32, shape.rows); + for (indices, 0..) |*x, i| x.* = el.semantic_index + @as(u32, @intCast(i)); + try out.append(e.arena, .{ + .id = @intCast(out.items.len), + .name = if (eff_kind == .arbitrary) el.semantic else signature.canonicalName(eff_kind), + .kind = eff_kind, + .interpretation = interp, + .comp = comp, + .interp = interpMode(el.interp, sp, comp, eff_kind), + .rows = shape.rows, + .cols = shape.cols, + .indices = indices, + }); + } + signature.pack(e.arena, out.items, sp) catch |err| switch (err) { + error.SignatureFull => return e.unsupported("the signature does not fit in 32 registers", .{}), + error.OutOfMemory => return error.OutOfMemory, + }; + return out.items; + } + + /// The interpolation mode of an element: the written modifiers, else + /// linear for floats and constant for the rest; SV_Position never + /// interpolates with perspective. + fn interpMode(q: types.Interp, sp: signature.SigPoint, comp: signature.CompType, kind: signature.SemanticKind) signature.InterpMode { + if (sp == .vs_in or sp == .ps_out) return .undefined; + var m: signature.InterpMode = if (q.nointerpolation) + .constant + else if (q.sample) + (if (q.noperspective) .linear_noperspective_sample else .linear_sample) + else if (q.centroid) + (if (q.noperspective) .linear_noperspective_centroid else .linear_centroid) + else if (q.noperspective) + .linear_noperspective + else if (q.linear or comp.isFloat()) + .linear + else + .constant; + if (kind == .position) m = switch (m) { + .linear => .linear_noperspective, + .linear_centroid => .linear_noperspective_centroid, + .linear_sample => .linear_noperspective_sample, + else => m, + }; + return m; + } + + const Shape = struct { rows: u32, cols: u32 }; + + /// Rows and columns a signature element occupies. + fn sigShape(e: *Emitter, ty: TypeId, row_major: bool) Error!Shape { + return switch (e.t.get(ty)) { + .scalar, .@"enum" => .{ .rows = 1, .cols = 1 }, + .vector => |v| .{ .rows = 1, .cols = v.len }, + .matrix => |m| if (row_major) .{ .rows = m.rows, .cols = m.cols } else .{ .rows = m.cols, .cols = m.rows }, + .array => |a| blk: { + const s = try e.sigShape(a.elem, row_major); + break :blk .{ .rows = s.rows * a.len, .cols = s.cols }; + }, + else => e.unsupported("signature elements of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), + }; + } + + /// Row and column (within its element) of flattened component `k`. + fn sigComponent(e: *Emitter, ty: TypeId, row_major: bool, k: u32) Error![2]u32 { + switch (e.t.get(ty)) { + .vector => return .{ 0, k }, + .matrix => |m| { + const r = k / m.cols; + const c = k % m.cols; + return if (row_major) .{ r, c } else .{ c, r }; + }, + .array => |a| { + const n = try e.flatCount(a.elem); + const s = try e.sigShape(a.elem, row_major); + const inner = try e.sigComponent(a.elem, row_major, k % n); + return .{ (k / n) * s.rows + inner[0], inner[1] }; + }, + else => return .{ 0, 0 }, + } + } + + fn sigCompType(e: *Emitter, ty: TypeId) Error!signature.CompType { + if (e.t.get(ty) == .array) return e.sigCompType(e.t.get(ty).array.elem); + const s = e.t.component(ty) orelse return e.unsupported("signature elements of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}); + return switch (s) { + .bool => .i1, + .int, .literal_int => .i32, + .uint => .u32, + .float, .half, .literal_float => .f32, + .min16float, .min10float => .f16, + .min16int, .min12int => .i16, + .min16uint => .u16, + else => e.unsupported("signature elements of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), + }; + } + + /// The scalar a signature component travels as. + fn sigScalar(c: signature.CompType) Scalar { + return switch (c) { + .f32 => .float, + .f16 => .float16, + .i16 => .int16, + .u16 => .uint16, + .i32 => .int, + else => .uint, + }; + } + + /// A system value read with its own intrinsic (not a loadInput). + fn systemValueInput(e: *Emitter, semantic: []const u8, ty: TypeId) Error!Lowered { + const kind = signature.kindByName(semantic); + const i32t = try e.dm.intType(32); + const Sv = struct { kind: signature.SemanticKind, op: i64, fname: []const u8 }; + const svs = [_]Sv{ + .{ .kind = .sample_index, .op = 90, .fname = "dx.op.sampleIndex.i32" }, + .{ .kind = .coverage, .op = 91, .fname = "dx.op.coverage.i32" }, + .{ .kind = .inner_coverage, .op = 92, .fname = "dx.op.innerCoverage.i32" }, + .{ .kind = .view_id, .op = 138, .fname = "dx.op.viewID.i32" }, + .{ .kind = .start_vertex_location, .op = 256, .fname = "dx.op.startVertexLocation.i32" }, + .{ .kind = .start_instance_location, .op = 257, .fname = "dx.op.startInstanceLocation.i32" }, + }; + const out = try e.arena.alloc(Value, try e.flatCount(ty)); + if (kind == .cull_primitive) { + for (out) |*o| o.* = try e.constant(try e.t.scalar(e.compOf(ty)), .{ .int = 0 }); + return .{ .scalars = out }; + } + if (kind == .view_id) e.uses_view_id = true; + if (kind == .inner_coverage) e.uses_inner_coverage = true; + 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)}); + for (out) |*o| o.* = try e.convertScalar(v, .uint, e.compOf(ty)); + return .{ .scalars = out }; + }; + return e.unsupported("input '{s}' is not supported yet", .{semantic}); + } + fn input(e: *Emitter, k: u32, ty: TypeId) Error!Lowered { + const entry = e.m.entry.?; + if (entry.stage == .compute) 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); + 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.loadInput.{s}", .{e.overloadName(vt)}), vt, &.{ i32t, i32t, i32t, i8t, i32t }, .nounwind_readnone); + const undef = try e.dm.constant(.{ .ty = i32t, .kind = .undef }); + const out = try e.arena.alloc(Value, try e.flatCount(ty)); + const to = e.compOf(ty); + for (out, 0..) |*o, c| { + const rc = try e.sigComponent(el.ty, el.row_major, @intCast(c)); + const v = try e.callOp(fn_i, vt, &.{ try e.i32Const(4), try e.i32Const(se.id), try e.i32Const(rc[0]), try e.dm.constInt(8, rc[1]), undef }); + o.* = try e.convertScalar(v, via, to); + se.usage |= @as(u8, 1) << @intCast(rc[1]); + } + return .{ .scalars = out }; + } + + fn output(e: *Emitter, frame: *Frame, k: u32, value: Ref) Error!void { + 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 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.storeOutput.{s}", .{e.overloadName(vt)}), void_ty, &.{ i32t, i32t, i32t, i8t, vt }, .nounwind); + const from = e.compOf(el.ty); + const split = e.out_split[k]; + for (vals, 0..) |v, c| { + var rc = try e.sigComponent(el.ty, el.row_major, @intCast(c)); + var target = se; + if (split > 0) { + target = &e.sig_out[se.id + split - 1 - rc[0]]; + rc[0] = 0; + } + const sv = try e.convertScalar(v, from, via); + _ = try e.callOp(fn_i, void_ty, &.{ try e.i32Const(5), try e.i32Const(target.id), try e.i32Const(rc[0]), try e.dm.constInt(8, rc[1]), sv }); + target.usage |= @as(u8, 1) << @intCast(rc[1]); + } + } + + fn computeInput(e: *Emitter, k: u32, ty: TypeId) Error!Lowered { const el = e.m.entry.?.inputs.items[k]; const eqi = std.ascii.eqlIgnoreCase; const i32t = try e.dm.intType(32); @@ -1503,6 +1822,7 @@ const Emitter = struct { var flags: u64 = 0; if (e.uses_double) flags |= 1 << 2; if (e.uses_int64) flags |= 1 << 20; + if (e.uses_min_precision) flags |= 1 << 5; var uavs: u32 = 0; for (e.resources.items) |r| { if (r.kind == 11 or r.kind == 12) flags |= 1 << 4; @@ -1511,9 +1831,38 @@ const Emitter = struct { if (uavs > 8) flags |= 1 << 15; // Resources may not alias (DXIL 1.7+, when UAVs are used). if (uavs > 0 and e.profile.minor >= 7) flags |= 1 << 33; + const stage = e.m.entry.?.stage; + if (uavs > 0 and (stage == .vertex or stage == .geometry or stage == .hull or stage == .domain)) flags |= 1 << 16; + for (e.sig_out) |el| switch (el.kind) { + .render_target_array_index, .viewport_array_index => if (stage == .vertex) { + flags |= 1 << 9; + }, + .stencil_ref => flags |= 1 << 11, + .shading_rate => flags |= 1 << 24, + else => {}, + }; + for (e.sig_in) |el| if (el.kind == .shading_rate) { + flags |= 1 << 24; + }; + if (e.uses_view_id) flags |= 1 << 21; + if (e.uses_inner_coverage) flags |= 1 << 10; return flags; } + /// SFI0 feature bits implied by the shader flags. + fn featureInfo(flags: u64) u64 { + const map = [_][2]u64{ + .{ 1 << 2, 0x1 }, .{ 1 << 16, 0x4 }, .{ 1 << 15, 0x8 }, .{ 1 << 5, 0x10 }, + .{ 1 << 11, 0x200 }, .{ 1 << 10, 0x400 }, .{ 1 << 9, 0x2000 }, .{ 1 << 20, 0x8000 }, + .{ 1 << 21, 0x10000 }, .{ 1 << 24, 0x80000 }, + }; + var f: u64 = 0; + for (map) |m| if (flags & m[0] != 0) { + f |= m[1]; + }; + return f; + } + fn writeModule(e: *Emitter, entry: ir.Entry) Error![]u8 { const dm = &e.dm; const i32t = try dm.intType(32); @@ -1584,12 +1933,18 @@ const Emitter = struct { const i64t = try dm.intType(64); try props.appendSlice(e.arena, &.{ try mdI32(dm, 0), try dm.mdValue(i64t, try dm.constant(.{ .ty = i64t, .kind = .{ .int = @bitCast(flags) } })) }); } - const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) }); - try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads }); - const props_node = try dm.mdNode(props.items); + if (entry.stage == .compute) { + const threads = try dm.mdNode(&.{ try mdI32(dm, entry.num_threads[0]), try mdI32(dm, entry.num_threads[1]), try mdI32(dm, entry.num_threads[2]) }); + try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), threads }); + } + 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 }); + } 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 }); - const entry_md = try dm.mdNode(&.{ fn_ref, try dm.mdString(entry.name), null, resources, props_node }); + const entry_md = try dm.mdNode(&.{ fn_ref, try dm.mdString(entry.name), sigs, resources, props_node }); try dm.addNamedMetadata("llvm.ident", &.{ident}); try dm.addNamedMetadata("dx.version", &.{version}); @@ -1600,6 +1955,31 @@ const Emitter = struct { return dm.writeBitcode(dm.arena.child_allocator); } + /// `!{id, name, comp, kind, !{indices}, interp, rows, cols, row, col, + /// !{usage tag, mask}}` per element. + fn signatureMetadata(e: *Emitter, els: []const signature.Element) Error!?module.MdId { + if (els.len == 0) return null; + const dm = &e.dm; + const i8t = try dm.intType(8); + const nodes = try e.arena.alloc(?module.MdId, els.len); + for (els, nodes) |el, *n| { + const idx = try e.arena.alloc(?module.MdId, el.indices.len); + for (el.indices, idx) |x, *m| m.* = try dm.mdI32(x); + const usage: ?module.MdId = if (el.usage != 0) try dm.mdNode(&.{ try dm.mdI32(3), try dm.mdI32(el.usage) }) else null; + const row: i64 = if (el.start_row) |r| r else -1; + const col: i64 = if (el.start_row != null) el.start_col else -1; + n.* = try dm.mdNode(&.{ + try dm.mdI32(el.id), try dm.mdString(el.name), + try dm.mdValue(i8t, try dm.constInt(8, @intFromEnum(el.comp))), try dm.mdValue(i8t, try dm.constInt(8, @intFromEnum(el.kind))), + try dm.mdNode(idx), try dm.mdValue(i8t, try dm.constInt(8, @intFromEnum(el.interp))), + try dm.mdI32(el.rows), try dm.mdValue(i8t, try dm.constInt(8, el.cols)), + try dm.mdI32(row), try dm.mdValue(i8t, try dm.constInt(8, col)), + usage, + }); + } + return try dm.mdNode(nodes); + } + fn assemble(e: *Emitter, gpa: Allocator, entry: ir.Entry, bitcode: []const u8) Error![]u8 { const dxil_part = try shader.programPart(gpa, e.profile, bitcode); defer gpa.free(dxil_part); @@ -1623,18 +2003,47 @@ const Emitter = struct { }; try binds.append(e.arena, .{ .res_type = res_type, .space = b.space, .lower = b.index, .upper = b.index, .kind = r.kind }); }; - const psv = try shader.psvCompute(gpa, entry.name, entry.num_threads, binds.items); + var stage_info: [16]u8 = @splat(0); + switch (entry.stage) { + .vertex => for (e.sig_out) |el| { + if (el.kind == .position) stage_info[0] = 1; // OutputPositionPresent + }, + .pixel => { + for (e.sig_out) |el| switch (el.kind) { + .depth, .depth_less_equal, .depth_greater_equal => stage_info[0] = 1, // DepthOutput + else => {}, + }; + for (e.sig_in) |el| { + if (el.interp.isAnySample() or el.kind == .sample_index) stage_info[1] = 1; // SampleFrequency + } + }, + else => {}, + } + const kind: shader.ShaderKind = switch (entry.stage) { + .vertex => .vertex, + .pixel => .pixel, + else => .compute, + }; + const psv = try shader.psv(gpa, .{ + .kind = kind, + .entry = entry.name, + .stage_info = stage_info, + .num_threads = if (entry.stage == .compute) entry.num_threads else .{ 0, 0, 0 }, + .resources = binds.items, + .inputs = e.sig_in, + .outputs = e.sig_out, + }); defer gpa.free(psv); - const empty_sig = [_]u8{ 0, 0, 0, 0, 8, 0, 0, 0 }; + const isg1 = try signature.programSignature(gpa, e.sig_in, true); + defer gpa.free(isg1); + const osg1 = try signature.programSignature(gpa, e.sig_out, false); + defer gpa.free(osg1); var sfi0: [8]u8 = @splat(0); - var feature: u64 = 0; - if (e.uses_double) feature |= 0x1; - if (e.uses_int64) feature |= 0x8000; - std.mem.writeInt(u64, &sfi0, feature, .little); + std.mem.writeInt(u64, &sfi0, featureInfo(e.shaderFlags()), .little); const parts = [_]container.Part{ .{ .fourcc = container.fourcc("SFI0"), .data = &sfi0 }, - .{ .fourcc = container.fourcc("ISG1"), .data = &empty_sig }, - .{ .fourcc = container.fourcc("OSG1"), .data = &empty_sig }, + .{ .fourcc = container.fourcc("ISG1"), .data = isg1 }, + .{ .fourcc = container.fourcc("OSG1"), .data = osg1 }, .{ .fourcc = container.fourcc("PSV0"), .data = psv }, .{ .fourcc = container.fourcc("DXIL"), .data = dxil_part }, }; diff --git a/src/dxil/shader.zig b/src/dxil/shader.zig index b5fe5f7..6c5b43f 100644 --- a/src/dxil/shader.zig +++ b/src/dxil/shader.zig @@ -5,6 +5,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const Module = @import("module.zig").Module; const container = @import("container.zig"); +const signature = @import("signature.zig"); pub const ShaderKind = enum(u8) { pixel = 0, @@ -102,15 +103,15 @@ pub fn buildEmptyCompute(gpa: Allocator, info: ComputeInfo) ![]u8 { const dxil_part = try programPart(gpa, info.profile, bitcode); defer gpa.free(dxil_part); - const psv = try psvCompute(gpa, info.entry, info.num_threads, &.{}); - defer gpa.free(psv); + const psv_part = try psvCompute(gpa, info.entry, info.num_threads, &.{}); + defer gpa.free(psv_part); const empty_sig = [_]u8{ 0, 0, 0, 0, 8, 0, 0, 0 }; // ParamCount 0, ParamOffset 8 const parts = [_]container.Part{ .{ .fourcc = container.fourcc("SFI0"), .data = &@as([8]u8, @splat(0)) }, .{ .fourcc = container.fourcc("ISG1"), .data = &empty_sig }, .{ .fourcc = container.fourcc("OSG1"), .data = &empty_sig }, - .{ .fourcc = container.fourcc("PSV0"), .data = psv }, + .{ .fourcc = container.fourcc("PSV0"), .data = psv_part }, .{ .fourcc = container.fourcc("DXIL"), .data = dxil_part }, }; return container.assemble(gpa, &parts); @@ -135,51 +136,106 @@ pub fn programPart(gpa: Allocator, profile: Profile, bitcode: []const u8) ![]u8 /// One PSVResourceBindInfo1 record. pub const ResourceBind = struct { res_type: u32, space: u32, lower: u32, upper: u32, kind: u32, flags: u32 = 0 }; -/// PSV0 with PSVRuntimeInfo4 (60 bytes), as produced for validator 1.11. +pub const PsvInfo = struct { + kind: ShaderKind, + entry: []const u8, + /// The stage-specific PSVRuntimeInfo0 union. + stage_info: [16]u8 = @splat(0), + num_threads: [3]u32 = .{ 0, 0, 0 }, + resources: []const ResourceBind = &.{}, + inputs: []const signature.Element = &.{}, + outputs: []const signature.Element = &.{}, +}; + pub fn psvCompute(gpa: Allocator, entry: []const u8, num_threads: [3]u32, resources: []const ResourceBind) ![]u8 { + return psv(gpa, .{ .kind = .compute, .entry = entry, .num_threads = num_threads, .resources = resources }); +} + +/// PSV0 with PSVRuntimeInfo4 (60 bytes), as produced for validator 1.11. +pub fn psv(gpa: Allocator, info: PsvInfo) ![]u8 { var buf: std.ArrayList(u8) = .empty; errdefer buf.deinit(gpa); - const w = struct { - fn u32_(b: *std.ArrayList(u8), a: Allocator, v: u32) !void { - var tmp: [4]u8 = undefined; - std.mem.writeInt(u32, &tmp, v, .little); - try b.appendSlice(a, &tmp); - } - }.u32_; + const w = signature.put32; + 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)); try w(&buf, gpa, 60); // sizeof(PSVRuntimeInfo4) // PSVRuntimeInfo0 - try buf.appendNTimes(gpa, 0, 16); // stage-specific union + try buf.appendSlice(gpa, &info.stage_info); try w(&buf, gpa, 0); // MinimumExpectedWaveLaneCount try w(&buf, gpa, 0xFFFFFFFF); // MaximumExpectedWaveLaneCount - // PSVRuntimeInfo1 - try buf.appendSlice(gpa, &.{ @backingInt(ShaderKind.compute), 0, 0, 0 }); // stage, UsesViewID, union - try buf.appendNTimes(gpa, 0, 4); // sig element counts, SigInputVectors - try buf.appendNTimes(gpa, 0, 4); // SigOutputVectors[4] + // PSVRuntimeInfo1: stage, UsesViewID, MaxVertexCount, element counts, + // vector counts. + try buf.appendSlice(gpa, &.{ @backingInt(info.kind), 0, 0, 0 }); + try buf.appendSlice(gpa, &.{ @intCast(info.inputs.len), @intCast(info.outputs.len), 0, @intCast(in_vectors) }); + for (out_vectors) |v| try buf.append(gpa, @intCast(v)); // PSVRuntimeInfo2 - for (num_threads) |t| try w(&buf, gpa, t); - // PSVRuntimeInfo3: EntryFunctionName offset into string table (after leading NUL) - try w(&buf, gpa, 1); + for (info.num_threads) |t| try w(&buf, gpa, t); + + // String table: "\0", arbitrary semantic names, the entry name. + var strings: std.ArrayList(u8) = .empty; + defer strings.deinit(gpa); + try strings.append(gpa, 0); + // Semantic index table, with runs shared between elements. + var indices: std.ArrayList(u32) = .empty; + 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| { + var name_off: u32 = 0; + if (e.kind == .arbitrary and e.name.len > 0) { + name_off = @intCast(strings.items.len); + try strings.appendSlice(gpa, e.name); + try strings.append(gpa, 0); + } + const idx_off: u32 = blk: { + var off: usize = 0; + while (off + e.indices.len <= indices.items.len) : (off += 1) { + if (std.mem.eql(u32, indices.items[off..][0..e.indices.len], e.indices)) break :blk @intCast(off); + } + try indices.appendSlice(gpa, e.indices); + break :blk @intCast(indices.items.len - e.indices.len); + }; + try w(&records, gpa, name_off); + try w(&records, gpa, idx_off); + var cols_and_start: u8 = @intCast(e.cols); + if (e.start_row != null) cols_and_start |= 0x40 | @as(u8, @intCast(e.start_col << 4)); + try records.appendSlice(gpa, &.{ @intCast(e.rows), @intCast(e.start_row orelse 0), cols_and_start, @intFromEnum(e.kind), @intCast(e.comp.sigCompType()), @intFromEnum(e.interp), @intCast((e.stream & 3) << 4), 0 }); + }; + const entry_off: u32 = @intCast(strings.items.len); + try strings.appendSlice(gpa, info.entry); + try strings.append(gpa, 0); + while (strings.items.len % 4 != 0) try strings.append(gpa, 0); + + // PSVRuntimeInfo3: EntryFunctionName + try w(&buf, gpa, entry_off); // PSVRuntimeInfo4 try w(&buf, gpa, 0); // NumBytesGroupSharedMemory try w(&buf, gpa, 0); // Flags - try w(&buf, gpa, @intCast(resources.len)); // resource count - if (resources.len > 0) { + try w(&buf, gpa, @intCast(info.resources.len)); + if (info.resources.len > 0) { try w(&buf, gpa, 24); // sizeof(PSVResourceBindInfo1) - for (resources) |r| { + for (info.resources) |r| { for ([_]u32{ r.res_type, r.space, r.lower, r.upper, r.kind, r.flags }) |v| try w(&buf, gpa, v); } } - // String table: "\0" ++ entry ++ "\0", padded to 4 bytes. - const strtab_len = std.mem.alignForward(usize, entry.len + 2, 4); - try w(&buf, gpa, @intCast(strtab_len)); - try buf.append(gpa, 0); - try buf.appendSlice(gpa, entry); - try buf.appendNTimes(gpa, 0, strtab_len - entry.len - 1); - - try w(&buf, gpa, 0); // semantic index table count + try w(&buf, gpa, @intCast(strings.items.len)); + 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) { + try w(&buf, gpa, 16); // sizeof(PSVSignatureElement0) + try buf.appendSlice(gpa, records.items); + } + // Input-to-output dependency table (no ViewID). Left empty: the + // validator only checks it against dx.viewIdState, which zdxc omits. + if (in_vectors > 0 and out_vectors[0] > 0) { + const dwords = ((out_vectors[0] + 7) >> 3) * in_vectors * 4; + try buf.appendNTimes(gpa, 0, dwords * 4); + } return buf.toOwnedSlice(gpa); } diff --git a/src/dxil/signature.zig b/src/dxil/signature.zig new file mode 100644 index 0000000..d5a5d94 --- /dev/null +++ b/src/dxil/signature.zig @@ -0,0 +1,600 @@ +//! DXIL entry-point signatures: how each semantic is interpreted at a +//! signature point, element packing (a port of dxc's prefix-stable +//! DxilSignatureAllocator, so registers match dxc and shaders from both +//! compilers link), and the ISG1/OSG1 container parts. + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +pub const SemanticKind = enum(u8) { + arbitrary, + vertex_id, + instance_id, + position, + render_target_array_index, + viewport_array_index, + clip_distance, + cull_distance, + output_control_point_id, + domain_location, + primitive_id, + gs_instance_id, + sample_index, + is_front_face, + coverage, + inner_coverage, + target, + depth, + depth_less_equal, + depth_greater_equal, + stencil_ref, + dispatch_thread_id, + group_id, + group_index, + group_thread_id, + tess_factor, + inside_tess_factor, + view_id, + barycentrics, + shading_rate, + cull_primitive, + start_vertex_location, + start_instance_location, + invalid, +}; + +const sv_names = [_][]const u8{ + "", "SV_VertexID", "SV_InstanceID", "SV_Position", + "SV_RenderTargetArrayIndex", "SV_ViewportArrayIndex", "SV_ClipDistance", "SV_CullDistance", + "SV_OutputControlPointID", "SV_DomainLocation", "SV_PrimitiveID", "SV_GSInstanceID", + "SV_SampleIndex", "SV_IsFrontFace", "SV_Coverage", "SV_InnerCoverage", + "SV_Target", "SV_Depth", "SV_DepthLessEqual", "SV_DepthGreaterEqual", + "SV_StencilRef", "SV_DispatchThreadID", "SV_GroupID", "SV_GroupIndex", + "SV_GroupThreadID", "SV_TessFactor", "SV_InsideTessFactor", "SV_ViewID", + "SV_Barycentrics", "SV_ShadingRate", "SV_CullPrimitive", "SV_StartVertexLocation", + "SV_StartInstanceLocation", +}; + +/// The semantic a name (without its index) denotes: arbitrary unless it has +/// the `SV_` prefix. +pub fn kindByName(name: []const u8) SemanticKind { + if (!std.ascii.startsWithIgnoreCase(name, "SV_")) return .arbitrary; + for (sv_names[1..], 1..) |n, i| { + if (std.ascii.eqlIgnoreCase(name, n)) return @enumFromInt(i); + } + return .invalid; +} + +/// The canonical spelling of a system-value semantic. +pub fn canonicalName(kind: SemanticKind) []const u8 { + return sv_names[@intFromEnum(kind)]; +} + +pub const Interpretation = enum(u8) { na, sv, sgv, arb, not_in_sig, not_packed, target, tess_factor, shadow, clip_cull }; + +pub const SigPoint = enum { + vs_in, + vs_out, + gs_v_in, + gs_in, + gs_out, + ps_in, + ps_out, + + 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, + .ps_out => .target, + .gs_in => .none, + }; + } + + pub fn isInput(sp: SigPoint) bool { + return switch (sp) { + .vs_in, .gs_v_in, .gs_in, .ps_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). +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; + const na: I = .na; + 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), + else => @splat(na), + }; + return row[@intFromEnum(sp)]; +} + +pub fn shouldBeAllocated(i: Interpretation) bool { + return switch (i) { + .na, .not_in_sig, .not_packed, .shadow => false, + else => true, + }; +} + +pub const InterpMode = enum(u8) { + undefined, + constant, + linear, + linear_centroid, + linear_noperspective, + linear_noperspective_centroid, + linear_sample, + linear_noperspective_sample, + + pub fn isAnySample(m: InterpMode) bool { + return m == .linear_sample or m == .linear_noperspective_sample; + } +}; + +/// DXIL component types (DXIL::ComponentType). +pub const CompType = enum(u8) { + invalid, + i1, + i16, + u16, + i32, + u32, + i64, + u64, + f16, + f32, + f64, + + pub fn isFloat(c: CompType) bool { + return c == .f16 or c == .f32 or c == .f64; + } + + /// DxilProgramSigCompType. + pub fn sigCompType(c: CompType) u32 { + return switch (c) { + .i1, .u32 => 1, + .i32 => 2, + .f32 => 3, + .u16 => 4, + .i16 => 5, + .f16 => 6, + .u64 => 7, + .i64 => 8, + .f64 => 9, + .invalid => 0, + }; + } + + /// DxilProgramSigMinPrecision (min-precision mode). + fn minPrecision(c: CompType) u32 { + return switch (c) { + .f16 => 1, + .i16 => 4, + .u16 => 5, + else => 0, + }; + } +}; + +pub const Element = struct { + id: u32, + /// Semantic name without its index, as written. + name: []const u8, + kind: SemanticKind, + interpretation: Interpretation, + comp: CompType, + interp: InterpMode, + rows: u32, + cols: u32, + indices: []const u32, + start_row: ?u32 = null, + start_col: u32 = 0, + /// Components read (inputs) or written (outputs). + usage: u8 = 0, + stream: u32 = 0, + + pub fn colsMask(e: Element) u8 { + const m: u8 = @intCast((@as(u32, 1) << @intCast(e.cols)) - 1); + return m << @intCast(if (e.start_row != null) e.start_col else 0); + } +}; + +// ---------------------------------------------------------------------- +// Packing (DxilSignatureAllocator) + +const ef_occupied: u8 = 1 << 0; +const ef_arbitrary: u8 = 1 << 1; +const ef_sgv: u8 = 1 << 2; +const ef_sv: u8 = 1 << 3; +const ef_tess_factor: u8 = 1 << 4; +const ef_clip_cull: u8 = 1 << 5; +const ef_conflicts_with_indexed: u8 = ef_sgv | ef_sv; + +const indexed_up: u8 = 1 << 0; +const indexed_down: u8 = 1 << 1; + +fn indexFlags(row: u32, rows: u32) u8 { + return (if (row > 0) indexed_up else 0) | (if (row < rows - 1) indexed_down else 0); +} + +/// What the allocator needs to know about an element. +const PackElement = struct { + kind: SemanticKind = .arbitrary, + interp: InterpMode = .undefined, + interpretation: Interpretation = .arb, + rows: u32 = 1, + cols: u32 = 1, + row: ?u32 = null, + col: u32 = 0, + + fn flags(e: PackElement) u8 { + return switch (e.interpretation) { + .arb => ef_arbitrary, + .sv => ef_sv, + .sgv => ef_sgv, + .tess_factor => ef_tess_factor, + .clip_cull => ef_clip_cull, + else => 0, + }; + } +}; + +/// Element flags that may not be placed to the left of an element. +fn conflictFlagsLeft(f: u8) u8 { + var c: u8 = 0; + if (f & ef_arbitrary != 0) c |= ef_sgv | ef_sv | ef_tess_factor | ef_clip_cull; + if (f & (ef_sv | ef_tess_factor | ef_clip_cull) != 0) c |= ef_sgv; + return c; +} + +/// Element flags that may not be placed to the right of an element. +fn conflictFlagsRight(f: u8) u8 { + var c: u8 = 0; + if (f & ef_sgv != 0) c |= ef_arbitrary | ef_sv | ef_tess_factor | ef_clip_cull; + if (f & (ef_sv | ef_tess_factor | ef_clip_cull) != 0) c |= ef_arbitrary; + return c; +} + +const Register = struct { + flags: [4]u8 = @splat(0), + interp: InterpMode = .undefined, + index_flags: u8 = 0, + indexing_fixed: bool = false, + + fn rowConflict(r: Register, flags: u8, index: u8, interp: InterpMode, width: u32) bool { + if (r.index_flags != 0 and flags & ef_conflicts_with_indexed != 0) return true; + if (r.indexing_fixed and (index | r.index_flags) != r.index_flags) return true; + if (flags & ef_tess_factor != 0 and (index | r.index_flags) != index) return true; + if (r.interp != .undefined and r.interp != interp) return true; + // (All packed data is 32 bits wide in min-precision mode.) + var free: u32 = 0; + for (r.flags) |f| { + if (f & ef_occupied != 0 or f & flags != 0) free = 0 else free += 1; + if (width <= free) return false; + } + return true; + } + + fn colConflict(r: Register, flags: u8, col: u32, width: u32) bool { + if (col + width > 4) return true; + for (r.flags[col..][0..width]) |f| if (f & (flags | ef_occupied) != 0) return true; + return false; + } + + fn place(r: *Register, flags: u8, index: u8, interp: InterpMode, col: u32, width: u32) void { + r.interp = interp; + r.index_flags |= index; + if (flags & (ef_conflicts_with_indexed | ef_tess_factor) != 0) r.indexing_fixed = true; + const left = conflictFlagsLeft(flags); + const right = conflictFlagsRight(flags); + for (&r.flags, 0..) |*f, i| { + if (f.* & ef_occupied != 0) continue; + if (i < col) f.* |= left else if (i < col + width) f.* = ef_occupied | flags else f.* |= right; + } + } +}; + +const Allocator32 = struct { + regs: []Register, + + fn rowConflict(a: *const Allocator32, e: *const PackElement, row: u32) bool { + if (e.rows + row > a.regs.len) return true; + for (0..e.rows) |i| { + if (a.regs[row + i].rowConflict(e.flags(), indexFlags(@intCast(i), e.rows), e.interp, e.cols)) return true; + } + return false; + } + + fn colConflict(a: *const Allocator32, e: *const PackElement, row: u32, col: u32) bool { + for (0..e.rows) |i| if (a.regs[row + i].colConflict(e.flags(), col, e.cols)) return true; + return false; + } + + fn place(a: *Allocator32, e: *const PackElement, row: u32, col: u32) void { + for (0..e.rows) |i| a.regs[row + i].place(e.flags(), indexFlags(@intCast(i), e.rows), e.interp, col, e.cols); + } + + /// First free location at or after `start_row`; returns the row after + /// the element, or 0 if it does not fit. + fn findNext(a: *const Allocator32, row_out: *u32, col_out: *u32, e: *const PackElement, start_row: u32, num_rows: u32, start_col: u32) u32 { + if (e.rows > num_rows) return 0; + var row = start_row; + while (row <= start_row + num_rows - e.rows) : (row += 1) { + if (a.rowConflict(e, row)) continue; + var col = start_col; + while (col + e.cols <= 4) : (col += 1) { + if (a.colConflict(e, row, col)) continue; + row_out.* = row; + col_out.* = col; + return row + e.rows; + } + } + return 0; + } + + fn packNext(a: *Allocator32, e: *PackElement, start_row: u32, num_rows: u32, start_col: u32) u32 { + var row: u32 = 0; + var col: u32 = 0; + const used = a.findNext(&row, &col, e, start_row, num_rows, start_col); + if (used != 0) { + a.place(e, row, col); + e.row = row; + e.col = col; + } + return used; + } + + /// PackPrefixStable: elements are placed in order; appending elements + /// never moves earlier ones. + fn packPrefixStable(a: *Allocator32, elements: []*PackElement, start_row: u32, num_rows: u32) u32 { + var rows_used: u32 = 0; + // Clip/cull elements share at most two registers and are kept apart + // from other elements. + var cc_regs_buf: [2]Register = .{ .{}, .{} }; + var cc: Allocator32 = .{ .regs = &cc_regs_buf }; + var cc_used: u32 = 0; + var cc_indexed = false; + var cc_temp: [2]PackElement = .{ .{}, .{} }; + for (elements) |e| { + e.row = null; + switch (e.interpretation) { + .clip_cull => { + var row: u32 = 0; + var col: u32 = 0; + const used = cc.findNext(&row, &col, e, 0, 2, 0); + if (used == 0) continue; + if (e.rows > 1 and !cc_indexed) { + if (cc_used == 2 and cc_temp[0].row.? + 1 != cc_temp[1].row.?) continue; + cc_indexed = true; + } + if (used > cc_used) { + const de = &cc_temp[cc_used]; + de.* = .{ .kind = e.kind, .interp = e.interp, .interpretation = e.interpretation, .rows = 1, .cols = 4 }; + if (cc_indexed) { + if (cc_used < 1) { + de.rows = 2; + rows_used = @max(rows_used, a.packNext(de, start_row, num_rows, 0)); + if (de.row == null) continue; + cc_temp[1] = de.*; + cc_temp[1].row = de.row.? + 1; + cc_temp[1].rows = 1; + } else { + rows_used = @max(rows_used, a.packNext(de, cc_temp[0].row.? + 1, cc_temp[0].row.? + 2, 0)); + if (de.row == null) continue; + } + cc_used = 2; + } else { + rows_used = @max(rows_used, a.packNext(de, start_row, num_rows, 0)); + if (de.row == null) continue; + cc_used = used; + } + } + cc.place(e, row, col); + e.row = cc_temp[row].row; + e.col = col; + continue; + }, + .tess_factor => if (e.rows > 1) { + rows_used = @max(rows_used, a.packNext(e, start_row, num_rows, 3)); + continue; + }, + else => {}, + } + rows_used = @max(rows_used, a.packNext(e, start_row, num_rows, 0)); + } + return rows_used; + } +}; + +pub const PackError = error{SignatureFull} || Allocator.Error; + +/// Assigns registers to the allocatable elements of a signature, as dxc's +/// PackDxilSignature does with the default (prefix-stable) strategy. +pub fn pack(gpa: Allocator, elements: []Element, sp: SigPoint) PackError!void { + switch (sp.packing()) { + .none => {}, + .input_assembler => { + var row: u32 = 0; + for (elements) |*e| if (shouldBeAllocated(e.interpretation)) { + e.start_row = row; + e.start_col = 0; + row += e.rows; + }; + if (row > 32) return error.SignatureFull; + }, + .target => for (elements) |*e| if (e.kind == .target) { + e.start_row = e.indices[0]; + e.start_col = 0; + }, + .vertex => { + // One allocator per output stream. + for (0..4) |stream| { + var pes: std.ArrayList(PackElement) = .empty; + defer pes.deinit(gpa); + var owners: std.ArrayList(*Element) = .empty; + defer owners.deinit(gpa); + for (elements) |*e| if (shouldBeAllocated(e.interpretation) and e.stream == stream) { + try pes.append(gpa, .{ .kind = e.kind, .interp = e.interp, .interpretation = e.interpretation, .rows = e.rows, .cols = e.cols }); + try owners.append(gpa, e); + }; + if (pes.items.len == 0) continue; + const ptrs = try gpa.alloc(*PackElement, pes.items.len); + defer gpa.free(ptrs); + for (ptrs, pes.items) |*p, *pe| p.* = pe; + var regs: [32]Register = @splat(.{}); + var alloc: Allocator32 = .{ .regs = ®s }; + _ = alloc.packPrefixStable(ptrs, 0, 32); + for (pes.items, owners.items) |pe, e| { + e.start_row = pe.row orelse return error.SignatureFull; + e.start_col = pe.col; + } + } + }, + } +} + +/// Rows used by the allocated elements of `stream`. +pub fn vectorsUsed(elements: []const Element, stream: u32) u32 { + var n: u32 = 0; + for (elements) |e| if (e.start_row) |r| if (e.stream == stream) { + n = @max(n, r + e.rows); + }; + return n; +} + +// ---------------------------------------------------------------------- +// ISG1 / OSG1 + +/// D3D system-value code of a semantic (DxilProgramSigSemantic). +fn systemValue(kind: SemanticKind) u32 { + return switch (kind) { + .arbitrary, .invalid => 0, + .position => 1, + .clip_distance => 2, + .cull_distance => 3, + .render_target_array_index => 4, + .viewport_array_index => 5, + .vertex_id => 6, + .primitive_id => 7, + .instance_id => 8, + .is_front_face => 9, + .sample_index => 10, + .barycentrics => 23, + .shading_rate => 24, + .cull_primitive => 25, + .target => 64, + .depth => 65, + .coverage => 66, + .depth_greater_equal => 67, + .depth_less_equal => 68, + .stencil_ref => 69, + .inner_coverage => 70, + else => 0, + }; +} + +/// 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 { + 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); + var names: std.ArrayList([]const u8) = .empty; + defer names.deinit(gpa); + var name_offsets: std.ArrayList(u32) = .empty; + defer name_offsets.deinit(gpa); + + var count: u32 = 0; + for (elements) |e| count += @intCast(e.indices.len); + var str_off: u32 = 8 + 32 * count; + for (elements) |e| { + const name_off = for (names.items, name_offsets.items) |n, o| { + if (std.mem.eql(u8, n, e.name)) break o; + } else blk: { + try names.append(gpa, e.name); + try name_offsets.append(gpa, str_off); + str_off += @intCast(e.name.len + 1); + break :blk str_off - @as(u32, @intCast(e.name.len + 1)); + }; + var usage = e.usage; + 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; + 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() }); + if (e.start_row != null) reg += 1; + } + } + std.sort.insertion(Rec, recs.items, {}, struct { + fn lt(_: void, a: Rec, b: Rec) bool { + if (a.stream != b.stream) return a.stream < b.stream; + if (a.reg != b.reg) return a.reg < b.reg; + return a.name < b.name; + } + }.lt); + + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + try put32(&out, gpa, count); + try put32(&out, gpa, 8); + for (recs.items) |r| { + for ([_]u32{ r.stream, r.name, r.index, r.sv, r.comp, r.reg }) |v| try put32(&out, gpa, v); + try out.appendSlice(gpa, &.{ r.mask, r.rw, 0, 0 }); + try put32(&out, gpa, r.min_prec); + } + for (names.items) |n| { + try out.appendSlice(gpa, n); + try out.append(gpa, 0); + } + while (out.items.len % 4 != 0) try out.append(gpa, 0); + return out.toOwnedSlice(gpa); +} + +pub fn put32(out: *std.ArrayList(u8), gpa: Allocator, v: u32) Allocator.Error!void { + var tmp: [4]u8 = undefined; + std.mem.writeInt(u32, &tmp, v, .little); + try out.appendSlice(gpa, &tmp); +} + +test "prefix-stable packing matches dxc" { + const gpa = std.testing.allocator; + // dxc: PS input { SV_Position; float2 TEXCOORD0; nointerpolation uint + // TEXCOORD1; float3 NORMAL; bool SV_IsFrontFace } packs to rows 0, 1, + // 2, 3 and 2.y. + const idx0 = [_]u32{0}; + const idx1 = [_]u32{1}; + var els = [_]Element{ + .{ .id = 0, .name = "SV_Position", .kind = .position, .interpretation = .sv, .comp = .f32, .interp = .linear_noperspective, .rows = 1, .cols = 4, .indices = &idx0 }, + .{ .id = 1, .name = "TEXCOORD", .kind = .arbitrary, .interpretation = .arb, .comp = .f32, .interp = .linear, .rows = 1, .cols = 2, .indices = &idx0 }, + .{ .id = 2, .name = "TEXCOORD", .kind = .arbitrary, .interpretation = .arb, .comp = .u32, .interp = .constant, .rows = 1, .cols = 1, .indices = &idx1 }, + .{ .id = 3, .name = "NORMAL", .kind = .arbitrary, .interpretation = .arb, .comp = .f32, .interp = .linear, .rows = 1, .cols = 3, .indices = &idx0 }, + .{ .id = 4, .name = "SV_IsFrontFace", .kind = .is_front_face, .interpretation = .sgv, .comp = .u32, .interp = .constant, .rows = 1, .cols = 1, .indices = &idx0 }, + }; + try pack(gpa, &els, .ps_in); + const want = [_][2]u32{ .{ 0, 0 }, .{ 1, 0 }, .{ 2, 0 }, .{ 3, 0 }, .{ 2, 1 } }; + for (els, want) |e, w| { + try std.testing.expectEqual(w[0], e.start_row.?); + try std.testing.expectEqual(w[1], e.start_col); + } + try std.testing.expectEqual(@as(u32, 4), vectorsUsed(&els, 0)); +} diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 0a8ab72..0e68ddd 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -191,6 +191,9 @@ pub const SigElement = struct { semantic_index: u32, ty: TypeId, system_value: bool, + interp: types.Interp = .{}, + /// Matrices in the element are row_major (signature layout only). + row_major: bool = false, }; pub const Entry = struct { diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 63dcd37..5188347 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -9,6 +9,8 @@ const ast = @import("../front/ast.zig"); const ir = @import("ir.zig"); const semamod = @import("../sema/sema.zig"); const types = @import("../sema/types.zig"); +const Interp = types.Interp; +const Field = types.Field; const table = @import("intrinsics_table"); const Sema = semamod.Sema; @@ -939,22 +941,41 @@ const Lowerer = struct { // ------------------------------------------------------------------ // Entry point + /// Per-element modifiers that reach the signature. + const SigAttrs = struct { + interp: Interp = .{}, + row_major: bool = false, + + /// A field's modifiers, inheriting the enclosing interpolation. + fn field(outer: SigAttrs, fld: Field) SigAttrs { + const own: u8 = @bitCast(fld.interp); + return .{ .interp = if (own != 0) fld.interp else outer.interp, .row_major = fld.row_major }; + } + }; + + fn withAttrs(el: ir.SigElement, attrs: SigAttrs) ir.SigElement { + var r = el; + r.interp = attrs.interp; + r.row_major = attrs.row_major; + return r; + } + /// 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, loc: ast.Loc, what: []const u8) Error!Ref { + fn entryInput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, semantic: ?[]const u8, attrs: SigAttrs, loc: ast.Loc, what: []const u8) Error!Ref { if (semantic) |sem| if (l.s.types.get(ty) == .@"struct") { // A semantic on a struct numbers its fields: X, X1, X2, ... var el = sigElement(sem, ty); - return l.structInput(entry, ty, el.semantic, &el.semantic_index); + return l.structInput(entry, ty, el.semantic, &el.semantic_index, attrs); }; if (semantic) |sem| { - try entry.inputs.append(l.arena, sigElement(sem, ty)); + 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 }); } switch (l.s.types.get(ty)) { .@"struct" => |st| { const parts = try l.arena.alloc(Ref, st.fields.items.len); - for (parts, st.fields.items) |*p, fld| p.* = try l.entryInput(entry, fld.type, fld.semantic, loc, fld.name); + for (parts, st.fields.items) |*p, fld| p.* = try l.entryInput(entry, fld.type, fld.semantic, attrs.field(fld), loc, fld.name); return l.b.add(.{ .op = .{ .construct = parts }, .ty = ty }); }, else => { @@ -964,49 +985,49 @@ const Lowerer = struct { } } - fn structInput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, name: []const u8, index: *u32) Error!Ref { + fn structInput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, name: []const u8, index: *u32, attrs: SigAttrs) Error!Ref { const st = l.s.types.get(ty).@"struct"; const parts = try l.arena.alloc(Ref, st.fields.items.len); for (parts, st.fields.items) |*p, fld| { if (l.s.types.get(fld.type) == .@"struct") { - p.* = try l.structInput(entry, fld.type, name, index); + p.* = try l.structInput(entry, fld.type, name, index, attrs.field(fld)); continue; } - try entry.inputs.append(l.arena, .{ .semantic = name, .semantic_index = index.*, .ty = fld.type, .system_value = std.ascii.startsWithIgnoreCase(name, "SV_") }); + 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))); 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 }); } - fn structOutput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, name: []const u8, index: *u32, value: Ref) Error!void { + fn structOutput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, name: []const u8, index: *u32, value: Ref, attrs: SigAttrs) Error!void { const st = l.s.types.get(ty).@"struct"; for (st.fields.items, 0..) |fld, k| { const v = try l.b.add(.{ .op = .{ .extract = .{ .agg = value, .index = @intCast(k) } }, .ty = fld.type }); if (l.s.types.get(fld.type) == .@"struct") { - try l.structOutput(entry, fld.type, name, index, v); + try l.structOutput(entry, fld.type, name, index, v, attrs.field(fld)); continue; } - try entry.outputs.append(l.arena, .{ .semantic = name, .semantic_index = index.*, .ty = fld.type, .system_value = std.ascii.startsWithIgnoreCase(name, "SV_") }); + 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))); index.* += 1; _ = try l.b.add(.{ .op = .{ .output = .{ .element = @intCast(entry.outputs.items.len - 1), .value = v } }, .ty = TypeTable.void_type }); } } - fn entryOutput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, semantic: ?[]const u8, value: Ref, loc: ast.Loc, what: []const u8) Error!void { + fn entryOutput(l: *Lowerer, entry: *ir.Entry, ty: TypeId, semantic: ?[]const u8, attrs: SigAttrs, value: Ref, loc: ast.Loc, what: []const u8) Error!void { if (semantic) |sem| if (l.s.types.get(ty) == .@"struct") { var el = sigElement(sem, ty); - return l.structOutput(entry, ty, el.semantic, &el.semantic_index, value); + return l.structOutput(entry, ty, el.semantic, &el.semantic_index, value, attrs); }; if (semantic) |sem| { - try entry.outputs.append(l.arena, sigElement(sem, ty)); + 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; } 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 }); - try l.entryOutput(entry, fld.type, fld.semantic, v, loc, fld.name); + try l.entryOutput(entry, fld.type, fld.semantic, attrs.field(fld), v, loc, fld.name); }, else => { l.unsupported(loc, "entry {s} needs a semantic", .{what}); @@ -1015,7 +1036,36 @@ const Lowerer = struct { } } + /// Lowers the initializers of the static globals the program uses, + /// each into its own function (an initializer may use earlier statics, + /// which then need initializing too). Returns them by global. + fn staticInits(l: *Lowerer) Error!std.AutoHashMapUnmanaged(*const Variable, u32) { + var inits: std.AutoHashMapUnmanaged(*const Variable, u32) = .empty; + var changed = true; + while (changed) { + changed = false; + for (l.s.static_globals.items) |v| { + const init_e = v.init orelse continue; + if (!l.globals.contains(v) or inits.contains(v)) continue; + if (l.s.types.get(v.type) == .resource or l.s.types.get(v.type) == .sampler) continue; + const fi = try l.m.addFunction(.{ .name = try std.fmt.allocPrint(l.arena, "init.{s}", .{v.name}), .params = &.{}, .ret = v.type }); + try inits.put(l.arena, v, fi); + l.b = .{ .m = &l.m, .f = l.m.functions.items[fi] }; + l.vars = .empty; + l.loops = .empty; + l.ret_ty = v.type; + l.b.setBlock(try l.b.newBlock()); + const val = if (init_e.kind == .init_list) try l.initList(init_e, v.type) else try l.converted(init_e, v.type); + l.b.terminate(.{ .ret = val }); + try l.drain(); + changed = true; + } + } + return inits; + } + 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 }; for (f.decl.attrs) |a| { if (std.ascii.eqlIgnoreCase(a.name, "numthreads") and a.args.len == 3) { @@ -1025,22 +1075,28 @@ const Lowerer = struct { const wrapper = try l.m.addFunction(.{ .name = opts.entry, .params = &.{}, .ret = TypeTable.void_type }); l.b = .{ .m = &l.m, .f = l.m.functions.items[wrapper] }; l.b.setBlock(try l.b.newBlock()); + for (l.s.static_globals.items) |v| if (inits.get(v)) |fi| { + const g = l.globals.get(v).?; + const glob = l.m.globals.items[g]; + const ptr = try l.b.add(.{ .op = .{ .global = g }, .ty = glob.ty, .ptr = glob.space }); + try l.b.store(ptr, try l.b.add(.{ .op = .{ .call = .{ .func = fi, .args = &.{} } }, .ty = v.type })); + }; const args = try l.arena.alloc(Ref, f.params.len); const locals = try l.arena.alloc(Ref, f.params.len); for (f.decl.params, f.params, 0..) |pd, p, i| { locals[i] = try l.b.add(.{ .op = .local_var, .ty = p.type, .ptr = .function }); if (p.dir != .out) { - const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), pd.name_loc, pd.name); + const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), pd.name_loc, pd.name); try l.b.store(locals[i], v); } args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i]; } const ret = try l.b.add(.{ .op = .{ .call = .{ .func = main, .args = args } }, .ty = f.ret }); - if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), ret, f.loc, "return value"); + if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), paramAttrs(f.decl.quals), ret, f.loc, "return value"); for (f.decl.params, f.params, 0..) |pd, p, i| { if (p.dir == .in) continue; const v = try l.b.load(locals[i]); - try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), v, pd.name_loc, pd.name); + try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), paramAttrs(pd.quals), v, pd.name_loc, pd.name); } l.b.terminate(.{ .ret = .none }); entry.wrapper = wrapper; @@ -1059,6 +1115,10 @@ pub fn saturatingInt(f: f64) i64 { return @intFromFloat(@trunc(f)); } +fn paramAttrs(q: ast.Qualifiers) Lowerer.SigAttrs { + return .{ .interp = semamod.interpOf(q), .row_major = q.row_major }; +} + fn semanticOf(sems: []const ast.Semantic) ?[]const u8 { for (sems) |sem| if (sem.kind == .semantic) return sem.values[0]; return null; diff --git a/src/root.zig b/src/root.zig index ebd0ead..5fe6141 100644 --- a/src/root.zig +++ b/src/root.zig @@ -21,6 +21,7 @@ pub const dxil = struct { pub const hash = @import("dxil/hash.zig"); pub const module = @import("dxil/module.zig"); pub const shader = @import("dxil/shader.zig"); + pub const signature = @import("dxil/signature.zig"); pub const emit = @import("dxil/emit.zig"); }; diff --git a/src/sema/sema.zig b/src/sema/sema.zig index 43eda48..a1384f4 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -164,6 +164,9 @@ pub const Sema = struct { decl_vars: std.AutoHashMapUnmanaged(*const ast.VarDecl, *Variable) = .empty, /// Global uniforms outside cbuffers (dxc's `$Globals`), in order. uniform_globals: std.ArrayList(*Variable) = .empty, + /// `static` (and `static const`) globals and static members, in + /// declaration order. + static_globals: std.ArrayList(*Variable) = .empty, current_block: ?*const ast.Decl = null, loop_depth: u32 = 0, switch_depth: u32 = 0, @@ -967,7 +970,7 @@ pub const Sema = struct { for (v.semantics) |sem| if (sem.kind == .semantic) { fsem = sem.values[0]; }; - try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = isRowMajor(fattrs), .semantic = fsem }); + try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = isRowMajor(fattrs), .semantic = fsem, .interp = interpOf(v.quals) }); }, .func => {}, else => try s.decl(m, .member), @@ -1367,6 +1370,7 @@ pub const Sema = struct { try s.decl_vars.put(s.arena, v, variable); if (ctx == .cbuffer) variable.block = s.current_block; if (storage == .global_uniform) try s.uniform_globals.append(s.arena, variable); + if (storage == .global_static or storage == .constant) try s.static_globals.append(s.arena, variable); // Unsized arrays take their size from the initializer. if (v.init) |init_e| if (!is_auto) { if (s.types.get(ty) == .array and s.types.get(ty).array.len == 0 and init_e.kind == .init_list) { @@ -2876,6 +2880,10 @@ fn templateArgLoc(arg: ast.TemplateArg) Loc { }; } +pub fn interpOf(q: ast.Qualifiers) types.Interp { + return .{ .nointerpolation = q.nointerpolation, .linear = q.linear, .centroid = q.centroid, .sample = q.sample, .noperspective = q.noperspective }; +} + fn isRowMajor(a: TypeAttrs) bool { return if (a.orientation) |o| eql(o, "row_major") else false; } diff --git a/src/sema/types.zig b/src/sema/types.zig index 3c4ea60..9c7ded2 100644 --- a/src/sema/types.zig +++ b/src/sema/types.zig @@ -319,6 +319,18 @@ pub const Field = struct { row_major: bool = false, /// The field's semantic (`float4 pos : SV_Position;`). semantic: ?[]const u8 = null, + /// Interpolation modifiers (for entry-point inputs and outputs). + interp: Interp = .{}, +}; + +/// Interpolation modifiers written on a parameter, field or function. +pub const Interp = packed struct(u8) { + nointerpolation: bool = false, + linear: bool = false, + centroid: bool = false, + sample: bool = false, + noperspective: bool = false, + _pad: u3 = 0, }; /// A struct's layout-relevant information. Methods live in Sema. diff --git a/test/dxil/check.sh b/test/dxil/check.sh new file mode 100644 index 0000000..e232ca5 --- /dev/null +++ b/test/dxil/check.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# DXIL output checks beyond validation: for each test/dxil/*.hlsl, zdxc's +# signature tables (ISG1/OSG1 and PSV0, minus the "Used" column) must match +# dxc's, and every `// ZCHECK: text` line must appear in zdxc's disassembly +# (`{{.*}}` matches anything). +# +# Usage: test/dxil/check.sh +set -u +ZDXC=$1 +DXC_BUILD=${DXC_BUILD:-../build} +DXC=$DXC_BUILD/bin/dxc +DXV=$DXC_BUILD/bin/dxv +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT +pass=0 +fail=0 + +# Signature table rows, cut before the "Used" column. +sigtables() { + awk '/^; (Input|Output) signature:/ { on = 1; seen = 0; next } + on && /^; (-|Name)/ { next } + on && /^;$/ { if (seen) on = 0; next } + on { print substr($0, 1, 63); seen = 1 }' "$1" | sed 's/ *$//' +} + +for f in test/dxil/*.hlsl; do + profile=$(sed -n 's|^// PROFILE: *||p' "$f") + name=$(basename "$f" .hlsl) + if ! "$ZDXC" -T "$profile" "$f" -Fo "$TMP/z.dxo" > "$TMP/log" 2>&1; then + fail=$((fail + 1)); echo "FAIL $name: zdxc failed"; head -3 "$TMP/log"; continue + fi + if ! "$DXV" "$TMP/z.dxo" > "$TMP/log" 2>&1; then + fail=$((fail + 1)); echo "FAIL $name: dxv rejected the output"; head -3 "$TMP/log"; continue + fi + "$DXC" -dumpbin "$TMP/z.dxo" > "$TMP/z.ll" 2>&1 + "$DXC" -T "$profile" "$f" -Fc "$TMP/d.ll" > /dev/null 2>&1 + ok=1 + sigtables "$TMP/z.ll" > "$TMP/z.sig" + sigtables "$TMP/d.ll" > "$TMP/d.sig" + if ! diff "$TMP/d.sig" "$TMP/z.sig" > "$TMP/diff"; then + ok=0; echo "FAIL $name: signatures differ from dxc (< dxc, > zdxc)"; head -10 "$TMP/diff" + fi + sed -n 's|^// ZCHECK: *||p' "$f" > "$TMP/checks" + while IFS= read -r pat; do + re=$(printf '%s\n' "$pat" | sed -e 's/[][\.*^$()+?|{}]/\\&/g' -e 's/\\{\\{\\\.\\\*\\}\\}/.*/g') + grep -Eq -- "$re" "$TMP/z.ll" || { ok=0; echo "FAIL $name: missing '$pat'"; } + done < "$TMP/checks" + if [ $ok = 1 ]; then pass=$((pass + 1)); else fail=$((fail + 1)); fi +done +echo "dxil checks: $pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/test/dxil/sig_no_inputs.hlsl b/test/dxil/sig_no_inputs.hlsl new file mode 100644 index 0000000..a0efefc --- /dev/null +++ b/test/dxil/sig_no_inputs.hlsl @@ -0,0 +1,2 @@ +// PROFILE: vs_6_0 +float4 main() : SV_Position { return 1; } diff --git a/test/dxil/sig_order.hlsl b/test/dxil/sig_order.hlsl new file mode 100644 index 0000000..cea212a --- /dev/null +++ b/test/dxil/sig_order.hlsl @@ -0,0 +1,5 @@ +// PROFILE: vs_6_0 +// Return value first, then parameters; inout packs its output side; clip +// distances and matrices span rows. +struct O { float4 a : A; float2 b[2] : B; }; +float4 main(in float3 x : X, out float y : Y, inout float2 z : Z, float4x2 m : M, row_major float2x3 rm : RM, out O o, uint iid : SV_InstanceID, out float4 p : SV_Position, out float cd[2] : SV_ClipDistance) : R { y = x.x; z += 1; o.a = m[0].xyxy+rm[0].xyzx; o.b[0] = 1; o.b[1] = iid; p = 1; cd[0]=1; cd[1]=2; return 2; } diff --git a/test/dxil/sig_ps_struct.hlsl b/test/dxil/sig_ps_struct.hlsl new file mode 100644 index 0000000..43f168c --- /dev/null +++ b/test/dxil/sig_ps_struct.hlsl @@ -0,0 +1,5 @@ +// PROFILE: ps_6_0 +// ZCHECK: call void @dx.op.discard(i32 82, i1 true) +// ZCHECK: @dx.op.unary.f32(i32 83, +struct PSIn { float4 pos : SV_Position; float2 uv : TEXCOORD0; nointerpolation uint id : TEXCOORD1; float3 n : NORMAL; }; +float4 main(PSIn i, bool ff : SV_IsFrontFace) : SV_Target { if (i.uv.x < 0) discard; return float4(i.n * (ff ? 1 : -1), i.uv.y + i.id + ddx(i.uv.x)); } diff --git a/test/dxil/sig_ps_sv.hlsl b/test/dxil/sig_ps_sv.hlsl new file mode 100644 index 0000000..7ac4352 --- /dev/null +++ b/test/dxil/sig_ps_sv.hlsl @@ -0,0 +1,4 @@ +// PROFILE: ps_6_0 +// Interpolation modifiers, shadow (SV_SampleIndex) and unpacked outputs. +// ZCHECK: @dx.op.sampleIndex.i32(i32 90) +float4 main(float4 p : SV_Position, centroid float c : C, noperspective float2 np : NP, sample float s : S, uint pid : SV_PrimitiveID, uint si : SV_SampleIndex, out float d : SV_Depth, out float4 t1 : SV_Target1, out uint cov : SV_Coverage) : SV_Target0 { d = 0.5; t1 = 1; cov = 3; return c + np.x + pid + si + s+p.x; } diff --git a/test/dxil/sig_target_array.hlsl b/test/dxil/sig_target_array.hlsl new file mode 100644 index 0000000..05fbee2 --- /dev/null +++ b/test/dxil/sig_target_array.hlsl @@ -0,0 +1,15 @@ +// PROFILE: ps_6_0 +// SV_Target arrays split into one element per render target. +uint i; +float4 main(int4 a : A, out float4 o[2] : SV_TARGET, out float4 o2[2][2] : SV_TARGET2) : SV_TARGET7 +{ + o[0] = a+2; + o[1] = a+3; + o[i] = a+10; + o2[0][0] = a+5; + o2[0][1] = a+6; + o2[1][0] = a+7; + o2[1][1] = a+8; + o2[i][i] = a + 12; + return a + 16; +} diff --git a/test/dxil/sig_types.hlsl b/test/dxil/sig_types.hlsl new file mode 100644 index 0000000..9e12939 --- /dev/null +++ b/test/dxil/sig_types.hlsl @@ -0,0 +1,5 @@ +// PROFILE: vs_6_0 +// bool and min16float elements. +// ZCHECK: @dx.op.loadInput.f16( +struct O { float4 p : SV_Position; bool b : B; min16float h : H; int2 i : I; }; +O main(bool bi : BI, min16float2 hi : HI, float4 v : SV_Position) { O o; o.p = v; o.b = bi; o.h = hi.x; o.i = 3; return o; } diff --git a/test/dxil/sig_vs_struct.hlsl b/test/dxil/sig_vs_struct.hlsl new file mode 100644 index 0000000..a55702e --- /dev/null +++ b/test/dxil/sig_vs_struct.hlsl @@ -0,0 +1,5 @@ +// PROFILE: vs_6_0 +cbuffer C : register(b0) { float4x4 mvp; }; +struct VSIn { float3 pos : POSITION; float2 uv : TEXCOORD0; float3 n : NORMAL; uint id : SV_VertexID; }; +struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; nointerpolation uint id : TEXCOORD1; float3 n : NORMAL; }; +VSOut main(VSIn i) { VSOut o; o.pos = mul(mvp, float4(i.pos, 1)); o.uv = i.uv; o.id = i.id; o.n = i.n; return o; } diff --git a/test/dxil/static_init.hlsl b/test/dxil/static_init.hlsl new file mode 100644 index 0000000..2493981 --- /dev/null +++ b/test/dxil/static_init.hlsl @@ -0,0 +1,8 @@ +// PROFILE: vs_6_0 +// Static globals are initialized on entry; float constants keep their value. +// ZCHECK: store float 3.000000e+00 +// ZCHECK: store float 5.000000e+00 +// ZCHECK: fadd float {{.*}}, 1.500000e+00 +static const float2 offs[2] = { float2(1, 2), float2(3, 4) }; +static float g = 5; +float4 main(uint id : SV_VertexID) : SV_Position { g += 1.5; return float4(offs[id], g, 1); }