diff --git a/src/compile.zig b/src/compile.zig index ee218d6..443dd98 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -53,6 +53,9 @@ pub const Result = struct { /// The root signature container (-Frs) and its name. root_signature: ?[]const u8 = null, root_signature_name: ?[]const u8 = null, + /// DXIL: the shader's reflection (dxil/reflect.zig), for the DXC + /// drop-in's DXC_OUT_REFLECTION. + reflection: ?[]const u8 = null, /// Preprocessed source (-P) and its -Fi name. preprocessed: ?[]const u8 = null, preprocessed_name: ?[]const u8 = null, @@ -105,6 +108,7 @@ pub fn compile(arena: std.mem.Allocator, req: Request) error{OutOfMemory}!Result }; if (result.status != .ok) { result.object = null; + result.reflection = null; result.root_signature = null; result.preprocessed = null; } @@ -534,7 +538,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { if (opts.rootsig_define) |macro| if (m.entries.items.len == 1) { m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed; }; - const bytes = zdxc.dxil.emit.emit(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) { + const dxil_out = zdxc.dxil.emit.emitWithReflection(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) { error.Unsupported => { try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); return error.CompileFailed; @@ -542,7 +546,8 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { else => |x| return x, }; try ctx.needOutput(opts); - ctx.result.object = bytes; + ctx.result.object = dxil_out.object; + ctx.result.reflection = dxil_out.reflection; if (opts.rootsig_output != null) { const text = (if (m.entries.items.len == 1) m.entries.items[0].root_signature else null) orelse return ctx.fail("-Frs: the shader has no root signature", .{}); var d: zdxc.dxil.rootsig.Diagnostic = .{}; @@ -618,4 +623,4 @@ fn compileRootSignatureMacro(ctx: *Ctx, arena: std.mem.Allocator, opts: Options, /// 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 }}); -} \ No newline at end of file +} diff --git a/src/dxcapi.zig b/src/dxcapi.zig index ab2618f..240d5d2 100644 --- a/src/dxcapi.zig +++ b/src/dxcapi.zig @@ -55,6 +55,7 @@ const OutKind = enum(u32) { shader_hash = 4, hlsl = 6, text = 7, + reflection = 8, root_signature = 9, remarks = 11, _, @@ -94,6 +95,13 @@ const GUID = extern struct { const CLSID_DxcCompiler = GUID.parse("73e22d93-e6ce-47f3-b5bf-f0664f39c1b0"); const CLSID_DxcUtils = GUID.parse("6245d6af-66e0-48fd-80b4-4d271796748c"); // == CLSID_DxcLibrary +const CLSID_DxcContainerReflection = GUID.parse("b9f54489-55b8-400c-ba3a-1675e4728b91"); +const CLSID_DxcContainerBuilder = GUID.parse("94134294-411f-4574-b4d0-8741e25240d2"); +const IID_IDxcLibrary = GUID.parse("e5204dc7-d18c-4c3c-bdfb-851673980fe7"); +const IID_IDxcContainerReflection = GUID.parse("d2c21b26-8350-4bdc-976a-331ce6f4c54c"); +const IID_IDxcContainerBuilder = GUID.parse("334b1f50-2292-4b35-99a1-25588d8c17fe"); +const IID_ID3D12ShaderReflection = GUID.parse("5a58797d-a72c-478d-8ba2-efc6b0efe88e"); +const IID_ID3D12LibraryReflection = GUID.parse("8e349d19-54db-4a56-9dc9-119d87bdb804"); const IID_IUnknown = GUID.parse("00000000-0000-0000-c000-000000000046"); const IID_IDxcBlob = GUID.parse("8ba5fb08-5195-40e2-ac58-0d989c3a0102"); const IID_IDxcBlobEncoding = GUID.parse("7241d424-2646-4191-97c0-98e96e42fc68"); @@ -655,6 +663,7 @@ fn makeResult(c: compile.Result) !*Result { } else if (c.object) |obj| { try addOutput(r, .object, try Blob.copy(.binary, obj, CP_ACP), c.object_name); if (shaderHash(obj)) |h| try addOutput(r, .shader_hash, try Blob.copy(.binary, &h, CP_ACP), null); + if (c.reflection) |refl| try addOutput(r, .reflection, try Blob.copy(.binary, refl, CP_ACP), null); } else { r.primary = .text; }, @@ -892,10 +901,56 @@ const MallocVtbl = extern struct { Free: *const fn (This, ?*anyopaque) callconv(cc) void, }; +/// IDxcLibrary: the older blob helpers on the same object. +const LibraryVtbl = extern struct { + unknown: UnknownVtbl, + SetMalloc: *const fn (This, ?*anyopaque) callconv(cc) HRESULT, + CreateBlobFromBlob: *const fn (This, ?*anyopaque, u32, u32, ?Out) callconv(cc) HRESULT, + CreateBlobFromFile: *const fn (This, ?[*:0]const WCHAR, ?*u32, ?Out) callconv(cc) HRESULT, + CreateBlobWithEncodingFromPinned: *const fn (This, ?[*]const u8, u32, u32, ?Out) callconv(cc) HRESULT, + CreateBlobWithEncodingOnHeapCopy: *const fn (This, ?[*]const u8, u32, u32, ?Out) callconv(cc) HRESULT, + CreateBlobWithEncodingOnMalloc: *const fn (This, ?[*]const u8, ?*anyopaque, u32, u32, ?Out) callconv(cc) HRESULT, + CreateIncludeHandler: *const fn (This, ?Out) callconv(cc) HRESULT, + CreateStreamFromBlobReadOnly: *const fn (This, ?*anyopaque, ?Out) callconv(cc) HRESULT, + GetBlobAsUtf8: *const fn (This, ?*anyopaque, ?Out) callconv(cc) HRESULT, + GetBlobAsUtf16: *const fn (This, ?*anyopaque, ?Out) callconv(cc) HRESULT, +}; + const Utils = struct { iface: Iface(UtilsVtbl) = .{ .vtbl = &vtbl }, + library: Iface(LibraryVtbl) = .{ .vtbl = &library_vtbl }, rc: RefCount = .{}, + const library_vtbl: LibraryVtbl = .{ + .unknown = .{ .QueryInterface = libraryQueryInterface, .AddRef = libraryAddRef, .Release = libraryRelease }, + .SetMalloc = setMalloc, + .CreateBlobFromBlob = createBlobFromBlob, + .CreateBlobFromFile = loadFile, + .CreateBlobWithEncodingFromPinned = createBlobFromPinned, + .CreateBlobWithEncodingOnHeapCopy = createBlob, + .CreateBlobWithEncodingOnMalloc = moveToBlob, + .CreateIncludeHandler = createDefaultIncludeHandler, + .CreateStreamFromBlobReadOnly = notImplemented2, + .GetBlobAsUtf8 = getBlobAsUtf8, + .GetBlobAsUtf16 = getBlobAsWide, + }; + + fn libraryOf(this: This) *Utils { + return parent(Utils, "library", this); + } + fn libraryQueryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { + return queryInterface(&libraryOf(this).iface, iid, out); + } + fn libraryAddRef(this: This) callconv(cc) ULONG { + return libraryOf(this).rc.addRef(); + } + fn libraryRelease(this: This) callconv(cc) ULONG { + return release(&libraryOf(this).iface); + } + fn setMalloc(_: This, _: ?*anyopaque) callconv(cc) HRESULT { + return S_OK; + } + const vtbl: UtilsVtbl = .{ .unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release }, .CreateBlobFromBlob = createBlobFromBlob, @@ -918,12 +973,17 @@ const Utils = struct { } fn queryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { - if (!iid.eql(IID_IUnknown) and !iid.eql(IID_IDxcUtils)) { + const u = of(this); + const p: *anyopaque = if (iid.eql(IID_IUnknown) or iid.eql(IID_IDxcUtils)) + &u.iface + else if (iid.eql(IID_IDxcLibrary)) + &u.library + else { _ = put(out, null); return E_NOINTERFACE; - } - _ = of(this).rc.addRef(); - return put(out, this); + }; + _ = u.rc.addRef(); + return put(out, p); } fn addRef(this: This) callconv(cc) ULONG { return of(this).rc.addRef(); @@ -1033,9 +1093,19 @@ const Utils = struct { return S_OK; } - fn createReflection(_: This, _: ?*const Buffer, _: *const GUID, out: ?Out) callconv(cc) HRESULT { - _ = put(out, null); - return E_NOTIMPL; + /// ID3D12ShaderReflection / ID3D12LibraryReflection over a + /// DXC_OUT_REFLECTION blob of ours. + fn createReflection(_: This, data: ?*const Buffer, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { + const o = out orelse return E_POINTER; + o.* = null; + const buf = data orelse return E_INVALIDARG; + const bytes = (buf.ptr orelse return E_INVALIDARG)[0..buf.size]; + const r = ShaderReflection.create(bytes) catch |e| return switch (e) { + error.OutOfMemory => E_OUTOFMEMORY, + else => E_INVALIDARG, + }; + defer _ = ShaderReflection.release(&r.shader); + return r.query(iid, o); } fn getPdbContents(_: This, _: ?*anyopaque, hash: ?Out, container: ?Out) callconv(cc) HRESULT { @@ -1054,6 +1124,893 @@ const Utils = struct { } }; +// ---- Shader reflection ---------------------------------------------------- +// +// ID3D12ShaderReflection and ID3D12LibraryReflection (d3d12shader.h) over +// the reflection blob zdxc returns as DXC_OUT_REFLECTION (dxil/reflect.zig). +// Their constant buffer, variable, type and function objects are not +// IUnknowns: they live as long as the reflection object. A lookup that +// finds nothing returns an object whose GetDesc fails, as D3D's do. + +const reflect = zdxc.dxil.reflect; +const LPCSTR = ?[*:0]const u8; + +const ShaderDesc = extern struct { + Version: u32 = 0, + Creator: LPCSTR = null, + Flags: u32 = 0, + ConstantBuffers: u32 = 0, + BoundResources: u32 = 0, + InputParameters: u32 = 0, + OutputParameters: u32 = 0, + InstructionCount: u32 = 0, + TempRegisterCount: u32 = 0, + TempArrayCount: u32 = 0, + DefCount: u32 = 0, + DclCount: u32 = 0, + TextureNormalInstructions: u32 = 0, + TextureLoadInstructions: u32 = 0, + TextureCompInstructions: u32 = 0, + TextureBiasInstructions: u32 = 0, + TextureGradientInstructions: u32 = 0, + FloatInstructionCount: u32 = 0, + IntInstructionCount: u32 = 0, + UintInstructionCount: u32 = 0, + StaticFlowControlCount: u32 = 0, + DynamicFlowControlCount: u32 = 0, + MacroInstructionCount: u32 = 0, + ArrayInstructionCount: u32 = 0, + CutInstructionCount: u32 = 0, + EmitInstructionCount: u32 = 0, + GSOutputTopology: u32 = 0, + GSMaxOutputVertexCount: u32 = 0, + InputPrimitive: u32 = 0, + PatchConstantParameters: u32 = 0, + cGSInstanceCount: u32 = 0, + cControlPoints: u32 = 0, + HSOutputPrimitive: u32 = 0, + HSPartitioning: u32 = 0, + TessellatorDomain: u32 = 0, + cBarrierInstructions: u32 = 0, + cInterlockedInstructions: u32 = 0, + cTextureStoreInstructions: u32 = 0, +}; + +const BufferDesc = extern struct { Name: LPCSTR = null, Type: u32 = 0, Variables: u32 = 0, Size: u32 = 0, uFlags: u32 = 0 }; + +const VariableDesc = extern struct { + Name: LPCSTR = null, + StartOffset: u32 = 0, + Size: u32 = 0, + uFlags: u32 = 0, + DefaultValue: ?*anyopaque = null, + StartTexture: u32 = 0xFFFFFFFF, + TextureSize: u32 = 0, + StartSampler: u32 = 0xFFFFFFFF, + SamplerSize: u32 = 0, +}; + +const TypeDesc = extern struct { Class: u32 = 0, Type: u32 = 0, Rows: u32 = 0, Columns: u32 = 0, Elements: u32 = 0, Members: u32 = 0, Offset: u32 = 0, Name: LPCSTR = null }; + +const BindDesc = extern struct { Name: LPCSTR = null, Type: u32 = 0, BindPoint: u32 = 0, BindCount: u32 = 0, uFlags: u32 = 0, ReturnType: u32 = 0, Dimension: u32 = 0, NumSamples: u32 = 0, Space: u32 = 0, uID: u32 = 0 }; + +const SignatureParamDesc = extern struct { SemanticName: LPCSTR = null, SemanticIndex: u32 = 0, Register: u32 = 0, SystemValueType: u32 = 0, ComponentType: u32 = 0, Mask: u8 = 0, ReadWriteMask: u8 = 0, Stream: u32 = 0, MinPrecision: u32 = 0 }; + +const LibraryDesc = extern struct { Creator: LPCSTR = null, Flags: u32 = 0, FunctionCount: u32 = 0 }; + +const FunctionDesc = extern struct { + Version: u32 = 0, + Creator: LPCSTR = null, + Flags: u32 = 0, + ConstantBuffers: u32 = 0, + BoundResources: u32 = 0, + InstructionCount: u32 = 0, + TempRegisterCount: u32 = 0, + TempArrayCount: u32 = 0, + DefCount: u32 = 0, + DclCount: u32 = 0, + TextureNormalInstructions: u32 = 0, + TextureLoadInstructions: u32 = 0, + TextureCompInstructions: u32 = 0, + TextureBiasInstructions: u32 = 0, + TextureGradientInstructions: u32 = 0, + FloatInstructionCount: u32 = 0, + IntInstructionCount: u32 = 0, + UintInstructionCount: u32 = 0, + StaticFlowControlCount: u32 = 0, + DynamicFlowControlCount: u32 = 0, + MacroInstructionCount: u32 = 0, + ArrayInstructionCount: u32 = 0, + MovInstructionCount: u32 = 0, + MovcInstructionCount: u32 = 0, + ConversionInstructionCount: u32 = 0, + BitwiseInstructionCount: u32 = 0, + MinFeatureLevel: u32 = 0, + RequiredFeatureFlags: u64 = 0, + Name: LPCSTR = null, + FunctionParameterCount: i32 = 0, + HasReturn: i32 = 0, + Has10Level9VertexShader: i32 = 0, + Has10Level9PixelShader: i32 = 0, +}; + +const creator: [*:0]const u8 = "zdxc"; +/// D3D_FEATURE_LEVEL_12_0. +const feature_level_12_0 = 0xc000; + +const CBufferVtbl = extern struct { + GetDesc: *const fn (This, ?*BufferDesc) callconv(cc) HRESULT, + GetVariableByIndex: *const fn (This, u32) callconv(cc) *anyopaque, + GetVariableByName: *const fn (This, LPCSTR) callconv(cc) *anyopaque, +}; + +const VariableVtbl = extern struct { + GetDesc: *const fn (This, ?*VariableDesc) callconv(cc) HRESULT, + GetType: *const fn (This) callconv(cc) *anyopaque, + GetBuffer: *const fn (This) callconv(cc) *anyopaque, + GetInterfaceSlot: *const fn (This, u32) callconv(cc) u32, +}; + +const TypeVtbl = extern struct { + GetDesc: *const fn (This, ?*TypeDesc) callconv(cc) HRESULT, + GetMemberTypeByIndex: *const fn (This, u32) callconv(cc) *anyopaque, + GetMemberTypeByName: *const fn (This, LPCSTR) callconv(cc) *anyopaque, + GetMemberTypeName: *const fn (This, u32) callconv(cc) LPCSTR, + IsEqual: *const fn (This, ?*anyopaque) callconv(cc) HRESULT, + GetSubType: *const fn (This) callconv(cc) ?*anyopaque, + GetBaseClass: *const fn (This) callconv(cc) ?*anyopaque, + GetNumInterfaces: *const fn (This) callconv(cc) u32, + GetInterfaceByIndex: *const fn (This, u32) callconv(cc) ?*anyopaque, + IsOfType: *const fn (This, ?*anyopaque) callconv(cc) HRESULT, + ImplementsInterface: *const fn (This, ?*anyopaque) callconv(cc) HRESULT, +}; + +const ShaderReflectionVtbl = extern struct { + unknown: UnknownVtbl, + GetDesc: *const fn (This, ?*ShaderDesc) callconv(cc) HRESULT, + GetConstantBufferByIndex: *const fn (This, u32) callconv(cc) *anyopaque, + GetConstantBufferByName: *const fn (This, LPCSTR) callconv(cc) *anyopaque, + GetResourceBindingDesc: *const fn (This, u32, ?*BindDesc) callconv(cc) HRESULT, + GetInputParameterDesc: *const fn (This, u32, ?*SignatureParamDesc) callconv(cc) HRESULT, + GetOutputParameterDesc: *const fn (This, u32, ?*SignatureParamDesc) callconv(cc) HRESULT, + GetPatchConstantParameterDesc: *const fn (This, u32, ?*SignatureParamDesc) callconv(cc) HRESULT, + GetVariableByName: *const fn (This, LPCSTR) callconv(cc) *anyopaque, + GetResourceBindingDescByName: *const fn (This, LPCSTR, ?*BindDesc) callconv(cc) HRESULT, + GetMovInstructionCount: *const fn (This) callconv(cc) u32, + GetMovcInstructionCount: *const fn (This) callconv(cc) u32, + GetConversionInstructionCount: *const fn (This) callconv(cc) u32, + GetBitwiseInstructionCount: *const fn (This) callconv(cc) u32, + GetGSInputPrimitive: *const fn (This) callconv(cc) u32, + IsSampleFrequencyShader: *const fn (This) callconv(cc) BOOL, + GetNumInterfaceSlots: *const fn (This) callconv(cc) u32, + GetMinFeatureLevel: *const fn (This, ?*u32) callconv(cc) HRESULT, + GetThreadGroupSize: *const fn (This, ?*u32, ?*u32, ?*u32) callconv(cc) u32, + GetRequiresFlags: *const fn (This) callconv(cc) u64, +}; + +const LibraryReflectionVtbl = extern struct { + unknown: UnknownVtbl, + GetDesc: *const fn (This, ?*LibraryDesc) callconv(cc) HRESULT, + GetFunctionByIndex: *const fn (This, i32) callconv(cc) *anyopaque, +}; + +const FunctionVtbl = extern struct { + GetDesc: *const fn (This, ?*FunctionDesc) callconv(cc) HRESULT, + GetConstantBufferByIndex: *const fn (This, u32) callconv(cc) *anyopaque, + GetConstantBufferByName: *const fn (This, LPCSTR) callconv(cc) *anyopaque, + GetResourceBindingDesc: *const fn (This, u32, ?*BindDesc) callconv(cc) HRESULT, + GetVariableByName: *const fn (This, LPCSTR) callconv(cc) *anyopaque, + GetResourceBindingDescByName: *const fn (This, LPCSTR, ?*BindDesc) callconv(cc) HRESULT, + GetFunctionParameter: *const fn (This, i32) callconv(cc) *anyopaque, +}; + +const ParameterVtbl = extern struct { + GetDesc: *const fn (This, ?*anyopaque) callconv(cc) HRESULT, +}; + +fn eqlZ(a: LPCSTR, b: [*:0]const u8) bool { + return std.mem.eql(u8, std.mem.span(a orelse return false), std.mem.span(b)); +} + +/// A constant buffer of a reflection. +const CBufferObj = struct { + iface: Iface(CBufferVtbl) = .{ .vtbl = &vtbl }, + desc: BufferDesc, + vars: []VariableObj, + + const vtbl: CBufferVtbl = .{ .GetDesc = getDesc, .GetVariableByIndex = getVariableByIndex, .GetVariableByName = getVariableByName }; + fn of(this: This) *CBufferObj { + return parent(CBufferObj, "iface", this); + } + fn getDesc(this: This, d: ?*BufferDesc) callconv(cc) HRESULT { + const c = of(this); + if (c == &invalid_cbuffer) return E_FAIL; + (d orelse return E_INVALIDARG).* = c.desc; + return S_OK; + } + fn getVariableByIndex(this: This, i: u32) callconv(cc) *anyopaque { + const c = of(this); + return if (i < c.vars.len) &c.vars[i].iface else &invalid_variable.iface; + } + fn getVariableByName(this: This, name: LPCSTR) callconv(cc) *anyopaque { + for (of(this).vars) |*v| if (eqlZ(name, v.desc.Name.?)) return &v.iface; + return &invalid_variable.iface; + } +}; + +const VariableObj = struct { + iface: Iface(VariableVtbl) = .{ .vtbl = &vtbl }, + desc: VariableDesc, + ty: *TypeObj, + buffer: *CBufferObj, + + const vtbl: VariableVtbl = .{ .GetDesc = getDesc, .GetType = getType, .GetBuffer = getBuffer, .GetInterfaceSlot = getInterfaceSlot }; + fn of(this: This) *VariableObj { + return parent(VariableObj, "iface", this); + } + fn getDesc(this: This, d: ?*VariableDesc) callconv(cc) HRESULT { + const v = of(this); + if (v == &invalid_variable) return E_FAIL; + (d orelse return E_INVALIDARG).* = v.desc; + return S_OK; + } + fn getType(this: This) callconv(cc) *anyopaque { + return &of(this).ty.iface; + } + fn getBuffer(this: This) callconv(cc) *anyopaque { + return &of(this).buffer.iface; + } + fn getInterfaceSlot(_: This, _: u32) callconv(cc) u32 { + return 0xFFFFFFFF; + } +}; + +const TypeObj = struct { + iface: Iface(TypeVtbl) = .{ .vtbl = &vtbl }, + desc: TypeDesc, + members: []const *TypeObj = &.{}, + member_names: []const [*:0]const u8 = &.{}, + + const vtbl: TypeVtbl = .{ + .GetDesc = getDesc, + .GetMemberTypeByIndex = getMemberTypeByIndex, + .GetMemberTypeByName = getMemberTypeByName, + .GetMemberTypeName = getMemberTypeName, + .IsEqual = isEqual, + .GetSubType = getNull, + .GetBaseClass = getNull, + .GetNumInterfaces = getZero, + .GetInterfaceByIndex = getNullIndex, + .IsOfType = isEqual, + .ImplementsInterface = notImplementedObj, + }; + fn of(this: This) *TypeObj { + return parent(TypeObj, "iface", this); + } + fn getDesc(this: This, d: ?*TypeDesc) callconv(cc) HRESULT { + const t = of(this); + if (t == &invalid_type) return E_FAIL; + (d orelse return E_INVALIDARG).* = t.desc; + return S_OK; + } + fn getMemberTypeByIndex(this: This, i: u32) callconv(cc) *anyopaque { + const t = of(this); + return if (i < t.members.len) &t.members[i].iface else &invalid_type.iface; + } + fn getMemberTypeByName(this: This, name: LPCSTR) callconv(cc) *anyopaque { + const t = of(this); + for (t.member_names, t.members) |n, m| if (eqlZ(name, n)) return &m.iface; + return &invalid_type.iface; + } + fn getMemberTypeName(this: This, i: u32) callconv(cc) LPCSTR { + const t = of(this); + return if (i < t.member_names.len) t.member_names[i] else null; + } + fn isEqual(this: This, other: ?*anyopaque) callconv(cc) HRESULT { + // S_FALSE when they differ. + return if (other == this) S_OK else 1; + } + fn getNull(_: This) callconv(cc) ?*anyopaque { + return null; + } + fn getNullIndex(_: This, _: u32) callconv(cc) ?*anyopaque { + return null; + } + fn getZero(_: This) callconv(cc) u32 { + return 0; + } + fn notImplementedObj(_: This, _: ?*anyopaque) callconv(cc) HRESULT { + return E_NOTIMPL; + } +}; + +var invalid_type: TypeObj = .{ .desc = .{} }; +var invalid_cbuffer: CBufferObj = .{ .desc = .{}, .vars = &.{} }; +var invalid_variable: VariableObj = .{ .desc = .{}, .ty = &invalid_type, .buffer = &invalid_cbuffer }; + +/// A library function: its own resources and constant buffers. +const FunctionObj = struct { + iface: Iface(FunctionVtbl) = .{ .vtbl = &vtbl }, + desc: FunctionDesc, + binds: []const *const BindDesc, + cbuffers: []const *CBufferObj, + + const vtbl: FunctionVtbl = .{ + .GetDesc = getDesc, + .GetConstantBufferByIndex = getConstantBufferByIndex, + .GetConstantBufferByName = getConstantBufferByName, + .GetResourceBindingDesc = getResourceBindingDesc, + .GetVariableByName = getVariableByName, + .GetResourceBindingDescByName = getResourceBindingDescByName, + .GetFunctionParameter = getFunctionParameter, + }; + fn of(this: This) *FunctionObj { + return parent(FunctionObj, "iface", this); + } + fn getDesc(this: This, d: ?*FunctionDesc) callconv(cc) HRESULT { + const f = of(this); + if (f == &invalid_function) return E_FAIL; + (d orelse return E_INVALIDARG).* = f.desc; + return S_OK; + } + fn getConstantBufferByIndex(this: This, i: u32) callconv(cc) *anyopaque { + const f = of(this); + return if (i < f.cbuffers.len) &f.cbuffers[i].iface else &invalid_cbuffer.iface; + } + fn getConstantBufferByName(this: This, name: LPCSTR) callconv(cc) *anyopaque { + for (of(this).cbuffers) |c| if (eqlZ(name, c.desc.Name.?)) return &c.iface; + return &invalid_cbuffer.iface; + } + fn getResourceBindingDesc(this: This, i: u32, d: ?*BindDesc) callconv(cc) HRESULT { + const f = of(this); + const out = d orelse return E_INVALIDARG; + if (i >= f.binds.len) return E_INVALIDARG; + out.* = f.binds[i].*; + return S_OK; + } + fn getVariableByName(this: This, name: LPCSTR) callconv(cc) *anyopaque { + for (of(this).cbuffers) |c| for (c.vars) |*v| if (eqlZ(name, v.desc.Name.?)) return &v.iface; + return &invalid_variable.iface; + } + fn getResourceBindingDescByName(this: This, name: LPCSTR, d: ?*BindDesc) callconv(cc) HRESULT { + const out = d orelse return E_INVALIDARG; + for (of(this).binds) |b| if (eqlZ(name, b.Name.?)) { + out.* = b.*; + return S_OK; + }; + return E_INVALIDARG; + } + fn getFunctionParameter(_: This, _: i32) callconv(cc) *anyopaque { + return &invalid_parameter; + } +}; + +var invalid_function: FunctionObj = .{ .desc = .{}, .binds = &.{}, .cbuffers = &.{} }; +const invalid_parameter_vtbl: ParameterVtbl = .{ .GetDesc = struct { + fn f(_: This, _: ?*anyopaque) callconv(cc) HRESULT { + return E_FAIL; + } +}.f }; +var invalid_parameter: Iface(ParameterVtbl) = .{ .vtbl = &invalid_parameter_vtbl }; + +/// ID3D12ShaderReflection and ID3D12LibraryReflection: one object, with +/// everything decoded up front into its arena. +const ShaderReflection = struct { + shader: Iface(ShaderReflectionVtbl) = .{ .vtbl = &shader_vtbl }, + library: Iface(LibraryReflectionVtbl) = .{ .vtbl = &library_vtbl }, + rc: RefCount = .{}, + arena: std.heap.ArenaAllocator, + r: reflect.Reflection, + desc: ShaderDesc, + binds: []BindDesc, + cbuffers: []CBufferObj, + inputs: []SignatureParamDesc, + outputs: []SignatureParamDesc, + patch: []SignatureParamDesc, + functions: []FunctionObj, + + const shader_vtbl: ShaderReflectionVtbl = .{ + .unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release }, + .GetDesc = getDesc, + .GetConstantBufferByIndex = getConstantBufferByIndex, + .GetConstantBufferByName = getConstantBufferByName, + .GetResourceBindingDesc = getResourceBindingDesc, + .GetInputParameterDesc = getInputParameterDesc, + .GetOutputParameterDesc = getOutputParameterDesc, + .GetPatchConstantParameterDesc = getPatchConstantParameterDesc, + .GetVariableByName = getVariableByName, + .GetResourceBindingDescByName = getResourceBindingDescByName, + .GetMovInstructionCount = zero, + .GetMovcInstructionCount = zero, + .GetConversionInstructionCount = zero, + .GetBitwiseInstructionCount = zero, + .GetGSInputPrimitive = getGSInputPrimitive, + .IsSampleFrequencyShader = isSampleFrequencyShader, + .GetNumInterfaceSlots = zero, + .GetMinFeatureLevel = getMinFeatureLevel, + .GetThreadGroupSize = getThreadGroupSize, + .GetRequiresFlags = getRequiresFlags, + }; + const library_vtbl: LibraryReflectionVtbl = .{ + .unknown = .{ .QueryInterface = libraryQueryInterface, .AddRef = libraryAddRef, .Release = libraryRelease }, + .GetDesc = getLibraryDesc, + .GetFunctionByIndex = getFunctionByIndex, + }; + + fn of(this: This) *ShaderReflection { + return parent(ShaderReflection, "shader", this); + } + fn libraryOf(this: This) *ShaderReflection { + return parent(ShaderReflection, "library", this); + } + + fn create(blob: []const u8) !*ShaderReflection { + const s = try gpa.create(ShaderReflection); + errdefer gpa.destroy(s); + s.* = .{ .arena = .init(gpa), .r = undefined, .desc = .{}, .binds = &.{}, .cbuffers = &.{}, .inputs = &.{}, .outputs = &.{}, .patch = &.{}, .functions = &.{} }; + errdefer s.arena.deinit(); + try s.load(blob); + return s; + } + + fn load(s: *ShaderReflection, blob: []const u8) !void { + const a = s.arena.allocator(); + const bytes = try a.dupe(u8, blob); + const json = containerPart(bytes, reflect.part) orelse return error.InvalidArgument; + const r = try reflect.decode(a, json); + s.r = r; + + const types = try a.alloc(TypeObj, r.types.len); + for (types, r.types) |*t, rt| { + const members = try a.alloc(*TypeObj, rt.members.len); + const names = try a.alloc([*:0]const u8, rt.members.len); + for (members, names, rt.members) |*m, *n, rm| { + m.* = if (rm.ty < types.len) &types[rm.ty] else &invalid_type; + n.* = try a.dupeSentinel(u8, rm.name, 0); + } + t.* = .{ + .desc = .{ .Class = rt.class, .Type = rt.kind, .Rows = rt.rows, .Columns = rt.cols, .Elements = rt.elements, .Members = @intCast(rt.members.len), .Offset = rt.offset, .Name = try a.dupeSentinel(u8, rt.name, 0) }, + .members = members, + .member_names = names, + }; + } + s.cbuffers = try a.alloc(CBufferObj, r.cbuffers.len); + for (s.cbuffers, r.cbuffers) |*c, rc| { + const vars = try a.alloc(VariableObj, rc.vars.len); + c.* = .{ .desc = .{ .Name = try a.dupeSentinel(u8, rc.name, 0), .Type = rc.kind, .Variables = @intCast(rc.vars.len), .Size = rc.size, .uFlags = rc.flags }, .vars = vars }; + for (vars, rc.vars) |*v, rv| v.* = .{ + .desc = .{ .Name = try a.dupeSentinel(u8, rv.name, 0), .StartOffset = rv.offset, .Size = rv.size, .uFlags = rv.flags }, + .ty = if (rv.ty < types.len) &types[rv.ty] else &invalid_type, + .buffer = c, + }; + } + s.binds = try a.alloc(BindDesc, r.binds.len); + for (s.binds, r.binds) |*b, rb| b.* = .{ + .Name = try a.dupeSentinel(u8, rb.name, 0), + .Type = rb.type, + .BindPoint = rb.bind_point, + .BindCount = rb.bind_count, + .uFlags = rb.flags, + .ReturnType = rb.return_type, + .Dimension = rb.dimension, + .NumSamples = rb.num_samples, + .Space = rb.space, + .uID = rb.id, + }; + s.inputs = try signatureParams(a, containerPart(bytes, reflect.input_part)); + s.outputs = try signatureParams(a, containerPart(bytes, reflect.output_part)); + s.patch = try signatureParams(a, containerPart(bytes, reflect.patch_part)); + s.desc = .{ + .Version = r.version, + .Creator = creator, + .ConstantBuffers = @intCast(r.cbuffers.len), + .BoundResources = @intCast(r.binds.len), + .InputParameters = @intCast(s.inputs.len), + .OutputParameters = @intCast(s.outputs.len), + .InstructionCount = r.instructions, + .GSOutputTopology = r.gs_output_topology, + .GSMaxOutputVertexCount = r.gs_max_vertices, + .InputPrimitive = r.input_primitive, + .PatchConstantParameters = @intCast(s.patch.len), + .cGSInstanceCount = r.gs_instances, + .cControlPoints = r.control_points, + .HSOutputPrimitive = r.hs_output_primitive, + .HSPartitioning = r.hs_partitioning, + .TessellatorDomain = r.tess_domain, + }; + s.functions = try a.alloc(FunctionObj, r.functions.len); + for (s.functions, r.functions) |*f, rf| { + const binds = try a.alloc(*const BindDesc, rf.binds.len); + for (binds, rf.binds) |*b, i| b.* = if (i < s.binds.len) &s.binds[i] else &.{}; + const cbs = try a.alloc(*CBufferObj, rf.cbuffers.len); + for (cbs, rf.cbuffers) |*c, i| c.* = if (i < s.cbuffers.len) &s.cbuffers[i] else &invalid_cbuffer; + f.* = .{ + .desc = .{ + .Version = rf.version, + .Creator = creator, + .ConstantBuffers = @intCast(cbs.len), + .BoundResources = @intCast(binds.len), + .MinFeatureLevel = feature_level_12_0, + .RequiredFeatureFlags = rf.requires, + .Name = try a.dupeSentinel(u8, rf.name, 0), + }, + .binds = binds, + .cbuffers = cbs, + }; + } + } + + /// The parameters of a DxilProgramSignature part (ISG1, OSG1, PSG1), + /// which are D3D12_SIGNATURE_PARAMETER_DESC's fields. + fn signatureParams(a: std.mem.Allocator, part: ?[]const u8) ![]SignatureParamDesc { + const p = part orelse return &.{}; + if (p.len < 8) return &.{}; + const count = std.mem.readInt(u32, p[0..4], .little); + const first = std.mem.readInt(u32, p[4..8], .little); + if (first > p.len or count > (p.len - first) / 32) return error.InvalidArgument; + const out = try a.alloc(SignatureParamDesc, count); + for (out, 0..) |*d, i| { + const rec = p[first + 32 * i ..][0..32]; + const word = struct { + fn f(b: []const u8, k: usize) u32 { + return std.mem.readInt(u32, b[4 * k ..][0..4], .little); + } + }.f; + const name_off = word(rec, 1); + const name: LPCSTR = if (name_off < p.len) blk: { + const end = std.mem.indexOfScalarPos(u8, p, name_off, 0) orelse return error.InvalidArgument; + const n = try a.dupeSentinel(u8, p[name_off..end], 0); + // System values read back uppercase, as D3D reports them. + if (word(rec, 3) != 0) _ = std.ascii.upperString(n, n); + break :blk n.ptr; + } else null; + // Minimum-precision values are reported as their 32-bit types + // (UINT16/SINT16/FLOAT16 -> UINT32/SINT32/FLOAT32). + const comp = word(rec, 4); + d.* = .{ + .SemanticName = name, + .SemanticIndex = word(rec, 2), + .Register = word(rec, 5), + .SystemValueType = word(rec, 3), + .ComponentType = if (word(rec, 7) != 0 and comp >= 4 and comp <= 6) comp - 3 else comp, + .Mask = rec[24], + .ReadWriteMask = rec[25], + .Stream = word(rec, 0), + .MinPrecision = word(rec, 7), + }; + } + return out; + } + + fn query(s: *ShaderReflection, iid: *const GUID, out: Out) HRESULT { + const p: *anyopaque = if (iid.eql(IID_IUnknown) or iid.eql(IID_ID3D12ShaderReflection)) + &s.shader + else if (iid.eql(IID_ID3D12LibraryReflection)) + &s.library + else { + out.* = null; + return E_NOINTERFACE; + }; + _ = s.rc.addRef(); + out.* = p; + return S_OK; + } + + fn queryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { + return of(this).query(iid, out orelse return E_POINTER); + } + fn addRef(this: This) callconv(cc) ULONG { + return of(this).rc.addRef(); + } + fn release(this: This) callconv(cc) ULONG { + const s = of(this); + const n = s.rc.release(); + if (n == 0) { + s.arena.deinit(); + gpa.destroy(s); + } + return n; + } + fn libraryQueryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { + return libraryOf(this).query(iid, out orelse return E_POINTER); + } + fn libraryAddRef(this: This) callconv(cc) ULONG { + return libraryOf(this).rc.addRef(); + } + fn libraryRelease(this: This) callconv(cc) ULONG { + return release(&libraryOf(this).shader); + } + + fn getDesc(this: This, d: ?*ShaderDesc) callconv(cc) HRESULT { + (d orelse return E_INVALIDARG).* = of(this).desc; + return S_OK; + } + fn getConstantBufferByIndex(this: This, i: u32) callconv(cc) *anyopaque { + const s = of(this); + return if (i < s.cbuffers.len) &s.cbuffers[i].iface else &invalid_cbuffer.iface; + } + fn getConstantBufferByName(this: This, name: LPCSTR) callconv(cc) *anyopaque { + for (of(this).cbuffers) |*c| if (eqlZ(name, c.desc.Name.?)) return &c.iface; + return &invalid_cbuffer.iface; + } + fn getResourceBindingDesc(this: This, i: u32, d: ?*BindDesc) callconv(cc) HRESULT { + const s = of(this); + const out = d orelse return E_INVALIDARG; + if (i >= s.binds.len) return E_INVALIDARG; + out.* = s.binds[i]; + return S_OK; + } + fn paramDesc(params: []const SignatureParamDesc, i: u32, d: ?*SignatureParamDesc) HRESULT { + const out = d orelse return E_INVALIDARG; + if (i >= params.len) return E_INVALIDARG; + out.* = params[i]; + return S_OK; + } + fn getInputParameterDesc(this: This, i: u32, d: ?*SignatureParamDesc) callconv(cc) HRESULT { + return paramDesc(of(this).inputs, i, d); + } + fn getOutputParameterDesc(this: This, i: u32, d: ?*SignatureParamDesc) callconv(cc) HRESULT { + return paramDesc(of(this).outputs, i, d); + } + fn getPatchConstantParameterDesc(this: This, i: u32, d: ?*SignatureParamDesc) callconv(cc) HRESULT { + return paramDesc(of(this).patch, i, d); + } + fn getVariableByName(this: This, name: LPCSTR) callconv(cc) *anyopaque { + for (of(this).cbuffers) |*c| for (c.vars) |*v| if (eqlZ(name, v.desc.Name.?)) return &v.iface; + return &invalid_variable.iface; + } + fn getResourceBindingDescByName(this: This, name: LPCSTR, d: ?*BindDesc) callconv(cc) HRESULT { + const out = d orelse return E_INVALIDARG; + for (of(this).binds) |b| if (eqlZ(name, b.Name.?)) { + out.* = b; + return S_OK; + }; + return E_INVALIDARG; + } + fn zero(_: This) callconv(cc) u32 { + return 0; + } + fn getGSInputPrimitive(this: This) callconv(cc) u32 { + return of(this).r.input_primitive; + } + /// DXC's reflection answers false. + fn isSampleFrequencyShader(_: This) callconv(cc) BOOL { + return if (windows) 0 else false; + } + fn getMinFeatureLevel(_: This, level: ?*u32) callconv(cc) HRESULT { + (level orelse return E_INVALIDARG).* = feature_level_12_0; + return S_OK; + } + fn getThreadGroupSize(this: This, x: ?*u32, y: ?*u32, z: ?*u32) callconv(cc) u32 { + const t = of(this).r.thread_group; + if (x) |p| p.* = t[0]; + if (y) |p| p.* = t[1]; + if (z) |p| p.* = t[2]; + return t[0] * t[1] * t[2]; + } + fn getRequiresFlags(this: This) callconv(cc) u64 { + return of(this).r.requires; + } + fn getLibraryDesc(this: This, d: ?*LibraryDesc) callconv(cc) HRESULT { + (d orelse return E_INVALIDARG).* = .{ .Creator = creator, .FunctionCount = @intCast(libraryOf(this).functions.len) }; + return S_OK; + } + fn getFunctionByIndex(this: This, i: i32) callconv(cc) *anyopaque { + const s = libraryOf(this); + return if (i >= 0 and i < s.functions.len) &s.functions[@intCast(i)].iface else &invalid_function.iface; + } +}; + +// ---- Containers ------------------------------------------------------------- + +/// The parts of a DXIL container, as (fourcc, bytes) slices into it. +fn containerParts(a: std.mem.Allocator, obj: []const u8) !std.ArrayList(zdxc.dxil.container.Part) { + const view = zdxc.dxil.container.parse(a, obj) catch return error.InvalidArgument; + return view.parts; +} + +const ContainerReflectionVtbl = extern struct { + unknown: UnknownVtbl, + Load: *const fn (This, ?*anyopaque) callconv(cc) HRESULT, + GetPartCount: *const fn (This, ?*u32) callconv(cc) HRESULT, + GetPartKind: *const fn (This, u32, ?*u32) callconv(cc) HRESULT, + GetPartContent: *const fn (This, u32, ?Out) callconv(cc) HRESULT, + FindFirstPartKind: *const fn (This, u32, ?*u32) callconv(cc) HRESULT, + GetPartReflection: *const fn (This, u32, *const GUID, ?Out) callconv(cc) HRESULT, +}; + +/// IDxcContainerReflection: the parts of a loaded container. +const ContainerReflection = struct { + iface: Iface(ContainerReflectionVtbl) = .{ .vtbl = &vtbl }, + rc: RefCount = .{}, + bytes: []u8 = &.{}, + parts: std.ArrayList(zdxc.dxil.container.Part) = .empty, + + const vtbl: ContainerReflectionVtbl = .{ + .unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release }, + .Load = load, + .GetPartCount = getPartCount, + .GetPartKind = getPartKind, + .GetPartContent = getPartContent, + .FindFirstPartKind = findFirstPartKind, + .GetPartReflection = getPartReflection, + }; + + fn of(this: This) *ContainerReflection { + return parent(ContainerReflection, "iface", this); + } + fn clear(c: *ContainerReflection) void { + c.parts.deinit(gpa); + c.parts = .empty; + gpa.free(c.bytes); + c.bytes = &.{}; + } + fn queryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { + if (!iid.eql(IID_IUnknown) and !iid.eql(IID_IDxcContainerReflection)) { + _ = put(out, null); + return E_NOINTERFACE; + } + _ = of(this).rc.addRef(); + return put(out, this); + } + fn addRef(this: This) callconv(cc) ULONG { + return of(this).rc.addRef(); + } + fn release(this: This) callconv(cc) ULONG { + const c = of(this); + const n = c.rc.release(); + if (n == 0) { + c.clear(); + gpa.destroy(c); + } + return n; + } + fn load(this: This, blob: ?*anyopaque) callconv(cc) HRESULT { + const c = of(this); + c.clear(); + const b = blob orelse return E_INVALIDARG; + c.bytes = gpa.dupe(u8, blobBytes(b)) catch return E_OUTOFMEMORY; + c.parts = containerParts(gpa, c.bytes) catch |e| { + c.clear(); + return if (e == error.OutOfMemory) E_OUTOFMEMORY else E_INVALIDARG; + }; + return S_OK; + } + fn getPartCount(this: This, count: ?*u32) callconv(cc) HRESULT { + (count orelse return E_INVALIDARG).* = @intCast(of(this).parts.items.len); + return S_OK; + } + fn getPartKind(this: This, i: u32, kind: ?*u32) callconv(cc) HRESULT { + const c = of(this); + const k = kind orelse return E_INVALIDARG; + if (i >= c.parts.items.len) return E_INVALIDARG; + k.* = c.parts.items[i].fourcc; + return S_OK; + } + fn getPartContent(this: This, i: u32, out: ?Out) callconv(cc) HRESULT { + const c = of(this); + const o = out orelse return E_INVALIDARG; + o.* = null; + if (i >= c.parts.items.len) return E_INVALIDARG; + const b = Blob.copy(.binary, c.parts.items[i].data, CP_ACP) catch return E_OUTOFMEMORY; + o.* = b.ptr(); + return S_OK; + } + fn findFirstPartKind(this: This, kind: u32, index: ?*u32) callconv(cc) HRESULT { + const c = of(this); + const out = index orelse return E_INVALIDARG; + for (c.parts.items, 0..) |p, i| if (p.fourcc == kind) { + out.* = @intCast(i); + return S_OK; + }; + return code(0x80AA0013); // DXC_E_MISSING_PART + } + /// Reflection of one of our reflection blobs' parts is the blob's. + fn getPartReflection(this: This, _: u32, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { + const c = of(this); + const o = out orelse return E_INVALIDARG; + o.* = null; + const r = ShaderReflection.create(c.bytes) catch |e| return if (e == error.OutOfMemory) E_OUTOFMEMORY else E_NOTIMPL; + defer _ = ShaderReflection.release(&r.shader); + return r.query(iid, o); + } +}; + +const ContainerBuilderVtbl = extern struct { + unknown: UnknownVtbl, + Load: *const fn (This, ?*anyopaque) callconv(cc) HRESULT, + AddPart: *const fn (This, u32, ?*anyopaque) callconv(cc) HRESULT, + RemovePart: *const fn (This, u32) callconv(cc) HRESULT, + SerializeContainer: *const fn (This, ?Out) callconv(cc) HRESULT, +}; + +/// IDxcContainerBuilder: adds and removes parts, then writes the container +/// again (signed, as the validator signs). +const ContainerBuilder = struct { + iface: Iface(ContainerBuilderVtbl) = .{ .vtbl = &vtbl }, + rc: RefCount = .{}, + arena: std.heap.ArenaAllocator = .init(gpa), + parts: std.ArrayList(zdxc.dxil.container.Part) = .empty, + + const vtbl: ContainerBuilderVtbl = .{ + .unknown = .{ .QueryInterface = queryInterface, .AddRef = addRef, .Release = release }, + .Load = load, + .AddPart = addPart, + .RemovePart = removePart, + .SerializeContainer = serializeContainer, + }; + + fn of(this: This) *ContainerBuilder { + return parent(ContainerBuilder, "iface", this); + } + fn queryInterface(this: This, iid: *const GUID, out: ?Out) callconv(cc) HRESULT { + if (!iid.eql(IID_IUnknown) and !iid.eql(IID_IDxcContainerBuilder)) { + _ = put(out, null); + return E_NOINTERFACE; + } + _ = of(this).rc.addRef(); + return put(out, this); + } + fn addRef(this: This) callconv(cc) ULONG { + return of(this).rc.addRef(); + } + fn release(this: This) callconv(cc) ULONG { + const c = of(this); + const n = c.rc.release(); + if (n == 0) { + c.arena.deinit(); + gpa.destroy(c); + } + return n; + } + fn load(this: This, blob: ?*anyopaque) callconv(cc) HRESULT { + const c = of(this); + const a = c.arena.allocator(); + const b = blob orelse return E_INVALIDARG; + const bytes = a.dupe(u8, blobBytes(b)) catch return E_OUTOFMEMORY; + c.parts = containerParts(a, bytes) catch |e| return if (e == error.OutOfMemory) E_OUTOFMEMORY else E_INVALIDARG; + return S_OK; + } + fn addPart(this: This, fourcc: u32, blob: ?*anyopaque) callconv(cc) HRESULT { + const c = of(this); + const a = c.arena.allocator(); + const b = blob orelse return E_INVALIDARG; + for (c.parts.items) |p| if (p.fourcc == fourcc) return code(0x80AA0014); // DXC_E_DUPLICATE_PART + const data = a.dupe(u8, blobBytes(b)) catch return E_OUTOFMEMORY; + c.parts.append(a, .{ .fourcc = fourcc, .data = data }) catch return E_OUTOFMEMORY; + return S_OK; + } + /// Removing a part the container does not have succeeds: zdxc's + /// objects carry no STAT part, which clients strip as a matter of + /// course. + fn removePart(this: This, fourcc: u32) callconv(cc) HRESULT { + const c = of(this); + var i: usize = 0; + while (i < c.parts.items.len) { + if (c.parts.items[i].fourcc == fourcc) _ = c.parts.orderedRemove(i) else i += 1; + } + return S_OK; + } + fn serializeContainer(this: This, out: ?Out) callconv(cc) HRESULT { + const c = of(this); + const o = out orelse return E_POINTER; + o.* = null; + const bytes = zdxc.dxil.container.assemble(gpa, c.parts.items) catch return E_OUTOFMEMORY; + defer gpa.free(bytes); + const r = gpa.create(Result) catch return E_OUTOFMEMORY; + r.* = .{ .status = S_OK, .primary = .object }; + addOutput(r, .object, Blob.copy(.binary, bytes, CP_ACP) catch { + r.destroy(); + return E_OUTOFMEMORY; + }, null) catch { + r.destroy(); + return E_OUTOFMEMORY; + }; + o.* = &r.iface; + return S_OK; + } +}; + // --------------------------------------------------------------------------- // Exports @@ -1074,6 +2031,18 @@ fn createInstance(clsid: ?*const GUID, iid: ?*const GUID, out: ?Out) HRESULT { defer _ = Utils.release(&u.iface); return Utils.queryInterface(&u.iface, want, o); } + if (class.eql(CLSID_DxcContainerReflection)) { + const c = gpa.create(ContainerReflection) catch return E_OUTOFMEMORY; + c.* = .{}; + defer _ = ContainerReflection.release(&c.iface); + return ContainerReflection.queryInterface(&c.iface, want, o); + } + if (class.eql(CLSID_DxcContainerBuilder)) { + const c = gpa.create(ContainerBuilder) catch return E_OUTOFMEMORY; + c.* = .{}; + defer _ = ContainerBuilder.release(&c.iface); + return ContainerBuilder.queryInterface(&c.iface, want, o); + } return REGDB_E_CLASSNOTREG; } diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 5cd77c0..4771612 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -21,6 +21,7 @@ const mangle = @import("mangle.zig"); const rdat = @import("rdat.zig"); const linalg_info = @import("linalg_info.zig"); const libinfo = @import("libinfo.zig"); +const reflect = @import("reflect.zig"); const rootsig = @import("rootsig.zig"); const promote = @import("promote.zig"); const opt = @import("../ir/opt.zig"); @@ -38,13 +39,25 @@ pub const Error = Allocator.Error || error{Unsupported}; /// passes arrays to callees that only read them in place and reuses /// inlined callees' arrays. pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error![]u8 { + const out = try emitWithReflection(gpa, m, profile, diags, optimize); + gpa.free(out.reflection); + return out.object; +} + +/// The DXIL container and its reflection (reflect.zig), both owned by the +/// caller. +pub const Output = struct { object: []u8, reflection: []u8 }; + +pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output { var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = optimize }; defer e.dm.deinit(); // Native 16-bit types are laid out at their own size. if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64"; - return e.run(gpa); + const object = try e.run(gpa); + errdefer gpa.free(object); + return .{ .object = object, .reflection = e.reflection orelse return error.OutOfMemory }; } /// A lowered IR value. @@ -249,6 +262,9 @@ const Emitter = struct { param_copies: std.AutoHashMapUnmanaged(u32, []const u32) = .empty, uses_barycentrics: bool = false, uses_sampler_heap: bool = false, + /// The shader's reflection (reflect.zig), made with the object; owned + /// by the caller of `emit`. + reflection: ?[]u8 = null, sig_in: []signature.Element = &.{}, sig_out: []signature.Element = &.{}, @@ -473,11 +489,37 @@ const Emitter = struct { try e.finish(e.pc_fn.?); } + if (e.optimize) e.inputUsage(); const bitcode = try e.writeModule(entry); defer gpa.free(bitcode); return e.assemble(gpa, entry, bitcode); } + /// The input components read, from the optimized code (lowering marks + /// every read, including ones optimized away), as DXC reports them in + /// the signature and its reflection. + fn inputUsage(e: *Emitter) void { + const readers = [_][]const u8{ "dx.op.loadInput.", "dx.op.attributeAtVertex.", "dx.op.evalSnapped.", "dx.op.evalSampleIndex.", "dx.op.evalCentroid." }; + var usage: [64]u8 = @splat(0); + if (e.sig_in.len > usage.len) return; + for (e.dm.functions.items) |f| for (f.insts.items) |inst| { + const c = switch (inst.op) { + .call => |c| c, + else => continue, + }; + const name = e.dm.functions.items[c.callee].name; + for (readers) |r| { + if (!std.mem.startsWith(u8, name, r)) continue; + const id = e.constInt(c.args[1]) orelse return; + const col = e.constInt(c.args[3]) orelse return; + for (e.sig_in, 0..) |el, k| if (el.id == id) { + usage[k] |= @as(u8, 1) << @intCast(col); + }; + } + }; + for (e.sig_in, usage[0..e.sig_in.len]) |*el, u| el.usage = u; + } + /// The resource entry for a value of resource type `ty` (global, /// id and count left for the caller). fn resourceFor(e: *Emitter, ty: TypeId) Error!Resource { @@ -5509,12 +5551,404 @@ const Emitter = struct { return dm.writeBitcode(dm.arena.child_allocator); } + // ---- Reflection (reflect.zig) ----------------------------------------- + + /// The bytes of a constant buffer (or tbuffer) the shader reads. + const BufferUse = struct { + /// Read at a dynamic register: all of it counts as read. + all: bool = false, + bytes: std.ArrayList(bool) = .empty, + + fn reads(u: BufferUse, offset: u32, size: u32) bool { + if (u.all) return true; + const end = @min(offset + @max(size, 1), u.bytes.items.len); + if (offset >= end) return false; + return std.mem.indexOfScalar(bool, u.bytes.items[offset..end], true) != null; + } + }; + + fn constInt(e: *Emitter, v: Value) ?i64 { + return switch (v) { + .constant => |c| switch (e.dm.constants.items[c].kind) { + .int => |i| i, + else => null, + }, + else => null, + }; + } + + /// The resource (index into `resources`) a handle in `f` stands for, + /// when the handle's creation says. + fn handleResource(e: *Emitter, f: *const module.Function, handle: Value) ?u32 { + var cur = handle; + for (0..8) |_| { + const i = switch (cur) { + .inst => |i| i, + else => return null, + }; + const c = switch (f.insts.items[i].op) { + .call => |c| c, + else => return null, + }; + const name = e.dm.functions.items[c.callee].name; + if (std.mem.eql(u8, name, "dx.op.annotateHandle")) { + cur = c.args[1]; + continue; + } + if (std.mem.eql(u8, name, "dx.op.createHandle")) { + const class = e.constInt(c.args[1]) orelse return null; + const id = e.constInt(c.args[2]) orelse return null; + for (e.resources.items, 0..) |r, ri| { + if (!r.view and @backingInt(r.class) == class and r.id == id) return @intCast(ri); + } + return null; + } + if (std.mem.eql(u8, name, "dx.op.createHandleFromBinding")) { + const k = switch (c.args[1]) { + .constant => |k| k, + else => return null, + }; + const fields = switch (e.dm.constants.items[k].kind) { + .aggregate => |p| p, + else => return null, + }; + const lower = e.constInt(.{ .constant = fields[0] }) orelse return null; + const space = e.constInt(.{ .constant = fields[2] }) orelse return null; + const class = e.constInt(.{ .constant = fields[3] }) orelse return null; + for (e.resources.items, 0..) |r, ri| { + const b = e.binding(r); + if (!r.view and @backingInt(r.class) == class and b.space == space and b.index == lower) return @intCast(ri); + } + return null; + } + if (std.mem.startsWith(u8, name, "dx.op.createHandleForLib.")) { + var p = c.args[1]; + while (p == .inst) p = switch (f.insts.items[p.inst].op) { + .load => |x| x.ptr, + .gep => |x| x.ptr, + else => return null, + }; + if (p != .global) return null; + for (e.resources.items, 0..) |r, ri| { + if (!r.view and r.lib_global == p.global) return @intCast(ri); + } + return null; + } + return null; + } + return null; + } + + /// What each constant buffer and tbuffer (by resource index) is read + /// for, from the final module's loads, at the precision DXC's + /// reflection marks variables used: the components extracted. + fn bufferUses(e: *Emitter) Error![]BufferUse { + const uses = try e.arena.alloc(BufferUse, e.resources.items.len); + @memset(uses, .{}); + for (e.dm.functions.items) |*f| { + if (f.insts.items.len == 0) continue; + // The elements each instruction's extractvalue users take. + var elems: std.AutoHashMapUnmanaged(u32, std.ArrayList(u32)) = .empty; + for (f.insts.items) |inst| switch (inst.op) { + .extractvalue => |x| if (x.agg == .inst) { + const gop = try elems.getOrPut(e.arena, x.agg.inst); + if (!gop.found_existing) gop.value_ptr.* = .empty; + try gop.value_ptr.append(e.arena, x.index); + }, + else => {}, + }; + for (f.insts.items, 0..) |inst, i| { + const c = switch (inst.op) { + .call => |c| c, + else => continue, + }; + const name = e.dm.functions.items[c.callee].name; + const legacy = std.mem.startsWith(u8, name, "dx.op.cbufferLoadLegacy."); + if (!legacy and !std.mem.startsWith(u8, name, "dx.op.bufferLoad.")) continue; + const ri = e.handleResource(f, c.args[1]) orelse continue; + const r = e.resources.items[ri]; + if (r.class != .cbuffer and r.kind != 15) continue; + const u = &uses[ri]; + if (u.all) continue; + const row = e.constInt(c.args[2]) orelse { + u.all = true; + continue; + }; + // A register's elements: 4 32-bit, 2 64-bit or 8 16-bit. + const size: usize = if (!legacy) 4 else if (std.mem.endsWith(u8, name, "16")) 2 else if (std.mem.endsWith(u8, name, "64")) 8 else 4; + const base: usize = @intCast(row * 16); + if (u.bytes.items.len < base + 16) try u.bytes.appendNTimes(e.arena, false, base + 16 - u.bytes.items.len); + if (elems.get(@intCast(i))) |taken| { + for (taken.items) |k| @memset(u.bytes.items[base + k * size ..][0..size], true); + } else @memset(u.bytes.items[base..][0..16], true); + } + } + return uses; + } + + /// D3D_SHADER_VARIABLE_TYPE. + fn svType(e: *Emitter, s: Scalar) u32 { + return switch (s) { + .bool => 1, + .int, .literal_int => 2, + .uint, .int8_4packed, .uint8_4packed => 19, + .float, .literal_float => 3, + .half => if (e.m.native_16bit) 58 else 3, + .double => 39, + .min16float => 52, + .min10float => 51, + .min16int => 54, + .min12int => 53, + .min16uint => 55, + .int16 => 56, + .uint16 => 57, + .float16 => 58, + .int64 => 59, + .uint64 => 60, + }; + } + + /// Adds the type description of `ty` (and of its members) to `types`; + /// returns its index. + fn reflectType(e: *Emitter, tys: *std.ArrayList(reflect.Type), ty: TypeId, row_major: bool, offset: u32) Error!u32 { + var t = ty; + var elements: u32 = 0; + while (e.t.get(t) == .array) { + const a = e.t.get(t).array; + elements = if (elements == 0) a.len else elements * a.len; + t = a.elem; + } + var d: reflect.Type = .{ .class = reflect.svc.object, .kind = 0, .elements = elements, .offset = offset }; + switch (e.t.get(t)) { + .scalar => |s| { + d.class = reflect.svc.scalar; + d.kind = e.svType(s); + d.rows = 1; + d.cols = 1; + // D3D's name for uint. + d.name = if (s == .uint) "dword" else s.name(); + }, + .@"enum" => { + d.class = reflect.svc.scalar; + d.kind = 2; + d.rows = 1; + d.cols = 1; + d.name = "int"; + }, + .vector => |v| { + d.class = reflect.svc.vector; + d.kind = e.svType(v.elem); + d.rows = 1; + d.cols = v.len; + d.name = try std.fmt.allocPrint(e.arena, "{s}{d}", .{ v.elem.name(), v.len }); + }, + .matrix => |m| { + d.class = if (row_major) reflect.svc.matrix_rows else reflect.svc.matrix_columns; + d.kind = e.svType(m.elem); + d.rows = m.rows; + d.cols = m.cols; + d.name = try std.fmt.allocPrint(e.arena, "{s}{d}x{d}", .{ m.elem.name(), m.rows, m.cols }); + }, + .@"struct" => |s| { + d.class = reflect.svc.@"struct"; + d.rows = 1; + d.cols = layout.flatCount(e.t, t) catch 0; + d.name = s.name; + const offs = layout.fieldOffsets(e.arena, e.t, s, .dx_legacy) catch return e.unsupported("reflection of '{s}'", .{s.name}); + var members: std.ArrayList(reflect.Member) = .empty; + for (s.fields.items, offs) |fld, off| { + if (fld.bits or layout.isOpaque(e.t, fld.type)) continue; + try members.append(e.arena, .{ .name = fld.name, .ty = try e.reflectType(tys, fld.type, fld.row_major, off) }); + } + d.members = members.items; + }, + else => {}, + } + try tys.append(e.arena, d); + return @intCast(tys.items.len - 1); + } + + /// The scalar and component count of a texture or typed buffer element. + fn elemShape(e: *Emitter, elem: TypeId) ?struct { scalar: Scalar, comps: u32 } { + return switch (e.t.get(elem)) { + .scalar => |s| .{ .scalar = s, .comps = 1 }, + .vector => |v| .{ .scalar = v.elem, .comps = v.len }, + else => null, + }; + } + + const ReflectedResources = struct { + binds: []const reflect.Bind, + cbuffers: []const reflect.CBuffer, + types: []const reflect.Type, + /// Bind index -> cbuffer index (constant buffers and tbuffers). + cbuffer_of: []const ?u32, + }; + + /// The bound resources (CBVs, samplers, SRVs, UAVs, as PSV and RDAT + /// list them) and the constant buffers' variables. + fn reflectResources(e: *Emitter) Error!ReflectedResources { + const uses = try e.bufferUses(); + var binds: std.ArrayList(reflect.Bind) = .empty; + var cbuffers: std.ArrayList(reflect.CBuffer) = .empty; + var tys: std.ArrayList(reflect.Type) = .empty; + var cbuffer_of: std.ArrayList(?u32) = .empty; + for ([_]Resource.Class{ .cbuffer, .sampler, .srv, .uav }) |cls| for (e.resources.items, 0..) |r, ri| if (r.class == cls and !r.view) { + const g = e.m.globals.items[r.global]; + const b = e.binding(r); + var bd: reflect.Bind = .{ + .name = g.name, + .type = 0, + .bind_point = b.index, + .bind_count = if (r.count == std.math.maxInt(u32)) 0 else r.count, + .space = b.space, + .id = r.id, + }; + const shape = e.elemShape(r.elem); + const dims = [_]u32{ 0, 2, 4, 6, 8, 9, 3, 5, 7, 10, 1, 1, 1 }; + const dim: u32 = if (r.kind < dims.len) dims[r.kind] else if (r.kind == 17) 4 else if (r.kind == 18) 5 else 0; + const typed_ret: u32 = if (shape) |sh| switch (sh.scalar) { + .int, .int16, .int64, .min16int, .min12int => reflect.ret.sint, + .uint, .uint16, .uint64, .min16uint, .bool => reflect.ret.uint, + .double => reflect.ret.double, + else => reflect.ret.float, + } else reflect.ret.float; + const comps_flags: u32 = if (shape) |sh| ((sh.comps - 1) & 3) << 2 else 0; + const rkind: ?types.ResourceKind = if (r.rty != 0 and e.t.get(r.rty) == .resource) e.t.get(r.rty).resource.kind else null; + var cbuffer_index: ?u32 = null; + switch (r.class) { + .cbuffer => { + bd.type = reflect.sit.cbuffer; + bd.flags = reflect.sif_userpacked; + cbuffer_index = try e.reflectCBuffer(&cbuffers, &tys, r, uses[ri], reflect.ct_cbuffer); + }, + .sampler => { + bd.type = reflect.sit.sampler; + if (r.comparison) bd.flags |= reflect.sif_comparison_sampler; + }, + .srv => switch (r.kind) { + 12 => { + bd.type = reflect.sit.structured; + bd.return_type = reflect.ret.mixed; + bd.dimension = 1; + bd.num_samples = layout.sizeOf(e.t, r.elem, false, .dx_packed) catch 0; + cbuffer_index = try e.reflectElementBuffer(&cbuffers, &tys, try e.elementBufferName(g.name, r.count), r.elem, bd.num_samples); + }, + 11 => { + bd.type = reflect.sit.byteaddress; + bd.return_type = reflect.ret.mixed; + bd.dimension = 1; + }, + 15 => { + bd.type = reflect.sit.tbuffer; + bd.flags = reflect.sif_userpacked; + cbuffer_index = try e.reflectCBuffer(&cbuffers, &tys, r, uses[ri], reflect.ct_tbuffer); + }, + 16 => { + bd.type = reflect.sit.rtaccelerationstructure; + bd.return_type = reflect.ret.sint; + bd.num_samples = std.math.maxInt(u32); + }, + else => { + bd.type = reflect.sit.texture; + bd.dimension = dim; + bd.return_type = typed_ret; + bd.flags |= comps_flags; + if (r.kind != 3 and r.kind != 8) bd.num_samples = std.math.maxInt(u32); + }, + }, + .uav => switch (r.kind) { + 12 => { + // Append and consume buffers too, as DXC reports them. + bd.type = if (r.has_counter or rkind == .append_structured_buffer or rkind == .consume_structured_buffer) + reflect.sit.uav_rwstructured_with_counter + else + reflect.sit.uav_rwstructured; + bd.return_type = reflect.ret.mixed; + bd.dimension = 1; + bd.num_samples = layout.sizeOf(e.t, r.elem, false, .dx_packed) catch 0; + cbuffer_index = try e.reflectElementBuffer(&cbuffers, &tys, try e.elementBufferName(g.name, r.count), r.elem, bd.num_samples); + }, + 11 => { + bd.type = reflect.sit.uav_rwbyteaddress; + bd.return_type = reflect.ret.mixed; + bd.dimension = 1; + }, + 17, 18 => { + bd.type = reflect.sit.uav_feedbacktexture; + bd.dimension = dim; + }, + else => { + bd.type = reflect.sit.uav_rwtyped; + bd.dimension = dim; + bd.return_type = typed_ret; + bd.flags |= comps_flags; + if (r.kind != 3 and r.kind != 8) bd.num_samples = std.math.maxInt(u32); + }, + }, + } + try binds.append(e.arena, bd); + try cbuffer_of.append(e.arena, cbuffer_index); + }; + return .{ .binds = binds.items, .cbuffers = cbuffers.items, .types = tys.items, .cbuffer_of = cbuffer_of.items }; + } + + /// An array's resource-bind-info buffer is named for its first element. + fn elementBufferName(e: *Emitter, name: []const u8, count: u32) Error![]const u8 { + return if (count == 1) name else std.fmt.allocPrint(e.arena, "{s}[0]", .{name}); + } + + /// Adds a structured buffer's resource-bind-info buffer, as DXC lists + /// them: one variable, `$Element`, of the element type. + fn reflectElementBuffer(e: *Emitter, cbuffers: *std.ArrayList(reflect.CBuffer), tys: *std.ArrayList(reflect.Type), name: []const u8, elem: TypeId, elem_size: u32) Error!u32 { + const vars = try e.arena.alloc(reflect.Variable, 1); + vars[0] = .{ .name = "$Element", .offset = 0, .size = elem_size, .flags = reflect.svf_used, .ty = try e.reflectType(tys, elem, false, 0) }; + try cbuffers.append(e.arena, .{ .name = name, .kind = reflect.ct_resource_bind_info, .size = elem_size, .vars = vars }); + return @intCast(cbuffers.items.len - 1); + } + + /// Adds the constant buffer (or tbuffer) `r`'s description; returns + /// its index. + fn reflectCBuffer(e: *Emitter, cbuffers: *std.ArrayList(reflect.CBuffer), tys: *std.ArrayList(reflect.Type), r: Resource, use: BufferUse, kind: u32) Error!u32 { + const g = e.m.globals.items[r.global]; + var vars: std.ArrayList(reflect.Variable) = .empty; + var size: u32 = 0; + if (g.space == .cbuffer and e.t.get(g.ty) == .@"struct") { + // A cbuffer block: its members are the variables. + const s = e.t.get(g.ty).@"struct"; + const offs = layout.fieldOffsets(e.arena, e.t, s, .dx_legacy) catch return e.unsupported("reflection of constant buffer '{s}'", .{g.name}); + for (s.fields.items, offs) |fld, off| { + if (fld.bits) continue; + const fsize = layout.sizeOf(e.t, fld.type, fld.row_major, .dx_legacy) catch 0; + var flags: u32 = if (fld.pack_offset != null) reflect.svf_userpacked else 0; + if (use.reads(off, fsize)) flags |= reflect.svf_used; + try vars.append(e.arena, .{ .name = fld.name, .offset = off, .size = fsize, .flags = flags, .ty = try e.reflectType(tys, fld.type, fld.row_major, 0) }); + } + size = layout.sizeOf(e.t, g.ty, false, .dx_legacy) catch 0; + } else if (r.count == 1 and e.t.get(r.elem) == .@"struct") { + // ConstantBuffer / TextureBuffer: one variable, the block. + size = layout.sizeOf(e.t, r.elem, false, .dx_legacy) catch 0; + const flags: u32 = if (use.reads(0, size)) reflect.svf_used else 0; + try vars.append(e.arena, .{ .name = g.name, .offset = 0, .size = size, .flags = flags, .ty = try e.reflectType(tys, r.elem, false, 0) }); + } + try cbuffers.append(e.arena, .{ .name = g.name, .kind = kind, .size = std.mem.alignForward(u32, size, 16), .vars = vars.items }); + return @intCast(cbuffers.items.len - 1); + } + + fn instructionCount(e: *Emitter) u32 { + var n: usize = 0; + for (e.dm.functions.items) |f| n += f.insts.items.len; + return @intCast(n); + } + /// 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); + const refl = try e.reflectResources(); + var refl_funcs: std.ArrayList(reflect.Function) = .empty; var b = try rdat.Builder.init(gpa); defer b.deinit(); // Resources: CBVs, samplers, SRVs, UAVs. @@ -5553,6 +5987,16 @@ const Emitter = struct { } } std.mem.sort(u32, used.items, {}, std.sort.asc(u32)); + // Reflection lists resources in the same order as RDAT. + var func_cbuffers: std.ArrayList(u32) = .empty; + for (used.items) |ri| if (refl.cbuffer_of[ri]) |ci| try func_cbuffers.append(e.arena, ci); + try refl_funcs.append(e.arena, .{ + .name = lf.name, + .version = reflect.version(reflect.programType(@tagName(lf.stage)), e.profile.major, e.profile.minor), + .requires = libinfo.featureInfo(info.flags) & reflect.required_features, + .binds = try e.arena.dupe(u32, used.items), + .cbuffers = func_cbuffers.items, + }); const resources = if (used.items.len > 0) try b.array(used.items) else rdat.null_ref; const props = if (e.uses_linalg) try linalg_info.rdatProperties(e.arena, &b, &try linalg_info.functionInfo(e.arena, &e.dm, mats, lf.func)) else rdat.null_ref; const kind = shaderKind(lf.stage); @@ -5597,6 +6041,24 @@ const Emitter = struct { defer gpa.free(rdat_part); var sfi0: [8]u8 = @splat(0); std.mem.writeInt(u64, &sfi0, libinfo.featureInfo(analysis.flags), .little); + e.reflection = try reflect.encode(gpa, .{ + .version = reflect.version(reflect.programType("library"), e.profile.major, e.profile.minor), + .requires = libinfo.featureInfo(analysis.flags) & reflect.required_features, + .instructions = e.instructionCount(), + .binds = refl.binds, + .cbuffers = refl.cbuffers, + .types = refl.types, + .functions = sorted: { + // By name, as DXC lists them. + std.mem.sort(reflect.Function, refl_funcs.items, {}, struct { + fn lt(_: void, x: reflect.Function, y: reflect.Function) bool { + return std.mem.lessThan(u8, x.name, y.name); + } + }.lt); + break :sorted refl_funcs.items; + }, + }, &.{.{ .fourcc = container.fourcc("SFI0"), .data = &sfi0 }}); + errdefer if (e.reflection) |r| gpa.free(r); return container.assemble(gpa, &.{ .{ .fourcc = container.fourcc("SFI0"), .data = &sfi0 }, .{ .fourcc = container.fourcc("RDAT"), .data = rdat_part }, @@ -5844,6 +6306,38 @@ const Emitter = struct { defer gpa.free(psg1); var sfi0: [8]u8 = @splat(0); std.mem.writeInt(u64, &sfi0, libinfo.featureInfo(e.shaderFlags()), .little); + const refl = try e.reflectResources(); + const refl_in = try signature.declarationOrderSignature(gpa, e.sig_in, true, domain); + defer gpa.free(refl_in); + const refl_out = try signature.declarationOrderSignature(gpa, e.sig_out, false, domain); + defer gpa.free(refl_out); + const refl_pc = try signature.declarationOrderSignature(gpa, e.sig_pc, entry.stage == .domain, domain); + defer gpa.free(refl_pc); + const gs = entry.stage == .geometry; + const tess = entry.stage == .hull or entry.stage == .domain; + e.reflection = try reflect.encode(gpa, .{ + .version = reflect.version(reflect.programType(@tagName(entry.stage)), e.profile.major, e.profile.minor), + .requires = libinfo.featureInfo(e.shaderFlags()) & reflect.required_features, + .instructions = e.instructionCount(), + .thread_group = if (threaded) entry.num_threads else .{ 0, 0, 0 }, + .binds = refl.binds, + .cbuffers = refl.cbuffers, + .types = refl.types, + // Hull shaders: the input patch (D3D_PRIMITIVE_1_CONTROL_POINT_PATCH is 8). + .input_primitive = if (gs) @intFromEnum(entry.geometry.input) else if (entry.stage == .hull) 7 + entry.tess.input_control_points else 0, + .gs_output_topology = if (gs) gsTopology(entry.geometry) else 0, + .gs_max_vertices = if (gs) entry.geometry.max_vertex_count else 0, + .gs_instances = if (gs) entry.geometry.instance_count else 0, + .control_points = if (entry.stage == .hull) entry.tess.output_control_points else if (entry.stage == .domain) entry.tess.input_control_points else 0, + .hs_output_primitive = if (entry.stage == .hull) @intFromEnum(entry.tess.output_topology) else 0, + .hs_partitioning = if (entry.stage == .hull) @intFromEnum(entry.tess.partitioning) else 0, + .tess_domain = if (tess) @intFromEnum(entry.tess.domain) else 0, + }, &.{ + .{ .fourcc = container.fourcc("SFI0"), .data = &sfi0 }, + .{ .fourcc = reflect.input_part, .data = refl_in }, + .{ .fourcc = reflect.output_part, .data = refl_out }, + .{ .fourcc = reflect.patch_part, .data = refl_pc }, + }); var parts: std.ArrayList(container.Part) = .empty; try parts.appendSlice(e.arena, &.{ .{ .fourcc = container.fourcc("SFI0"), .data = &sfi0 }, diff --git a/src/dxil/reflect.zig b/src/dxil/reflect.zig new file mode 100644 index 0000000..7a91751 --- /dev/null +++ b/src/dxil/reflect.zig @@ -0,0 +1,206 @@ +//! Shader reflection: what D3D12's ID3D12ShaderReflection and +//! ID3D12LibraryReflection report about a compiled shader. The DXIL emitter +//! builds it; the DXC drop-in hands it out as DXC_OUT_REFLECTION and reads +//! it back in IDxcUtils::CreateReflection. +//! +//! The blob is a DXIL container: the object's SFI0 part, its signatures' +//! records in declaration order (the parameters reflection reports), and a +//! ZRFL part holding the rest as JSON. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const container = @import("container.zig"); + +pub const part = container.fourcc("ZRFL"); +/// The signatures in declaration order (ISG1 / OSG1 / PSG1's records, which +/// those parts sort by register). +pub const input_part = container.fourcc("ZIS1"); +pub const output_part = container.fourcc("ZOS1"); +pub const patch_part = container.fourcc("ZPS1"); + +/// The feature bits reflection reports as required (D3D_SHADER_REQUIRES_*): +/// the bits from 40 up are DXC's optional feature info. +pub const required_features: u64 = (1 << 40) - 1; + +/// D3D12_SHADER_INPUT_BIND_DESC. +pub const Bind = struct { + name: []const u8, + /// D3D_SHADER_INPUT_TYPE. + type: u32, + bind_point: u32, + /// 0 for an unbounded range. + bind_count: u32, + /// D3D_SHADER_INPUT_FLAGS. + flags: u32 = 0, + /// D3D_RESOURCE_RETURN_TYPE. + return_type: u32 = 0, + /// D3D_SRV_DIMENSION. + dimension: u32 = 0, + /// The sample count of multisampled textures; the stride of structured + /// buffers. + num_samples: u32 = 0, + space: u32, + id: u32, +}; + +/// D3D12_SHADER_TYPE_DESC (members by index into Reflection.types). +pub const Type = struct { + /// D3D_SHADER_VARIABLE_CLASS. + class: u32, + /// D3D_SHADER_VARIABLE_TYPE. + kind: u32, + rows: u32 = 0, + cols: u32 = 0, + elements: u32 = 0, + offset: u32 = 0, + name: []const u8 = "", + members: []const Member = &.{}, +}; + +pub const Member = struct { name: []const u8, ty: u32 }; + +/// D3D12_SHADER_VARIABLE_DESC. +pub const Variable = struct { + name: []const u8, + offset: u32, + size: u32, + /// D3D_SHADER_VARIABLE_FLAGS: `used` when the shader reads it. + flags: u32, + ty: u32, +}; + +/// D3D12_SHADER_BUFFER_DESC and its variables. +pub const CBuffer = struct { + name: []const u8, + /// D3D_CBUFFER_TYPE. + kind: u32, + size: u32, + flags: u32 = 0, + vars: []const Variable, +}; + +/// A library function (ID3D12FunctionReflection): indices into +/// Reflection.binds and Reflection.cbuffers. +pub const Function = struct { + name: []const u8, + version: u32, + requires: u64, + binds: []const u32, + cbuffers: []const u32, +}; + +pub const Reflection = struct { + /// D3D12_SHVER: program type << 16, major << 4, minor. + version: u32, + requires: u64 = 0, + instructions: u32 = 0, + thread_group: [3]u32 = .{ 0, 0, 0 }, + binds: []const Bind = &.{}, + cbuffers: []const CBuffer = &.{}, + types: []const Type = &.{}, + functions: []const Function = &.{}, + /// Geometry and tessellation state (D3D12_SHADER_DESC). + input_primitive: u32 = 0, + gs_output_topology: u32 = 0, + gs_max_vertices: u32 = 0, + gs_instances: u32 = 0, + control_points: u32 = 0, + hs_output_primitive: u32 = 0, + hs_partitioning: u32 = 0, + tess_domain: u32 = 0, + sample_frequency: bool = false, +}; + +// D3D enums (d3dcommon.h) used here. +pub const sit = struct { + pub const cbuffer = 0; + pub const tbuffer = 1; + pub const texture = 2; + pub const sampler = 3; + pub const uav_rwtyped = 4; + pub const structured = 5; + pub const uav_rwstructured = 6; + pub const byteaddress = 7; + pub const uav_rwbyteaddress = 8; + pub const uav_append_structured = 9; + pub const uav_consume_structured = 10; + pub const uav_rwstructured_with_counter = 11; + pub const rtaccelerationstructure = 12; + pub const uav_feedbacktexture = 13; +}; +pub const sif_userpacked = 1; +pub const sif_comparison_sampler = 2; +pub const svf_userpacked = 1; +pub const svf_used = 2; +pub const ct_cbuffer = 0; +pub const ct_tbuffer = 1; +pub const ct_resource_bind_info = 3; +pub const svc = struct { + pub const scalar = 0; + pub const vector = 1; + pub const matrix_rows = 2; + pub const matrix_columns = 3; + pub const object = 4; + pub const @"struct" = 5; +}; +pub const ret = struct { + pub const unorm = 1; + pub const snorm = 2; + pub const sint = 3; + pub const uint = 4; + pub const float = 5; + pub const mixed = 6; + pub const double = 7; +}; + +/// D3D12_SHVER program types. +pub fn programType(stage: []const u8) u32 { + const names = [_][]const u8{ "pixel", "vertex", "geometry", "hull", "domain", "compute", "library", "raygeneration", "intersection", "anyhit", "closesthit", "miss", "callable", "mesh", "amplification", "node" }; + for (names, 0..) |n, i| if (std.mem.eql(u8, n, stage)) return @intCast(i); + return 5; +} + +pub fn version(program_type: u32, major: u32, minor: u32) u32 { + return program_type << 16 | major << 4 | minor; +} + +/// The reflection blob: `parts` (SFI0 and the signatures) and the ZRFL +/// part. +pub fn encode(gpa: Allocator, r: Reflection, parts: []const container.Part) Allocator.Error![]u8 { + const json = try std.json.Stringify.valueAlloc(gpa, r, .{}); + defer gpa.free(json); + var all: std.ArrayList(container.Part) = .empty; + defer all.deinit(gpa); + try all.appendSlice(gpa, parts); + try all.append(gpa, .{ .fourcc = part, .data = json }); + return container.assemble(gpa, all.items); +} + +/// The ZRFL part of a reflection blob (padding included), parsed into +/// `arena`. +pub fn decode(arena: Allocator, json: []const u8) !Reflection { + const text = std.mem.trimEnd(u8, json, "\x00"); + return std.json.parseFromSliceLeaky(Reflection, arena, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always }); +} + +test "encode and decode" { + const a = std.testing.allocator; + const r: Reflection = .{ + .version = version(0, 6, 6), + .requires = 1 << 40, + .binds = &.{.{ .name = "Tex", .type = sit.texture, .bind_point = 3, .bind_count = 1, .space = 0, .id = 0 }}, + .cbuffers = &.{.{ .name = "$Globals", .kind = ct_cbuffer, .size = 16, .vars = &.{.{ .name = "A", .offset = 0, .size = 16, .flags = svf_used, .ty = 0 }} }}, + .types = &.{.{ .class = svc.vector, .kind = 3, .rows = 1, .cols = 4, .name = "float4" }}, + }; + const blob = try encode(a, r, &.{}); + defer a.free(blob); + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const view = try container.parse(arena.allocator(), blob); + const back = try decode(arena.allocator(), view.find(part) orelse return error.TestUnexpectedResult); + try std.testing.expectEqual(r.version, back.version); + try std.testing.expectEqual(r.requires, back.requires); + try std.testing.expectEqualStrings("Tex", back.binds[0].name); + try std.testing.expectEqualStrings("$Globals", back.cbuffers[0].name); + try std.testing.expectEqual(@as(u32, svf_used), back.cbuffers[0].vars[0].flags); +} diff --git a/src/dxil/signature.zig b/src/dxil/signature.zig index 0d7507e..e9e1975 100644 --- a/src/dxil/signature.zig +++ b/src/dxil/signature.zig @@ -44,14 +44,14 @@ pub const SemanticKind = enum(u8) { }; const sv_names = [_][]const u8{ - "", "SV_VertexID", "SV_InstanceID", "SV_Position", - "SV_RenderTargetArrayIndex", "SV_ViewportArrayIndex", "SV_ClipDistance", "SV_CullDistance", - "SV_OutputControlPointID", "SV_DomainLocation", "SV_PrimitiveID", "SV_GSInstanceID", - "SV_SampleIndex", "SV_IsFrontFace", "SV_Coverage", "SV_InnerCoverage", - "SV_Target", "SV_Depth", "SV_DepthLessEqual", "SV_DepthGreaterEqual", - "SV_StencilRef", "SV_DispatchThreadID", "SV_GroupID", "SV_GroupIndex", - "SV_GroupThreadID", "SV_TessFactor", "SV_InsideTessFactor", "SV_ViewID", - "SV_Barycentrics", "SV_ShadingRate", "SV_CullPrimitive", "SV_StartVertexLocation", + "", "SV_VertexID", "SV_InstanceID", "SV_Position", + "SV_RenderTargetArrayIndex", "SV_ViewportArrayIndex", "SV_ClipDistance", "SV_CullDistance", + "SV_OutputControlPointID", "SV_DomainLocation", "SV_PrimitiveID", "SV_GSInstanceID", + "SV_SampleIndex", "SV_IsFrontFace", "SV_Coverage", "SV_InnerCoverage", + "SV_Target", "SV_Depth", "SV_DepthLessEqual", "SV_DepthGreaterEqual", + "SV_StencilRef", "SV_DispatchThreadID", "SV_GroupID", "SV_GroupIndex", + "SV_GroupThreadID", "SV_TessFactor", "SV_InsideTessFactor", "SV_ViewID", + "SV_Barycentrics", "SV_ShadingRate", "SV_CullPrimitive", "SV_StartVertexLocation", "SV_StartInstanceLocation", }; @@ -60,14 +60,14 @@ const sv_names = [_][]const u8{ pub fn kindByName(name: []const u8) SemanticKind { if (!std.ascii.startsWithIgnoreCase(name, "SV_")) return .arbitrary; for (sv_names[1..], 1..) |n, i| { - if (std.ascii.eqlIgnoreCase(name, n)) return @enumFromInt(i); + if (std.ascii.eqlIgnoreCase(name, n)) return @fromBackingInt(@intCast(i)); } return .invalid; } /// The canonical spelling of a system-value semantic. pub fn canonicalName(kind: SemanticKind) []const u8 { - return sv_names[@intFromEnum(kind)]; + return sv_names[@backingInt(kind)]; } pub const Interpretation = enum(u8) { na, sv, sgv, arb, not_in_sig, not_packed, target, tess_factor, shadow, clip_cull }; @@ -150,7 +150,7 @@ pub fn interpretation(kind: SemanticKind, sp: SigPoint, minor: u8) Interpretatio .start_vertex_location, .start_instance_location => if (minor >= 8) .{ nis, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na } else @splat(na), else => @splat(na), }; - return row[@intFromEnum(sp)]; + return row[@backingInt(sp)]; } pub fn shouldBeAllocated(i: Interpretation) bool { @@ -553,6 +553,15 @@ fn systemValue(kind: SemanticKind, domain: Domain) u32 { /// A DxilProgramSignature part (ISG1 or OSG1) for elements in the /// signature (not NotInSig ones). pub fn programSignature(gpa: Allocator, elements: []const Element, is_input: bool, domain: Domain) Allocator.Error![]u8 { + return signaturePart(gpa, elements, is_input, domain, true); +} + +/// The same records in declaration order, as reflection lists parameters. +pub fn declarationOrderSignature(gpa: Allocator, elements: []const Element, is_input: bool, domain: Domain) Allocator.Error![]u8 { + return signaturePart(gpa, elements, is_input, domain, false); +} + +fn signaturePart(gpa: Allocator, elements: []const Element, is_input: bool, domain: Domain, sorted: bool) Allocator.Error![]u8 { const Rec = struct { stream: u32, name: u32, index: u32, sv: u32, comp: u32, reg: u32, mask: u8, rw: u8, min_prec: u32 }; var recs: std.ArrayList(Rec) = .empty; defer recs.deinit(gpa); @@ -584,7 +593,7 @@ pub fn programSignature(gpa: Allocator, elements: []const Element, is_input: boo if (sv == 16) sv = 15; // isoline: density, then detail } } - std.sort.insertion(Rec, recs.items, {}, struct { + if (sorted) std.sort.insertion(Rec, recs.items, {}, struct { fn lt(_: void, a: Rec, b: Rec) bool { if (a.stream != b.stream) return a.stream < b.stream; if (a.reg != b.reg) return a.reg < b.reg; diff --git a/src/root.zig b/src/root.zig index a1bcadd..bf959e3 100644 --- a/src/root.zig +++ b/src/root.zig @@ -26,6 +26,7 @@ pub const dxil = struct { pub const signature = @import("dxil/signature.zig"); pub const emit = @import("dxil/emit.zig"); pub const rootsig = @import("dxil/rootsig.zig"); + pub const reflect = @import("dxil/reflect.zig"); }; pub const ir = struct {