From 717a0a9fad62f4b3f1bf9cddba6ada20a806af73 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sun, 1 Nov 2026 08:53:09 -0800 Subject: [PATCH] zdxc: -Zpr / -Zpc and #pragma pack_matrix -Zpr and #pragma pack_matrix were accepted but ignored, so row-major matrices silently got the column-major layout. Now, as in dxc: - #pragma pack_matrix sets the orientation of matrices declared after it and may come between any two tokens; typedefs keep theirs. - -Zpr is the default for matrices with neither; -Zpc is accepted and the two together are an error. - Entry parameters take an orientation written on them or the pragma's, not a typedef's (dxc's signatures lose that sugar). - Structured buffer matrix elements follow -Zpr only in DXIL; in SPIR-V they take the template argument's orientation too. --- src/dxil/emit.zig | 10 ++++---- src/front/ast.zig | 3 +++ src/front/parser.zig | 41 +++++++++++++++++++++++++++++++- src/ir/ir.zig | 4 ++++ src/ir/lower.zig | 35 ++++++++++++++------------- src/main.zig | 7 ++++++ src/options.zig | 4 ++-- src/sema/sema.zig | 56 ++++++++++++++++++++++++++++++++++---------- src/sema/types.zig | 6 +++-- src/spirv/emit.zig | 25 +++++++++++++------- 10 files changed, 145 insertions(+), 46 deletions(-) diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 4640151..51753ab 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -1763,7 +1763,7 @@ const Emitter = struct { if (rk == 13 or rk == 15) return e.cbufferAccess(frame, .{ .res = ri }, e.resources.items[ri].elem, a.indices); if (rk >= 1 and rk <= 10) return .{ .texel = .{ .res = ri, .coords = try e.scalars(frame, a.indices[0]) } }; if (rk != 12) return e.unsupported("member access into this resource is not supported yet", .{}); - const start: @FieldType(Lowered, "buf") = .{ .res = ri, .index = (try e.scalars(frame, a.indices[0]))[0] }; + const start: @FieldType(Lowered, "buf") = .{ .res = ri, .index = (try e.scalars(frame, a.indices[0]))[0], .row_major = e.m.row_major }; return e.bufferAccess(frame, start, e.t.get(f.inst(a.base).ty).resource.elem, a.indices[1..]); } if (frame.vals[a.base.index()] == .buf) return e.bufferAccess(frame, frame.vals[a.base.index()].buf, f.inst(a.base).ty, a.indices); @@ -3394,10 +3394,10 @@ const Emitter = struct { const fn_i = try e.dxOp("dx.op.bufferUpdateCounter", i32t, &.{ i32t, e.handle_ty, i8t }, .nounwind); const n = try e.callOp(fn_i, i32t, &.{ try e.i32Const(70), res.handle, try e.dm.constant(.{ .ty = i8t, .kind = .{ .int = if (inc) 1 else -1 } }) }); if (eq(u8, name, "Append")) { - try e.structuredStore(res.*, n, 0, null, false, frame.f.inst(arg_refs[0]).ty, try e.scalars(frame, arg_refs[0])); + try e.structuredStore(res.*, n, 0, null, e.m.row_major, frame.f.inst(arg_refs[0]).ty, try e.scalars(frame, arg_refs[0])); return .none; } - if (eq(u8, name, "Consume")) return .{ .scalars = try e.structuredLoad(res.*, n, 0, null, false, ty) }; + if (eq(u8, name, "Consume")) return .{ .scalars = try e.structuredLoad(res.*, n, 0, null, e.m.row_major, ty) }; // (BufferUpdateCounter returns the old value for increments and // the new one for decrements, matching HLSL.) return e.list(&.{n}); @@ -3868,7 +3868,7 @@ const Emitter = struct { return .{ .scalars = try e.textureLoad(res.*, mip, coords, null, ty) }; } const idx = (try e.scalars(frame, index_ref))[0]; - if (res.kind == 12) return .{ .scalars = try e.structuredLoad(res.*, idx, 0, null, false, ty) }; + if (res.kind == 12) return .{ .scalars = try e.structuredLoad(res.*, idx, 0, null, e.m.row_major, ty) }; if (res.kind == 11 and !try e.simpleRaw(ty)) return .{ .scalars = try e.rawLoad(res.*, idx, ty) }; const n = try e.flatCount(ty); const c = try e.uniformScalar(ty); @@ -4021,7 +4021,7 @@ const Emitter = struct { if (res.kind >= 1 and res.kind <= 9) return e.textureStore(res.*, try e.scalars(frame, index_ref), try e.scalars(frame, value_ref), frame.f.inst(value_ref).ty); const idx = (try e.scalars(frame, index_ref))[0]; const vals = try e.scalars(frame, value_ref); - if (res.kind == 12) return e.structuredStore(res.*, idx, 0, null, false, frame.f.inst(value_ref).ty, vals); + if (res.kind == 12) return e.structuredStore(res.*, idx, 0, null, e.m.row_major, frame.f.inst(value_ref).ty, vals); if (res.kind == 11 and !try e.simpleRaw(frame.f.inst(value_ref).ty)) return e.rawStore(res.*, idx, frame.f.inst(value_ref).ty, vals); const vt = frame.f.inst(value_ref).ty; const c = try e.uniformScalar(vt); diff --git a/src/front/ast.zig b/src/front/ast.zig index 776e525..bff7163 100644 --- a/src/front/ast.zig +++ b/src/front/ast.zig @@ -48,6 +48,9 @@ pub const TypeRef = struct { /// Type attributes written on this reference, in order: `row_major`, /// `column_major`, `unorm`, `snorm` (template arguments, typedefs). attr_words: []const QualWord = &.{}, + /// `#pragma pack_matrix` in effect where the type was written (true: + /// row_major): the orientation of a matrix declared without one. + pack_matrix: ?bool = null, }; /// Storage classes, type qualifiers and parameter / interpolation diff --git a/src/front/parser.zig b/src/front/parser.zig index b3a97f6..8f0e5de 100644 --- a/src/front/parser.zig +++ b/src/front/parser.zig @@ -49,18 +49,55 @@ pub const Parser = struct { /// The last parseName ended in `::template X`: X takes template /// arguments whatever it names. forced_template: bool = false, + /// `#pragma pack_matrix` lines: the position of the token after them, + /// and row_major. + pack_pragmas: []const PackPragma = &.{}, + + const PackPragma = struct { pos: usize, row_major: bool }; /// Collect every token from `pp` and set up a parser over them. pub fn fromPreprocessor(arena: Allocator, diags: *Diagnostics, pp: *Preprocessor) !Parser { var toks: std.ArrayList(Token) = .empty; + var packs: std.ArrayList(PackPragma) = .empty; while (true) { // Preprocessor diagnostics are ordered by the token being produced. diags.position = toks.items.len; const t = try pp.next(); + // `#pragma pack_matrix` may come between any two tokens (as in + // dxc): it is kept aside, not in the token stream. + if (t.kind == .pragma) if (packMatrix(t.text)) |rm| { + try packs.append(arena, .{ .pos = toks.items.len, .row_major = rm }); + continue; + }; try toks.append(arena, t); if (t.kind == .eof) break; } - return .{ .arena = arena, .diags = diags, .toks = toks.items }; + return .{ .arena = arena, .diags = diags, .toks = toks.items, .pack_pragmas = packs.items }; + } + + /// `pack_matrix(row_major)` / `pack_matrix(column_major)`. + fn packMatrix(text: []const u8) ?bool { + var buf: [64]u8 = undefined; + var n: usize = 0; + for (text) |c| if (!std.ascii.isWhitespace(c)) { + if (n == buf.len) return null; + buf[n] = c; + n += 1; + }; + const s = buf[0..n]; + if (std.mem.eql(u8, s, "pack_matrix(row_major)")) return true; + if (std.mem.eql(u8, s, "pack_matrix(column_major)")) return false; + return null; + } + + /// The `#pragma pack_matrix` in effect at token `pos`. + fn packMatrixAt(p: *const Parser, pos: usize) ?bool { + var r: ?bool = null; + for (p.pack_pragmas) |pp| { + if (pp.pos > pos) break; + r = pp.row_major; + } + return r; } pub fn parseTranslationUnit(p: *Parser) Allocator.Error!ast.TranslationUnit { @@ -503,7 +540,9 @@ pub const Parser = struct { if (w.isIdent("unorm")) norm = .unorm; if (w.isIdent("snorm")) norm = .snorm; } + const type_pos = p.pos; const t = try p.parseTypeInner(); + t.pack_matrix = p.packMatrixAt(type_pos); if (norm != .none) t.norm = norm; if (words.items.len > 0) t.attr_words = words.items; if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes(); diff --git a/src/ir/ir.zig b/src/ir/ir.zig index ed2cb17..ac27764 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -526,6 +526,10 @@ pub const Module = struct { resource_structs: bool = false, /// -enable-16bit-types: half and 16-bit integers are native types. native_16bit: bool = false, + /// -Zpr: matrices that are structured buffer elements themselves + /// (not fields, which carry their own orientation) are row_major. + /// DXIL only: dxc's SPIR-V keeps those column_major. + row_major: bool = false, /// Root signatures: version 1.0 or 1.1 (-force-rootsig-ver), and /// -Qstrip_rootsignature. rootsig_version: enum { v1_0, v1_1 } = .v1_1, diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 5d605c2..ee8454b 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -1942,10 +1942,16 @@ const Lowerer = struct { return r; } + /// A parameter's (or the return value's) interpolation and matrix + /// orientation. + fn paramAttrs(l: *Lowerer, q: ast.Qualifiers, ty: *const ast.TypeRef) SigAttrs { + return .{ .interp = semamod.interpOf(q), .row_major = l.s.sig_row_major.get(ty) orelse q.row_major }; + } + /// A parameter's (or, with the function's attributes, the return /// value's) signature modifiers. - fn sigAttrs(l: *Lowerer, q: ast.Qualifiers, attrs: []const ast.Attribute) SigAttrs { - var a = paramAttrs(q); + fn sigAttrs(l: *Lowerer, q: ast.Qualifiers, attrs: []const ast.Attribute, ty: *const ast.TypeRef) SigAttrs { + var a = l.paramAttrs(q, ty); a.vk_location = l.s.vkAttrInt(attrs, "vk::location"); a.vk_index = l.s.vkAttrInt(attrs, "vk::index"); for (attrs) |at| if (std.mem.eql(u8, at.name, "vk::builtin") and at.args.len == 1 and at.args[0].kind == .string_lit) { @@ -2244,7 +2250,7 @@ const Lowerer = struct { const points = try l.arena.alloc(Ref, patch.count); for (points, 0..) |*v, k| { var next = first; - v.* = try l.vertexIn(entry, patch.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), @intCast(k), register and k == 0, &next, null, pd.name_loc); + v.* = try l.vertexIn(entry, patch.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), @intCast(k), register and k == 0, &next, null, pd.name_loc); } try l.b.store(local, try l.b.add(.{ .op = .{ .construct = points }, .ty = l.irType(pty) })); } @@ -2316,16 +2322,16 @@ const Lowerer = struct { args[i] = try l.b.load(locals[i]); continue; } - if (p.dir != .out) try l.b.store(locals[i], try l.entryInput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name)); + if (p.dir != .out) try l.b.store(locals[i], try l.entryInput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), pd.name_loc, pd.name)); args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i]; } const ret = try l.b.add(.{ .op = .{ .call = .{ .func = pci, .args = args } }, .ty = pcf.ret }); l.patch_io = true; defer l.patch_io = false; - if (pcf.ret != TypeTable.void_type) try l.entryOutput(entry, pcf.ret, semanticOf(pcf.decl.ret_semantics), paramAttrs(pcf.decl.quals), ret, pcf.loc, "return value"); + if (pcf.ret != TypeTable.void_type) try l.entryOutput(entry, pcf.ret, semanticOf(pcf.decl.ret_semantics), l.paramAttrs(pcf.decl.quals, pcf.decl.ret), ret, pcf.loc, "return value"); for (pcf.decl.params, pcf.params, 0..) |pd, p, i| { if (p.dir == .in) continue; - try l.entryOutput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), try l.b.load(locals[i]), pd.name_loc, pd.name); + try l.entryOutput(entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), try l.b.load(locals[i]), pd.name_loc, pd.name); } l.b.terminate(.{ .ret = .none }); entry.patch_wrapper = wrapper; @@ -2384,12 +2390,12 @@ const Lowerer = struct { .vertices => { entry.mesh.max_vertices = arr.len; var next: u32 = @intCast(entry.outputs.items.len); - try l.streamOut(&entry.outputs, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs), null, &next, 0, null, pd.name_loc); + try l.streamOut(&entry.outputs, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs, pd.type), null, &next, 0, null, pd.name_loc); }, .primitives => { entry.mesh.max_primitives = arr.len; var next: u32 = @intCast(entry.patch_constants.items.len); - try l.streamOut(&entry.patch_constants, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs), null, &next, 0, null, pd.name_loc); + try l.streamOut(&entry.patch_constants, arr.elem, semanticOf(pd.semantics), l.sigAttrs(q, pd.attrs, pd.type), null, &next, 0, null, pd.name_loc); }, .indices => { entry.mesh.max_primitives = arr.len; @@ -2419,7 +2425,7 @@ const Lowerer = struct { // Everything else a domain shader reads is per patch. l.patch_io = true; defer l.patch_io = false; - try l.b.store(locals[i], try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name)); + try l.b.store(locals[i], try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), pd.name_loc, pd.name)); args[i] = if (p.dir == .in) try l.b.load(locals[i]) else locals[i]; continue; } @@ -2432,7 +2438,7 @@ const Lowerer = struct { const verts = try l.arena.alloc(Ref, arr.len); for (verts, 0..) |*v, vx| { var next = first; - v.* = try l.vertexIn(&entry, arr.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), @intCast(vx), vx == 0, &next, null, pd.name_loc); + v.* = try l.vertexIn(&entry, arr.elem, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), @intCast(vx), vx == 0, &next, null, pd.name_loc); } try l.b.store(locals[i], try l.b.add(.{ .op = .{ .construct = verts }, .ty = p.type })); args[i] = try l.b.load(locals[i]); @@ -2448,7 +2454,7 @@ const Lowerer = struct { continue; } if (p.dir != .out) { - const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), pd.name_loc, pd.name); + const v = try l.entryInput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), 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]; @@ -2457,7 +2463,7 @@ const Lowerer = struct { for (f.params, 0..) |p, i| if (l.s.types.get(p.type) != .stream) try call_args.append(l.arena, args[i]); std.debug.assert(call_args.items.len == n_args); const ret = try l.b.add(.{ .op = .{ .call = .{ .func = main, .args = call_args.items } }, .ty = f.ret }); - if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), l.sigAttrs(f.decl.quals, f.decl.attrs), ret, f.loc, "return value"); + if (f.ret != TypeTable.void_type) try l.entryOutput(&entry, f.ret, semanticOf(f.decl.ret_semantics), l.sigAttrs(f.decl.quals, f.decl.attrs, f.decl.ret), ret, f.loc, "return value"); for (f.decl.params, f.params, 0..) |pd, p, i| { if (p.dir == .in or l.s.types.get(p.type) == .stream) continue; if (l.b.f.inst(locals[i]).ptr == .mesh) continue; @@ -2466,7 +2472,7 @@ const Lowerer = struct { try l.b.store(ray_srcs[i], v); continue; } - try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs), v, pd.name_loc, pd.name); + try l.entryOutput(&entry, p.type, semanticOf(pd.semantics), l.sigAttrs(pd.quals, pd.attrs, pd.type), v, pd.name_loc, pd.name); } l.b.terminate(.{ .ret = .none }); entry.wrapper = wrapper; @@ -2658,9 +2664,6 @@ pub fn isObject(t: *TypeTable, ty: TypeId) bool { }; } -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]; diff --git a/src/main.zig b/src/main.zig index 8733da2..67e7697 100644 --- a/src/main.zig +++ b/src/main.zig @@ -18,6 +18,8 @@ const Options = struct { preprocess: bool = false, pp_output: ?[]const u8 = null, enable_16bit: bool = false, + row_major: bool = false, + col_major: bool = false, /// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs. rootsig_ver: ?[]const u8 = null, strip_rootsig: bool = false, @@ -132,6 +134,8 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std .spirv => opts.spirv = true, .fspv_target_env_EQ => opts.target_env = v, .enable_16bit_types => opts.enable_16bit = true, + .Zpr => opts.row_major = true, + .Zpc => opts.col_major = true, .force_rootsig_ver, .force_rootsig_ver_ => opts.rootsig_ver = v, .Qstrip_rootsignature => opts.strip_rootsig = true, .rootsig_define => opts.rootsig_define = v, @@ -226,6 +230,7 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std }, } } + if (opts.row_major and opts.col_major) return cli.fail("Cannot specify /Zpr and /Zpc together, use /? to get usage information", .{}); // Like dxc, the last input wins (dxc reads getLastArgValue(OPT_INPUT)). if (parsed.inputs.len > 0) opts.input = parsed.inputs[parsed.inputs.len - 1]; @@ -324,6 +329,7 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: * .sm_minor = if (profile) |p| p.minor else 10, .library = is_lib, .root = opts.entry, + .row_major = opts.row_major, }); try sema.checkUnit(tu); if (!opts.sema and !diags.hasErrors() and profile != null) { @@ -344,6 +350,7 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: * }; if (module) |*mm| { mm.native_16bit = opts.enable_16bit; + mm.row_major = opts.row_major; mm.vk = opts.vk; mm.strip_rootsig = opts.strip_rootsig; if (opts.rootsig_ver) |rv| { diff --git a/src/options.zig b/src/options.zig index 37e871f..e1a635d 100644 --- a/src/options.zig +++ b/src/options.zig @@ -221,7 +221,7 @@ const not_yet = "not supported by zdxc yet"; pub fn support(id: Id) Support { return switch (id) { // Core compilation. - .target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types, .fspv_target_env_EQ => .implemented, + .target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types, .fspv_target_env_EQ, .Zpr, .Zpc => .implemented, .Frs, .Qstrip_rootsignature, .force_rootsig_ver, .force_rootsig_ver_, .rootsig_define => .implemented, .auto_binding_space, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_auto_shift_bindings, .fvk_stage_io_order_EQ, .fspv_flatten_resource_arrays, .fspv_use_legacy_buffer_matrix_order, .fspv_preserve_interface, .fspv_use_vulkan_memory_model, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_unknown_image_format, .fspv_extension_EQ, .fspv_reflect => .implemented, // (Output is the same with or without the unoptimized-IR switch.) @@ -237,7 +237,7 @@ pub fn support(id: Id) Support { .VD, .validator_version => .implemented, // Accepted for build-script compatibility; no effect yet. - .Zpr, .Zpc, .Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .exports, .export_shaders_only, .default_linkage, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_preserve_bindings, .Oconfig => .ignored, + .Gis, .Gfa, .Gfp, .Ges, .Gec, .denorm, .all_resources_bound, .all_resources_bound_, .res_may_alias, .res_may_alias_, .pack_optimized, .pack_optimized_, .pack_prefix_stable, .pack_prefix_stable_, .ffinite_math_only, .fno_finite_math_only, .flegacy_macro_expansion, .flegacy_resource_reservation, .no_legacy_cbuf_layout, .not_use_legacy_cbuf_load_, .enable_payload_qualifiers, .disable_payload_qualifiers, .enable_lifetime_markers, .disable_lifetime_markers, .force_zero_store_lifetimes, .ignore_line_directives, .Qunused_arguments, .fdiagnostics_show_option, .fno_diagnostics_show_option, .fdiagnostics_show_category_EQ, ._vi, .verbose, .v, .encoding, .Wall, .Wdeprecated, ._all_warnings, .Fh, .Vn, .Fsh, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .exports, .export_shaders_only, .default_linkage, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_preserve_bindings, .Oconfig => .ignored, // Dropped by design (see the zdxc plan). ._SLASH_Zi, .Zs, .Fd, .Qembed_debug, .Qsource_in_debug_module, .Qpdb_in_private, .fspv_debug_EQ => .{ .unsupported = dropped_debug }, diff --git a/src/sema/sema.zig b/src/sema/sema.zig index 62c2eb2..fe4c83e 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -31,11 +31,15 @@ pub const Options = struct { /// translation-unit checks; otherwise `root` (the entry point name). library: bool = true, root: ?[]const u8 = null, + /// `-Zpr`: matrices without an orientation (or `#pragma pack_matrix`) + /// are row_major. + row_major: bool = false, }; /// Matrix orientation and float normalization written on a type: sugar -/// that does not change type identity. -pub const TypeAttrs = struct { orientation: ?[]const u8 = null, norm: ?[]const u8 = null }; +/// that does not change type identity. `pack` is the `#pragma +/// pack_matrix` in effect where the type was written (true: row_major). +pub const TypeAttrs = struct { orientation: ?[]const u8 = null, norm: ?[]const u8 = null, pack: ?bool = null }; pub const Storage = enum { global_uniform, global_static, groupshared, cbuffer, local, local_static, param, constant }; @@ -184,6 +188,9 @@ pub const Sema = struct { all_functions: std.ArrayList(*Function) = .empty, /// Type attributes carried by typedef names (clang's attributed-type /// sugar: `typedef row_major float4x4 rm;`). Keyed by name. + /// Function parameters' and return types' matrix orientation (for + /// entry point signatures), keyed by the type as written. + sig_row_major: std.AutoHashMapUnmanaged(*const ast.TypeRef, bool) = .empty, typedef_attrs: std.StringHashMapUnmanaged(TypeAttrs) = .empty, /// Type attributes of the last resolveType result. last_attrs: TypeAttrs = .{}, @@ -1053,6 +1060,7 @@ pub const Sema = struct { } }; for (t.attr_words) |w| s.applyTypeAttr(w, base, &attrs); + if (s.types.get(base) == .matrix) attrs.pack = t.pack_matrix; var ty = base; // Array dimensions on template arguments (`float[3]`). var i = t.array_dims.len; @@ -1064,6 +1072,24 @@ pub const Sema = struct { return ty; } + /// Written orientation, else `#pragma pack_matrix`'s, else `-Zpr`'s. + pub fn isRowMajor(s: *const Sema, a: TypeAttrs) bool { + if (a.orientation) |o| return eql(o, "row_major"); + return a.pack orelse s.opts.row_major; + } + + /// A parameter's or return value's orientation in a signature: as + /// written on it or by `#pragma pack_matrix`. A typedef's orientation + /// is lost there in dxc (and blocks the pragma), leaving `-Zpr`'s. + fn sigRowMajor(s: *const Sema, words: []const ast.QualWord, type_attrs: TypeAttrs) bool { + for (words) |w| { + if (eql(w.word, "row_major")) return true; + if (eql(w.word, "column_major")) return false; + } + if (type_attrs.orientation != null) return s.opts.row_major; + return type_attrs.pack orelse s.opts.row_major; + } + /// Applies a type attribute (dxc's handleHLSLTypeAttr checks). fn applyTypeAttr(s: *Sema, w: ast.QualWord, ty: TypeId, a: *TypeAttrs) void { if (ty == TypeTable.error_type) return; @@ -1156,8 +1182,11 @@ pub const Sema = struct { return TypeTable.error_type; } var elem: TypeId = TypeTable.void_type; + var row_major = false; if (args.len > 0) { elem = try s.typeArg(args[0]) orelse TypeTable.error_type; + const structured = kind == .structured_buffer or kind == .rw_structured_buffer or kind == .append_structured_buffer or kind == .consume_structured_buffer; + if (structured and s.types.get(elem) == .matrix) row_major = s.isRowMajor(if (args[0] == .type) s.last_attrs else .{}); } else if (isTextureOrTypedBuffer(kind)) { elem = try s.types.vector(.float, 4); // Texture2D == Texture2D } @@ -1175,7 +1204,7 @@ pub const Sema = struct { } } if ((kind == .constant_buffer or kind == .texture_buffer) and args.len > 0) s.checkLongVectors(elem, templateArgLoc(args[0]), "ConstantBuffers or TextureBuffers"); - return s.types.intern(.{ .resource = .{ .kind = kind, .elem = elem, .name = n } }); + return s.types.intern(.{ .resource = .{ .kind = kind, .elem = elem, .name = n, .row_major = row_major } }); } const streams = [_]struct { []const u8, @FieldType(@FieldType(types.Type, "stream"), "kind") }{ .{ "PointStream", .point }, .{ "LineStream", .line }, .{ "TriangleStream", .triangle } }; for (streams) |st| if (std.mem.eql(u8, n, st[0])) { @@ -1660,7 +1689,10 @@ pub const Sema = struct { } var base = try s.resolveType(td.type); if (s.types.get(base) == .spirv and td.attrs.len > 0) base = try s.spirvTypeWithAttrs(base, td.attrs); - const attrs = s.checkModifiers(.typedef, td.qual_words, d.loc, base, s.last_attrs); + var attrs = s.checkModifiers(.typedef, td.qual_words, d.loc, base, s.last_attrs); + if (attrs.orientation == null) if (attrs.pack) |rm| { + attrs.orientation = if (rm) "row_major" else "column_major"; + }; const ty = try s.applyArrayDims(base, td.array_dims); try s.declare(td.name, .{ .type = ty }, d.loc); if (attrs.orientation != null or attrs.norm != null) try s.typedef_attrs.put(s.arena, td.name, attrs); @@ -1852,7 +1884,7 @@ pub const Sema = struct { if (s.opts.spirv) if (s.vkAttrInt(v.attrs, "vk::offset")) |vo| if (vo % 16 != 0 and s.types.get(ft) == .@"struct") { s.warn(v.name_loc, null, "The offset provided in the attribute should be 16-byte aligned.", .{}); }; - try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = isRowMajor(fattrs), .semantic = fsem, .interp = interpOf(v.quals), .vk_location = s.vkAttrInt(v.attrs, "vk::location"), .vk_index = s.vkAttrInt(v.attrs, "vk::index"), .vk_offset = if (s.opts.spirv) s.vkAttrInt(v.attrs, "vk::offset") else null, .vk_builtin = vkAttrString(v.attrs, "vk::builtin"), .decorations = if (s.opts.spirv) try s.memberDecorations(v.attrs) else &.{} }); + try info.fields.append(s.arena, .{ .name = v.name, .type = ft, .row_major = s.isRowMajor(fattrs), .semantic = fsem, .interp = interpOf(v.quals), .vk_location = s.vkAttrInt(v.attrs, "vk::location"), .vk_index = s.vkAttrInt(v.attrs, "vk::index"), .vk_offset = if (s.opts.spirv) s.vkAttrInt(v.attrs, "vk::offset") else null, .vk_builtin = vkAttrString(v.attrs, "vk::builtin"), .decorations = if (s.opts.spirv) try s.memberDecorations(v.attrs) else &.{} }); }, .func => {}, else => try s.decl(m, .member), @@ -2251,7 +2283,7 @@ pub const Sema = struct { .init = v.init, .init_scope = s.scope, .decl = v, - .row_major = isRowMajor(decl_attrs), + .row_major = s.isRowMajor(decl_attrs), }; try s.declare(v.name, .{ .variable = variable }, v.name_loc); try s.decl_vars.put(s.arena, v, variable); @@ -2335,11 +2367,15 @@ pub const Sema = struct { // `auto` return types are deduced in HLSL 202x; unconstrained here. const ret = if (f.ret.name.isSimple("auto")) TypeTable.error_type else try s.applyArrayDims(try s.resolveType(f.ret), f.ret_dims); const params = try s.arena.alloc(Param, f.params.len); - _ = s.checkModifiers(if (owner != null) .method else .function, f.qual_words, if (f.qual_words.len > 0) f.qual_words[0].loc else f.ret.loc, ret, s.last_attrs); + const ret_type_attrs = s.last_attrs; + _ = s.checkModifiers(if (owner != null) .method else .function, f.qual_words, if (f.qual_words.len > 0) f.qual_words[0].loc else f.ret.loc, ret, ret_type_attrs); + try s.sig_row_major.put(s.arena, f.ret, s.sigRowMajor(f.qual_words, ret_type_attrs)); s.checkFunctionAttrs(f.attrs); for (f.params, params) |p, *out| { const pbase = try s.resolveType(p.type); - _ = s.checkModifiers(.parameter, p.qual_words, if (p.qual_words.len > 0) p.qual_words[0].loc else p.type.loc, pbase, s.last_attrs); + const ptype_attrs = s.last_attrs; + _ = s.checkModifiers(.parameter, p.qual_words, if (p.qual_words.len > 0) p.qual_words[0].loc else p.type.loc, pbase, ptype_attrs); + try s.sig_row_major.put(s.arena, p.type, s.sigRowMajor(p.qual_words, ptype_attrs)); try s.checkArrayDims(p.name_loc, pbase, p.array_dims); const pt = try s.applyArrayDims(pbase, p.array_dims); s.checkSemantics(.parameter, p.semantics, pt, false); @@ -4128,10 +4164,6 @@ 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; -} - fn eql(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } diff --git a/src/sema/types.zig b/src/sema/types.zig index 6f826a8..18acfc9 100644 --- a/src/sema/types.zig +++ b/src/sema/types.zig @@ -469,7 +469,9 @@ pub const Type = union(enum) { @"enum": *EnumInfo, /// `elem` is the template argument (or the void type when absent). /// `flags`: RayQuery's constant ray flags (template arguments). - resource: struct { kind: ResourceKind, elem: TypeId, name: []const u8, flags: u32 = 0, flags2: u32 = 0 }, + /// `row_major`: a structured buffer's matrix elements are (as written, + /// by `#pragma pack_matrix` or -Zpr; dxc's SPIR-V honors it). + resource: struct { kind: ResourceKind, elem: TypeId, name: []const u8, flags: u32 = 0, flags2: u32 = 0, row_major: bool = false }, sampler: struct { comparison: bool }, string, /// PointStream / LineStream / TriangleStream. @@ -527,7 +529,7 @@ pub const TypeTable = struct { .array => |a| .{ .tag = 4, .a = a.elem, .b = a.len }, .@"struct" => |s| .{ .tag = 5, .a = @intFromPtr(s), .b = 0 }, .@"enum" => |e| .{ .tag = 6, .a = @intFromPtr(e), .b = 0 }, - .resource => |r| .{ .tag = 7, .a = (@as(u64, @backingInt(r.kind)) << 32) | r.elem, .b = std.hash.Wyhash.hash(r.flags | (@as(u64, r.flags2) << 32), r.name) }, + .resource => |r| .{ .tag = 7, .a = (@as(u64, @intFromBool(r.row_major)) << 48) | (@as(u64, @backingInt(r.kind)) << 32) | r.elem, .b = std.hash.Wyhash.hash(r.flags | (@as(u64, r.flags2) << 32), r.name) }, .sampler => |s| .{ .tag = 8, .a = @intFromBool(s.comparison), .b = 0 }, .string => .{ .tag = 9, .a = 0, .b = 0 }, .stream => |s| .{ .tag = 10, .a = @backingInt(s.kind), .b = s.elem }, diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index a69ef65..3f9dabd 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -2202,7 +2202,7 @@ const Emitter = struct { } e.ptr_layouts[ri] = switch (e.m.globals.items[g].space) { .cbuffer => if (e.m.globals.items[g].tbuffer) .{ .rules = e.tbRules(), .row_major = false, .buffer = true } else .{ .rules = e.cbRules(), .row_major = false }, - .resource => .{ .rules = e.sbRules(), .row_major = false, .buffer = true }, + .resource => .{ .rules = e.sbRules(), .row_major = bufferRowMajor(e.t, e.m.globals.items[g].ty), .buffer = true }, else => null, }; }, @@ -2322,7 +2322,7 @@ const Emitter = struct { .cbuffer, .resource => .uniform, else => return e.unsupported("access into this storage is not supported yet", .{}), }; - var pl = if (shader_record) PtrLayout{ .rules = e.sbRules(), .row_major = false } else if (into_cb) PtrLayout{ .rules = e.cbRules(), .row_major = false } else if (into_tb) PtrLayout{ .rules = e.tbRules(), .row_major = false, .buffer = true } else if (into_buffer) PtrLayout{ .rules = e.sbRules(), .row_major = false, .buffer = true } else e.ptr_layouts[a.base.index()]; + var pl = if (shader_record) PtrLayout{ .rules = e.sbRules(), .row_major = false } else if (into_cb) PtrLayout{ .rules = e.cbRules(), .row_major = false } else if (into_tb) PtrLayout{ .rules = e.tbRules(), .row_major = false, .buffer = true } else if (into_buffer) PtrLayout{ .rules = e.sbRules(), .row_major = bufferRowMajor(e.t, f.inst(a.base).ty), .buffer = true } else e.ptr_layouts[a.base.index()]; var ops: std.ArrayList(u32) = .empty; try ops.appendSlice(e.arena, &.{ 0, 0, e.val(a.base) }); var cur = f.inst(a.base).ty; @@ -2952,6 +2952,15 @@ const Emitter = struct { } /// The laid-out element type of a structured / byte-address buffer. + /// A structured buffer type's matrix elements are row_major. + fn bufferRowMajor(t: *TypeTable, ty: TypeId) bool { + return switch (t.get(ty)) { + .resource => |r| r.row_major, + .array => |a| bufferRowMajor(t, a.elem), + else => false, + }; + } + fn bufferElemType(e: *Emitter, ty: TypeId) Error!?Id { const r = switch (e.t.get(ty)) { .resource => |r| r, @@ -2962,7 +2971,7 @@ const Emitter = struct { .structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer => r.elem, else => return null, }; - return try e.layoutTypeId(elem_ty, e.sbRules(), false); + return try e.layoutTypeId(elem_ty, e.sbRules(), r.row_major); } /// The BufferBlock struct of a buffer type (one per HLSL type, so @@ -2972,7 +2981,7 @@ const Emitter = struct { const r = e.t.get(ty).resource; const elem_ty = if (r.kind == .byte_address_buffer or r.kind == .rw_byte_address_buffer) try e.t.scalar(.uint) else r.elem; const elem = (try e.bufferElemType(ty)).?; - const stride = layout.arrayStride(e.t, elem_ty, false, e.sbRules()) catch return e.unsupported("buffer element type '{s}'", .{try e.t.format(e.arena, elem_ty)}); + const stride = layout.arrayStride(e.t, elem_ty, r.row_major, e.sbRules()) catch return e.unsupported("buffer element type '{s}'", .{try e.t.format(e.arena, elem_ty)}); const rt = e.b.newId(); try e.b.emit(.types_globals, .type_runtime_array, &.{ rt, elem }); try e.b.emit(.annotations, .decorate, &.{ rt, 6, stride }); // ArrayStride @@ -2980,10 +2989,10 @@ const Emitter = struct { try e.b.emit(.types_globals, .type_struct, &.{ st, rt }); try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 35, 0 }); // Offset 0 if (e.isTrueMatrix(elem_ty) and storageScalar(e.t.get(elem_ty).matrix.elem).isFloat()) { - // Buffers of (column-major) matrices: HLSL rows are SPIR-V - // columns. - try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 7, layout.matrixStride(e.t, elem_ty, false, e.sbRules()) }); // MatrixStride - try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 4 }); // RowMajor + // Buffers of matrices: HLSL rows are SPIR-V columns, so + // column_major is RowMajor. + try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 7, layout.matrixStride(e.t, elem_ty, r.row_major, e.sbRules()) }); // MatrixStride + try e.b.emit(.annotations, .member_decorate, &.{ st, 0, if (r.row_major) 5 else 4 }); // ColMajor / RowMajor } if (!r.kind.isWritable() and r.kind != .consume_structured_buffer) try e.b.emit(.annotations, .member_decorate, &.{ st, 0, 24 }); // NonWritable try e.b.emit(.annotations, .decorate, &.{ st, e.bufferBlockDecoration() });