From a36fd077ba62d2ee7715a3ca050a50f19fc34b73 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sat, 31 Oct 2026 15:45:56 -0700 Subject: [PATCH] DXIL library targets with ray tracing shaders Libraries emit each entry as a function of its own: ray tracing shaders with Microsoft-mangled names taking payload / attributes / parameters by pointer, compute shaders by name. Resources become external globals whose handles come from createHandleForLib (annotated from SM 6.6) in the functions that use them; unbound ones stay at -1 until linked. Adds the ray tracing operations (TraceRay, CallShader, ReportHit, IgnoreHit, AcceptHitAndEndSearch, system values), library metadata (function annotations, entries by name with payload / attribute sizes), and the RDAT part, built as dxc builds it: per-function flags, valid stages and minimum shader model come from the emitted instructions and a table of dxc's per-operation requirements. Libraries without shaders are empty, as in dxc. The DXIL checks compare RDAT with dxc's byte for byte. Co-Authored-By: Claude Opus 5.5 --- src/dxil/emit.zig | 578 +++++++++++++++++++++++++++++++++++++---- src/dxil/libinfo.zig | 314 ++++++++++++++++++++++ src/dxil/mangle.zig | 135 ++++++++++ src/dxil/module.zig | 12 +- src/dxil/op_compat.zig | 219 ++++++++++++++++ src/dxil/rdat.zig | 168 ++++++++++++ src/ir/lower.zig | 4 - src/spirv/emit.zig | 10 +- 8 files changed, 1373 insertions(+), 67 deletions(-) create mode 100644 src/dxil/libinfo.zig create mode 100644 src/dxil/mangle.zig create mode 100644 src/dxil/op_compat.zig create mode 100644 src/dxil/rdat.zig diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index dc4637e..e8d2fcc 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -16,6 +16,9 @@ const hash = @import("hash.zig"); const layout = @import("../ir/layout.zig"); const signature = @import("signature.zig"); const texture = @import("../ir/texture.zig"); +const mangle = @import("mangle.zig"); +const rdat = @import("rdat.zig"); +const libinfo = @import("libinfo.zig"); const TypeId = types.TypeId; const TypeTable = types.TypeTable; @@ -112,6 +115,8 @@ const Resource = struct { view: bool = false, /// The resource type (without array dimensions); 0 for cbuffer blocks. rty: TypeId = 0, + /// Libraries: the module global standing for the resource. + lib_global: ?u32 = null, const Class = enum(u8) { srv = 0, uav = 1, cbuffer = 2, sampler = 3 }; }; @@ -199,6 +204,14 @@ const Emitter = struct { handle_ty: DType = 0, + /// Libraries: each entry is a function of its own; resources are + /// globals whose handles are made in each function that uses them. + lib: bool = false, + /// The current function's arguments (ray tracing payload / attributes). + lib_args: []const Value = &.{}, + /// Prologue instructions dropped again if unused (resource handles). + lib_removable: std.AutoHashMapUnmanaged(u32, void) = .empty, + fn unsupported(e: *Emitter, comptime fmt: []const u8, args: anytype) Error { _ = e.diags.report(.{ .severity = .@"error", .loc = .none }, "DXIL code generation: " ++ fmt, args); return error.Unsupported; @@ -342,7 +355,8 @@ const Emitter = struct { fn run(e: *Emitter, gpa: Allocator) Error![]u8 { const m = e.m; - if (m.entries.items.len != 1 or e.profile.kind == .library) return e.unsupported("library targets are not supported yet", .{}); + if (e.profile.kind == .library) return e.runLibrary(gpa); + if (m.entries.items.len != 1) return e.unsupported("several entry points are not supported here", .{}); const entry = m.entries.items[0]; e.entry = entry; switch (entry.stage) { @@ -410,6 +424,235 @@ const Emitter = struct { return .{ .global = 0, .class = class, .kind = kind, .elem = r.elem, .rty = ty, .has_counter = r.kind == .append_structured_buffer or r.kind == .consume_structured_buffer }; } + // ------------------------------------------------------------------ + // Libraries + + const LibFunc = struct { + func: u32, + name: []const u8, + unmangled: []const u8, + stage: ir.Stage, + entry: ir.Entry, + payload_size: u32 = 0, + attr_size: u32 = 0, + /// Parameter qualifiers for the function annotation (0 in, + /// 1 out, 2 inout). + quals: []const u32 = &.{}, + }; + + fn shaderKind(stage: ir.Stage) u32 { + return switch (stage) { + .pixel => 0, + .vertex => 1, + .geometry => 2, + .hull => 3, + .domain => 4, + .compute => 5, + .library => 6, + .raygeneration => 7, + .intersection => 8, + .anyhit => 9, + .closesthit => 10, + .miss => 11, + .callable => 12, + .mesh => 13, + .amplification => 14, + }; + } + + fn runLibrary(e: *Emitter, gpa: Allocator) Error![]u8 { + const m = e.m; + e.lib = true; + if (m.exports.items.len > 0) return e.unsupported("exported library functions are not supported yet", .{}); + const i8p = try e.dm.ptrType(try e.dm.intType(8)); + e.handle_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.Handle", .elems = &.{i8p} } }); + try e.collectResources(); + // A global per resource, named as dxc mangles it. + for (e.resources.items) |*r| { + if (r.view) continue; + if (r.count != 1) return e.unsupported("resource arrays in libraries are not supported yet", .{}); + const g = m.globals.items[r.global]; + const ty = try e.classType(r.*); + const name = if (g.space == .resource) try mangle.global(e.arena, e.t, g.name, g.ty) else g.name; + const v = try e.dm.addGlobal(name, ty, 0); + e.dm.globals.items[v.global].constant = true; + r.lib_global = v.global; + } + var funcs: std.ArrayList(LibFunc) = .empty; + for (m.entries.items) |entry| { + switch (entry.stage) { + .compute, .raygeneration, .intersection, .anyhit, .closesthit, .miss, .callable => {}, + else => return e.unsupported("{s} shaders in libraries are not supported yet", .{@tagName(entry.stage)}), + } + e.entry = entry; + e.blocks = .empty; + e.prologue = .empty; + e.next_id = 0; + e.private_globals = .empty; + e.private_typed = .empty; + e.nonuniform = .empty; + e.res_locals = .empty; + e.rq_locals = .empty; + e.forwarded = .empty; + e.status_vals = .empty; + const hf = m.functions.items[entry.func]; + const ray = entry.stage.isRayTracing(); + var params: std.ArrayList(DType) = .empty; + var mparams: std.ArrayList(mangle.Param) = .empty; + var quals: std.ArrayList(u32) = .empty; + var lf: LibFunc = .{ .func = 0, .name = entry.name, .unmangled = entry.name, .stage = entry.stage, .entry = entry }; + if (ray) for (hf.params, 0..) |p, k| { + try params.append(e.arena, try e.dm.ptrType(try e.memoryType(p.ty))); + try mparams.append(e.arena, .{ .ty = p.ty }); + try quals.append(e.arena, if (p.by_ref) 2 else 0); + const size = try e.payloadSize(p.ty); + if (k == 0) lf.payload_size = size else lf.attr_size = size; + }; + if (ray) lf.name = try mangle.function(e.arena, e.t, entry.name, TypeTable.void_type, mparams.items); + lf.quals = quals.items; + const fn_ty = try e.dm.fnType(try e.voidTy(), params.items); + lf.func = try e.dm.addFunction(.{ .name = lf.name, .ty = fn_ty, .num_blocks = 1 }); + const args = try e.arena.alloc(Value, params.items.len); + for (args, 0..) |*a, k| a.* = .{ .arg = @intCast(k) }; + e.lib_args = args; + try e.buildSignatures(entry); + e.cur = try e.newBlock(); + try e.libHandles(); + _ = try e.inlineCall(entry.wrapper, &.{}); + try e.finish(lf.func); + try funcs.append(e.arena, lf); + } + const bitcode = try e.writeLibraryModule(funcs.items); + defer gpa.free(bitcode); + return e.assembleLibrary(gpa, funcs.items, bitcode); + } + + /// Handles of the library's resources for the current function (in + /// the prologue; dropped again where unused). + fn libHandles(e: *Emitter) Error!void { + const i32t = try e.dm.intType(32); + for (e.resources.items) |*res| { + const lg = res.lib_global orelse continue; + const gty = e.dm.globals.items[lg].ty; + const loaded = try e.addPrologue(gty, .{ .load = .{ .ptr = .{ .global = lg }, .@"align" = 4 } }); + try e.lib_removable.put(e.arena, loaded.inst, {}); + const struct_name = e.dm.types.items[gty].@"struct".name; + const create = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.createHandleForLib.{s}", .{struct_name}), e.handle_ty, &.{ i32t, gty }, .nounwind_readonly); + var h = try e.addPrologue(e.handle_ty, .{ .call = .{ .callee = create, .args = try e.arena.dupe(Value, &.{ try e.i32Const(160), loaded }) } }); + try e.lib_removable.put(e.arena, h.inst, {}); + if (e.self_sm66()) { + const props_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.ResourceProperties", .elems = &.{ i32t, i32t } } }); + const annotate = try e.dxOp("dx.op.annotateHandle", e.handle_ty, &.{ i32t, e.handle_ty, props_ty }, .nounwind_readnone); + h = try e.addPrologue(e.handle_ty, .{ .call = .{ .callee = annotate, .args = try e.arena.dupe(Value, &.{ try e.i32Const(216), h, try e.propertiesConst(res.*) }) } }); + try e.lib_removable.put(e.arena, h.inst, {}); + } + res.handle = h; + } + } + + /// Ray tracing intrinsics (library shaders); null for other names. + fn rayIntrinsic(e: *Emitter, frame: *Frame, name: []const u8, ty: TypeId, args: []const Ref) Error!?Lowered { + const eq = std.mem.eql; + const i32t = try e.dm.intType(32); + const i8t = try e.dm.intType(8); + const f32t = try e.dm.getType(.float); + const void_ty = try e.voidTy(); + const Sys = struct { []const u8, i64, []const u8, enum { scalar, vector, m34, m43 } }; + const table = [_]Sys{ + .{ "DispatchRaysIndex", 145, "dispatchRaysIndex", .vector }, .{ "DispatchRaysDimensions", 146, "dispatchRaysDimensions", .vector }, + .{ "WorldRayOrigin", 147, "worldRayOrigin", .vector }, .{ "WorldRayDirection", 148, "worldRayDirection", .vector }, + .{ "ObjectRayOrigin", 149, "objectRayOrigin", .vector }, .{ "ObjectRayDirection", 150, "objectRayDirection", .vector }, + .{ "RayTMin", 153, "rayTMin", .scalar }, .{ "RayTCurrent", 154, "rayTCurrent", .scalar }, + .{ "InstanceID", 141, "instanceID", .scalar }, .{ "InstanceIndex", 142, "instanceIndex", .scalar }, + .{ "HitKind", 143, "hitKind", .scalar }, .{ "RayFlags", 144, "rayFlags", .scalar }, + .{ "PrimitiveIndex", 161, "primitiveIndex", .scalar }, .{ "GeometryIndex", 213, "geometryIndex", .scalar }, + .{ "ObjectToWorld3x4", 151, "objectToWorld", .m34 }, .{ "ObjectToWorld", 151, "objectToWorld", .m34 }, + .{ "ObjectToWorld4x3", 151, "objectToWorld", .m43 }, .{ "WorldToObject3x4", 152, "worldToObject", .m34 }, + .{ "WorldToObject", 152, "worldToObject", .m34 }, .{ "WorldToObject4x3", 152, "worldToObject", .m43 }, + }; + for (table) |x| { + if (!eq(u8, name, x[0])) continue; + const rt = try e.scalarTy(e.compOf(ty)); + const fname = try std.fmt.allocPrint(e.arena, "dx.op.{s}.{s}", .{ x[2], e.overloadName(rt) }); + // (RayTCurrent changes during intersection shaders.) + const attrs: module.FnAttrs = if (x[1] == 154) .nounwind_readonly else .nounwind_readnone; + switch (x[3]) { + .scalar => { + const f = try e.dxOp(fname, rt, &.{i32t}, attrs); + return try e.list(&.{try e.callOp(f, rt, &.{try e.i32Const(x[1])})}); + }, + .vector => { + const f = try e.dxOp(fname, rt, &.{ i32t, i8t }, attrs); + const out = try e.arena.alloc(Value, try e.flatCount(ty)); + for (out, 0..) |*o, k| o.* = try e.callOp(f, rt, &.{ try e.i32Const(x[1]), try e.dm.constInt(8, @intCast(k)) }); + return .{ .scalars = out }; + }, + .m34, .m43 => { + const f = try e.dxOp(fname, rt, &.{ i32t, i32t, i8t }, attrs); + const mt = e.t.get(ty).matrix; + const out = try e.arena.alloc(Value, @as(usize, mt.rows) * mt.cols); + for (0..mt.rows) |r| for (0..mt.cols) |c| { + const row, const col = if (x[3] == .m34) .{ r, c } else .{ c, r }; + out[r * mt.cols + c] = try e.callOp(f, rt, &.{ try e.i32Const(x[1]), try e.i32Const(@intCast(row)), try e.dm.constInt(8, @intCast(col)) }); + }; + return .{ .scalars = out }; + }, + } + } + if (eq(u8, name, "IgnoreHit") or eq(u8, name, "AcceptHitAndEndSearch")) { + const ignore = eq(u8, name, "IgnoreHit"); + const f = try e.dxOp(if (ignore) "dx.op.ignoreHit" else "dx.op.acceptHitAndEndSearch", void_ty, &.{i32t}, .noreturn_nounwind); + _ = try e.callOp(f, void_ty, &.{try e.i32Const(if (ignore) 155 else 156)}); + _ = try e.add(void_ty, .@"unreachable"); + // What follows is unreachable. + e.cur = try e.newBlock(); + return .none; + } + if (eq(u8, name, "TraceRay") or eq(u8, name, "CallShader") or eq(u8, name, "ReportHit")) { + if (!e.lib) return e.unsupported("'{s}' outside library shaders", .{name}); + // The payload / parameter / attributes go in struct-typed + // memory of their own. + const data = args[args.len - 1]; + const dty_hl = frame.f.inst(data).ty; + const dty = try e.memoryType(dty_hl); + const ptr_t = try e.dm.ptrType(dty); + const mem = try e.addPrologue(ptr_t, .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } }); + const tp: @FieldType(Lowered, "typed") = .{ .base = mem, .dty = dty, .addr_space = 0, .ty = dty_hl }; + const report = eq(u8, name, "ReportHit"); + const vals = if (report) try e.scalars(frame, data) else (try e.loadPtr(try e.outPtr(frame, data), dty_hl)).scalars; + try e.typedStore(tp, vals, dty_hl); + const sname = e.dm.types.items[dty].@"struct".name; + if (report) { + const i1t = try e.dm.intType(1); + const f = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.reportHit.{s}", .{sname}), i1t, &.{ i32t, f32t, i32t, ptr_t }, .nounwind); + return try e.list(&.{try e.callOp(f, i1t, &.{ try e.i32Const(158), (try e.scalars(frame, args[0]))[0], (try e.scalars(frame, args[1]))[0], mem })}); + } + if (eq(u8, name, "TraceRay")) { + const accel = try e.resourceOf(frame, args[0]); + var ps: [16]DType = undefined; + ps[0] = i32t; + ps[1] = e.handle_ty; + for (ps[2..7]) |*p| p.* = i32t; + for (ps[7..15]) |*p| p.* = f32t; + ps[15] = ptr_t; + const f = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.traceRay.{s}", .{sname}), void_ty, &ps, .nounwind); + var call_args: std.ArrayList(Value) = .empty; + try call_args.appendSlice(e.arena, &.{ try e.i32Const(157), accel.handle }); + for (args[1..6]) |a| try call_args.append(e.arena, (try e.scalars(frame, a))[0]); + try call_args.appendSlice(e.arena, try e.scalars(frame, args[6])); + try call_args.append(e.arena, mem); + _ = try e.callOp(f, void_ty, call_args.items); + } else { + const f = try e.dxOp(try std.fmt.allocPrint(e.arena, "dx.op.callShader.{s}", .{sname}), void_ty, &.{ i32t, i32t, ptr_t }, .nounwind); + _ = try e.callOp(f, void_ty, &.{ try e.i32Const(159), (try e.scalars(frame, args[0]))[0], mem }); + } + const back = try e.typedLoad(tp, dty_hl); + try e.storePtr(try e.outPtr(frame, data), back.scalars, dty_hl); + return .none; + } + return null; + } + fn collectResources(e: *Emitter) Error!void { var counts = [_]u32{ 0, 0, 0, 0 }; // Constant buffers: `$Globals` first, then the others in order. @@ -497,6 +740,12 @@ const Emitter = struct { for (e.resources.items) |res| { const g = &e.m.globals.items[res.global]; if (g.binding.explicit) continue; + if (e.lib) { + // Libraries leave them unbound (-1) until linked. + @constCast(g).binding.index = std.math.maxInt(u32); + @constCast(g).binding.space = std.math.maxInt(u32); + continue; + } var i: u32 = 0; while (true) : (i += 1) { const free = for (0..span(res.count)) |k| { @@ -636,6 +885,7 @@ const Emitter = struct { /// Assigns final instruction indices: prologue first, then blocks in /// creation order. fn finish(e: *Emitter, func: u32) Error!void { + if (e.lib_removable.count() > 0) try e.pruneProlog(); const map = try e.arena.alloc(u32, e.next_id); var n: u32 = 0; for (e.prologue.items) |pi| { @@ -663,6 +913,45 @@ const Emitter = struct { for (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap)); } + /// Drops removable prologue instructions nothing uses (repeatedly: a + /// handle's load goes once the handle has). + fn pruneProlog(e: *Emitter) Error!void { + const used = try e.arena.alloc(bool, e.next_id); + var changed = true; + while (changed) { + changed = false; + @memset(used, false); + const all = [_][]const PInst{e.prologue.items}; + for (all) |items| for (items) |pi| markUses(e.arena, pi.inst, used); + for (e.blocks.items) |blk| for (blk.items) |pi| markUses(e.arena, pi.inst, used); + var k: usize = 0; + while (k < e.prologue.items.len) { + const pi = e.prologue.items[k]; + if (e.lib_removable.contains(pi.id) and !used[pi.id]) { + _ = e.prologue.orderedRemove(k); + changed = true; + } else k += 1; + } + } + e.lib_removable = .empty; + } + + fn markUses(a: Allocator, inst: module.Inst, used: []bool) void { + const M = struct { + var u: []bool = &.{}; + fn v(_: []const u32, x: Value) Value { + if (x == .inst) u[x.inst] = true; + return x; + } + fn vs(_: Allocator, _: []const u32, xs: []const Value) Allocator.Error![]const Value { + for (xs) |x| _ = v(&.{}, x); + return xs; + } + }; + M.u = used; + _ = remapInst(a, &.{}, inst, M) catch {}; + } + fn remapInst(a: Allocator, map: []const u32, inst: module.Inst, comptime R: type) Allocator.Error!module.Inst { var out = inst; switch (out.op) { @@ -865,7 +1154,12 @@ const Emitter = struct { switch (i.op) { .constant => |c| return e.list(&.{try e.constant(i.ty, c)}), .param => |p| return frame.params[p], - .ray_incoming => return e.unsupported("ray tracing shaders are not supported yet", .{}), + .ray_incoming => |k| { + // The shader's payload / attribute / parameter argument. + const idx: usize = if (k == .attributes) 1 else 0; + if (idx >= e.lib_args.len) return e.unsupported("ray tracing shaders outside libraries", .{}); + return .{ .typed = .{ .base = e.lib_args[idx], .dty = try e.memoryType(i.ty), .addr_space = 0, .ty = i.ty } }; + }, .heap_resource => |h| { if (e.t.get(i.ty) != .resource and e.t.get(i.ty) != .sampler) return .none; if (e.profile.minor < 6) return e.unsupported("descriptor heaps need shader model 6.6", .{}); @@ -1449,6 +1743,7 @@ const Emitter = struct { fn intrinsic(e: *Emitter, frame: *Frame, name: []const u8, ty: TypeId, args: []const Ref) Error!Lowered { const eq = std.mem.eql; + if (try e.rayIntrinsic(frame, name, ty, args)) |r| return r; if (try e.outIntrinsic(frame, name, ty, args)) |r| return r; if (eq(u8, name, "DispatchMesh")) { const tp = switch (frame.vals[args[3].index()]) { @@ -3708,9 +4003,38 @@ const Emitter = struct { return f; } - fn writeModule(e: *Emitter, entry: ir.Entry) Error![]u8 { + /// The LLVM type a resource's metadata (and, in libraries, its global) + /// points to: a named struct, an array of them for ranges. + fn classType(e: *Emitter, r: Resource) Error!DType { + const dm = &e.dm; + const g = e.m.globals.items[r.global]; + const one: DType = blk: { + if (r.kind == 15 or r.class == .cbuffer) { + // tbuffers and cbuffers: a struct of one float. + const name = if (r.rty != 0) try std.fmt.allocPrint(e.arena, "struct.{s}", .{try e.t.format(e.arena, r.elem)}) else g.name; + break :blk try dm.getType(.{ .@"struct" = .{ .name = name, .elems = &.{try dm.getType(.float)} } }); + } + if (r.class == .sampler) break :blk try dm.getType(.{ .@"struct" = .{ .name = if (r.comparison) "struct.SamplerComparisonState" else "struct.SamplerState", .elems = &.{try dm.intType(32)} } }); + if (r.kind == 16) break :blk try dm.getType(.{ .@"struct" = .{ .name = "struct.RaytracingAccelerationStructure", .elems = &.{try dm.intType(32)} } }); + var rty = g.ty; + while (e.t.get(rty) == .array) rty = e.t.get(rty).array.elem; + const rt = e.t.get(rty).resource; + const class_name = try std.fmt.allocPrint(e.arena, "class.{s}<{s}>", .{ rt.name, try e.t.format(e.arena, r.elem) }); + // The class type only names the resource; aggregates get a + // placeholder element. + var elem_dt = try e.scalarTy(if (r.kind == 11) .uint else if (e.t.shape(r.elem) == null) .int else e.compOf(r.elem)); + // Typed resources carry their component count in the element + // (the validator reads it from here). + if (r.kind >= 1 and r.kind <= 10 and e.t.get(r.elem) == .vector) elem_dt = try dm.getType(.{ .vector = .{ .len = e.t.get(r.elem).vector.len, .elem = elem_dt } }); + break :blk try dm.getType(.{ .@"struct" = .{ .name = class_name, .elems = &.{elem_dt} } }); + }; + if (r.count == 1) return one; + return dm.getType(.{ .array = .{ .len = if (r.count == std.math.maxInt(u32)) 0 else r.count, .elem = one } }); + } + + /// `dx.resources`: SRVs, UAVs, CBVs and samplers. + fn resourcesMd(e: *Emitter) Error!?module.MdId { const dm = &e.dm; - const i32t = try dm.intType(32); const i1t = try dm.intType(1); const mdI32 = struct { fn f(m: *module.Module, v: i64) !module.MdId { @@ -3722,13 +4046,6 @@ const Emitter = struct { return m.mdValue(t, try m.constant(.{ .ty = t, .kind = .{ .int = @intFromBool(v) } })); } }.f; - _ = i32t; - - const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")}); - const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) }); - const val_ver = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, 11) }); - const sm = try dm.mdNode(&.{ try dm.mdString(e.profile.kind.profilePrefix()), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) }); - // Resource lists by class. var lists: [4]std.ArrayList(?module.MdId) = .{ .empty, .empty, .empty, .empty }; for (e.resources.items) |r| { @@ -3736,61 +4053,32 @@ const Emitter = struct { const g = e.m.globals.items[r.global]; // Ranges: the pointer is to an array; unsized ones have size -1. const range: i64 = if (r.count == std.math.maxInt(u32)) -1 else r.count; - const rangeTy = struct { - fn f(m: *module.Module, n: u32, t: DType) !DType { - if (n == 1) return t; - return m.getType(.{ .array = .{ .len = if (n == std.math.maxInt(u32)) 0 else n, .elem = t } }); - } - }.f; + const class_ty = try e.classType(r); + // Libraries point at the resource's global and name it. + const sym = if (r.lib_global) |lg| try dm.mdValue(try dm.ptrType(class_ty), .{ .global = lg }) else try dm.mdValue(try dm.ptrType(class_ty), try dm.constant(.{ .ty = try dm.ptrType(class_ty), .kind = .undef })); + const name = try dm.mdString(if (r.lib_global != null) g.name else ""); + const b = g.binding; + const head = [_]?module.MdId{ try mdI32(dm, r.id), sym, name, try mdI32(dm, @as(i32, @bitCast(b.space))), try mdI32(dm, @as(i32, @bitCast(b.index))), try mdI32(dm, range) }; if (r.kind == 15) { // tbuffer / TextureBuffer: an SRV of 32-bit elements. - const f32t = try dm.getType(.float); - const tb_name = if (r.rty != 0) try std.fmt.allocPrint(e.arena, "struct.{s}", .{try e.t.format(e.arena, r.elem)}) else g.name; - const tb_ty = try rangeTy(dm, r.count, try dm.getType(.{ .@"struct" = .{ .name = tb_name, .elems = &.{f32t} } })); - const undef_tb = try dm.constant(.{ .ty = try dm.ptrType(tb_ty), .kind = .undef }); - const b = g.binding; - try lists[0].append(e.arena, try dm.mdNode(&.{ try mdI32(dm, r.id), try dm.mdValue(try dm.ptrType(tb_ty), undef_tb), try dm.mdString(""), try mdI32(dm, b.space), try mdI32(dm, b.index), try mdI32(dm, range), try mdI32(dm, 15), try mdI32(dm, 0), try dm.mdNode(&.{ try mdI32(dm, 0), try mdI32(dm, 5) }) })); + try lists[0].append(e.arena, try dm.mdNode(&(head ++ [_]?module.MdId{ try mdI32(dm, 15), try mdI32(dm, 0), try dm.mdNode(&.{ try mdI32(dm, 0), try mdI32(dm, 5) }) }))); continue; } if (r.class == .cbuffer) { - const f32t = try dm.getType(.float); - const cb_name = if (r.rty != 0) try std.fmt.allocPrint(e.arena, "struct.{s}", .{try e.t.format(e.arena, r.elem)}) else g.name; - const cb_ty = try rangeTy(dm, r.count, try dm.getType(.{ .@"struct" = .{ .name = cb_name, .elems = &.{f32t} } })); - const undef_cb = try dm.constant(.{ .ty = try dm.ptrType(cb_ty), .kind = .undef }); - const b = g.binding; - try lists[2].append(e.arena, try dm.mdNode(&.{ try mdI32(dm, r.id), try dm.mdValue(try dm.ptrType(cb_ty), undef_cb), try dm.mdString(""), try mdI32(dm, b.space), try mdI32(dm, b.index), try mdI32(dm, range), try mdI32(dm, try e.cbufferSize(r)), null })); + try lists[2].append(e.arena, try dm.mdNode(&(head ++ [_]?module.MdId{ try mdI32(dm, try e.cbufferSize(r)), null }))); continue; } if (r.class == .sampler) { - const name = if (r.comparison) "struct.SamplerComparisonState" else "struct.SamplerState"; - const st = try rangeTy(dm, r.count, try dm.getType(.{ .@"struct" = .{ .name = name, .elems = &.{try dm.intType(32)} } })); - const undef_s = try dm.constant(.{ .ty = try dm.ptrType(st), .kind = .undef }); - const b = g.binding; - try lists[3].append(e.arena, try dm.mdNode(&.{ try mdI32(dm, r.id), try dm.mdValue(try dm.ptrType(st), undef_s), try dm.mdString(""), try mdI32(dm, b.space), try mdI32(dm, b.index), try mdI32(dm, range), try mdI32(dm, @intFromBool(r.comparison)), null })); + try lists[3].append(e.arena, try dm.mdNode(&(head ++ [_]?module.MdId{ try mdI32(dm, @intFromBool(r.comparison)), null }))); continue; } if (r.kind == 16) { - const st = try rangeTy(dm, r.count, try dm.getType(.{ .@"struct" = .{ .name = "struct.RaytracingAccelerationStructure", .elems = &.{try dm.intType(32)} } })); - const undef_s = try dm.constant(.{ .ty = try dm.ptrType(st), .kind = .undef }); - const b = g.binding; - try lists[0].append(e.arena, try dm.mdNode(&.{ try mdI32(dm, r.id), try dm.mdValue(try dm.ptrType(st), undef_s), try dm.mdString(""), try mdI32(dm, b.space), try mdI32(dm, b.index), try mdI32(dm, range), try mdI32(dm, 16), try mdI32(dm, 0), try dm.mdNode(&.{ try mdI32(dm, 0), try mdI32(dm, 4) }) })); + try lists[0].append(e.arena, try dm.mdNode(&(head ++ [_]?module.MdId{ try mdI32(dm, 16), try mdI32(dm, 0), try dm.mdNode(&.{ try mdI32(dm, 0), try mdI32(dm, 4) }) }))); continue; } - var rty = g.ty; - while (e.t.get(rty) == .array) rty = e.t.get(rty).array.elem; - const rt = e.t.get(rty).resource; - const class_name = try std.fmt.allocPrint(e.arena, "class.{s}<{s}>", .{ rt.name, try e.t.format(e.arena, r.elem) }); - // The class type only names the resource; aggregates get a - // placeholder element. - var elem_dt = try e.scalarTy(if (r.kind == 11) .uint else if (e.t.shape(r.elem) == null) .int else e.compOf(r.elem)); - // Typed resources carry their component count in the element - // (the validator reads it from here). - if (r.kind >= 1 and r.kind <= 10 and e.t.get(r.elem) == .vector) elem_dt = try dm.getType(.{ .vector = .{ .len = e.t.get(r.elem).vector.len, .elem = elem_dt } }); - const class_ty = try rangeTy(dm, r.count, try dm.getType(.{ .@"struct" = .{ .name = class_name, .elems = &.{elem_dt} } })); - const undef_ptr = try dm.constant(.{ .ty = try dm.ptrType(class_ty), .kind = .undef }); - const b = g.binding; var fields: std.ArrayList(?module.MdId) = .empty; - try fields.appendSlice(e.arena, &.{ try mdI32(dm, r.id), try dm.mdValue(try dm.ptrType(class_ty), undef_ptr), try dm.mdString(""), try mdI32(dm, b.space), try mdI32(dm, b.index), try mdI32(dm, range), try mdI32(dm, r.kind) }); + try fields.appendSlice(e.arena, &head); + try fields.append(e.arena, try mdI32(dm, r.kind)); if (r.class == .uav) { try fields.appendSlice(e.arena, &.{ try mdBool(dm, i1t, false), try mdBool(dm, i1t, r.has_counter), try mdBool(dm, i1t, false) }); } else try fields.append(e.arena, try mdI32(dm, 0)); // sample count @@ -3810,6 +4098,192 @@ const Emitter = struct { } resources = try dm.mdNode(&slots); } + return resources; + } + + /// Per-function flags and compatibility of a library's functions, and + /// the module's flags (their union, without function-local ones, plus + /// resource-wide ones). + fn libAnalysis(e: *Emitter, funcs: []const LibFunc) Error!struct { infos: []libinfo.Info, flags: u64 } { + const globals = try e.arena.alloc(?libinfo.GlobalRes, e.dm.globals.items.len); + @memset(globals, null); + var uavs: u32 = 0; + var raw = false; + for (e.resources.items) |r| { + if (r.view) continue; + if (r.class == .uav) uavs += @min(r.count, 9); + if ((r.class == .uav or r.class == .srv) and (r.kind == 11 or r.kind == 12)) raw = true; + const lg = r.lib_global orelse continue; + globals[lg] = .{ .uav = r.class == .uav, .typed_multi = r.kind >= 1 and r.kind <= 10 and try e.flatCount(r.elem) > 1 }; + } + const opts: libinfo.Options = .{ .native16 = e.native16(), .res_may_not_alias = e.profile.minor >= 7, .globals = globals }; + const infos = try e.arena.alloc(libinfo.Info, funcs.len); + var flags: u64 = 0; + for (funcs, infos) |lf, *info| { + info.* = libinfo.analyze(&e.dm, &e.dm.functions.items[lf.func], opts); + flags |= info.flags; + } + flags &= ~@as(u64, libinfo.bit.local); + if (raw) flags |= libinfo.bit.raw_structured; + if (uavs > 8) flags |= 1 << 15; + return .{ .infos = infos, .flags = flags }; + } + + fn native16(e: *Emitter) bool { + _ = e; + return false; + } + + fn writeLibraryModule(e: *Emitter, funcs: []const LibFunc) Error![]u8 { + const dm = &e.dm; + const mdI32 = struct { + fn f(m: *module.Module, v: i64) !module.MdId { + return m.mdI32(v); + } + }.f; + const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")}); + const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) }); + const val_ver = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, 11) }); + const sm = try dm.mdNode(&.{ try dm.mdString("lib"), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) }); + const resources = try e.resourcesMd(); + const analysis = try e.libAnalysis(funcs); + + // Function annotations: per parameter (return value first) its + // input qualifier. + const empty = try dm.mdNode(&.{}); + var annotations: std.ArrayList(?module.MdId) = .empty; + try annotations.append(e.arena, try mdI32(dm, 1)); + for (funcs) |lf| { + var ps: std.ArrayList(?module.MdId) = .empty; + const ret_qual: i64 = if (lf.stage.isRayTracing()) 1 else 0; + try ps.append(e.arena, try dm.mdNode(&.{ try mdI32(dm, ret_qual), empty, empty })); + for (lf.quals) |q| try ps.append(e.arena, try dm.mdNode(&.{ try mdI32(dm, q), empty, empty })); + const fty = dm.functions.items[lf.func].ty; + try annotations.append(e.arena, try dm.mdValue(try dm.ptrType(fty), .{ .function = lf.func })); + try annotations.append(e.arena, try dm.mdNode(ps.items)); + } + const type_annotations = try dm.mdNode(annotations.items); + + // Entries: the library's own (resources, module flags), then each + // shader by name. + var entries: std.ArrayList(module.MdId) = .empty; + var lib_props: ?module.MdId = null; + if (analysis.flags != 0) { + const i64t = try dm.intType(64); + lib_props = try dm.mdNode(&.{ try mdI32(dm, 0), try dm.mdValue(i64t, try dm.constant(.{ .ty = i64t, .kind = .{ .int = @bitCast(analysis.flags) } })) }); + } + try entries.append(e.arena, try dm.mdNode(&.{ null, try dm.mdString(""), null, resources, lib_props })); + const order = try e.arena.alloc(usize, funcs.len); + for (order, 0..) |*o, k| o.* = k; + std.sort.insertion(usize, order, funcs, struct { + fn lt(fs: []const LibFunc, a: usize, b: usize) bool { + return std.mem.order(u8, fs[a].name, fs[b].name) == .lt; + } + }.lt); + const auto_space = try dm.mdNode(&.{try mdI32(dm, 0)}); + for (order) |k| { + const lf = funcs[k]; + var props: std.ArrayList(?module.MdId) = .empty; + try props.appendSlice(e.arena, &.{ try mdI32(dm, 8), try mdI32(dm, shaderKind(lf.stage)) }); + if (lf.stage == .compute) { + const t = lf.entry.num_threads; + try props.appendSlice(e.arena, &.{ try mdI32(dm, 4), try dm.mdNode(&.{ try mdI32(dm, t[0]), try mdI32(dm, t[1]), try mdI32(dm, t[2]) }) }); + } + switch (lf.stage) { + .miss, .callable, .anyhit, .closesthit => try props.appendSlice(e.arena, &.{ try mdI32(dm, 6), try mdI32(dm, lf.payload_size) }), + else => {}, + } + if (lf.stage == .anyhit or lf.stage == .closesthit) try props.appendSlice(e.arena, &.{ try mdI32(dm, 7), try mdI32(dm, lf.attr_size) }); + try props.appendSlice(e.arena, &.{ try mdI32(dm, 5), auto_space }); + const fty = dm.functions.items[lf.func].ty; + try entries.append(e.arena, try dm.mdNode(&.{ try dm.mdValue(try dm.ptrType(fty), .{ .function = lf.func }), try dm.mdString(lf.name), null, null, try dm.mdNode(props.items) })); + } + + try dm.addNamedMetadata("llvm.ident", &.{ident}); + try dm.addNamedMetadata("dx.version", &.{version}); + try dm.addNamedMetadata("dx.valver", &.{val_ver}); + try dm.addNamedMetadata("dx.shaderModel", &.{sm}); + if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r}); + if (funcs.len > 0) try dm.addNamedMetadata("dx.typeAnnotations", &.{type_annotations}); + try dm.addNamedMetadata("dx.entryPoints", entries.items); + return dm.writeBitcode(dm.arena.child_allocator); + } + + /// The library container: feature info, runtime data (RDAT) and the + /// program. + fn assembleLibrary(e: *Emitter, gpa: Allocator, funcs: []const LibFunc, bitcode: []const u8) Error![]u8 { + const dxil_part = try shader.programPart(gpa, e.profile, bitcode); + defer gpa.free(dxil_part); + const analysis = try e.libAnalysis(funcs); + var b = try rdat.Builder.init(gpa); + defer b.deinit(); + // Resources: CBVs, samplers, SRVs, UAVs. + var res_index: std.AutoHashMapUnmanaged(u32, u32) = .empty; + var count: u32 = 0; + for ([_]Resource.Class{ .cbuffer, .sampler, .srv, .uav }) |cls| for (e.resources.items) |r| if (r.class == cls and !r.view) { + const bd = e.binding(r); + const upper: u32 = if (r.count == std.math.maxInt(u32)) std.math.maxInt(u32) else bd.index +% (r.count - 1); + const rdat_class: u32 = switch (r.class) { + .srv => 0, + .uav => 1, + .cbuffer => 2, + .sampler => 3, + }; + try b.addResource(.{ .class = rdat_class, .kind = r.kind, .id = r.id, .space = bd.space, .lower = bd.index, .upper = upper, .name = try b.string(e.m.globals.items[r.global].name), .flags = if (r.class == .uav and r.has_counter) 2 else 0 }); + if (r.lib_global) |lg| try res_index.put(e.arena, lg, count); + count += 1; + }; + for (funcs, analysis.infos) |lf, info| { + const f = &e.dm.functions.items[lf.func]; + const name = try b.string(lf.name); + const unmangled = try b.string(lf.unmangled); + // Resources whose globals the function loads, in table order. + var used: std.ArrayList(u32) = .empty; + for (f.insts.items) |inst| if (inst.op == .load and inst.op.load.ptr == .global) { + if (res_index.get(inst.op.load.ptr.global)) |ri| { + if (std.mem.indexOfScalar(u32, used.items, ri) == null) try used.append(e.arena, ri); + } + }; + std.mem.sort(u32, used.items, {}, std.sort.asc(u32)); + const kind = shaderKind(lf.stage); + try b.addFunction(.{ + .name = name, + .unmangled_name = unmangled, + .resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref, + .shader_kind = kind, + .payload_size = lf.payload_size, + .attribute_size = lf.attr_size, + .feature_info1 = @truncate(libinfo.featureInfo(info.flags)), + .feature_info2 = @truncate(libinfo.featureInfo(info.flags) >> 32), + .shader_stage_flag = info.mask & (@as(u32, 1) << @intCast(kind)), + .min_shader_target = (kind << 16) | (6 << 4) | libinfo.minMinor(info, kind), + }); + } + const rdat_part = try b.finish(); + defer gpa.free(rdat_part); + var sfi0: [8]u8 = @splat(0); + std.mem.writeInt(u64, &sfi0, libinfo.featureInfo(analysis.flags), .little); + return container.assemble(gpa, &.{ + .{ .fourcc = container.fourcc("SFI0"), .data = &sfi0 }, + .{ .fourcc = container.fourcc("RDAT"), .data = rdat_part }, + .{ .fourcc = container.fourcc("DXIL"), .data = dxil_part }, + }); + } + + fn writeModule(e: *Emitter, entry: ir.Entry) Error![]u8 { + const dm = &e.dm; + const mdI32 = struct { + fn f(m: *module.Module, v: i64) !module.MdId { + return m.mdI32(v); + } + }.f; + + const ident = try dm.mdNode(&.{try dm.mdString("zdxc 0.0.0")}); + const version = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, e.profile.minor) }); + const val_ver = try dm.mdNode(&.{ try mdI32(dm, 1), try mdI32(dm, 11) }); + const sm = try dm.mdNode(&.{ try dm.mdString(e.profile.kind.profilePrefix()), try mdI32(dm, e.profile.major), try mdI32(dm, e.profile.minor) }); + + const resources = try e.resourcesMd(); // Entry properties: shader flags and thread group size. var props: std.ArrayList(?module.MdId) = .empty; diff --git a/src/dxil/libinfo.zig b/src/dxil/libinfo.zig new file mode 100644 index 0000000..49c977b --- /dev/null +++ b/src/dxil/libinfo.zig @@ -0,0 +1,314 @@ +//! Per-function shader flags and compatibility (valid stages, minimum +//! shader model) of a DXIL library, computed from the emitted +//! instructions the way dxc's ShaderFlags::CollectShaderFlags and +//! DxilModule::ComputeShaderCompatInfo compute them (validator 1.8+): +//! the validator rebuilds RDAT from these and compares. + +const std = @import("std"); +const module = @import("module.zig"); +const op_compat = @import("op_compat.zig"); + +/// What a resource global (by module global index) is, for flags that +/// depend on the handles a function uses. +pub const GlobalRes = struct { uav: bool, typed_multi: bool = false }; + +pub const Options = struct { + /// -enable-16bit-types (native low precision). + native16: bool, + /// DXIL 1.7+: functions using UAVs set ResMayNotAlias. + res_may_not_alias: bool, + globals: []const ?GlobalRes, +}; + +pub const Info = struct { + /// Shader flags (bit positions of dxc's ShaderFlags raw value). + flags: u64 = 0, + min_minor: u8 = 0, + mask: u32 = op_compat.all_stages, +}; + +pub const bit = struct { + pub const double = 1 << 2; + pub const raw_structured = 1 << 4; + pub const low_precision = 1 << 5; + pub const double_extensions = 1 << 6; + pub const msad = 1 << 7; + pub const inner_coverage = 1 << 10; + pub const tiled_resources = 1 << 12; + pub const typed_uav_load = 1 << 13; + pub const wave = 1 << 19; + pub const int64 = 1 << 20; + pub const view_id = 1 << 21; + pub const barycentrics = 1 << 22; + pub const native_low_precision = 1 << 23; + pub const raytracing_1_1 = 1 << 25; + pub const sampler_feedback = 1 << 26; + pub const resource_heap = 1 << 30; + pub const sampler_heap = 1 << 31; + pub const res_may_not_alias = 1 << 33; + pub const advanced_texture_ops = 1 << 34; + pub const extended_command_info = 1 << 38; + pub const uses_derivatives = 1 << 39; + pub const requires_group = 1 << 40; + /// Not part of the module's flags. + pub const local = uses_derivatives | requires_group; +}; + +const stage_group: u32 = (1 << 5) | (1 << 13) | (1 << 14) | (1 << 15) | (1 << 6); // CS, MS, AS, Node, Library + +pub fn analyze(m: *const module.Module, f: *const module.Function, o: Options) Info { + var info: Info = .{}; + const fty = m.types.items[f.ty].function; + var fl: u64 = 0; + var has16 = false; + var check_access = false; + var lod_clamp = false; + var uses_uav = false; + for (f.insts.items) |inst| { + // Calls to other functions only count through their dx ops. + var op: ?u32 = null; + if (inst.op == .call) { + const callee = m.functions.items[inst.op.call.callee]; + if (!std.mem.startsWith(u8, callee.name, "dx.op.")) continue; + if (inst.op.call.args.len > 0) op = constInt(m, inst.op.call.args[0]); + } + var types_seen: [8]module.TypeId = undefined; + var n: usize = 0; + types_seen[n] = inst.ty; + n += 1; + var operands: [4]?module.Value = .{ null, null, null, null }; + const all_args: []const module.Value = switch (inst.op) { + .call => |c| c.args, + .gep => |g| g.indices, + else => &.{}, + }; + switch (inst.op) { + .binop => |b| operands = .{ b.lhs, b.rhs, null, null }, + .cast => |c| operands[0] = c.val, + .cmp => |c| operands = .{ c.lhs, c.rhs, null, null }, + .select => |s| operands = .{ s.cond, s.t, s.f, null }, + .extractvalue => |x| operands[0] = x.agg, + .load => |x| operands[0] = x.ptr, + .store => |x| operands = .{ x.ptr, x.val, null, null }, + .gep => |g| operands[0] = g.ptr, + .atomicrmw => |x| operands = .{ x.ptr, x.val, null, null }, + .cmpxchg => |x| operands = .{ x.ptr, x.cmp, x.new, null }, + .ret => |r| operands[0] = r, + .br => |b| operands[0] = b.cond, + .@"switch" => |s| operands[0] = s.cond, + .alloca => |a| operands[0] = a.size, + else => {}, + } + var is_double = false; + var is_int64 = false; + var is16 = false; + const visit = struct { + fn t(mm: *const module.Module, ty: module.TypeId, d: *bool, i64_: *bool, h: *bool, group: *bool) void { + switch (mm.types.items[ty]) { + .double => d.* = true, + .half => h.* = true, + .int => |w| { + if (w == 64) i64_.* = true; + if (w == 16) h.* = true; + }, + .pointer => |p| if (p.addr_space == 3) { + group.* = true; + }, + else => {}, + } + } + }; + var group = false; + visit.t(m, inst.ty, &is_double, &is_int64, &is16, &group); + for (operands) |ov| if (ov) |v| if (valueType(m, f, fty, v)) |vt| visit.t(m, vt, &is_double, &is_int64, &is16, &group); + for (all_args) |v| if (valueType(m, f, fty, v)) |vt| visit.t(m, vt, &is_double, &is_int64, &is16, &group); + if (group) fl |= bit.requires_group; + if (is_double) { + fl |= bit.double; + switch (inst.op) { + // (fdiv is sdiv on floating point types) + .binop => |b| if (b.op == .sdiv and isFloatOp(m, inst.ty)) { + fl |= bit.double_extensions; + }, + .cast => |c| switch (c.op) { + .uitofp, .sitofp, .fptoui, .fptosi => fl |= bit.double_extensions, + else => {}, + }, + else => {}, + } + } + if (is_int64) fl |= bit.int64; + if (is16) has16 = true; + const code = op orelse continue; + const c = op_compat.get(code); + info.min_minor = @max(info.min_minor, c.minor); + info.mask &= c.mask; + const args = inst.op.call.args; + if ((code >= 110 and code <= 123) or (code >= 135 and code <= 136) or (code >= 165 and code <= 167) or code == 222 or (code >= 312 and code <= 313)) fl |= bit.wave; + if (code >= 174 and code <= 177) fl |= bit.sampler_feedback; + switch (code) { + 71 => check_access = true, + 50 => fl |= bit.msad, + 91 => fl |= bit.inner_coverage, + 138 => fl |= bit.view_id, + 137 => fl |= bit.barycentrics, + 178, 258, 213 => fl |= bit.raytracing_1_1, + 60, 61, 64, 81, 83, 84, 85, 86 => { + fl |= bit.uses_derivatives; + if (code != 81 and code < 83 and clampArg(m, code, args)) lod_clamp = true; + }, + 62, 63 => if (code == 63 and clampArg(m, code, args)) { + lod_clamp = true; + }, + 68, 66 => if (handleRes(m, f, o, args[1])) |r| if (r.uav and r.typed_multi) { + fl |= bit.typed_uav_load; + }, + 218 => { + if (args.len > 2 and constInt(m, args[2]) == 1) fl |= bit.sampler_heap else fl |= bit.resource_heap; + }, + 57 => if (args.len > 1 and constInt(m, args[1]) == 1) { + uses_uav = true; + }, + 160 => if (handleRes(m, f, o, args[1])) |r| if (r.uav) { + uses_uav = true; + }, + 216 => if (args.len > 2 and annotateIsUav(m, args[2])) { + uses_uav = true; + }, + 256, 257 => fl |= bit.extended_command_info, + 80 => if (args.len > 1) if (constInt(m, args[1])) |mode| if (mode != 2) { + fl |= bit.requires_group; + info.mask &= stage_group; + }, + else => {}, + } + } + if (has16) fl |= bit.low_precision; + if (has16 and o.native16) fl |= bit.native_low_precision; + if (check_access or lod_clamp) fl |= bit.tiled_resources; + if (o.res_may_not_alias and uses_uav) fl |= bit.res_may_not_alias; + info.flags = fl; + return info; +} + +/// The minimum shader model of an entry (or library function) given its +/// flags (AdjustMinimumShaderModelAndFlags). +pub fn minMinor(info: Info, kind: ?u32) u8 { + var v = info.min_minor; + const fl = info.flags; + if (kind) |k| { + if (fl & bit.uses_derivatives != 0 and (k == 5 or k == 13 or k == 14)) v = @max(v, 6); + if (k == 13 or k == 14) v = @max(v, 5) else if (k >= 7 and k <= 12) v = @max(v, 3) else if (k == 15) v = @max(v, 8); + } + if (fl & bit.extended_command_info != 0) { + v = @max(v, 8); + } else if (fl & bit.advanced_texture_ops != 0) { + v = @max(v, 7); + } else if (fl & (bit.resource_heap | bit.sampler_heap) != 0) { + v = @max(v, 6); + } else if (fl & (bit.raytracing_1_1 | bit.sampler_feedback) != 0) { + v = @max(v, 5); + } else if (fl & bit.low_precision != 0 and fl & bit.native_low_precision != 0) { + v = @max(v, 2); + } else if (fl & (bit.view_id | bit.barycentrics) != 0) { + v = @max(v, 1); + } + return v; +} + +/// Feature info bits (SFI0 / RDAT) of shader flags. +pub fn featureInfo(fl: u64) u64 { + const map = [_][2]u64{ + .{ bit.double, 0x1 }, .{ 1 << 16, 0x4 }, .{ 1 << 15, 0x8 }, + .{ bit.double_extensions, 0x20 }, .{ bit.msad, 0x40 }, .{ 1 << 11, 0x200 }, + .{ bit.inner_coverage, 0x400 }, .{ 1 << 9, 0x2000 }, .{ bit.int64, 0x8000 }, + .{ bit.view_id, 0x10000 }, .{ 1 << 24, 0x80000 }, .{ bit.wave, 0x4000 }, + .{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 }, + .{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 }, + .{ 1 << 29, 0x1000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 }, + .{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 }, + }; + var out: u64 = 0; + for (map) |e| if (fl & e[0] != 0) { + out |= e[1]; + }; + if (fl & bit.low_precision != 0) out |= if (fl & bit.native_low_precision != 0) 0x40000 else 0x10; + return out; +} + +fn constInt(m: *const module.Module, v: module.Value) ?u32 { + if (v != .constant) return null; + const c = m.constants.items[v.constant]; + return switch (c.kind) { + .int => |x| @truncate(@as(u64, @bitCast(x))), + else => null, + }; +} + +fn isFloatOp(m: *const module.Module, ty: module.TypeId) bool { + return switch (m.types.items[ty]) { + .half, .float, .double => true, + else => false, + }; +} + +/// Sample / SampleBias / SampleCmp and SampleGrad: a clamp operand that is +/// not undef. +fn clampArg(m: *const module.Module, code: u32, args: []const module.Value) bool { + const idx: usize = switch (code) { + 60 => 10, + 61 => 11, + 64 => 11, + 63 => 16, + else => return false, + }; + if (idx >= args.len) return false; + const v = args[idx]; + if (v != .constant) return true; + return m.constants.items[v.constant].kind != .undef; +} + +fn annotateIsUav(m: *const module.Module, props: module.Value) bool { + if (props != .constant) return false; + const c = m.constants.items[props.constant]; + if (c.kind != .aggregate or c.kind.aggregate.len == 0) return false; + const basic = m.constants.items[c.kind.aggregate[0]]; + return basic.kind == .int and basic.kind.int & 0x1000 != 0; +} + +/// The resource global behind a handle made by createHandleForLib (of a +/// loaded global), possibly annotated. +fn handleRes(m: *const module.Module, f: *const module.Function, o: Options, h: module.Value) ?GlobalRes { + var v = h; + var steps: u32 = 0; + while (steps < 4) : (steps += 1) { + if (v != .inst) return null; + const inst = f.insts.items[v.inst]; + switch (inst.op) { + .call => |c| { + const code = if (c.args.len > 0) constInt(m, c.args[0]) else null; + if (code == 216 or code == 160) { + v = c.args[1]; + continue; + } + return null; + }, + .load => |l| { + if (l.ptr == .global) return o.globals[l.ptr.global]; + return null; + }, + else => return null, + } + } + return null; +} + +fn valueType(m: *const module.Module, f: *const module.Function, fty: @FieldType(module.Type, "function"), v: module.Value) ?module.TypeId { + return switch (v) { + .global => |g| m.globals.items[g].ptr_ty, + .function => null, + .constant => |c| m.constants.items[c].ty, + .arg => |a| fty.params[a], + .inst => |i| f.insts.items[i].ty, + }; +} diff --git a/src/dxil/mangle.zig b/src/dxil/mangle.zig new file mode 100644 index 0000000..fc0d58d --- /dev/null +++ b/src/dxil/mangle.zig @@ -0,0 +1,135 @@ +//! Microsoft-style C++ name mangling of library functions and resource +//! globals, as dxc spells them (`\x01?name@@YAXXZ`). D3D12 refers to +//! library exports by the unmangled name (recorded in RDAT next to this +//! one), so near enough is good enough for unusual types. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const types = @import("../sema/types.zig"); +const TypeTable = types.TypeTable; +const TypeId = types.TypeId; + +pub const Param = struct { ty: TypeId, by_ref: bool = false }; + +/// `\x01?name@@YAZ`. +pub fn function(a: Allocator, t: *TypeTable, name: []const u8, ret: TypeId, params: []const Param) Allocator.Error![]u8 { + var out: std.ArrayList(u8) = .empty; + try out.print(a, "\x01?{s}@@YA", .{name}); + var refs: std.ArrayList([]const u8) = .empty; + const rt = t.get(ret); + if (rt == .@"struct" or rt == .matrix or (rt == .vector and rt.vector.len > 1) or rt == .resource) try out.appendSlice(a, "?A"); + try typeCode(a, t, ret, &out); + if (params.len == 0) { + try out.append(a, 'X'); + } else { + for (params) |p| { + var code: std.ArrayList(u8) = .empty; + if (p.by_ref) try code.appendSlice(a, "AIA"); + try typeCode(a, t, p.ty, &code); + if (code.items.len == 1) { + try out.appendSlice(a, code.items); + continue; + } + // Repeated multi-character types are back-references. + const back = for (refs.items, 0..) |r, k| { + if (std.mem.eql(u8, r, code.items)) break k; + } else null; + if (back) |k| if (k < 10) { + try out.append(a, '0' + @as(u8, @intCast(k))); + continue; + }; + try out.appendSlice(a, code.items); + if (back == null) try refs.append(a, code.items); + } + try out.append(a, '@'); + } + try out.append(a, 'Z'); + return out.items; +} + +/// `\x01?name@@3A` (a global variable). +pub fn global(a: Allocator, t: *TypeTable, name: []const u8, ty: TypeId) Allocator.Error![]u8 { + var out: std.ArrayList(u8) = .empty; + try out.print(a, "\x01?{s}@@3", .{name}); + try typeCode(a, t, ty, &out); + try out.append(a, 'A'); + return out.items; +} + +fn number(a: Allocator, n: u64, out: *std.ArrayList(u8)) Allocator.Error!void { + if (n >= 1 and n <= 10) return out.append(a, '0' + @as(u8, @intCast(n - 1))); + if (n == 0) return out.appendSlice(a, "A@"); + var buf: [16]u8 = undefined; + var k: usize = buf.len; + var v = n; + while (v != 0) : (v >>= 4) { + k -= 1; + buf[k] = 'A' + @as(u8, @intCast(v & 0xf)); + } + try out.appendSlice(a, buf[k..]); + try out.append(a, '@'); +} + +fn scalarCode(s: types.Scalar) []const u8 { + return switch (s) { + .bool => "_N", + .int, .literal_int => "H", + .uint => "I", + .float, .literal_float => "M", + .double => "N", + .half => "$halff@", + .float16 => "$f16@", + .int16 => "F", + .uint16 => "G", + .int64 => "_J", + .uint64 => "_K", + .min16float => "$min16f@", + .min10float => "$min10f@", + .min16int => "$min16i@", + .min12int => "$min12i@", + .min16uint => "$min16ui@", + else => "H", + }; +} + +fn typeCode(a: Allocator, t: *TypeTable, ty: TypeId, out: *std.ArrayList(u8)) Allocator.Error!void { + if (ty == TypeTable.void_type) return out.append(a, 'X'); + switch (t.get(ty)) { + .scalar => |s| try out.appendSlice(a, scalarCode(s)), + .@"enum" => |en| try out.print(a, "W4{s}@@", .{en.name}), + .vector => |v| { + try out.print(a, "V?$vector@{s}", .{scalarCode(v.elem)}); + try out.append(a, '$'); + try number(a, v.len, out); + try out.appendSlice(a, "@@"); + }, + .matrix => |m| { + try out.print(a, "V?$matrix@{s}", .{scalarCode(m.elem)}); + try out.append(a, '$'); + try number(a, m.rows, out); + try out.append(a, '$'); + try number(a, m.cols, out); + try out.appendSlice(a, "@@"); + }, + .array => |arr| { + // Y... + var dims: std.ArrayList(u32) = .empty; + var et = ty; + while (t.get(et) == .array) : (et = t.get(et).array.elem) try dims.append(a, t.get(et).array.len); + _ = arr; + try out.append(a, 'Y'); + try number(a, dims.items.len - 1, out); + for (dims.items) |d| try number(a, d, out); + try typeCode(a, t, et, out); + }, + .@"struct" => |st| try out.print(a, "U{s}@@", .{st.name}), + .resource => |r| { + if (r.elem == TypeTable.void_type or r.kind == .raytracing_acceleration_structure) return out.print(a, "U{s}@@", .{r.name}); + try out.print(a, "V?${s}@", .{r.name}); + try typeCode(a, t, r.elem, out); + try out.appendSlice(a, "@@"); + }, + .sampler => |s| try out.appendSlice(a, if (s.comparison) "USamplerComparisonState@@" else "USamplerState@@"), + else => try out.append(a, 'X'), + } +} diff --git a/src/dxil/module.zig b/src/dxil/module.zig index 1f7a9d5..e7e0d14 100644 --- a/src/dxil/module.zig +++ b/src/dxil/module.zig @@ -55,7 +55,7 @@ pub const Constant = struct { pub const Linkage = enum(u32) { external = 0, internal = 3 }; /// Attribute group for function declarations (e.g. dx.op functions). -pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly }; +pub const FnAttrs = enum { none, nounwind, nounwind_readnone, nounwind_readonly, noreturn_nounwind }; pub const Value = union(enum) { /// Index into Module.globals (a pointer to the variable). @@ -73,7 +73,7 @@ pub const RmwOp = enum(u32) { xchg = 0, add = 1, sub = 2, @"and" = 3, nand = 4, /// A module-level variable (groupshared memory: address space 3), /// declared without an initializer as dxc does. -pub const GlobalVar = struct { name: []const u8, ty: TypeId, addr_space: u32, ptr_ty: TypeId }; +pub const GlobalVar = struct { name: []const u8, ty: TypeId, addr_space: u32, ptr_ty: TypeId, constant: bool = false }; pub const CastOp = enum(u32) { trunc = 0, zext = 1, sext = 2, fptoui = 3, fptosi = 4, uitofp = 5, sitofp = 6, fptrunc = 7, fpext = 8, ptrtoint = 9, inttoptr = 10, bitcast = 11 }; @@ -354,7 +354,7 @@ const Encoder = struct { for (e.m.globals.items) |g| { // GLOBALVAR: [type, addrspace << 2 | explicit type, init (none), // linkage (external), align 4, section] - try e.ops.appendSlice(e.gpa(), &.{ g.ty, (@as(u64, g.addr_space) << 2) | 2, 0, 0, 3, 0 }); + try e.ops.appendSlice(e.gpa(), &.{ g.ty, (@as(u64, g.addr_space) << 2) | 2 | @intFromBool(g.constant), 0, 0, 3, 0 }); try e.rec(7); } for (e.m.functions.items) |f| { @@ -380,11 +380,11 @@ const Encoder = struct { } fn writeAttributes(e: *Encoder) !void { - // Groups 1..3 match FnAttrs order; each applies to the function (index 0xFFFFFFFF). - // Attribute kinds: nounwind = 18, readnone = 20, readonly = 21. + // Groups 1..4 match FnAttrs order; each applies to the function (index 0xFFFFFFFF). + // Attribute kinds: noreturn = 17, nounwind = 18, readnone = 20, readonly = 21. const w = &e.w; try w.enterBlock(block_paramattr_group, 3); - const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 } }; + const groups = [_][]const u64{ &.{18}, &.{ 18, 20 }, &.{ 18, 21 }, &.{ 17, 18 } }; for (groups, 1..) |kinds, id| { try e.push(id); try e.push(0xFFFFFFFF); diff --git a/src/dxil/op_compat.zig b/src/dxil/op_compat.zig new file mode 100644 index 0000000..44b92f8 --- /dev/null +++ b/src/dxil/op_compat.zig @@ -0,0 +1,219 @@ +//! Minimum shader model and valid shader stages of each DXIL operation, as +//! used for library compatibility info (RDAT). Generated from the +//! OPCODE-SMMASK block of dxc's lib/DXIL/DxilOperations.cpp +//! (OP::GetMinShaderModelAndMask, with translation, as for libraries) at +//! commit f9fc72ad3. + +/// Shader stage bits (1 << DXIL::ShaderKind). +pub const all_stages: u32 = 0xffff; + +pub const Compat = struct { minor: u8, mask: u32 }; + +/// Entries for operations other than shader model 6.0 in every stage. +const table = [_]struct { u16, u8, u32 }{ + .{ 60, 0, 0xe061 }, + .{ 61, 0, 0xe061 }, + .{ 64, 0, 0xe061 }, + .{ 76, 0, 0x1 }, + .{ 77, 0, 0x1 }, + .{ 81, 0, 0xe061 }, + .{ 82, 0, 0x1 }, + .{ 83, 0, 0xe061 }, + .{ 84, 0, 0xe061 }, + .{ 85, 0, 0xe061 }, + .{ 86, 0, 0xe061 }, + .{ 87, 0, 0x1 }, + .{ 88, 0, 0x1 }, + .{ 89, 0, 0x1 }, + .{ 90, 0, 0x1 }, + .{ 91, 0, 0x1 }, + .{ 92, 0, 0x1 }, + .{ 93, 0, 0xe020 }, + .{ 94, 0, 0xe020 }, + .{ 95, 0, 0xe020 }, + .{ 96, 0, 0xe020 }, + .{ 97, 0, 0x4 }, + .{ 98, 0, 0x4 }, + .{ 99, 0, 0x4 }, + .{ 100, 0, 0x4 }, + .{ 103, 0, 0x18 }, + .{ 104, 0, 0x18 }, + .{ 105, 0, 0x10 }, + .{ 106, 0, 0x8 }, + .{ 107, 0, 0x8 }, + .{ 108, 0, 0x1c }, + .{ 122, 0, 0xe061 }, + .{ 123, 0, 0xe061 }, + .{ 137, 1, 0x1 }, + .{ 138, 1, 0x201f }, + .{ 141, 3, 0x740 }, + .{ 142, 3, 0x740 }, + .{ 143, 3, 0x740 }, + .{ 144, 3, 0xf40 }, + .{ 145, 3, 0x1fc0 }, + .{ 146, 3, 0x1fc0 }, + .{ 147, 3, 0xf40 }, + .{ 148, 3, 0xf40 }, + .{ 149, 3, 0x740 }, + .{ 150, 3, 0x740 }, + .{ 151, 3, 0x740 }, + .{ 152, 3, 0x740 }, + .{ 153, 3, 0xf40 }, + .{ 154, 3, 0xf40 }, + .{ 155, 3, 0x200 }, + .{ 156, 3, 0x200 }, + .{ 157, 3, 0xcc0 }, + .{ 158, 3, 0x140 }, + .{ 159, 3, 0x1cc0 }, + .{ 161, 3, 0x740 }, + .{ 162, 4, 0xffff }, + .{ 163, 4, 0xffff }, + .{ 164, 4, 0xffff }, + .{ 165, 5, 0xffff }, + .{ 166, 5, 0xffff }, + .{ 167, 5, 0xffff }, + .{ 168, 5, 0x2000 }, + .{ 169, 5, 0x2000 }, + .{ 170, 5, 0x2000 }, + .{ 171, 5, 0x2000 }, + .{ 172, 5, 0x2000 }, + .{ 173, 5, 0x4000 }, + .{ 174, 5, 0x41 }, + .{ 175, 5, 0x41 }, + .{ 176, 5, 0xffff }, + .{ 177, 5, 0xffff }, + .{ 178, 5, 0xffff }, + .{ 179, 5, 0xffff }, + .{ 180, 5, 0xffff }, + .{ 181, 5, 0xffff }, + .{ 182, 5, 0xffff }, + .{ 183, 5, 0xffff }, + .{ 184, 5, 0xffff }, + .{ 185, 5, 0xffff }, + .{ 186, 5, 0xffff }, + .{ 187, 5, 0xffff }, + .{ 188, 5, 0xffff }, + .{ 189, 5, 0xffff }, + .{ 190, 5, 0xffff }, + .{ 191, 5, 0xffff }, + .{ 192, 5, 0xffff }, + .{ 193, 5, 0xffff }, + .{ 194, 5, 0xffff }, + .{ 195, 5, 0xffff }, + .{ 196, 5, 0xffff }, + .{ 197, 5, 0xffff }, + .{ 198, 5, 0xffff }, + .{ 199, 5, 0xffff }, + .{ 200, 5, 0xffff }, + .{ 201, 5, 0xffff }, + .{ 202, 5, 0xffff }, + .{ 203, 5, 0xffff }, + .{ 204, 5, 0xffff }, + .{ 205, 5, 0xffff }, + .{ 206, 5, 0xffff }, + .{ 207, 5, 0xffff }, + .{ 208, 5, 0xffff }, + .{ 209, 5, 0xffff }, + .{ 210, 5, 0xffff }, + .{ 211, 5, 0xffff }, + .{ 212, 5, 0xffff }, + .{ 213, 5, 0x740 }, + .{ 214, 5, 0xffff }, + .{ 215, 5, 0xffff }, + .{ 218, 6, 0xffff }, + .{ 219, 6, 0xffff }, + .{ 220, 6, 0xffff }, + .{ 221, 6, 0xffff }, + .{ 222, 0, 0xe061 }, + .{ 223, 7, 0xffff }, + .{ 224, 7, 0xffff }, + .{ 225, 7, 0xffff }, + .{ 238, 8, 0x8000 }, + .{ 239, 8, 0x8000 }, + .{ 240, 8, 0x8000 }, + .{ 241, 8, 0x8000 }, + .{ 242, 8, 0x8000 }, + .{ 243, 8, 0x8000 }, + .{ 245, 8, 0xffff }, + .{ 246, 8, 0x8000 }, + .{ 247, 8, 0x8000 }, + .{ 248, 8, 0x8000 }, + .{ 249, 8, 0x8000 }, + .{ 250, 8, 0x8000 }, + .{ 251, 8, 0x8000 }, + .{ 252, 8, 0x8000 }, + .{ 253, 8, 0x8000 }, + .{ 254, 8, 0xffff }, + .{ 255, 8, 0xe061 }, + .{ 256, 8, 0x2 }, + .{ 257, 8, 0x2 }, + .{ 258, 9, 0xffff }, + .{ 262, 9, 0xcc0 }, + .{ 263, 9, 0xcc0 }, + .{ 264, 9, 0xcc0 }, + .{ 265, 9, 0xcc0 }, + .{ 266, 9, 0xcc0 }, + .{ 267, 9, 0xcc0 }, + .{ 268, 9, 0xc0 }, + .{ 269, 9, 0xcc0 }, + .{ 270, 9, 0xcc0 }, + .{ 271, 9, 0xcc0 }, + .{ 272, 9, 0xcc0 }, + .{ 273, 9, 0xcc0 }, + .{ 274, 9, 0xcc0 }, + .{ 275, 9, 0xcc0 }, + .{ 276, 9, 0xcc0 }, + .{ 277, 9, 0xcc0 }, + .{ 278, 9, 0xcc0 }, + .{ 279, 9, 0xcc0 }, + .{ 280, 9, 0xcc0 }, + .{ 281, 9, 0xcc0 }, + .{ 282, 9, 0xcc0 }, + .{ 283, 9, 0xcc0 }, + .{ 284, 9, 0xcc0 }, + .{ 285, 9, 0xcc0 }, + .{ 286, 9, 0xcc0 }, + .{ 287, 9, 0xcc0 }, + .{ 288, 9, 0xcc0 }, + .{ 289, 9, 0xcc0 }, + .{ 303, 9, 0xffff }, + .{ 304, 9, 0xffff }, + .{ 312, 10, 0x6020 }, + .{ 313, 10, 0x6020 }, + .{ 314, 10, 0x640 }, + .{ 315, 10, 0xffff }, + .{ 316, 10, 0xffff }, + .{ 317, 10, 0xcc0 }, + .{ 318, 10, 0x640 }, + .{ 319, 10, 0xffff }, + .{ 320, 10, 0xffff }, + .{ 321, 10, 0xcc0 }, + .{ 322, 10, 0x20 }, + .{ 323, 10, 0x20 }, + .{ 324, 10, 0x20 }, + .{ 325, 10, 0xffff }, + .{ 326, 10, 0x20 }, + .{ 327, 10, 0x20 }, + .{ 328, 10, 0x20 }, + .{ 329, 10, 0x20 }, + .{ 330, 10, 0x20 }, + .{ 331, 10, 0x20 }, + .{ 332, 10, 0x20 }, + .{ 333, 10, 0xffff }, + .{ 334, 10, 0x20 }, + .{ 335, 10, 0x20 }, + .{ 336, 10, 0xffff }, + .{ 337, 10, 0xffff }, + .{ 338, 10, 0xffff }, + .{ 339, 10, 0x20 }, + .{ 340, 10, 0xffff }, + .{ 341, 10, 0xffff }, + .{ 342, 10, 0xffff }, + .{ 343, 10, 0xffff }, + .{ 344, 10, 0xffff }, +}; + +pub fn get(op: u32) Compat { + for (table) |t| if (t[0] == op) return .{ .minor = t[1], .mask = t[2] }; + return .{ .minor = 0, .mask = all_stages }; +} diff --git a/src/dxil/rdat.zig b/src/dxil/rdat.zig new file mode 100644 index 0000000..3715cbf --- /dev/null +++ b/src/dxil/rdat.zig @@ -0,0 +1,168 @@ +//! The runtime data part (RDAT) of DXIL libraries, built the way dxc's +//! DxilRDATWriter / DxilRDATBuilder build it: the validator regenerates +//! the part from the module and requires the same bytes. +//! +//! Layout: a header (version, part count), part offsets, then each +//! non-empty part as (type, size) and its 4-byte aligned contents. Parts +//! come in the order dxc adds them: strings, resources, functions, index +//! arrays, raw bytes, subobjects (only the first four are produced here). + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +pub const null_ref: u32 = 0xffff_ffff; + +pub const Resource = struct { + class: u32, + kind: u32, + id: u32, + space: u32, + lower: u32, + upper: u32, + name: u32, + flags: u32 = 0, +}; + +/// RuntimeDataFunctionInfo3 (validator 1.10+). +pub const Function = struct { + name: u32, + unmangled_name: u32, + resources: u32 = null_ref, + function_dependencies: u32 = null_ref, + shader_kind: u32, + payload_size: u32 = 0, + attribute_size: u32 = 0, + feature_info1: u32 = 0, + feature_info2: u32 = 0, + shader_stage_flag: u32, + min_shader_target: u32, + min_wave_lanes: u8 = 0, + max_wave_lanes: u8 = 0, + shader_flags: u16 = 0, + raw_shader_ref: u32 = null_ref, + extended_properties: u32 = null_ref, +}; + +pub const Builder = struct { + gpa: Allocator, + strings: std.ArrayList(u8) = .empty, + string_map: std.StringHashMapUnmanaged(u32) = .empty, + indices: std.ArrayList(u32) = .empty, + resources: std.ArrayList([8]u32) = .empty, + functions: std.ArrayList([14]u32) = .empty, + + pub fn init(gpa: Allocator) Allocator.Error!Builder { + var b: Builder = .{ .gpa = gpa }; + _ = try b.string(""); + return b; + } + + /// Offset of `s` in the string buffer (each string once). + pub fn string(b: *Builder, s: []const u8) Allocator.Error!u32 { + if (b.string_map.get(s)) |off| return off; + const off: u32 = @intCast(b.strings.items.len); + try b.strings.appendSlice(b.gpa, s); + try b.strings.append(b.gpa, 0); + try b.string_map.put(b.gpa, s, off); + return off; + } + + /// Offset of the index array (count, then the values); identical + /// arrays are shared. + pub fn array(b: *Builder, vals: []const u32) Allocator.Error!u32 { + var at: usize = 0; + while (at < b.indices.items.len) { + const n = b.indices.items[at]; + if (n == vals.len and std.mem.eql(u32, b.indices.items[at + 1 ..][0..n], vals)) return @intCast(at); + at += n + 1; + } + const off: u32 = @intCast(b.indices.items.len); + try b.indices.append(b.gpa, @intCast(vals.len)); + try b.indices.appendSlice(b.gpa, vals); + return off; + } + + pub fn addResource(b: *Builder, r: Resource) Allocator.Error!void { + try b.resources.append(b.gpa, .{ r.class, r.kind, r.id, r.space, r.lower, r.upper, r.name, r.flags }); + } + + pub fn addFunction(b: *Builder, f: Function) Allocator.Error!void { + const packed_wave: u32 = @as(u32, f.min_wave_lanes) | (@as(u32, f.max_wave_lanes) << 8) | (@as(u32, f.shader_flags) << 16); + try b.functions.append(b.gpa, .{ + f.name, f.unmangled_name, f.resources, f.function_dependencies, + f.shader_kind, f.payload_size, f.attribute_size, f.feature_info1, + f.feature_info2, f.shader_stage_flag, f.min_shader_target, packed_wave, + f.raw_shader_ref, f.extended_properties, + }); + } + + /// The finished part. + pub fn finish(b: *Builder) Allocator.Error![]u8 { + const Part = struct { ty: u32, data: []const u8 }; + var parts: std.ArrayList(Part) = .empty; + defer parts.deinit(b.gpa); + var tables: std.ArrayList([]u8) = .empty; + defer { + for (tables.items) |t| b.gpa.free(t); + tables.deinit(b.gpa); + } + if (b.strings.items.len > 0) try parts.append(b.gpa, .{ .ty = 1, .data = b.strings.items }); + if (b.resources.items.len > 0) { + const t = try table(b.gpa, 8, std.mem.sliceAsBytes(b.resources.items), b.resources.items.len); + try tables.append(b.gpa, t); + try parts.append(b.gpa, .{ .ty = 3, .data = t }); + } + if (b.functions.items.len > 0) { + const t = try table(b.gpa, 14, std.mem.sliceAsBytes(b.functions.items), b.functions.items.len); + try tables.append(b.gpa, t); + try parts.append(b.gpa, .{ .ty = 4, .data = t }); + } + if (b.indices.items.len > 0) try parts.append(b.gpa, .{ .ty = 2, .data = std.mem.sliceAsBytes(b.indices.items) }); + + var size: usize = 8 + 4 * parts.items.len; + for (parts.items) |p| size += 8 + std.mem.alignForward(usize, p.data.len, 4); + const out = try b.gpa.alloc(u8, size); + @memset(out, 0); + std.mem.writeInt(u32, out[0..4], 0x10, .little); // RDAT_Version_10 + std.mem.writeInt(u32, out[4..8], @intCast(parts.items.len), .little); + var at: usize = 8 + 4 * parts.items.len; + for (parts.items, 0..) |p, k| { + std.mem.writeInt(u32, out[8 + 4 * k ..][0..4], @intCast(at), .little); + const padded = std.mem.alignForward(usize, p.data.len, 4); + std.mem.writeInt(u32, out[at..][0..4], p.ty, .little); + std.mem.writeInt(u32, out[at + 4 ..][0..4], @intCast(padded), .little); + @memcpy(out[at + 8 ..][0..p.data.len], p.data); + at += 8 + padded; + } + return out; + } + + fn table(gpa: Allocator, words: usize, rows: []const u8, count: usize) Allocator.Error![]u8 { + const t = try gpa.alloc(u8, 8 + rows.len); + std.mem.writeInt(u32, t[0..4], @intCast(count), .little); + std.mem.writeInt(u32, t[4..8], @intCast(words * 4), .little); + @memcpy(t[8..], rows); + return t; + } + + pub fn deinit(b: *Builder) void { + b.strings.deinit(b.gpa); + b.string_map.deinit(b.gpa); + b.indices.deinit(b.gpa); + b.resources.deinit(b.gpa); + b.functions.deinit(b.gpa); + } +}; + +test "rdat of one resource and function" { + var b = try Builder.init(std.testing.allocator); + defer b.deinit(); + const n = try b.string("buf"); + try b.addResource(.{ .class = 1, .kind = 12, .id = 0, .space = 0, .lower = 0, .upper = 0, .name = n }); + const res = try b.array(&.{0}); + try std.testing.expectEqual(res, try b.array(&.{0})); + try b.addFunction(.{ .name = try b.string("cs"), .unmangled_name = try b.string("cs"), .resources = res, .shader_kind = 5, .shader_stage_flag = 32, .min_shader_target = 0x50060 }); + const out = try b.finish(); + defer std.testing.allocator.free(out); + try std.testing.expectEqual(@as(u32, 4), std.mem.readInt(u32, out[4..8], .little)); +} diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 54db047..ef990d4 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -54,10 +54,6 @@ pub fn lowerUnit(arena: Allocator, s: *Sema, opts: Options) Error!ir.Module { try l.drain(); try l.m.exports.append(l.arena, fi); } - if (l.m.entries.items.len == 0 and l.m.exports.items.len == 0) { - l.unsupported(.none, "libraries without shader entry points or exported functions", .{}); - return error.Unsupported; - } return l.m; } const entry_fn = for (s.all_functions.items) |f| { diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index 0133432..b746d2f 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -3192,11 +3192,11 @@ const Emitter = struct { /// Whether pointer / resource `r` reaches into a shader record buffer. fn inShaderRecord(e: *Emitter, r: Ref) bool { var x = r; - while (true) switch (e.f.inst(x).op) { - .access => |a| x = a.base, - .load => |p| x = p, - else => break, - }; + while (e.f.inst(x).op == .access) x = e.f.inst(x).op.access.base; + if (e.f.inst(x).op == .global) return e.m.globals.items[e.f.inst(x).op.global].shader_record; + // ConstantBuffer values (through locals and parameters). + const t = e.t.get(e.f.inst(x).ty); + if (t != .resource or t.resource.kind != .constant_buffer) return false; const g = e.globalOf(x) orelse return false; return e.m.globals.items[g].shader_record; }