From 1ac6d65718245a6b58fe1051ea726e29b9edc75e Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sat, 31 Oct 2026 16:55:14 -0700 Subject: [PATCH] SPIR-V reflection, extension and entry point options; vk::builtin -fspv-reflect adds SPV_GOOGLE UserSemantic, UserTypeGOOGLE and CounterBuffer decorations; -fspv-extension= restricts the extensions used (KHR allows all KHR ones; the NV compute derivatives extension is used when only it is allowed); -fspv-entrypoint-name= renames the entry point; -fspv-enable-maximal-reconvergence; -fvk-support-nonzero-base- instance / -vertex subtract the base instance / vertex as dxc does; -fspv-use-unknown-image-format. [[vk::builtin(...)]] on parameters and fields (PointSize, HelperInvocation, BaseVertex, BaseInstance, DrawIndex, DeviceIndex). Constant buffer block types are named type. only. Co-Authored-By: Claude Opus 5.5 --- src/ir/ir.zig | 16 +++++- src/ir/lower.zig | 8 ++- src/main.zig | 7 +++ src/options.zig | 4 +- src/sema/sema.zig | 11 +++- src/sema/types.zig | 1 + src/spirv/builder.zig | 2 + src/spirv/emit.zig | 104 +++++++++++++++++++++++++++++++++++-- test/spirv/tbuffer.hlsl | 2 +- test/spirv/vk_options.hlsl | 30 +++++++++++ 10 files changed, 175 insertions(+), 10 deletions(-) create mode 100644 test/spirv/vk_options.hlsl diff --git a/src/ir/ir.zig b/src/ir/ir.zig index ff92666..0a61d81 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -236,6 +236,19 @@ pub const VkOptions = struct { alpha_io_order: bool = false, /// -fvk-use-gl-layout, -fvk-use-dx-layout, -fvk-use-scalar-layout. layout: enum { default, gl, dx, scalar } = .default, + /// -fspv-entrypoint-name=, -fspv-enable-maximal-reconvergence, + /// -fvk-support-nonzero-base-instance / -vertex, + /// -fspv-use-unknown-image-format. + entry_name: ?[]const u8 = null, + /// -fspv-reflect: SPV_GOOGLE semantic / user type / counter + /// decorations. + reflect: bool = false, + /// -fspv-extension=: the only extensions allowed (empty: any). + extensions: std.ArrayList([]const u8) = .empty, + maximal_reconvergence: bool = false, + nonzero_base_instance: bool = false, + nonzero_base_vertex: bool = false, + unknown_image_format: bool = false, /// -fvk-invert-y, -fvk-use-dx-position-w. invert_y: bool = false, dx_position_w: bool = false, @@ -338,9 +351,10 @@ pub const SigElement = struct { per_vertex: bool = false, /// The semantic as written (`TEXCOORD`, `TEXCOORD3`). spelling: ?[]const u8 = null, - /// [[vk::location(n)]], [[vk::index(n)]]. + /// [[vk::location(n)]], [[vk::index(n)]], [[vk::builtin("...")]]. vk_location: ?u32 = null, vk_index: ?u32 = null, + vk_builtin: ?[]const u8 = null, }; pub const Primitive = enum(u8) { point = 1, line = 2, triangle = 3, line_adj = 6, triangle_adj = 7 }; diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 68be324..da3fe0c 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -1599,11 +1599,12 @@ const Lowerer = struct { row_major: bool = false, vk_location: ?u32 = null, vk_index: ?u32 = null, + vk_builtin: ?[]const u8 = null, /// 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, .vk_location = fld.vk_location, .vk_index = fld.vk_index }; + return .{ .interp = if (own != 0) fld.interp else outer.interp, .row_major = fld.row_major, .vk_location = fld.vk_location, .vk_index = fld.vk_index, .vk_builtin = fld.vk_builtin }; } }; @@ -1613,6 +1614,7 @@ const Lowerer = struct { r.row_major = attrs.row_major; r.vk_location = attrs.vk_location; r.vk_index = attrs.vk_index; + r.vk_builtin = attrs.vk_builtin; return r; } @@ -1622,6 +1624,10 @@ const Lowerer = struct { var a = paramAttrs(q); 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) { + const lit = at.args[0].kind.string_lit; + a.vk_builtin = lit[1 .. lit.len - 1]; + }; return a; } diff --git a/src/main.zig b/src/main.zig index 73b77fe..9104b72 100644 --- a/src/main.zig +++ b/src/main.zig @@ -168,6 +168,13 @@ fn parseArgs(cli: Cli, arena: std.mem.Allocator, argv: []const [:0]const u8, std .fvk_use_gl_layout => opts.vk.layout = .gl, .fvk_use_dx_layout => opts.vk.layout = .dx, .fvk_use_scalar_layout => opts.vk.layout = .scalar, + .fspv_entrypoint_name_EQ => opts.vk.entry_name = v, + .fspv_extension_EQ => try opts.vk.extensions.append(arena, v), + .fspv_reflect => opts.vk.reflect = true, + .fspv_enable_maximal_reconvergence => opts.vk.maximal_reconvergence = true, + .fvk_support_nonzero_base_instance => opts.vk.nonzero_base_instance = true, + .fvk_support_nonzero_base_vertex => opts.vk.nonzero_base_vertex = true, + .fspv_use_unknown_image_format => opts.vk.unknown_image_format = true, .fvk_use_dx_position_w => opts.vk.dx_position_w = true, .fvk_stage_io_order_EQ => { if (std.mem.eql(u8, v, "alpha")) opts.vk.alpha_io_order = true else if (!std.mem.eql(u8, v, "decl")) return cli.fail("unknown -fvk-stage-io-order '{s}'", .{v}); diff --git a/src/options.zig b/src/options.zig index f76f9a9..5c90279 100644 --- a/src/options.zig +++ b/src/options.zig @@ -223,7 +223,7 @@ pub fn support(id: Id) Support { // Core compilation. .target_profile, .entrypoint, .Fo, .D, .I, .P, .Fi, .hlsl_version, .spirv, .enable_16bit_types, .fspv_target_env_EQ => .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, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout => .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, .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.) .fcgl => .ignored, // Diagnostics. @@ -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, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fspv_use_legacy_buffer_matrix_order, .fspv_reflect, .fspv_extension_EQ, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_entrypoint_name_EQ, .fspv_enable_maximal_reconvergence, .fspv_use_vulkan_memory_model, .fspv_use_unknown_image_format, .fspv_preserve_bindings, .fspv_preserve_interface, .Oconfig => .ignored, + .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_use_legacy_buffer_matrix_order, .fspv_reduce_load_size, .fspv_fix_func_call_arguments, .fspv_use_vulkan_memory_model, .fspv_preserve_bindings, .fspv_preserve_interface, .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 5c3cf93..ad874ad 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -1081,6 +1081,15 @@ pub const Sema = struct { return TypeTable.error_type; } + /// The string argument of attribute `name` (`[[vk::builtin("X")]]`). + pub fn vkAttrString(attrs: []const ast.Attribute, name: []const u8) ?[]const u8 { + for (attrs) |a| if (std.mem.eql(u8, a.name, name) and a.args.len == 1 and a.args[0].kind == .string_lit) { + const lit = a.args[0].kind.string_lit; + return lit[1 .. lit.len - 1]; + }; + return null; + } + /// The constant argument of attribute `name` (`[[vk::location(2)]]`). pub fn vkAttrInt(s: *Sema, attrs: []const ast.Attribute, name: []const u8) ?u32 { for (attrs) |a| if (std.mem.eql(u8, a.name, name) and a.args.len >= 1) { @@ -1488,7 +1497,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 }); + 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") }); }, .func => {}, else => try s.decl(m, .member), diff --git a/src/sema/types.zig b/src/sema/types.zig index 09695a5..0b294ef 100644 --- a/src/sema/types.zig +++ b/src/sema/types.zig @@ -348,6 +348,7 @@ pub const Field = struct { vk_location: ?u32 = null, vk_index: ?u32 = null, vk_offset: ?u32 = null, + vk_builtin: ?[]const u8 = null, }; /// A bitfield member: `width` bits at `offset` in storage field `storage`. diff --git a/src/spirv/builder.zig b/src/spirv/builder.zig index e05a2cd..3c610d1 100644 --- a/src/spirv/builder.zig +++ b/src/spirv/builder.zig @@ -37,6 +37,8 @@ pub const Op = enum(u16) { spec_constant_true = 48, spec_constant_false = 49, spec_constant = 50, + decorate_id = 332, + decorate_string = 5632, constant_false = 42, constant = 43, constant_composite = 44, diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index 4efee4e..eb4c8ed 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -45,6 +45,7 @@ const Capability = enum(u32) { clip_distance = 32, cull_distance = 33, draw_parameters = 4427, + device_group = 4437, multi_view = 4439, fragment_shading_rate_khr = 4422, stencil_export_ext = 5013, @@ -780,7 +781,12 @@ const Emitter = struct { .library => return e.unsupported("library targets are not supported", .{}), }; const wrapper = e.func_ids[entry.wrapper]; - try e.b.emitWithString(.entry_points, .entry_point, &.{ model, wrapper }, entry.name, try e.entryInterface(wrapper)); + const name = if (e.m.entries.items.len == 1) e.vk.entry_name orelse entry.name else entry.name; + try e.b.emitWithString(.entry_points, .entry_point, &.{ model, wrapper }, name, try e.entryInterface(wrapper)); + if (e.vk.maximal_reconvergence) { + try e.extension("SPV_KHR_maximal_reconvergence"); + try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 6023 }); // MaximallyReconvergesKHR + } switch (entry.stage) { .compute => try e.b.emit(.execution_modes, .execution_mode, &.{ wrapper, 17, entry.num_threads[0], entry.num_threads[1], entry.num_threads[2] }), .geometry => { @@ -904,11 +910,14 @@ const Emitter = struct { try e.b.emit(.annotations, .decorate, &.{ var_id, 34, slot.set }); // DescriptorSet try e.b.emit(.annotations, .decorate, &.{ var_id, 33, slot.binding }); // Binding try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{}); + try e.userType(var_id, g.ty, g); e.global_vars[gi] = var_id; }, .cbuffer => { // tbuffers: read-only storage buffers, std430. - const st = try e.layoutTypeId(g.ty, if (g.tbuffer) e.tbRules() else e.cbRules(), false); + // (A struct of its own, named `type.` as in dxc.) + const st = e.b.newId(); + try e.layoutStruct(st, e.t.get(g.ty).@"struct", if (g.tbuffer) e.tbRules() else e.cbRules(), try std.fmt.allocPrint(e.arena, "type.{s}", .{g.name})); try e.b.emit(.annotations, .decorate, &.{ st, if (g.tbuffer) e.bufferBlockDecoration() else 2 }); // Block if (g.tbuffer) for (0..e.t.get(g.ty).@"struct".fields.items.len) |k| { try e.b.emit(.annotations, .member_decorate, &.{ st, @intCast(k), 24 }); // NonWritable @@ -920,8 +929,8 @@ const Emitter = struct { const slot = try e.slotOf(@intCast(gi), false); try e.b.emit(.annotations, .decorate, &.{ var_id, 34, slot.set }); // DescriptorSet try e.b.emit(.annotations, .decorate, &.{ var_id, 33, slot.binding }); // Binding - try e.b.emitWithString(.debug_names, .name, &.{st}, try std.fmt.allocPrint(e.arena, "type.{s}", .{g.name}), &.{}); try e.b.emitWithString(.debug_names, .name, &.{var_id}, g.name, &.{}); + try e.userType(var_id, g.ty, g); e.global_vars[gi] = var_id; }, .groupshared, .private => { @@ -987,6 +996,10 @@ const Emitter = struct { try e.b.emit(.annotations, .decorate, &.{ var_id, 33, slot.binding }); // Binding try e.b.emitWithString(.debug_names, .name, &.{var_id}, try std.fmt.allocPrint(e.arena, "counter.var.{s}", .{g.name}), &.{}); e.counter_vars[gi] = var_id; + if (e.vk.reflect and e.global_vars[gi] != 0) { + try e.extension("SPV_GOOGLE_hlsl_functionality1"); + try e.b.emit(.annotations, .decorate_id, &.{ e.global_vars[gi], 5634, var_id }); // CounterBuffer + } } } @@ -1295,6 +1308,29 @@ const Emitter = struct { const uint1 = try t.scalar(.uint); const float4 = try t.vector(.float, 4); const eq = std.ascii.eqlIgnoreCase; + // [[vk::builtin("...")]]: the named builtin, of the declared type. + if (el.vk_builtin) |vb| { + const named = [_]struct { []const u8, u32 }{ + .{ "PointSize", 1 }, .{ "HelperInvocation", 23 }, .{ "BaseVertex", 4424 }, + .{ "BaseInstance", 4425 }, .{ "DrawIndex", 4426 }, .{ "DeviceIndex", 4438 }, + .{ "ViewportMaskNV", 5253 }, + }; + for (named) |b| if (std.mem.eql(u8, vb, b[0])) { + switch (b[1]) { + 4424, 4425, 4426 => { + try e.cap(.draw_parameters); + if (e.spv_minor < 3) try e.extension("SPV_KHR_shader_draw_parameters"); + }, + 4438 => { + try e.cap(.device_group); + if (e.spv_minor < 3) try e.extension("SPV_KHR_device_group"); + }, + else => {}, + } + return .{ .id = b[1], .ty = el.ty }; + }; + return e.unsupported("[[vk::builtin(\"{s}\")]] is not supported yet", .{vb}); + } // Builtins exist only for some stages and directions; elsewhere a // system value is an ordinary located variable (as in dxc). if ((stage == .compute or stage == .mesh or stage == .amplification) and input) { @@ -1502,6 +1538,7 @@ const Emitter = struct { // (Named after the semantic as written, as dxc.) const name = if (el.spelling) |sp| try std.fmt.allocPrint(e.arena, "{s}.var.{s}", .{ if (input) "in" else "out", sp }) else try std.fmt.allocPrint(e.arena, "{s}.var.{s}{d}", .{ if (input) "in" else "out", el.semantic, el.semantic_index }); try e.b.emitWithString(.debug_names, .name, &.{var_id}, name, &.{}); + try e.userSemantic(var_id, el); iface.* = .{ .var_id = var_id, .ty = vty, .elem_array = bi != null and e.t.get(bi.?.ty) == .array, .builtin = if (bi) |x| x.id else std.math.maxInt(u32) }; try e.useVar(var_id); } @@ -2269,6 +2306,14 @@ const Emitter = struct { e.vals[ri] = try e.loadInterface(iface, .input, i.ty); // -fvk-use-dx-position-w: SV_Position.w as in DirectX (w, // not 1 / w). + // -fvk-support-nonzero-base-*: DX's vertex / instance IDs + // start at 0. + if ((iface.builtin == 43 and e.vk.nonzero_base_instance) or (iface.builtin == 42 and e.vk.nonzero_base_vertex)) { + try e.cap(.draw_parameters); + if (e.spv_minor < 3) try e.extension("SPV_KHR_shader_draw_parameters"); + const base = try e.op1(.load, i.ty, &.{try e.builtinInput(if (iface.builtin == 43) 4425 else 4424, i.ty)}); + e.vals[ri] = try e.op1(.i_sub, i.ty, &.{ e.vals[ri], base }); + } if (e.vk.dx_position_w and iface.builtin == 15 and e.entry.stage == .pixel) { const f1 = try e.t.scalar(.float); const w = try e.op1(.composite_extract, f1, &.{ e.vals[ri], 3 }); @@ -2503,7 +2548,8 @@ const Emitter = struct { else => return e.unsupported("derivatives are not available in {s} shaders", .{@tagName(entry.stage)}), } if (e.st.derivative_mode != 0) return; - try e.extension("SPV_KHR_compute_shader_derivatives"); + // (The NV extension has the same capabilities and modes.) + try e.extension(if (!e.extensionAllowed("SPV_KHR_compute_shader_derivatives") and e.extensionAllowed("SPV_NV_compute_shader_derivatives")) "SPV_NV_compute_shader_derivatives" else "SPV_KHR_compute_shader_derivatives"); const t = entry.num_threads; if (t[0] % 2 == 0 and t[1] % 2 == 0) { try e.cap(.compute_derivative_group_quads); @@ -2668,8 +2714,19 @@ const Emitter = struct { return e.unsupported("resource type '{s}' is not supported yet", .{try e.t.format(e.arena, ty)}); } + fn extensionAllowed(e: *Emitter, name: []const u8) bool { + if (e.vk.extensions.items.len == 0) return true; + for (e.vk.extensions.items) |x| { + if (std.mem.eql(u8, x, name)) return true; + // `KHR`: every KHR extension. + if (std.mem.eql(u8, x, "KHR") and std.mem.startsWith(u8, name, "SPV_KHR_")) return true; + } + return false; + } + fn extension(e: *Emitter, name: []const u8) Error!void { for (e.extensions.items) |x| if (std.mem.eql(u8, x, name)) return; + if (!e.extensionAllowed(name)) return e.unsupported("SPIR-V extension '{s}' required but not permitted to use (-fspv-extension)", .{name}); try e.extensions.append(e.arena, name); try e.b.emitWithString(.extensions, .extension, &.{}, name, &.{}); } @@ -2782,6 +2839,44 @@ const Emitter = struct { }; } + /// -fspv-reflect: the semantic of a stage variable. + fn userSemantic(e: *Emitter, v: Id, el: ir.SigElement) Error!void { + if (!e.vk.reflect) return; + try e.extension("SPV_GOOGLE_hlsl_functionality1"); + const sem = el.spelling orelse if (el.semantic_index > 0) try std.fmt.allocPrint(e.arena, "{s}{d}", .{ el.semantic, el.semantic_index }) else el.semantic; + try e.b.emitWithString(.annotations, .decorate_string, &.{ v, 5635 }, sem, &.{}); // UserSemantic + } + + /// -fspv-reflect: the HLSL type of a resource (`structuredbuffer:`). + fn userType(e: *Emitter, v: Id, ty: TypeId, g: ir.Global) Error!void { + if (!e.vk.reflect) return; + var t = ty; + while (e.t.get(t) == .array) t = e.t.get(t).array.elem; + const text: []const u8 = switch (e.t.get(t)) { + .resource => |r| blk: { + const name = try std.ascii.allocLowerString(e.arena, r.name); + if (r.elem == TypeTable.void_type or r.kind == .byte_address_buffer or r.kind == .rw_byte_address_buffer or r.kind == .raytracing_acceleration_structure) break :blk name; + break :blk try std.fmt.allocPrint(e.arena, "{s}:<{s}>", .{ name, try e.hlslTypeName(r.elem) }); + }, + .@"struct" => if (g.space == .cbuffer) (if (g.tbuffer) "tbuffer" else "cbuffer") else return, + else => return, + }; + try e.extension("SPV_GOOGLE_hlsl_functionality1"); + try e.extension("SPV_GOOGLE_user_type"); + try e.b.emitWithString(.annotations, .decorate_string, &.{ v, 5636 }, text, &.{}); // UserTypeGOOGLE + } + + /// A type as HLSL writes it (`float4`, `uint2x3`, `S`). + fn hlslTypeName(e: *Emitter, ty: TypeId) Error![]const u8 { + return switch (e.t.get(ty)) { + .scalar => |s| @tagName(s), + .vector => |v| std.fmt.allocPrint(e.arena, "{s}{d}", .{ @tagName(v.elem), v.len }), + .matrix => |m| std.fmt.allocPrint(e.arena, "{s}{d}x{d}", .{ @tagName(m.elem), m.rows, m.cols }), + .@"struct" => |st| st.name, + else => e.t.format(e.arena, ty), + }; + } + fn accelType(e: *Emitter) Error!Id { if (e.accel_type == 0) { e.accel_type = e.b.newId(); @@ -2968,6 +3063,7 @@ const Emitter = struct { /// dxc's image format for typed buffers and RW textures. fn imageFormat(e: *Emitter, elem: TypeId) u32 { + if (e.vk.unknown_image_format) return 0; const n = e.t.componentCount(elem) orelse return 0; const c = e.t.component(elem) orelse return 0; const k: usize = switch (n) { diff --git a/test/spirv/tbuffer.hlsl b/test/spirv/tbuffer.hlsl index 902898d..c352a8e 100644 --- a/test/spirv/tbuffer.hlsl +++ b/test/spirv/tbuffer.hlsl @@ -1,7 +1,7 @@ // PROFILE: cs_6_0 // tbuffer blocks and TextureBuffer: read-only std430 buffer blocks. // ZCHECK: OpMemberDecorate %type_TextureBuffer_S 0 NonWritable -// ZCHECK: OpMemberDecorate %TB 0 NonWritable +// ZCHECK: OpMemberDecorate %type_TB 0 NonWritable struct S { float4 a; float b; float3 c; }; tbuffer TB : register(t0) { float4 x; float y; S s; }; TextureBuffer tbs : register(t1); diff --git a/test/spirv/vk_options.hlsl b/test/spirv/vk_options.hlsl new file mode 100644 index 0000000..9c24efb --- /dev/null +++ b/test/spirv/vk_options.hlsl @@ -0,0 +1,30 @@ +// PROFILE: vs_6_0 +// FLAGS: -E main -fvk-invert-y -fvk-support-nonzero-base-instance -fspv-entrypoint-name=vsmain -fspv-reflect -fvk-use-gl-layout -fspv-enable-maximal-reconvergence +// Vulkan options: flipped SV_Position.y, instance IDs counted from the base +// instance, a renamed entry point, reflection decorations, strict GLSL +// layout, maximal reconvergence, and [[vk::builtin]]. +// ZCHECK: OpEntryPoint Vertex %main "vsmain" +// ZCHECK: OpExecutionMode %main MaximallyReconvergesKHR +// ZCHECK: OpExtension "SPV_GOOGLE_hlsl_functionality1" +// ZCHECK: OpDecorateString %in_var_POSITION UserSemantic "POSITION" +// ZCHECK: OpDecorateString %Params UserTypeGOOGLE "cbuffer" +// ZCHECK: BuiltIn PointSize +// ZCHECK: BuiltIn BaseInstance +// ZCHECK: OpMemberDecorate %type_Params 1 Offset 16 +// ZCHECK: OpFNegate %float +// ZCHECK: OpISub %uint +cbuffer Params { float a; float3 b; }; + +struct Out { + float4 pos : SV_Position; + [[vk::builtin("PointSize")]] float size : PSIZE; + uint id : ID; +}; + +Out main(float3 p : POSITION, uint inst : SV_InstanceID) { + Out o; + o.pos = float4(p * b, a); + o.size = 1; + o.id = inst; + return o; +}