Root signatures in shaders, libraries and rootsig targets

[RootSignature(...)] on an entry compiles (global mode, version 1.1 or
-force-rootsig-ver) into an RTS0 part after PSV0; errors are reported as
dxc reports them. Libraries' GlobalRootSignature / LocalRootSignature
subobjects carry their serialized root signature in RDAT's raw bytes.
-T rootsig_1_0 / rootsig_1_1 compile the macro -E names into a root
signature container; -rootsig-define, -Frs and -Qstrip_rootsignature
are supported. All 49 corpus shaders with root signatures match dxc's
RTS0; the DXIL checks now compare RTS0 as well as RDAT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Peter Li 2026-10-31 16:09:26 -07:00
parent 305eadfa51
commit ebd1ea55c2
5 changed files with 148 additions and 8 deletions

View File

@ -19,6 +19,7 @@ const texture = @import("../ir/texture.zig");
const mangle = @import("mangle.zig");
const rdat = @import("rdat.zig");
const libinfo = @import("libinfo.zig");
const rootsig = @import("rootsig.zig");
const TypeId = types.TypeId;
const TypeTable = types.TypeTable;
@ -4516,7 +4517,11 @@ const Emitter = struct {
rec[2] = so.ints[0];
for (so.strings, 0..) |x, k| rec[3 + k] = try b.string(x);
},
.global_root_signature, .local_root_signature => return e.unsupported("root signature subobjects are not supported yet", .{}),
.global_root_signature, .local_root_signature => {
const blob = try e.compileRootSignature(so.strings[0], if (so.kind == .local_root_signature) .local else .global);
rec[2] = try b.bytes(blob);
rec[3] = @intCast(blob.len);
},
}
try b.addSubobject(rec);
}
@ -4584,6 +4589,17 @@ const Emitter = struct {
}
}
/// A root signature's serialized form (RTS0), or an error reported.
fn compileRootSignature(e: *Emitter, text: []const u8, flags: rootsig.CompilationFlags) Error![]u8 {
var d: rootsig.Diagnostic = .{};
const version: rootsig.Version = if (e.m.rootsig_version == .v1_0) .v1_0 else .v1_1;
const blob = try rootsig.compileWithOptions(e.arena, text, .{ .version = version, .flags = flags }, &d) orelse {
_ = e.diags.report(.{ .severity = .@"error", .loc = .none }, "root signature error - {s}", .{d.message()});
return error.Unsupported;
};
return blob;
}
fn writeModule(e: *Emitter, entry: ir.Entry) Error![]u8 {
const dm = &e.dm;
const mdI32 = struct {
@ -4764,10 +4780,11 @@ const Emitter = struct {
.{ .fourcc = container.fourcc("OSG1"), .data = osg1 },
});
if (entry.stage == .hull or entry.stage == .domain or entry.stage == .mesh) try parts.append(e.arena, .{ .fourcc = container.fourcc("PSG1"), .data = psg1 });
try parts.appendSlice(e.arena, &.{
.{ .fourcc = container.fourcc("PSV0"), .data = psv },
.{ .fourcc = container.fourcc("DXIL"), .data = dxil_part },
});
try parts.append(e.arena, .{ .fourcc = container.fourcc("PSV0"), .data = psv });
if (entry.root_signature) |text| if (!e.m.strip_rootsig) {
try parts.append(e.arena, .{ .fourcc = container.fourcc("RTS0"), .data = try e.compileRootSignature(text, .global) });
};
try parts.append(e.arena, .{ .fourcc = container.fourcc("DXIL"), .data = dxil_part });
return container.assemble(gpa, parts.items);
}
};

View File

@ -327,6 +327,8 @@ pub const Entry = struct {
patch_wrapper: ?u32 = null,
/// The HLSL patch constant function.
patch_func: ?u32 = null,
/// `[RootSignature("...")]`: the root signature text.
root_signature: ?[]const u8 = null,
/// The wrapper with no parameters that reads `inputs`, calls `func`
/// and writes `outputs`.
wrapper: u32 = 0,
@ -370,6 +372,10 @@ pub const Module = struct {
subobjects: std.ArrayList(Subobject) = .empty,
/// -enable-16bit-types: half and 16-bit integers are native types.
native_16bit: 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,
strip_rootsig: bool = false,
pub fn addFunction(m: *Module, f: Function) !u32 {
const p = try m.arena.create(Function);

View File

@ -158,7 +158,7 @@ const Lowerer = struct {
var strs: std.ArrayList([]const u8) = .empty;
var ints: std.ArrayList(u32) = .empty;
for (items) |it| switch (it.kind) {
.string_lit => |lit| try strs.append(l.arena, lit[1 .. lit.len - 1]),
.string_lit => |lit| try strs.append(l.arena, try stringContents(l.arena, lit)),
else => try ints.append(l.arena, @truncate(@as(u64, @bitCast(l.s.evalInt(it) orelse 0)))),
};
for (ints.items[0..@min(2, ints.items.len)], 0..) |x, k| so.ints[k] = x;
@ -1891,6 +1891,7 @@ const Lowerer = struct {
}
if (std.ascii.eqlIgnoreCase(a.name, "maxvertexcount") and a.args.len == 1) entry.geometry.max_vertex_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
if (std.ascii.eqlIgnoreCase(a.name, "instance") and a.args.len == 1) entry.geometry.instance_count = @intCast(@max(1, l.s.evalInt(a.args[0]) orelse 1));
if (std.ascii.eqlIgnoreCase(a.name, "RootSignature") and a.args.len == 1 and a.args[0].kind == .string_lit) entry.root_signature = try stringContents(l.arena, a.args[0].kind.string_lit);
}
for (l.streams.items, 0..) |sm, k| entry.geometry.streams[k] = switch (sm.kind.kind) {
.point => .point,
@ -2050,6 +2051,30 @@ fn isMethod(f: *const semamod.Function) bool {
return f.owner != null and !f.decl.quals.static;
}
/// The characters of a string literal (quotes removed, escapes
/// resolved).
pub fn stringContents(a: Allocator, lit: []const u8) Allocator.Error![]const u8 {
const body = if (lit.len >= 2 and lit[0] == '"') lit[1 .. lit.len - 1] else lit;
if (std.mem.indexOfScalar(u8, body, '\\') == null) return body;
var out: std.ArrayList(u8) = .empty;
var k: usize = 0;
while (k < body.len) : (k += 1) {
if (body[k] != '\\' or k + 1 == body.len) {
try out.append(a, body[k]);
continue;
}
k += 1;
try out.append(a, switch (body[k]) {
'n' => '\n',
't' => '\t',
'r' => '\r',
'0' => 0,
else => body[k],
});
}
return out.items;
}
fn isShaderRecord(attrs: []const ast.Attribute) bool {
for (attrs) |a| {
if (std.mem.eql(u8, a.name, "vk::shader_record_ext") or std.mem.eql(u8, a.name, "vk::shader_record_nv")) return true;

View File

@ -18,6 +18,11 @@ const Options = struct {
preprocess: bool = false,
pp_output: ?[]const u8 = null,
enable_16bit: bool = false,
/// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs.
rootsig_ver: ?[]const u8 = null,
strip_rootsig: bool = false,
rootsig_define: ?[]const u8 = null,
rootsig_output: ?[]const u8 = null,
defines: std.ArrayList(front.preproc.Define) = .empty,
include_dirs: std.ArrayList([]const u8) = .empty,
empty: bool = false,
@ -126,6 +131,10 @@ 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,
.force_rootsig_ver, .force_rootsig_ver_ => opts.rootsig_ver = v,
.Qstrip_rootsignature => opts.strip_rootsig = true,
.rootsig_define => opts.rootsig_define = v,
.Frs => opts.rootsig_output = v,
._SLASH_WX => opts.warnings_as_errors = true,
.no_warnings => opts.no_warnings = true,
.W_Joined => {
@ -213,6 +222,16 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
return;
}
// Root signature targets: the root signature in the macro -E names.
if (opts.profile) |p| if (std.mem.eql(u8, p, "rootsig_1_0") or std.mem.eql(u8, p, "rootsig_1_1")) {
const input = opts.input orelse return cli.fail("no input file", .{});
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
const version: zdxc.dxil.rootsig.Version = if (std.mem.eql(u8, p, "rootsig_1_0")) .v1_0 else .v1_1;
const blob = try compileRootSignatureMacro(cli, arena, opts, input, opts.entry, version, .none) orelse return error.CompileFailed;
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = try rootSignatureContainer(arena, blob) });
return;
};
const profile: ?shader.Profile = if (opts.profile) |p|
shader.Profile.parse(p) orelse return cli.fail("unknown profile '{s}'", .{p})
else
@ -275,7 +294,13 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
error.Unsupported => null,
else => |x| return x,
};
if (module) |*mm| mm.native_16bit = opts.enable_16bit;
if (module) |*mm| {
mm.native_16bit = opts.enable_16bit;
mm.strip_rootsig = opts.strip_rootsig;
if (opts.rootsig_ver) |rv| {
if (std.mem.eql(u8, rv, "rootsig_1_0")) mm.rootsig_version = .v1_0 else if (!std.mem.eql(u8, rv, "rootsig_1_1")) return cli.fail("unknown root signature version '{s}'", .{rv});
}
}
}
}
}
@ -311,6 +336,10 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = bytes });
return;
}
// -rootsig-define: the macro's root signature for the entry.
if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) {
m.entries.items[0].root_signature = try rootSignatureMacroText(cli, arena, opts, input, macro) orelse return error.CompileFailed;
};
const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags) catch |err| switch (err) {
error.Unsupported => {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
@ -321,6 +350,12 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
};
const path = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = path, .data = bytes });
if (opts.rootsig_output) |rs_path| {
const text = (if (m.entries.items.len == 1) m.entries.items[0].root_signature else null) orelse return cli.fail("-Frs: the shader has no root signature", .{});
var d: zdxc.dxil.rootsig.Diagnostic = .{};
const blob = try zdxc.dxil.rootsig.compileWithOptions(arena, text, .{ .version = if (m.rootsig_version == .v1_0) .v1_0 else .v1_1, .flags = .global }, &d) orelse return cli.fail("root signature error - {s}", .{d.message()});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = rs_path, .data = try rootSignatureContainer(arena, blob) });
}
return;
}
return cli.fail("code generation is not implemented yet: the input was checked but no output was written (use -zdxc-empty for a placeholder shader)", .{});
@ -338,3 +373,59 @@ fn run(cli: Cli, arena: std.mem.Allocator, args: []const [:0]const u8, stdout: *
const out = opts.output orelse return cli.fail("missing -Fo <file>", .{});
try Io.Dir.cwd().writeFile(cli.io, .{ .sub_path = out, .data = bytes });
}
/// The text of the root signature macro `macro` defines in `input` (its
/// string literals concatenated), or null after reporting an error.
fn rootSignatureMacroText(cli: Cli, arena: std.mem.Allocator, opts: Options, input: []const u8, macro: []const u8) !?[]const u8 {
const text = try Io.Dir.cwd().readFileAlloc(cli.io, input, arena, .limited(256 << 20));
var disk: front.source.DiskFs = .{ .io = cli.io };
var sm = front.source.SourceManager.init(arena, disk.fileSystem());
var diags = zdxc.Diagnostics.init(arena);
var pp = front.preproc.Preprocessor.init(arena, &sm, &diags, .{
.defines = opts.defines.items,
.include_dirs = opts.include_dirs.items,
.stage = 6,
});
// Expand the macro after a marker at the end of the file.
const marker = "__zdxc_root_signature__";
try pp.enterMainText(input, try std.mem.concat(arena, u8, &.{ text, "\n" ++ marker ++ " ", macro, "\n" }));
var parts: std.ArrayList(u8) = .empty;
var seen = false;
var any = false;
while (true) {
const t = try pp.next();
if (t.kind == .eof) break;
if (!seen) {
seen = t.kind == .identifier and std.mem.eql(u8, t.text, marker);
continue;
}
if (t.kind != .string) {
_ = diags.report(.{ .severity = .@"error", .loc = t.loc }, "root signature macro '{s}' must expand to string literals", .{macro});
break;
}
any = true;
try parts.appendSlice(arena, try zdxc.ir.lower.stringContents(arena, t.text));
}
if (!any and !diags.hasErrors()) _ = diags.report(.{ .severity = .@"error", .loc = .none }, "root signature macro '{s}' is not defined", .{macro});
if (diags.hasErrors()) {
try diags.render(&sm, cli.stderr, .{ .format = opts.diag_format, .color = false });
try cli.stderr.flush();
return null;
}
return parts.items;
}
fn compileRootSignatureMacro(cli: Cli, arena: std.mem.Allocator, opts: Options, input: []const u8, macro: []const u8, version: zdxc.dxil.rootsig.Version, flags: zdxc.dxil.rootsig.CompilationFlags) !?[]const u8 {
const text = try rootSignatureMacroText(cli, arena, opts, input, macro) orelse return null;
var d: zdxc.dxil.rootsig.Diagnostic = .{};
return try zdxc.dxil.rootsig.compileWithOptions(arena, text, .{ .version = version, .flags = flags }, &d) orelse {
try cli.stderr.print("{s}: error: root signature error - {s}\n", .{ input, d.message() });
try cli.stderr.flush();
return null;
};
}
/// A container holding only the root signature (RTS0) part.
fn rootSignatureContainer(arena: std.mem.Allocator, blob: []const u8) ![]u8 {
return zdxc.dxil.container.assemble(arena, &.{.{ .fourcc = zdxc.dxil.container.fourcc("RTS0"), .data = blob }});
}

View File

@ -222,6 +222,7 @@ 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,
.Frs, .Qstrip_rootsignature, .force_rootsig_ver, .force_rootsig_ver_, .rootsig_define => .implemented,
// Diagnostics.
._SLASH_WX, .no_warnings, .W_Joined, .Wno_vk_ignored_features, .Wno_vk_emulated_features => .implemented,
.fdiagnostics_format_EQ, .ferror_limit_EQ, .fdiagnostics_color, .fdiagnostics_color_EQ => .implemented,
@ -233,7 +234,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, .Frs, .Fre, .Zss, .Zsb, .Qstrip_reflect, .Qstrip_debug, .Qstrip_priv, .Qstrip_rootsignature, .Qkeep_reflect_in_dxil, .Qstrip_reflect_from_dxil, .force_rootsig_ver, .force_rootsig_ver_, .rootsig_define, .auto_binding_space, .exports, .export_shaders_only, .default_linkage, .fvk_stage_io_order_EQ, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fspv_use_legacy_buffer_matrix_order, .fspv_reflect, .fspv_extension_EQ, .fspv_flatten_resource_arrays, .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, .fvk_auto_shift_bindings, .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, .auto_binding_space, .exports, .export_shaders_only, .default_linkage, .fvk_stage_io_order_EQ, .fvk_b_shift, .fvk_t_shift, .fvk_s_shift, .fvk_u_shift, .fvk_bind_globals, .fvk_bind_register, .vkbr, .fvk_invert_y, .fvk_use_dx_position_w, .fvk_support_nonzero_base_instance, .fvk_support_nonzero_base_vertex, .fvk_use_gl_layout, .fvk_use_dx_layout, .fvk_use_scalar_layout, .fspv_use_legacy_buffer_matrix_order, .fspv_reflect, .fspv_extension_EQ, .fspv_flatten_resource_arrays, .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, .fvk_auto_shift_bindings, .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 },